コード例 #1
0
ファイル: rf903_numintcache.C プロジェクト: adevress/root-1
void rf903_numintcache(Int_t mode=0)
{
  // Mode = 0 : Run plain fit (slow)
  // Mode = 1 : Generate workspace with precalculated integral and store it on file (prepare for accelerated running)
  // Mode = 2 : Run fit from previously stored workspace including cached integrals (fast, requires run in mode=1 first)

  // C r e a t e ,   s a v e   o r   l o a d   w o r k s p a c e   w i t h   p . d . f . 
  // -----------------------------------------------------------------------------------

  // Make/load workspace, exit here in mode 1
  RooWorkspace* w = getWorkspace(mode) ;
  if (mode==1) {

    // Show workspace that was created
    w->Print() ;

    // Show plot of cached integral values
    RooDataHist* hhcache = (RooDataHist*) w->expensiveObjectCache().getObj(1) ;

    new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
    hhcache->createHistogram("a")->Draw() ;
    
    return ;
  }


  // U s e   p . d . f .   f r o m   w o r k s p a c e   f o r   g e n e r a t i o n   a n d   f i t t i n g 
  // -----------------------------------------------------------------------------------

  // This is always slow (need to find maximum function value empirically in 3D space)
  RooDataSet* d = w->pdf("model")->generate(RooArgSet(*w->var("x"),*w->var("y"),*w->var("z")),1000) ;

  // This is slow in mode 0, but fast in mode 1
  w->pdf("model")->fitTo(*d,Verbose(kTRUE),Timer(kTRUE)) ; 

  // Projection on x (always slow as 2D integral over Y,Z at fitted value of a is not cached)
  RooPlot* framex = w->var("x")->frame(Title("Projection of 3D model on X")) ;
  d->plotOn(framex) ;
  w->pdf("model")->plotOn(framex) ;

  // Draw x projection on canvas
  new TCanvas("rf903_numintcache","rf903_numintcache",600,600) ;
  framex->Draw() ;

  // Make workspace available on command line after macro finishes
  gDirectory->Add(w) ;

  return ;

 
}
コード例 #2
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();
}
コード例 #3
0
int main() {

  gROOT->ProcessLine(".x ~/Scratch/lhcb/lhcbStyle.C");

  flagMultCands( "root/AnalysisOut.root", "AnalysisTree" );
  fillDatasets( "root/AnalysisOut.root", "AnalysisTree", "root/MassFitWorkspace.root" );

  TFile *tf = TFile::Open("root/MassFitWorkspace.root");
  RooWorkspace *w = (RooWorkspace*)tf->Get("w");
  drawData( w );

  constructPdfs( w, "root/MassFitWorkspaceWithPDFs.root" );

  w->Print("v");
  return 0;
}
コード例 #4
0
ファイル: dimuon.C プロジェクト: neumeist/twobody
Int_t TwoBody::AddWorkspace(std::string filename,
			    std::string ws_name,
			    std::string channel_name,
			    std::string shared_vars){
  //
  // Load a single channel model and data from a workspace
  //

  std::string _legend = "[TwoBody::AddWorkspace]: ";

   // load workspace from a file
  TFile _file(filename.c_str(), "read");
  RooWorkspace * _ws = (RooWorkspace *)_file.Get( ws_name.c_str() );

  // get the single channel model PDF
  RooAbsPdf * _model = _ws->pdf("model"),
            * _prior = _ws->pdf("prior");

  // import the channel model PDF into the combined workspace
  // add prefix channel_name to all nodes except shared_vars
  ws->import( RooArgSet(*_model,*_prior),
     	      RooFit::RenameAllNodes( channel_name.c_str() ),
    	      RooFit::RenameAllVariablesExcept(channel_name.c_str(), shared_vars.c_str()) );
  delete data; 
  data = new RooDataSet( *(RooDataSet *) _ws->data("data") );
  data->changeObservableName("vertex_m","mass");

  //realdata = new RooDataSet( *(RooDataSet *) data );
  //new RooDataSet( *(RooDataSet *) ws->data("data") );
  //realdata->SetName("RealData");
  //realdata->changeObservableName("vertex_m","mass");

  ws->import( *data );

  ws->Print();
  //  for (int i=0; i!=100; ++i){
  //  RooRealVar * _var = (RooRealVar *)(data->get(i)->first());
  //  cerr<<_var->getVal()<<",";
  //}
  _file.Close();

  return 0;
}
コード例 #5
0
ファイル: rf510_wsnamedsets.C プロジェクト: adevress/root-1
void rf510_wsnamedsets()
{
  // C r e a t e   m o d e l   a n d   d a t a s e t
  // -----------------------------------------------

  RooWorkspace* w = new RooWorkspace("w") ;
  fillWorkspace(*w) ;

  // Exploit convention encoded in named set "parameters" and "observables"
  // to use workspace contents w/o need for introspected
  RooAbsPdf* model = w->pdf("model") ;

  // Generate data from p.d.f. in given observables
  RooDataSet* data = model->generate(*w->set("observables"),1000) ;

  // Fit model to data
  model->fitTo(*data) ;
  
  // Plot fitted model and data on frame of first (only) observable
  RooPlot* frame = ((RooRealVar*)w->set("observables")->first())->frame() ;
  data->plotOn(frame) ;
  model->plotOn(frame) ;

  // Overlay plot with model with reference parameters as stored in snapshots
  w->loadSnapshot("reference_fit") ;
  model->plotOn(frame,LineColor(kRed)) ;
  w->loadSnapshot("reference_fit_bkgonly") ;
  model->plotOn(frame,LineColor(kRed),LineStyle(kDashed)) ;


  // Draw the frame on the canvas
  new TCanvas("rf510_wsnamedsets","rf503_wsnamedsets",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


  // Print workspace contents
  w->Print() ;


  // Workspace will remain in memory after macro finishes
  gDirectory->Add(w) ;

}
コード例 #6
0
ファイル: rf509_wsinteractive.C プロジェクト: adevress/root-1
void rf509_wsinteractive()
{
  // C r e a t e  a n d   f i l l   w o r k s p a c e
  // ------------------------------------------------

  // Create a workspace named 'w' that exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  RooWorkspace* w = new RooWorkspace("w",kTRUE) ;

  // Fill workspace with p.d.f. and data in a separate function
  fillWorkspace(*w) ;

  // Print workspace contents
  w->Print() ;

  // U s e   w o r k s p a c e   c o n t e n t s   t h r o u g h   C I N T   C + +   n a m e s p a c e
  // -------------------------------------------------------------------------------------------------

  // Use the name space prefix operator to access the workspace contents
  RooDataSet* d = w::model.generate(w::x,1000) ;
  RooFitResult* r = w::model.fitTo(*d) ;

  RooPlot* frame = w::x.frame() ;
  d->plotOn(frame) ;


  // NB: The 'w::' prefix can be omitted if namespace w is imported in local namespace
  // in the usual C++ way
  using namespace w;
  model.plotOn(frame) ;
  model.plotOn(frame,Components(bkg),LineStyle(kDashed)) ;


  // Draw the frame on the canvas
  new TCanvas("rf509_wsinteractive","rf509_wsinteractive",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


}
コード例 #7
0
ファイル: rf509_wsinteractive.C プロジェクト: MycrofD/root
void rf509_wsinteractive()
{
  // C r e a t e  a n d   f i l l   w o r k s p a c e
  // ------------------------------------------------

  // Create a workspace named 'w'
  // With CINT w could exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  // but this does not work anymore in CLING. 
  // so this tutorial is an example on how to 
  // change the code
  RooWorkspace* w = new RooWorkspace("w",kTRUE) ;

  // Fill workspace with p.d.f. and data in a separate function
  fillWorkspace(*w) ;

  // Print workspace contents
  w->Print() ;

  // this does not work anymore with CLING 
  // use normal workspace functionality 

 
  // U s e   w o r k s p a c e   c o n t e n t s   
  // ----------------------------------------------


  // Old syntax to use the name space prefix operator to access the workspace contents
  //
  //RooDataSet* d = w::model.generate(w::x,1000) ;
  //RooFitResult* r = w::model.fitTo(*d) ;

  // use normal workspace methods
  RooAbsPdf * model = w->pdf("model");
  RooRealVar * x = w->var("x");

  RooDataSet* d = model->generate(*x,1000) ;
  RooFitResult* r = model->fitTo(*d) ;

  // old syntax to access the variable x
  // RooPlot* frame = w::x.frame() ;

  RooPlot* frame = x->frame() ;
  d->plotOn(frame) ;

  // OLD syntax to ommit x::
  // NB: The 'w::' prefix can be omitted if namespace w is imported in local namespace
  // in the usual C++ way
  //
  // using namespace w;
  // model.plotOn(frame) ;
  // model.plotOn(frame,Components(bkg),LineStyle(kDashed)) ;

  // new correct syntax 
  RooAbsPdf *bkg = w->pdf("bkg");
  model->plotOn(frame);
  model->plotOn(frame,Components(*bkg),LineStyle(kDashed)) ;

  // Draw the frame on the canvas
  new TCanvas("rf509_wsinteractive","rf509_wsinteractive",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


}
コード例 #8
0
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

     

    epdf->Var("sig_yield");
    epdf->Var("sig_yield").setVal(153000);
    epdf->Var("sig_yield").setConstant(false);
    //decay time
    epdf->Var("obsTime");
    epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
    epdf->Var("obsTime").setUnit("ps");
    epdf->Var("obsTime").setRange(0.,16.);

    // tag, respectively the initial state of the produced B meson
    epdf->Cat("obsTag");
    epdf->Cat("obsTag").defineType("B_S",1);
    epdf->Cat("obsTag").defineType("Bbar_S",-1);

    //finalstate
    epdf->Cat("catFinalState");
    epdf->Cat("catFinalState").defineType("f",1);
    epdf->Cat("catFinalState").defineType("fbar",-1);

    epdf->Var("obsEtaOS");
    epdf->Var("obsEtaOS").setRange(0.0,0.5);


     std::vector<double> knots;
            knots.push_back(0.07);
            knots.push_back(0.10);
            knots.push_back(0.138);
            knots.push_back(0.16);
            knots.push_back(0.23);
            knots.push_back(0.28);
            knots.push_back(0.35);
            knots.push_back(0.42);
            knots.push_back(0.44);
            knots.push_back(0.48);
            knots.push_back(0.5);

            // empty arg list for coefficients
            RooArgList* list = new RooArgList();

            // create first coefficient
            RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
            coeff_first->setRange(0,10000);
            coeff_first->setVal(1);
            coeff_first->setConstant(false);
            list->add( *coeff_first );

            for (unsigned int i=1; i <= knots.size(); ++i){
               std::string number = boost::lexical_cast<std::string>(i);
               RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
               coeff->setRange(0,10000);
               coeff->setVal(1);
               coeff->setConstant(false);
               list->add( *coeff );
            }

            // create last coefficient
            RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
            coeff_last->setRange(0,10000);
            coeff_last->setVal(1);
            coeff_last->setConstant(false);
            list->add( *coeff_last );



            list->Print();

            doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
            //doofit::roofit::pdfs::DooCubicSplinePdf* splinePdf = new doofit::roofit::pdfs::DooCubicSplinePdf("splinePdf", epdf->Var("obsEtaOS"), knots, *list,0,0.5);



     //Koeffizienten
            DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

            epdf->AddRealToStore(coeff_ch);
            epdf->AddRealToStore(coeff_sh);
            epdf->AddRealToStore(coeff_c);
            epdf->AddRealToStore(coeff_s);


    ///////////////////Generiere PDF's/////////////////////
    //Zeit
    epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
    epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));


     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));


     epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));



     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     /*epdf->Product("pdf_bkg", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_mass_time")));
     //Signal * Zerfall
     epdf->Product("pdf_sig", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdfSigTime")));
    //Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));*/





     RooWorkspace ws;
                 ws.import(epdf->Pdf("pdfExtend"));
                 ws.defineSet("Observables",Observables, true);

                 ws.Print();

                 doofit::config::CommonConfig cfg_com("common");
                 cfg_com.InitializeOptions(argc, argv);
                 doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
                 cfg_tfac.InitializeOptions(cfg_com);
                 doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
                 cfg_tstudy.InitializeOptions(cfg_tfac);

                 // set a previously defined workspace to get PDF from (not mandatory, but convenient)
                 cfg_tfac.set_workspace(&ws);

                 // Check for a set --help flag and if so, print help and exit gracefully
                 // (recommended).
                 cfg_com.CheckHelpFlagAndPrintHelp();

                 // More custom code, e.g. to set options internally.
                 // Not required as configuration via command line/config file is enough.
                 cfg_com.PrintAll();

                 // Print overview of all options (optional)
                 // cfg_com.PrintAll();

                 // Initialize the toy factory module with the config objects and start
                 // generating toy samples.
                 doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
                 doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);




          RooDataSet* data = tfac.Generate();
          data->Print();
          epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt");
          epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt.new");

          //epdf->Pdf("pdfExtend").fitTo(*data);
          //epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-fit-result.txt");
		      RooFitResult* fit_result = epdf->Pdf("pdfExtend").fitTo(*data, RooFit::Save(true));
       	  tstudy.StoreFitResult(fit_result);

          /*using namespace doofit::plotting;

          PlotConfig cfg_plot("cfg_plot");
          cfg_plot.InitializeOptions();
          cfg_plot.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/time/");
          // plot PDF and directly specify components
          Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
          myplot.PlotItLogNoLogY();

          PlotConfig cfg_plotEta("cfg_plotEta");
          cfg_plotEta.InitializeOptions();
          cfg_plotEta.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/eta/");
          // plot PDF and directly specify components
          Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
          myplotEta.PlotIt();*/

 }
コード例 #9
0
void StandardBayesianNumericalDemo(const char* infile = "",
                                   const char* workspaceName = "combined",
                                   const char* modelConfigName = "ModelConfig",
                                   const char* dataName = "obsData") {

   // option definitions 
   double confLevel = optBayes.confLevel; 
   TString integrationType = optBayes.integrationType;
   int nToys = optBayes.nToys; 
   bool scanPosterior = optBayes.scanPosterior; 
   int nScanPoints = optBayes.nScanPoints; 
   int intervalType = optBayes.intervalType;
   int  maxPOI =  optBayes.maxPOI;
   double  nSigmaNuisance = optBayes.nSigmaNuisance;
   


  /////////////////////////////////////////////////////////////
  // 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;
   }


  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // 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;
  }

  /////////////////////////////////////////////
  // create and use the BayesianCalculator
  // to find and plot the 95% credible interval
  // on the parameter of interest as specified
  // in the model config

  // before we do that, we must specify our prior
  // it belongs in the model config, but it may not have
  // been specified
  RooUniform prior("prior","",*mc->GetParametersOfInterest());
  w->import(prior);
  mc->SetPriorPdf(*w->pdf("prior"));

  // do without systematics
  //mc->SetNuisanceParameters(RooArgSet() );
  if (nSigmaNuisance > 0) {
     RooAbsPdf * pdf = mc->GetPdf();
     assert(pdf);
     RooFitResult * res = pdf->fitTo(*data, Save(true), Minimizer(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str()), Hesse(true),
                                     PrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1) );

     res->Print();
     RooArgList nuisPar(*mc->GetNuisanceParameters());
     for (int i = 0; i < nuisPar.getSize(); ++i) {
        RooRealVar * v = dynamic_cast<RooRealVar*> (&nuisPar[i] );
        assert( v);
        v->setMin( TMath::Max( v->getMin(), v->getVal() - nSigmaNuisance * v->getError() ) );
        v->setMax( TMath::Min( v->getMax(), v->getVal() + nSigmaNuisance * v->getError() ) );
        std::cout << "setting interval for nuisance  " << v->GetName() << " : [ " << v->getMin() << " , " << v->getMax() << " ]" << std::endl;
     }
  }


  BayesianCalculator bayesianCalc(*data,*mc);
  bayesianCalc.SetConfidenceLevel(confLevel); // 95% interval

  // default of the calculator is central interval.  here use shortest , central or upper limit depending on input
  // doing a shortest interval might require a longer time since it requires a scan of the posterior function
  if (intervalType == 0)  bayesianCalc.SetShortestInterval(); // for shortest interval
  if (intervalType == 1)  bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
  if (intervalType == 2)  bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit

  if (!integrationType.IsNull() ) {
     bayesianCalc.SetIntegrationType(integrationType); // set integrationType
     bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
  }

  // in case of toyMC make a nnuisance pdf
  if (integrationType.Contains("TOYMC") ) {
    RooAbsPdf * nuisPdf = RooStats::MakeNuisancePdf(*mc, "nuisance_pdf");
    cout << "using TOYMC integration: make nuisance pdf from the model " << std::endl;
    nuisPdf->Print();
    bayesianCalc.ForceNuisancePdf(*nuisPdf);
    scanPosterior = true; // for ToyMC the posterior is scanned anyway so used given points
  }

  // compute interval by scanning the posterior function
  if (scanPosterior)
     bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooRealVar* poi = (RooRealVar*) mc->GetParametersOfInterest()->first();
  if (maxPOI != -999 &&  maxPOI > poi->getMin())
    poi->setMax(maxPOI);


  SimpleInterval* interval = bayesianCalc.GetInterval();

  // print out the iterval on the first Parameter of Interest
  cout << "\n>>>> RESULT : " << confLevel*100 << "% interval on " << poi->GetName()<<" is : ["<<
    interval->LowerLimit() << ", "<<
    interval->UpperLimit() <<"] "<<endl;


  // make a plot
  // since plotting may take a long time (it requires evaluating
  // the posterior in many points) this command will speed up
  // by reducing the number of points to plot - do 50

  // ignore errors of PDF if is zero
  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::Ignore) ;

  
  cout << "\nDrawing plot of posterior function....." << endl;

  // always plot using numer of scan points
  bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooPlot * plot = bayesianCalc.GetPosteriorPlot();
  plot->Draw();

}
コード例 #10
0
void StandardProfileLikelihoodDemo(const char* infile = "",
                                   const char* workspaceName = "combined",
                                   const char* modelConfigName = "ModelConfig",
                                   const char* dataName = "obsData"){

      double confLevel = optPL.confLevel;
      double nScanPoints = optPL.nScanPoints;
      bool plotAsTF1 = optPL.plotAsTF1;
      double poiXMin = optPL.poiMinPlot;
      double poiXMax = optPL.poiMaxPlot;
      bool doHypoTest = optPL.doHypoTest;
      double nullParamValue = optPL.nullValue;

   // -------------------------------------------------------
   // 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;
      }

   // -------------------------------------------------------
   // Tutorial starts here
   // -------------------------------------------------------

   // 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;
   }

   // ---------------------------------------------
   // create and use the ProfileLikelihoodCalculator
   // to find and plot the 95% confidence interval
   // on the parameter of interest as specified
   // in the model config
   ProfileLikelihoodCalculator pl(*data,*mc);
   pl.SetConfidenceLevel(confLevel); // 95% interval
   LikelihoodInterval* interval = pl.GetInterval();

   // print out the interval on the first Parameter of Interest
   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   cout << "\n>>>> RESULT : " << confLevel*100 << "% interval on " <<firstPOI->GetName()<<" is : ["<<
      interval->LowerLimit(*firstPOI) << ", "<<
      interval->UpperLimit(*firstPOI) <<"]\n "<<endl;

   // make a plot

   cout << "making a plot of the profile likelihood function ....(if it is taking a lot of time use less points or the TF1 drawing option)\n";
   LikelihoodIntervalPlot plot(interval);
   plot.SetNPoints(nScanPoints);  // do not use too many points, it could become very slow for some models
   if (poiXMin < poiXMax) plot.SetRange(poiXMin, poiXMax);
   TString opt;
   if (plotAsTF1) opt += TString("tf1");
   plot.Draw(opt);  // use option TF1 if too slow (plot.Draw("tf1")


   // if requested perform also an hypothesis test for the significance
   if (doHypoTest) {
      RooArgSet nullparams("nullparams");
      nullparams.addClone(*firstPOI);
      nullparams.setRealValue(firstPOI->GetName(), nullParamValue);
      pl.SetNullParameters(nullparams);
      std::cout << "Perform Test of Hypothesis : null Hypothesis is " << firstPOI->GetName() << nullParamValue << std::endl;
      auto result = pl.GetHypoTest();
      std::cout << "\n>>>> Hypotheis Test Result \n";
      result->Print();
   }


}
コード例 #11
0
ファイル: rf511_wsfactory_basic.C プロジェクト: MycrofD/root
void rf511_wsfactory_basic(Bool_t compact=kFALSE)
{
  RooWorkspace* w = new RooWorkspace("w") ;

  // C r e a t i n g   a n d   a d d i n g   b a s i c  p . d . f . s 
  // ----------------------------------------------------------------


  // Remake example p.d.f. of tutorial rs502_wspacewrite.C:
  //
  // Basic p.d.f. construction: ClassName::ObjectName(constructor arguments)
  // Variable construction    : VarName[x,xlo,xhi], VarName[xlo,xhi], VarName[x]
  // P.d.f. addition          : SUM::ObjectName(coef1*pdf1,...coefM*pdfM,pdfN)
  //

  if (!compact) {

    // Use object factory to build p.d.f. of tutorial rs502_wspacewrite
    w->factory("Gaussian::sig1(x[-10,10],mean[5,0,10],0.5)") ;
    w->factory("Gaussian::sig2(x,mean,1)") ;
    w->factory("Chebychev::bkg(x,{a0[0.5,0.,1],a1[-0.2,0.,1.]})") ;
    w->factory("SUM::sig(sig1frac[0.8,0.,1.]*sig1,sig2)") ;
    w->factory("SUM::model(bkgfrac[0.5,0.,1.]*bkg,sig)") ;

  } else {

    // Use object factory to build p.d.f. of tutorial rs502_wspacewrite but 
    //  - Contracted to a single line recursive expression, 
    //  - Omitting explicit names for components that are not referred to explicitly later

    w->factory("SUM::model(bkgfrac[0.5,0.,1.]*Chebychev::bkg(x[-10,10],{a0[0.5,0.,1],a1[-0.2,0.,1.]}),"
                                              "SUM(sig1frac[0.8,0.,1.]*Gaussian(x,mean[5,0,10],0.5), Gaussian(x,mean,1)))") ;
  }


  // A d v a n c e d   p . d . f .  c o n s t r u c t o r   a r g u m e n t s
  // ----------------------------------------------------------------
  //
  // P.d.f. constructor arguments may by any type of RooAbsArg, but also
  //
  // Double_t --> converted to RooConst(...)
  // {a,b,c} --> converted to RooArgSet() or RooArgList() depending on required ctor arg
  // dataset name --> convered to RooAbsData reference for any dataset residing in the workspace
  // enum --> Any enum label that belongs to an enum defined in the (base) class


  // Make a dummy dataset p.d.f. 'model' and import it in the workspace
  RooDataSet* data = w->pdf("model")->generate(*w->var("x"),1000) ;
  w->import(*data,Rename("data")) ;   

  // Construct a KEYS p.d.f. passing a dataset name and an enum type defining the
  // mirroring strategy
  w->factory("KeysPdf::k(x,data,NoMirror,0.2)") ;


  // Print workspace contents
  w->Print() ;

  // Make workspace visible on command line
  gDirectory->Add(w) ;

}
コード例 #12
0
ファイル: CreateBkgTemplates.C プロジェクト: UAEDF/vbfHbb
void CreateBkgTemplates(float XMIN, float XMAX, TString OUTPATH, bool MERGE)
{
  gROOT->ProcessLineSync(".x ../common/styleCMSTDR.C");
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  const int NSEL(2);
  if (!MERGE) {const int NCAT[NSEL] = {4,3};}
  else {const int NCAT[NSEL] = {4,2};}
  if (!MERGE) {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};}
  else {const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,1}};}
  float LUMI[2] = {19784,18281};
  TString SELECTION[2] = {"NOM","VBF"};
  TString SELNAME[2] = {"NOM","PRK"};
  TString MASS_VAR[2] = {"mbbReg[1]","mbbReg[2]"};
  TString TRIG_WT[2] = {"trigWtNOM[1]","trigWtVBF"};
  TString PATH("flat/");
  TFile *inf[9];
  TTree *tr;
  TH1F *hMbb[9],*hMbbYield[9],*hPass;
  TH1F *hZ,*hW,*hTT,*hST,*hTop;
  TH1F *hZYield,*hWYield,*hTTYield,*hSTYield,*hTopYield;
  char name[1000];
  float LUMI;
  float XSEC[9] = {56.4,11.1,3.79,30.7,11.1,1.76,245.8,650,1.2*1205};
  RooDataHist *roohist_Z[5],*roohist_T[5];
  RooRealVar *kJES[10],*kJER[10];
  RooWorkspace *w = new RooWorkspace("w","workspace");
  
  TString tMERGE = MERGE ? "_CATmerge56" : "";
  
  //RooRealVar x("mbbReg","mbbReg",XMIN,XMAX);
  int counter(0);
  for(int isel=0;isel<NSEL;isel++) {
    inf[0] = TFile::Open(PATH+"Fit_T_t-channel_sel"+SELECTION[isel]+".root");
    inf[1] = TFile::Open(PATH+"Fit_T_tW-channel_sel"+SELECTION[isel]+".root");
    inf[2] = TFile::Open(PATH+"Fit_T_s-channel_sel"+SELECTION[isel]+".root");
    inf[3] = TFile::Open(PATH+"Fit_Tbar_t-channel_sel"+SELECTION[isel]+".root");
    inf[4] = TFile::Open(PATH+"Fit_Tbar_tW-channel_sel"+SELECTION[isel]+".root");
    inf[5] = TFile::Open(PATH+"Fit_Tbar_s-channel_sel"+SELECTION[isel]+".root");
    inf[6] = TFile::Open(PATH+"Fit_TTJets_sel"+SELECTION[isel]+".root");
    inf[7] = TFile::Open(PATH+"Fit_ZJets_sel"+SELECTION[isel]+".root");
    inf[8] = TFile::Open(PATH+"Fit_WJets_sel"+SELECTION[isel]+".root");
     
    TCanvas *canZ = new TCanvas("canZ_"+SELECTION[isel],"canZ_"+SELECTION[isel],900,600); 
    TCanvas *canT = new TCanvas("canT_"+SELECTION[isel],"canT_"+SELECTION[isel],900,600);  
    canZ->Divide(2,2);
    canT->Divide(2,2);
    TCanvas *can = new TCanvas(); 
    
    sprintf(name,"CMS_vbfbb_scale_mbb_sel%s",SELECTION[isel].Data()); 
    kJES[isel] = new RooRealVar(name,name,1.0);
    sprintf(name,"CMS_vbfbb_res_mbb_sel%s",SELECTION[isel].Data()); 
    kJER[isel] = new RooRealVar(name,name,1.0);
    kJES[isel]->setConstant(kTRUE);
    kJER[isel]->setConstant(kTRUE);
  
    for(int icat=0;icat<NCAT[isel];icat++) {
		if (MERGE && SELECTION[isel]=="VBF" && icat==1) counter = 56;
      /*
      sprintf(name,"CMS_vbfbb_scale_mbb_CAT%d",counter); 
      kJES[counter] = new RooRealVar(name,name,1.0);
      sprintf(name,"CMS_vbbb_res_mbb_CAT%d",counter); 
      kJER[counter] = new RooRealVar(name,name,1.0);
      kJES[counter]->setConstant(kTRUE);
      kJER[counter]->setConstant(kTRUE);
      */ 
      for(int i=0;i<9;i++) {
        hPass = (TH1F*)inf[i]->Get("TriggerPass");
        sprintf(name,"Hbb/events",icat);
        tr = (TTree*)inf[i]->Get(name); 
        sprintf(name,"puWt[0]*%s*(mva%s>%1.2f && mva%s<=%1.2f)",TRIG_WT[isel].Data(),SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
        TCut cut(name); 
        int NBINS(20);
        //if (icat > 1 && icat<=2) NBINS = 20; 
        if (icat > 2) NBINS = 12;
        sprintf(name,"hMbb%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbb[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbb[i]->Sumw2();
        can->cd();        
        tr->Draw(MASS_VAR[isel]+">>"+hMbb[i]->GetName(),cut);
        sprintf(name,"hMbbYield%d_sel%s_CAT%d",i,SELECTION[isel].Data(),icat);
        hMbbYield[i] = new TH1F(name,name,NBINS,XMIN,XMAX);
        hMbbYield[i]->Sumw2();
        tr->Draw(MASS_VAR[isel]+">>"+hMbbYield[i]->GetName(),cut);
        hMbbYield[i]->Scale(LUMI[isel]*XSEC[i]/hPass->GetBinContent(1)); 
      }
      hZ  = (TH1F*)hMbb[7]->Clone("Z");
      hW  = (TH1F*)hMbb[8]->Clone("W");
      hTT = (TH1F*)hMbb[6]->Clone("TT");
      hST = (TH1F*)hMbb[0]->Clone("ST");
      hST->Add(hMbb[1]);
      hST->Add(hMbb[2]);
      hST->Add(hMbb[3]);
      hST->Add(hMbb[4]);
      hST->Add(hMbb[5]);
      hTop = (TH1F*)hTT->Clone("Top");
      hTop->Add(hST);
      //hZ->Add(hW);
      hZYield  = (TH1F*)hMbbYield[7]->Clone("ZYield");
      hWYield  = (TH1F*)hMbbYield[8]->Clone("WYield");
      hTTYield = (TH1F*)hMbbYield[6]->Clone("TTYield");
      hSTYield = (TH1F*)hMbbYield[0]->Clone("STYield");
      hSTYield->Add(hMbbYield[1]);
      hSTYield->Add(hMbbYield[2]);
      hSTYield->Add(hMbbYield[3]);
      hSTYield->Add(hMbbYield[4]);
      hSTYield->Add(hMbbYield[5]);
      hTopYield = (TH1F*)hTTYield->Clone("TopYield");
      hTopYield->Add(hSTYield);
      hZYield->Add(hWYield); 

      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *YieldZ = new RooRealVar(name,name,hZYield->Integral());
      sprintf(name,"yield_WJets_CAT%d",counter);
      RooRealVar *YieldW = new RooRealVar(name,name,hWYield->Integral());
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *YieldT = new RooRealVar(name,name,hTopYield->Integral());
      sprintf(name,"yield_TT_CAT%d",counter);
      RooRealVar *YieldTT = new RooRealVar(name,name,hTTYield->Integral());
      sprintf(name,"yield_ST_CAT%d",counter);
      RooRealVar *YieldST = new RooRealVar(name,name,hSTYield->Integral());

      sprintf(name,"roohist_Z_CAT%d",counter);
      roohist_Z[icat] = new RooDataHist(name,name,x,hZ);

      sprintf(name,"Z_mean_CAT%d",counter);
      RooRealVar mZ(name,name,95,80,110);
      sprintf(name,"Z_sigma_CAT%d",counter);
      RooRealVar sZ(name,name,12,9,20);

      sprintf(name,"Z_mean_shifted_CAT%d",counter);
      RooFormulaVar mZShift(name,"@0*@1",RooArgList(mZ,*(kJES[isel])));
      sprintf(name,"Z_sigma_shifted_CAT%d",counter);
      RooFormulaVar sZShift(name,"@0*@1",RooArgList(sZ,*(kJER[isel])));

      sprintf(name,"Z_a_CAT%d",counter);
      RooRealVar aZ(name,name,-1,-10,10);
      sprintf(name,"Z_n_CAT%d",counter);
      RooRealVar nZ(name,name,1,0,10);

      RooRealVar Zb0("Z_b0_CAT"+TString::Format("%d",counter),"Z_b0_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb1("Z_b1_CAT"+TString::Format("%d",counter),"Z_b1_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooRealVar Zb2("Z_b2_CAT"+TString::Format("%d",counter),"Z_b2_CAT"+TString::Format("%d",counter),0.5,0,1.);
      RooBernstein Zbkg("Z_bkg_CAT"+TString::Format("%d",counter),"Z_bkg_CAT"+TString::Format("%d",counter),x,RooArgSet(Zb0,Zb1,Zb2));
      
      RooRealVar fZsig("fZsig_CAT"+TString::Format("%d",counter),"fZsig_CAT"+TString::Format("%d",counter),0.7,0.,1.);
      RooCBShape Zcore("Zcore_CAT"+TString::Format("%d",counter),"Zcore_CAT"+TString::Format("%d",counter),x,mZShift,sZShift,aZ,nZ);
    
      RooAddPdf modelZ("Z_model_CAT"+TString::Format("%d",counter),"Z_model_CAT"+TString::Format("%d",counter),RooArgList(Zcore,Zbkg),fZsig);
    
      RooFitResult *resZ = modelZ.fitTo(*roohist_Z[icat],RooFit::Save(),RooFit::SumW2Error(kFALSE),"q"); 
  
      canZ->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_Z[icat]->plotOn(frame);
      modelZ.plotOn(frame,RooFit::LineWidth(2));
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      TPaveText *pave = new TPaveText(0.7,0.76,0.9,0.9,"NDC");
		pave->SetTextAlign(11);
      pave->SetFillColor(0);
      pave->SetBorderSize(0);
      pave->SetTextFont(62);
      pave->SetTextSize(0.045);
      pave->AddText(TString::Format("%s selection",SELNAME[isel].Data()));
		pave->AddText(TString::Format("CAT%d",counter));
		TText *lastline = pave->AddText("Z template");
		pave->SetY1NDC(pave->GetY2NDC()-0.055*3);
		TPaveText *paveorig = (TPaveText*)pave->Clone();
      paveorig->Draw();
    
      sprintf(name,"roohist_T_CAT%d",counter);
      if (icat < 3) { 
        roohist_T[icat] = new RooDataHist(name,name,x,hTopYield);
      }
      else {
        roohist_T[icat] = new RooDataHist(name,name,x,hSTYield);
      }

      sprintf(name,"Top_mean_CAT%d",counter);
      RooRealVar mT(name,name,130,0,200);
      sprintf(name,"Top_sigma_CAT%d",counter);
      RooRealVar sT(name,name,50,0,200);

      sprintf(name,"Top_mean_shifted_CAT%d",counter);
      RooFormulaVar mTShift(name,"@0*@1",RooArgList(mT,*(kJES[isel])));
      sprintf(name,"Top_sigma_shifted_CAT%d",counter);
      RooFormulaVar sTShift(name,"@0*@1",RooArgList(sT,*(kJER[isel])));

      sprintf(name,"Top_model_CAT%d",counter);

      RooGaussian *modelT = new RooGaussian(name,name,x,mTShift,sTShift); 
    
      RooFitResult *resT = modelT->fitTo(*roohist_T[icat],Save(),SumW2Error(kTRUE),"q");
      /*
      TF1 *tmp_func = new TF1("tmpFunc","gaus",XMIN,XMAX);
      tmp_func->SetParameters(1,a0.getVal(),a1.getVal());
      if (icat < 3) {
        float norm = tmp_func->Integral(XMIN,XMAX)/hTopYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hTopYield->Integral()/norm);
      }
      else {
        float norm = tmp_func->Integral(XMIN,XMAX)/hSTYield->GetBinWidth(1);
        tmp_func->SetParameter(0,hSTYield->Integral()/norm);
      }  
      */
      canT->cd(icat+1);
      RooPlot* frame = x.frame();
      roohist_T[icat]->plotOn(frame);
      modelT->plotOn(frame,RooFit::LineWidth(2));
      //modelT->plotOn(frame,VisualizeError(*resT,1,kTRUE),FillColor(kGray),MoveToBack());
      frame->GetXaxis()->SetTitle("M_{bb} (GeV)");
      frame->Draw();
      //tmp_func->Draw("sameL");
		lastline->SetTitle("Top template");
		pave->Draw();

      mZ.setConstant(kTRUE);
      sZ.setConstant(kTRUE);
      aZ.setConstant(kTRUE);
      nZ.setConstant(kTRUE);
      Zb0.setConstant(kTRUE);
      Zb1.setConstant(kTRUE);
      Zb2.setConstant(kTRUE);
      fZsig.setConstant(kTRUE);
      
      mT.setConstant(kTRUE);
      sT.setConstant(kTRUE);

      w->import(modelZ);
      w->import(*modelT);
      w->import(*YieldZ);
      w->import(*YieldT);
      w->import(*YieldTT);
      w->import(*YieldST);
      YieldZ->Print();
      YieldW->Print();
      YieldT->Print();
      YieldTT->Print();
      YieldST->Print();
      counter++;
    }// category loop
	 system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots ] && mkdir %s/plots",OUTPATH.Data(),OUTPATH.Data()).Data());
	 system(TString::Format("[ ! -d %s/plots/bkgTemplates ] && mkdir %s/plots/bkgTemplates",OUTPATH.Data(),OUTPATH.Data()).Data());
	 TString FULLPATH(OUTPATH+"/plots/bkgTemplates");
	 canT->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.png",FULLPATH.Data(),canZ->GetName()));
	 canT->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canT->GetName()));
	 canZ->SaveAs(TString::Format("%s/%s.pdf",FULLPATH.Data(),canZ->GetName()));
	 delete can;
  }// selection loop
  system(TString::Format("[ ! -d %s/ ] && mkdir %s/",OUTPATH.Data(),OUTPATH.Data()).Data());
  system(TString::Format("[ ! -d %s/output ] && mkdir %s/output",OUTPATH.Data(),OUTPATH.Data()).Data());
  w->Print();
  w->writeToFile(TString::Format("%s/output/bkg_shapes_workspace%s.root",OUTPATH.Data(),tMERGE.Data()).Data());
}
コード例 #13
0
ファイル: bayesian_mcmc.C プロジェクト: TENorbert/SUSY-TOOLS
int GetBayesianInterval( std::string filename = "workspace.root",
			  std::string wsname = "myWS" ){
  //
  // this function loads a workspace and computes
  // a Bayesian upper limit
  //

  // open file with workspace for reading
  TFile * pInFile = new TFile(filename.c_str(), "read");

  // load workspace
  RooWorkspace * pWs = (RooWorkspace *)pInFile->Get(wsname.c_str());
  if (!pWs){
    std::cout << "workspace " << wsname 
	      << " not found" << std::endl;
    return -1;
  }

  // printout workspace content
  pWs->Print();

  // load and print data from workspace
  RooAbsData * data = pWs->data("data");
  data->Print();
  
  // load and print S+B Model Config
  RooStats::ModelConfig * pSbHypo = (RooStats::ModelConfig *)pWs->obj("SbHypo");
  pSbHypo->Print();

  // create RooStats Bayesian MCMC calculator and set parameters

  // Metropolis-Hastings algorithm needs a proposal function
  RooStats::SequentialProposal sp(10.0);
  
  RooStats::MCMCCalculator mcmc( *data, *pSbHypo );
  mcmc.SetConfidenceLevel(0.95);
  mcmc.SetNumIters(100000);          // Metropolis-Hastings algorithm iterations
  mcmc.SetProposalFunction(sp);
  mcmc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in
  mcmc.SetLeftSideTailFraction(0.0);
  mcmc.SetNumBins(40); // for plotting only - does not affect limit calculation

      
  // estimate credible interval
  // NOTE: unfortunate notation: the UpperLimit() name refers
  //       to the upper boundary of an interval,
  //       NOT to the upper limit on the parameter of interest
  //       (it just happens to be the same for the one-sided
  //       interval starting at 0)
  RooStats::MCMCInterval * pMcmcInt = mcmc.GetInterval();
  double upper_bound = pMcmcInt->UpperLimit( *pWs->var("xsec") );
  double lower_bound = pMcmcInt->LowerLimit( *pWs->var("xsec") );

  std::cout << "one-sided 95%.C.L. bayesian credible interval for xsec: "
	    << "[" << lower_bound << ", " << upper_bound << "]"
	    << std::endl;

  // make posterior PDF plot for POI
  TCanvas c1("posterior");
  RooStats::MCMCIntervalPlot plot(*pMcmcInt);
  plot.Draw();
  c1.SaveAs("bayesian_mcmc_posterior.pdf");

  // make scatter plots to visualise the Markov chain
  TCanvas c2("xsec_vs_alpha_lumi");
  plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_lumi"));
  c2.SaveAs("scatter_mcmc_xsec_vs_alpha_lumi.pdf");

  TCanvas c3("xsec_vs_alpha_efficiency");
  plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_efficiency"));
  c3.SaveAs("scatter_mcmc_xsec_vs_alpha_efficiency.pdf");

  TCanvas c4("xsec_vs_alpha_nbkg");
  plot.DrawChainScatter( *pWs->var("xsec"), *pWs->var("alpha_nbkg"));
  c4.SaveAs("scatter_mcmc_xsec_vs_alpha_nbkg.pdf");

  // clean up a little
  delete pMcmcInt;

  return 0;
}
コード例 #14
0
void generateSigHist_for_combineMaker(Float_t lum =10, Int_t cc1 = 0, Int_t cc2 = 9) {

    const Int_t NCAT(4); // 4 categories in the source file
    TString myCut[NCAT] = {"EBHighR9","EBLowR9","EEHighR9","EELowR9"};
    //Float_t lum =10;
    TString lum_string = TString::Format("%g", lum);
    TFile *file=TFile::Open("workspaces/HighMassGG_m1500_01_mgg_lum_"+lum_string+".root");
    RooWorkspace *w_all = (RooWorkspace*)file->Get("w_all");

    RooRealVar *mgg = (RooRealVar*)w_all->var("mgg");
    RooRealVar *MH = (RooRealVar*)w_all->var("MH");
    RooRealVar *kpl = (RooRealVar*)w_all->var("kpl");

    RooNumConvPdf* numConv[NCAT];
    RooFormulaVar* norm[NCAT];

    // necessary to set a window as it is not saved when RooNumConvPdf is saved
    RooRealVar* W = new RooRealVar("W","W",500);
    W->setConstant();
    RooRealVar* C = new RooRealVar("C","C",0);
    C->setConstant();

    cout << "READ PDFs FROM WORKSPACE : SIGNAL FROM 4 CATEGORIES" << endl;
    cout << "READ ROOFORMULAs FROM WORKSPACE : NORMALIZATION OF 4 CATEGORIES" << endl;
    cout << "SET WINDOW FOR THE 4 CONVOLUTIONS (PDFs)" << endl;
    cout << "..." << endl;
    for(Int_t c = 0; c<NCAT; c++) {

        numConv[c] = (RooNumConvPdf*)w_all->pdf("mggSig_cat"+myCut[c]);
        norm[c] = (RooFormulaVar*)w_all->function("mggSig_cat"+myCut[c]+"_norm");
        numConv[c]->setConvolutionWindow(*C,*W);
    }
    cout << endl;
    cout << "ADD PDFs TO FORM THE TWO CATEGORIES EBEB AND EBEE" << endl;
    RooFormulaVar *mggSig_catEBEB_norm = new RooFormulaVar("mggSig_catEBEB_norm","mggSig_catEBEB_norm","@0+@1",RooArgList(*norm[0],*norm[1]));
    RooFormulaVar *mggSig_catEBEE_norm = new RooFormulaVar("mggSig_catEBEE_norm","mggSig_catEBEE_norm","@0+@1",RooArgList(*norm[2],*norm[3]));

    RooFormulaVar *frac1EBEB = new RooFormulaVar("frac1EBEB","frac1EBEB","@0/@1",RooArgList(*norm[0],*mggSig_catEBEB_norm));
    RooFormulaVar *frac2EBEB = new RooFormulaVar("frac2EBEB","frac2EBEB","@0/@1",RooArgList(*norm[1],*mggSig_catEBEB_norm));
    RooFormulaVar *frac1EBEE = new RooFormulaVar("frac1EBEE","frac1EBE","@0/@1",RooArgList(*norm[2],*mggSig_catEBEE_norm));
    RooFormulaVar *frac2EBEE = new RooFormulaVar("frac2EBEE","frac2EBEE","@0/@1",RooArgList(*norm[3],*mggSig_catEBEE_norm));

    RooAddPdf* mggSig_catEBEB = new RooAddPdf("mggSig_catEBEB","mggSig_catEBEB",RooArgList(*numConv[0],*numConv[1]),RooArgList(*frac1EBEB,*frac2EBEB));
    RooAddPdf* mggSig_catEBEE = new RooAddPdf("mggSig_catEBEE","mggSig_catEBEE",RooArgList(*numConv[2],*numConv[3]),RooArgList(*frac1EBEE,*frac2EBEE));

    cout << endl << endl ;
    cout << "READ CFG FROM BACKGROUND_FINAL TO BE USED IN COMBINE_MAKER.PY" << endl;
    TFile *fcfg = TFile::Open("../../Analysis/macros/workspace_cic2_dijet_lum_10/full_analysis_anv1_v18_bkg_ws_300.root");
    TObjString *cfg = (TObjString*)fcfg->Get("cfg");

    const Int_t nCouplings(9);
    Double_t couplings[nCouplings] = {0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.175, 0.2};

    cout << endl << endl ;
    cout << "SCAN OVER MH AND KAPPA VALUES TO GET DIFFERENT PDFs FOR EACH SET OF PARAMETERS..." << endl;

    for(Int_t icoupling = cc1; icoupling < cc2; icoupling++) {

        //CREATE FOLDER FOR THE COUPLING
        TString coupling_string = TString::Format("%g",couplings[icoupling]);
        coupling_string.ReplaceAll(".","");
        TString inDir("../../Analysis/macros/workspace_cic2_signalDataHist_lum_"+lum_string+"/");
        gSystem->mkdir(inDir);

        for(Int_t mass = 1000; mass < 5100 ; mass+=100) {

            TString mass_string = TString::Format("%d",mass);
            TString signame("grav_"+coupling_string+"_"+mass_string);
            cout << endl;
            cout << "********************************************" << endl;
            cout << "SET MH and KAPPA values" << endl << "kappa: " << couplings[icoupling] << endl << "mass: " << mass << endl;
            cout << "********************************************" << endl;
            MH->setVal(mass);
            kpl->setVal(couplings[icoupling]);

            cout << "CREATE ROODATAHIST WITH NORM..." << endl;
            RooDataHist* dhEBEB = mggSig_catEBEB->generateBinned(RooArgSet(*mgg),mggSig_catEBEB_norm->getVal(), RooFit::ExpectedData());
            RooDataHist* dhEBEE = mggSig_catEBEE->generateBinned(RooArgSet(*mgg),mggSig_catEBEE_norm->getVal(), RooFit::ExpectedData());

            dhEBEB->SetName("signal_"+signame+"_EBEB");
            dhEBEB->SetTitle("signal_"+signame+"_EBEB");
            dhEBEE->SetName("signal_"+signame+"_EBEE");
            dhEBEE->SetTitle("signal_"+signame+"_EBEE");

            //CREATE ROOHISTPDF
            //RooHistPdf *fhEBEB = new RooHistPdf("mggHistPdf_catEBEB","mggHistPdf_catEBEB",RooArgSet(*mgg),*dhEBEB);
            //RooHistPdf *fhEBEE = new RooHistPdf("mggHistPdf_catEBEE","mggHistPdf_catEBEE",RooArgSet(*mgg),*dhEBEE);

            //SAVE ALL IN A WORKSPACE WITH FILE NAME corresponding to MASS AND COUPLING VALUE
            RooWorkspace *wtemplates = new RooWorkspace("wtemplates","wtemplates");

            //wtemplates->import(*fhEBEB);
            //wtemplates->import(*fhEBEE);
            //wtemplates->import(*mggSig_catEBEB_norm,RecycleConflictNodes());
            //wtemplates->import(*mggSig_catEBEE_norm,RecycleConflictNodes());
            wtemplates->import(*dhEBEB);
            wtemplates->import(*dhEBEE);
            //wtemplates->import(*numConv[0],RecycleConflictNodes());

            cout << "******************************************" << endl;
            cout << "WORKSPACE CONTENT FOR COUPLING " << couplings[icoupling] << " AND MASS " << mass << endl;
            wtemplates->Print("V");

            //WRITE IN FILE
            TString filename = inDir+"300_"+signame+".root";
            TFile *fileOutput = TFile::Open(filename,"recreate");
            cfg->Write("cfg");
            wtemplates->Write("wtemplates");
            cout << "workspace imported to " << filename << endl;

        }
    }
}
コード例 #15
0
   void ws_profile_interval1( const char* wsfile = "ws-test1.root", const char* parName = "mu_susy_sig", double alpha = 0.10, double mu_susy_sig_val = 0., double xmax = -1. ) {




       TFile* wstf = new TFile( wsfile ) ;

       RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
       ws->Print() ;






 ////  ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;

 ////  printf("\n\n\n  ===== SbModel ====================\n\n") ;
 ////  modelConfig->Print() ;







       RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;
       printf("\n\n\n  ===== RooDataSet ====================\n\n") ;

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









       printf("\n\n\n  ===== Grabbing %s rrv ====================\n\n", parName ) ;
       RooRealVar* rrv_par = ws->var( parName ) ;
       if ( rrv_par == 0x0 ) {
          printf("\n\n\n *** can't find %s in workspace.  Quitting.\n\n\n", parName ) ; return ;
       } else {
          printf(" current value is : %8.3f\n", rrv_par->getVal() ) ; cout << flush ;
       }
       if ( xmax > 0 ) { rrv_par->setMax( xmax ) ; }

       printf("\n\n\n  ===== Grabbing mu_susy_sig rrv ====================\n\n") ;
       RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_sig") ;
       if ( rrv_mu_susy_sig == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_sig in workspace.  Quitting.\n\n\n") ; return ;
       }
       if ( strcmp( parName, "mu_susy_sig" ) != 0 ) {
          if ( mu_susy_sig_val >= 0. ) {
             printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
             printf(" fixing to %8.2f.\n", mu_susy_sig_val ) ;
             rrv_mu_susy_sig->setVal( mu_susy_sig_val ) ;
             rrv_mu_susy_sig->setConstant(kTRUE) ;
          } else {
             printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
             printf(" allowing mu_susy_sig to float.\n") ;
             rrv_mu_susy_sig->setConstant(kFALSE) ;
          }
       } else {
          printf("\n\n profile plot parameter is mu_susy_sig.\n") ;
          rrv_mu_susy_sig->setConstant(kFALSE) ;
       }

       printf("\n\n\n  ===== Grabbing likelihood pdf ====================\n\n") ;
       RooAbsPdf* likelihood = ws->pdf("likelihood") ;
       if ( likelihood == 0x0 ) {
          printf("\n\n\n *** can't find likelihood pdf in workspace.  Quitting.\n\n\n") ; return ;
       } else {
          printf("\n\n likelihood pdf: \n\n") ;
          likelihood->Print() ;
       }












       printf("\n\n\n  ===== Doing a fit ====================\n\n") ;

       likelihood->fitTo( *rds ) ;

       double mlValue = rrv_par->getVal() ;
       printf("  Maximum likelihood value of %s : %8.3f +/- %8.3f\n",
            parName, rrv_par->getVal(), rrv_par->getError() ) ;






       printf("\n\n ========== Creating ProfileLikelihoodCalculator\n\n" ) ; cout << flush ;

    // ProfileLikelihoodCalculator plc( *rds, *modelConfig ) ;
       ProfileLikelihoodCalculator plc( *rds, *likelihood, RooArgSet( *rrv_par ) ) ;

       plc.SetTestSize( alpha ) ;
       ConfInterval* plinterval = plc.GetInterval() ;
       double low  = ((LikelihoodInterval*) plinterval)->LowerLimit(*rrv_par) ;
       double high = ((LikelihoodInterval*) plinterval)->UpperLimit(*rrv_par) ;

       printf("\n\n  Limits: %8.3f,  %8.3f\n\n", low, high ) ;








       printf("\n\n ========= Making profile likelihood plot\n\n") ; cout << flush ;

       LikelihoodIntervalPlot* profPlot = new LikelihoodIntervalPlot((LikelihoodInterval*)plinterval) ;

       TCanvas* cplplot = new TCanvas("cplplot","cplplot", 500, 400) ;
       profPlot->Draw() ;
       gPad->SetGridy(1) ;
       char plotname[10000] ;
       sprintf( plotname, "plplot-%s.png", parName ) ;
       cplplot->SaveAs( plotname ) ;



       if ( alpha > 0.3 ) {
          printf("\n\n\n 1 standard-deviation errors for %s : %8.2f   + %8.2f  - %8.2f\n\n\n",
              parName, mlValue, high-mlValue, mlValue-low ) ;
       }



   }
コード例 #16
0
void CreateDataTemplates(double dX,int BRN_ORDER)
{
  gROOT->ForceStyle();
  RooMsgService::instance().setSilentMode(kTRUE);
  for(int i=0;i<2;i++) {
    RooMsgService::instance().setStreamStatus(i,kFALSE);
  }
  double XMIN = 80;
  double XMAX = 200;
  const int NSEL(2);
  const int NCAT[NSEL] = {4,3};
  const double MVA_BND[NSEL][NCAT[0]+1] = {{-0.6,0.0,0.7,0.84,1},{-0.1,0.4,0.8,1}};
  char name[1000];
  TString SELECTION[NSEL] = {"NOM","VBF"};
  TString SELTAG[NSEL]    = {"NOM","PRK"};
  TString MASS_VAR[NSEL]  = {"mbbReg[1]","mbbReg[2]"};

  TFile *fBKG  = TFile::Open("limit_BRN5+4_dX0p1_80-200_CAT0-6/output/bkg_shapes_workspace.root");
  RooWorkspace *wBkg = (RooWorkspace*)fBKG->Get("w");
  RooWorkspace *w = new RooWorkspace("w","workspace");
  //RooRealVar x(*(RooRealVar*)wBkg->var("mbbReg"));
  TTree *tr;
  TH1F *h,*hBlind;
  TCanvas *canFit[5]; 
  RooDataHist *roohist[5],*roohist_blind[5];

  TFile *fTransfer = TFile::Open("limit_BRN5+4_dX0p1_80-200_CAT0-6/output/transferFunctions.root");
  TF1 *transFunc;

  int counter(0);
  int NPAR = BRN_ORDER;

  for(int isel=0;isel<NSEL;isel++) {
    TFile *fDATA = TFile::Open("flat/Fit_data_sel"+SELECTION[isel]+".root");
    RooRealVar *brn[8];
    RooArgSet brn_params;
    if (isel == 1) {
      NPAR = 4;
    } 
    for(int ib=0;ib<=NPAR;ib++) {
      brn[ib] = new RooRealVar("b"+TString::Format("%d",ib)+"_sel"+SELECTION[isel],"b"+TString::Format("%d",ib)+"_sel"+SELECTION[isel],0.5,0,10.);
      brn_params.add(*brn[ib]);
    }
    for(int icat=0;icat<NCAT[isel];icat++) {
      RooRealVar x("mbbReg_"+TString::Format("CAT%d",counter),"mbbReg_"+TString::Format("CAT%d",counter),XMIN,XMAX);

      sprintf(name,"fitRatio_sel%s_CAT%d",SELTAG[isel].Data(),counter);
      transFunc = (TF1*)fTransfer->Get(name);
		transFunc->Print();
      // --- The error on the tranfer function parameters is shrinked because the correlations are ingored. 
      // --- Must be consistent with TransferFunctions.C
      float p0 = transFunc->GetParameter(0);
      float e0 = transFunc->GetParError(0);
      float p1 = transFunc->GetParameter(1);
      float e1 = transFunc->GetParError(1);
      float p2 = transFunc->GetParameter(2);
      float e2 = transFunc->GetParError(2);
      RooRealVar trans_p2(TString::Format("trans_p2_CAT%d",counter),TString::Format("trans_p2_CAT%d",counter),p2);
      RooRealVar trans_p1(TString::Format("trans_p1_CAT%d",counter),TString::Format("trans_p1_CAT%d",counter),p1);
      RooRealVar trans_p0(TString::Format("trans_p0_CAT%d",counter),TString::Format("trans_p0_CAT%d",counter),p0);
		printf("%.2f %.2f %.2f\n",p0,p1,p2);
      RooGenericPdf *transfer;
      if (isel == 0) {
        trans_p2.setError(0.5*e2);
        trans_p1.setError(0.5*e1);
        trans_p0.setError(0.5*e0);
        transfer = new RooGenericPdf(TString::Format("transfer_CAT%d",counter),"@2*@0+@1",RooArgList(x,trans_p0,trans_p1)); 
      }
      else {
        trans_p2.setError(0.05*e2);
        trans_p1.setError(0.05*e1);
        trans_p0.setError(0.05*e0);
        transfer = new RooGenericPdf(TString::Format("transfer_CAT%d",counter),"@3*@0*@0+@2*@0+@1",RooArgList(x,trans_p0,trans_p1,trans_p2));
      }
      trans_p2.setConstant(kTRUE);
      trans_p1.setConstant(kTRUE);
      trans_p0.setConstant(kTRUE);

		transfer->Print();
            
      sprintf(name,"FitData_sel%s_CAT%d",SELECTION[isel].Data(),icat);
      canFit[icat] = new TCanvas(name,name,900,600);
      canFit[icat]->cd(1)->SetBottomMargin(0.4);
      sprintf(name,"Hbb/events");
      tr = (TTree*)fDATA->Get(name); 
      sprintf(name,"hMbb_%s_CAT%d",SELECTION[isel].Data(),icat);
      int NBINS = (XMAX[isel][icat]-XMIN[isel][icat])/dX;
      
      h = new TH1F(name,name,NBINS,XMIN[isel][icat],XMAX[isel][icat]);

      sprintf(name,"hMbb_blind_%s_CAT%d",SELECTION[isel].Data(),icat);
      hBlind = new TH1F(name,name,NBINS,XMIN[isel][icat],XMAX[isel][icat]);

      sprintf(name,"mva%s>%1.2f && mva%s<=%1.2f",SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1]);
      TCut cut(name);
      sprintf(name,"mva%s>%1.2f && mva%s<=%1.2f && %s>100 && %s<150",SELECTION[isel].Data(),MVA_BND[isel][icat],SELECTION[isel].Data(),MVA_BND[isel][icat+1],MASS_VAR[isel].Data(),MASS_VAR[isel].Data());
      TCut cutBlind(name);
      tr->Draw(MASS_VAR[isel]+">>"+h->GetName(),cut); 
      tr->Draw(MASS_VAR[isel]+">>"+hBlind->GetName(),cutBlind); 
      sprintf(name,"yield_data_CAT%d",counter);
      RooRealVar *Yield = new RooRealVar(name,name,h->Integral());
      
      sprintf(name,"data_hist_CAT%d",counter);
      roohist[icat] = new RooDataHist(name,name,x,h);

      sprintf(name,"data_hist_blind_CAT%d",counter);
      roohist_blind[icat] = new RooDataHist(name,name,x,hBlind);
        
      RooAbsPdf *qcd_pdf;
      if (icat == 0) {
        for(int ib=0;ib<=NPAR;ib++) {
          brn[ib]->setConstant(kFALSE);
        }
        sprintf(name,"qcd_model_CAT%d",counter);
        RooBernstein *qcd_pdf_aux = new RooBernstein(name,name,x,brn_params);
        qcd_pdf = dynamic_cast<RooAbsPdf*> (qcd_pdf_aux);
      }
      else {
        for(int ib=0;ib<=NPAR;ib++) {
          brn[ib]->setConstant(kTRUE);
        }
        sprintf(name,"qcd_model_aux1_CAT%d",counter);
        RooBernstein *qcd_pdf_aux1 = new RooBernstein(name,name,x,brn_params);
        sprintf(name,"qcd_model_CAT%d",counter);
        RooProdPdf *qcd_pdf_aux2 = new RooProdPdf(name,name,RooArgSet(*transfer,*qcd_pdf_aux1));
        qcd_pdf = dynamic_cast<RooAbsPdf*> (qcd_pdf_aux2);
      } 

      sprintf(name,"Z_model_CAT%d",counter);
      RooAbsPdf *z_pdf = (RooAbsPdf*)wBkg->pdf(name);
      sprintf(name,"Top_model_CAT%d",counter);
      RooAbsPdf *top_pdf = (RooAbsPdf*)wBkg->pdf(name);

      sprintf(name,"yield_ZJets_CAT%d",counter);
      RooRealVar *nZ = (RooRealVar*)wBkg->var(name);
      sprintf(name,"yield_Top_CAT%d",counter);
      RooRealVar *nT = (RooRealVar*)wBkg->var(name);
      sprintf(name,"yield_QCD_CAT%d",counter);
      RooRealVar nQCD(name,name,1000,0,1e+10);
      nZ->setConstant(kTRUE);
      nT->setConstant(kTRUE);
    
      sprintf(name,"bkg_model_CAT%d",counter);
      RooAddPdf model(name,name,RooArgList(*z_pdf,*top_pdf,*qcd_pdf),RooArgList(*nZ,*nT,nQCD));
      
      RooFitResult *res = model.fitTo(*roohist[icat],RooFit::Save());
      res->Print();
      
      RooPlot* frame = x.frame();
      RooPlot* frame1 = x.frame();
      roohist[icat]->plotOn(frame);
      model.plotOn(frame,LineWidth(2));
      cout<<"chi2/ndof = "<<frame->chiSquare()<<endl;
      RooHist *hresid = frame->residHist(); 
      //model.plotOn(frame,RooFit::VisualizeError(*res,1,kFALSE),FillColor(kGray)MoveToBack());
      model.plotOn(frame,Components(*qcd_pdf),LineWidth(2),LineColor(kBlack),LineStyle(kDashed));
      model.plotOn(frame,Components(*z_pdf),LineWidth(2),LineColor(kBlue));
      model.plotOn(frame,Components(*top_pdf),LineWidth(2),LineColor(kGreen+1));
      frame->Draw(); 
      gPad->Update();
      TPad* pad = new TPad("pad", "pad", 0., 0., 1., 1.);
      pad->SetTopMargin(0.6);
      pad->SetFillColor(0);
      pad->SetFillStyle(0);
      pad->Draw();
      pad->cd(0);
      frame1->addPlotable(hresid,"p");
      frame1->Draw();

      for(int ib=0;ib<=NPAR;ib++) {
        brn[ib]->setConstant(kFALSE);
      }
      
      if (icat > 0) {
        trans_p2.setConstant(kFALSE);
        trans_p1.setConstant(kFALSE);
        trans_p0.setConstant(kFALSE);
      }
      if (isel == 0) {
        w->import(trans_p1);
        w->import(trans_p0);
      }
      else {
        w->import(trans_p2);
        w->import(trans_p1);
        w->import(trans_p0);
      }
      w->import(*roohist[icat]);
      w->import(*roohist_blind[icat]);
      w->import(model);
      w->import(*Yield);
      counter++; 
    }// category loop
  }// selection loop
  w->Print();
  w->writeToFile("data_shapes_workspace_"+TString::Format("BRN%d",BRN_ORDER)+".root");
}
コード例 #17
0
ファイル: counting.C プロジェクト: TENorbert/SUSY-TOOLS
void MakeWorkspace( void ){
  //
  // this function implements a RooFit model for a counting experiment
  //

  // create workspace
  RooWorkspace * pWs = new RooWorkspace("myWS");
  
  // observable: number of events
  pWs->factory( "n[0.0]" );

  // integrated luminosity with systematics
  pWs->factory( "lumi_nom[5000.0, 4000.0, 6000.0]" );
  pWs->factory( "lumi_kappa[1.045]" );
  pWs->factory( "cexpr::alpha_lumi('pow(lumi_kappa,beta_lumi)',lumi_kappa,beta_lumi[0,-5,5])" );
  pWs->factory( "prod::lumi(lumi_nom,alpha_lumi)" );
  pWs->factory( "Gaussian::constr_lumi(beta_lumi,glob_lumi[0,-5,5],1)" );

  // cross section - parameter of interest
  pWs->factory( "xsec[0.001,0.0,0.1]" );

  // selection efficiency * acceptance with systematics
  pWs->factory( "efficiency_nom[0.1, 0.05, 0.15]" );
  pWs->factory( "efficiency_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_efficiency('pow(efficiency_kappa,beta_efficiency)',efficiency_kappa,beta_efficiency[0,-5,5])" );
  pWs->factory( "prod::efficiency(efficiency_nom,alpha_efficiency)" );
  pWs->factory( "Gaussian::constr_efficiency(beta_efficiency,glob_efficiency[0,-5,5],1)" );

  // signal yield
  pWs->factory( "prod::nsig(lumi,xsec,efficiency)" );

  // background yield with systematics
  pWs->factory( "nbkg_nom[10.0, 5.0, 15.0]" );
  pWs->factory( "nbkg_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_nbkg('pow(nbkg_kappa,beta_nbkg)',nbkg_kappa,beta_nbkg[0,-5,5])" );
  pWs->factory( "prod::nbkg(nbkg_nom,alpha_lumi,alpha_nbkg)" );
  pWs->factory( "Gaussian::constr_nbkg(beta_nbkg,glob_nbkg[0,-5,5],1)" );

  // full event yield
  pWs->factory("sum::yield(nsig,nbkg)");

  // Core model: Poisson probability with mean signal+bkg
  pWs->factory( "Poisson::model_core(n,yield)" );

  // define Bayesian prior PDF for POI
  pWs->factory( "Uniform::prior(xsec)" );

  // model with systematics
  pWs->factory( "PROD::model(model_core,constr_lumi,constr_efficiency,constr_nbkg)" );

  // create set of observables (will need it for datasets and ModelConfig later)
  RooRealVar * pObs = pWs->var("n"); // get the pointer to the observable
  RooArgSet obs("observables");
  obs.add(*pObs);

  // create the dataset
  pObs->setVal(11); // this is your observed data: we counted ten events
  RooDataSet * data = new RooDataSet("data", "data", obs);
  data->add( *pObs );

  // import dataset into workspace
  pWs->import(*data);

  // create set of global observables (need to be defined as constants)
  pWs->var("glob_lumi")->setConstant(true);
  pWs->var("glob_efficiency")->setConstant(true);
  pWs->var("glob_nbkg")->setConstant(true);
  RooArgSet globalObs("global_obs");
  globalObs.add( *pWs->var("glob_lumi") );
  globalObs.add( *pWs->var("glob_efficiency") );
  globalObs.add( *pWs->var("glob_nbkg") );

  // create set of parameters of interest (POI)
  RooArgSet poi("poi");
  poi.add( *pWs->var("xsec") );
  
  // create set of nuisance parameters
  RooArgSet nuis("nuis");
  nuis.add( *pWs->var("beta_lumi") );
  nuis.add( *pWs->var("beta_efficiency") );
  nuis.add( *pWs->var("beta_nbkg") );

  // create signal+background Model Config
  RooStats::ModelConfig sbHypo("SbHypo");
  sbHypo.SetWorkspace( *pWs );
  sbHypo.SetPdf( *pWs->pdf("model") );
  sbHypo.SetObservables( obs );
  sbHypo.SetGlobalObservables( globalObs );
  sbHypo.SetParametersOfInterest( poi );
  sbHypo.SetNuisanceParameters( nuis );
  sbHypo.SetPriorPdf( *pWs->pdf("prior") ); // this is optional

  // fix all other variables in model:
  // everything except observables, POI, and nuisance parameters
  // must be constant
  pWs->var("lumi_nom")->setConstant(true);
  pWs->var("efficiency_nom")->setConstant(true);
  pWs->var("nbkg_nom")->setConstant(true);
  pWs->var("lumi_kappa")->setConstant(true);
  pWs->var("efficiency_kappa")->setConstant(true);
  pWs->var("nbkg_kappa")->setConstant(true);
  RooArgSet fixed("fixed");
  fixed.add( *pWs->var("lumi_nom") );
  fixed.add( *pWs->var("efficiency_nom") );
  fixed.add( *pWs->var("nbkg_nom") );
  fixed.add( *pWs->var("lumi_kappa") );
  fixed.add( *pWs->var("efficiency_kappa") );
  fixed.add( *pWs->var("nbkg_kappa") );
  
  // set parameter snapshot that corresponds to the best fit to data
  RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data );
  RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
  pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
  pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
  sbHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import S+B ModelConfig into workspace
  pWs->import( sbHypo );

  // create background-only Model Config from the S+B one
  RooStats::ModelConfig bHypo = sbHypo;
  bHypo.SetName("BHypo");
  bHypo.SetWorkspace(*pWs);

  // set parameter snapshot for bHypo, setting xsec=0
  // it is useful to understand how this block of code works
  // but you can also use it as a recipe to make a parameter snapshot
  pNll = bHypo.GetPdf()->createNLL( *data );
  RooArgSet poiAndGlobalObs("poiAndGlobalObs");
  poiAndGlobalObs.add( poi );
  poiAndGlobalObs.add( globalObs );
  pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
  ((RooRealVar *)poi.first())->setVal( 0 );  // set xsec=0 here
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
  pPoiAndNuisance->add( nuis );
  pPoiAndNuisance->add( poi );
  bHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import model config into workspace
  pWs->import( bHypo );

  // print out the workspace contents
  pWs->Print();

  // save workspace to file
  pWs -> SaveAs("workspace.root");

  return;
}
コード例 #18
0
void StandardBayesianNumericalDemo(const char* infile = "",
		      const char* workspaceName = "combined",
		      const char* modelConfigName = "ModelConfig",
		      const char* dataName = "obsData"){

  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  TString filename = infile;
  if (filename.IsNull()) { 
    filename = "results/example_combined_GaussExample_model.root";
    std::cout << "Use standard file generated with HistFactory : " << filename << std::endl;
  }

  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified but not found, quit
  if(!file && !TString(infile).IsNull()){
     cout <<"file " << filename << " 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;
  }

  
  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // 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;
  }

  /////////////////////////////////////////////
  // create and use the BayesianCalculator
  // to find and plot the 95% credible interval
  // on the parameter of interest as specified
  // in the model config
  
  // before we do that, we must specify our prior
  // it belongs in the model config, but it may not have
  // been specified
  RooUniform prior("prior","",*mc->GetParametersOfInterest());
  w->import(prior);
  mc->SetPriorPdf(*w->pdf("prior"));

  // do without systematics
  //mc->SetNuisanceParameters(RooArgSet() );

  
  BayesianCalculator bayesianCalc(*data,*mc);
  bayesianCalc.SetConfidenceLevel(0.95); // 95% interval

  // default of the calculator is central interval.  here use shortest , central or upper limit depending on input
  // doing a shortest interval might require a longer time since it requires a scan of the posterior function
  if (intervalType == 0)  bayesianCalc.SetShortestInterval(); // for shortest interval
  if (intervalType == 1)  bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
  if (intervalType == 2)  bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit

  if (!integrationType.IsNull() ) { 
     bayesianCalc.SetIntegrationType(integrationType); // set integrationType
     bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
  }

  // compute interval by scanning the posterior function
  if (scanPosterior)   
     bayesianCalc.SetScanOfPosterior(nScanPoints);


  SimpleInterval* interval = bayesianCalc.GetInterval();

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


  // make a plot 
  // since plotting may take a long time (it requires evaluating 
  // the posterior in many points) this command will speed up 
  // by reducing the number of points to plot - do 50

  cout << "\nDrawing plot of posterior function....." << endl;

  bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooPlot * plot = bayesianCalc.GetPosteriorPlot();
  plot->Draw();  

}
コード例 #19
0
ファイル: frequentist.C プロジェクト: SusyRa2b/Statistics
//void RunToyScan5(TString fileName, double startVal, double stopVal, TString outFile) {
void frequentist(TString fileName) {
  cout << "Starting frequentist " << time(NULL) << endl;
  double startVal = 0;
  double stopVal = 200;
  TString outFile = "";

  int nToys = 1 ;
  int nscanpoints = 2 ;

  /*
  gROOT->LoadMacro("RooBetaPdf.cxx+") ;
  gROOT->LoadMacro("RooRatio.cxx+") ;
  gROOT->LoadMacro("RooPosDefCorrGauss.cxx+") ;
  */

  // get relevant objects out of the "ws" file

  TFile *file = TFile::Open(fileName);
  if(!file){
    cout <<"file not found" << endl;
    return;
  } 

  RooWorkspace* w = (RooWorkspace*) file->Get("workspace");
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  ModelConfig* mc = (ModelConfig*) w->obj("S+B_model");
  RooAbsData* data = w->data("data");

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

  RooRealVar* myPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  myPOI->setRange(0, 1000.);

  ModelConfig* bModel = (ModelConfig*) w->obj("B_model");
  ModelConfig* sbModel = (ModelConfig*) w->obj("S+B_model");

  ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
  profll.SetPrintLevel(2);
  profll.SetOneSided(1);
  TestStatistic * testStat = &profll;

  HypoTestCalculatorGeneric *  hc = 0;
  hc = new FrequentistCalculator(*data, *bModel, *sbModel);
  
  ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
  toymcs->SetMaxToys(10000);
  toymcs->SetNEventsPerToy(1);
  toymcs->SetTestStatistic(testStat);


  ((FrequentistCalculator *)hc)->SetToys(nToys,nToys);
  
  HypoTestInverter calc(*hc);
  calc.SetConfidenceLevel(0.95);
  calc.UseCLs(true);
  //calc.SetVerbose(true);
  calc.SetVerbose(2);

  cout << "About to set fixed scan " << time(NULL) << endl;
  calc.SetFixedScan(nscanpoints,startVal,stopVal);
  cout << "About to do inverter " << time(NULL) << endl;
  HypoTestInverterResult * res_toysCLs_calculator = calc.GetInterval();

  cout << "CLs = " << res_toysCLs_calculator->UpperLimit() 
	    << "   CLs_exp = " << res_toysCLs_calculator->GetExpectedUpperLimit(0) 
	    << "   CLs_exp(-1s) = " << res_toysCLs_calculator->GetExpectedUpperLimit(-1) 
	    << "   CLs_exp(+1s) = " << res_toysCLs_calculator->GetExpectedUpperLimit(1) << endl ;

  /*
  // dump results string to output file
  ofstream outStream ;
  outStream.open(outFile,ios::app) ;
  
  outStream << "CLs = " << res_toysCLs_calculator->UpperLimit() 
	    << "   CLs_exp = " << res_toysCLs_calculator->GetExpectedUpperLimit(0) 
	    << "   CLs_exp(-1s) = " << res_toysCLs_calculator->GetExpectedUpperLimit(-1) 
	    << "   CLs_exp(+1s) = " << res_toysCLs_calculator->GetExpectedUpperLimit(1) << endl ;
  
  outStream.close() ;
  */


  cout << "End of frequentist " << time(NULL) << endl;
  return ;

}
コード例 #20
0
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;

}
コード例 #21
0
ファイル: ztonunu1.c プロジェクト: SusyRa2b/Statistics
    void ztonunu1() {

    // RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooPoisson"),OutputFile("debug.log")) ;

       float acc_mm_mean( 0.98 ) ; float acc_mm_err(  0.02 ) ;
       float acc_ee_mean( 0.98 ) ; float acc_ee_err(  0.02 ) ;
       float eff_mm_mean( 0.77 ) ; float eff_mm_err(  0.08 ) ;
       float eff_ee_mean( 0.76 ) ; float eff_ee_err(  0.08 ) ;


       RooRealVar* rv_Nsbee  = new RooRealVar( "Nsbee"  ,"Nsbee"  , 0., 100. ) ;
       RooRealVar* rv_Nsbmm  = new RooRealVar( "Nsbmm"  ,"Nsbmm"  , 0., 100. ) ;
       RooRealVar* rv_Nsigee = new RooRealVar( "Nsigee" ,"Nsigee" , 0., 100. ) ;
       RooRealVar* rv_Nsigmm = new RooRealVar( "Nsigmm" ,"Nsigmm" , 0., 100. ) ;

       rv_Nsbee->setVal( 5 ) ;
       rv_Nsbmm->setVal( 3 ) ;

       rv_Nsigee->setVal( 4 ) ;
       rv_Nsigmm->setVal( 3 ) ;


       RooRealVar* rv_mu_Znnsb  = new RooRealVar( "mu_Znnsb"  , "mu_Znnsb"  , 0., 100. ) ;
       RooRealVar* rv_mu_Znnsig = new RooRealVar( "mu_Znnsig" , "mu_Znnsig" , 0., 100. ) ;


       rv_mu_Znnsb->setVal( 37 ) ; // starting value
       rv_mu_Znnsig->setVal( 17. ) ; // starting value

       RooRealVar* rv_bfRatio = new RooRealVar( "bfRatio", "bfRatio", 0., 10. ) ;

       rv_bfRatio->setVal( 5.95 ) ;
       rv_bfRatio->setConstant( kTRUE ) ;

       RooRealVar* rv_acc_mm = new RooRealVar( "acc_mm", "acc_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_acc_ee = new RooRealVar( "acc_ee", "acc_ee", 0.001, 1.000 ) ;

       RooRealVar* rv_eff_mm = new RooRealVar( "eff_mm", "eff_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_eff_ee = new RooRealVar( "eff_ee", "eff_ee", 0.001, 1.000 ) ;

       rv_acc_mm->setVal( acc_mm_mean ) ;
       rv_acc_ee->setVal( acc_ee_mean ) ;
       rv_eff_mm->setVal( eff_mm_mean ) ;
       rv_eff_ee->setVal( eff_ee_mean ) ;

       RooRealVar* rv_lumi_ratio = new RooRealVar( "lumi_ratio", "lumi_ratio", 0., 10. ) ;

       rv_lumi_ratio -> setVal( 686./869. ) ;
       rv_lumi_ratio -> setConstant( kTRUE) ;



       RooFormulaVar* rv_mu_Zeesb = new RooFormulaVar( "mu_Zeesb",
                       "mu_Znnsb * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsb = new RooFormulaVar( "mu_Zmmsb",
                       "mu_Znnsb * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zeesig = new RooFormulaVar( "mu_Zeesig",
                       "mu_Znnsig * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsig = new RooFormulaVar( "mu_Zmmsig",
                       "mu_Znnsig * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;



       RooFormulaVar* rv_n_sbee  = new RooFormulaVar( "n_sbee"  , "mu_Zeesb"  , RooArgSet( *rv_mu_Zeesb  ) ) ;
       RooFormulaVar* rv_n_sbmm  = new RooFormulaVar( "n_sbmm"  , "mu_Zmmsb"  , RooArgSet( *rv_mu_Zmmsb  ) ) ;
       RooFormulaVar* rv_n_sigee = new RooFormulaVar( "n_sigee" , "mu_Zeesig" , RooArgSet( *rv_mu_Zeesig ) ) ;
       RooFormulaVar* rv_n_sigmm = new RooFormulaVar( "n_sigmm" , "mu_Zmmsig" , RooArgSet( *rv_mu_Zmmsig ) ) ;



       RooGaussian* pdf_acc_mm = new RooGaussian( "pdf_acc_mm", "Gaussian pdf for Z to mumu acceptance",
                       *rv_acc_mm, RooConst( acc_mm_mean ), RooConst( acc_mm_err ) ) ;


       RooGaussian* pdf_acc_ee = new RooGaussian( "pdf_acc_ee", "Gaussian pdf for Z to ee acceptance",
                       *rv_acc_ee, RooConst( acc_ee_mean ), RooConst( acc_ee_err ) ) ;




       RooGaussian* pdf_eff_mm = new RooGaussian( "pdf_eff_mm", "Gaussian pdf for Z to mumu efficiency",
                       *rv_eff_mm, RooConst( eff_mm_mean ), RooConst( eff_mm_err ) ) ;



       RooGaussian* pdf_eff_ee = new RooGaussian( "pdf_eff_ee", "Gaussian pdf for Z to ee efficiency",
                       *rv_eff_ee, RooConst( eff_ee_mean ), RooConst( eff_ee_err ) ) ;



       RooPoisson* pdf_Nsbee   = new RooPoisson( "pdf_Nsbee"  , "Nsb , Z to ee Poisson PDF", *rv_Nsbee  , *rv_n_sbee  ) ;
       RooPoisson* pdf_Nsbmm   = new RooPoisson( "pdf_Nsbmm"  , "Nsb , Z to mm Poisson PDF", *rv_Nsbmm  , *rv_n_sbmm  ) ;
       RooPoisson* pdf_Nsigee  = new RooPoisson( "pdf_Nsigee" , "Nsig, Z to ee Poisson PDF", *rv_Nsigee , *rv_n_sigee ) ;
       RooPoisson* pdf_Nsigmm  = new RooPoisson( "pdf_Nsigmm" , "Nsig, Z to mm Poisson PDF", *rv_Nsigmm , *rv_n_sigmm ) ;

       RooArgSet pdflist ;
       pdflist.add( *pdf_acc_mm ) ;
       pdflist.add( *pdf_acc_ee ) ;
       pdflist.add( *pdf_eff_mm ) ;
       pdflist.add( *pdf_eff_ee ) ;
       pdflist.add( *pdf_Nsbee  ) ;
       pdflist.add( *pdf_Nsbmm  ) ;
       pdflist.add( *pdf_Nsigee  ) ;
       pdflist.add( *pdf_Nsigmm  ) ;

       RooProdPdf* znnLikelihood = new RooProdPdf( "znnLikelihood", "Z to nunu likelihood", pdflist ) ;


       RooArgSet observedParametersList ;
       observedParametersList.add( *rv_Nsbee ) ;
       observedParametersList.add( *rv_Nsbmm ) ;
       observedParametersList.add( *rv_Nsigee ) ;
       observedParametersList.add( *rv_Nsigmm ) ;

       RooDataSet* dsObserved = new RooDataSet( "ztonn_rds", "Z to nunu dataset", observedParametersList ) ;
       dsObserved->add( observedParametersList ) ;
       //// RooDataSet* dsObserved = znnLikelihood->generate( observedParametersList, 1) ;

       RooWorkspace* znnWorkspace = new RooWorkspace("ztonn_ws") ;
       znnWorkspace->import( *znnLikelihood ) ;
       znnWorkspace->import( *dsObserved ) ;

       znnWorkspace->Print() ;

       dsObserved->printMultiline(cout, 1, kTRUE, "") ;
       RooFitResult* fitResult = znnLikelihood->fitTo( *dsObserved, Verbose(true), Save(true) ) ;

       printf("\n\n----- Constant parameters:\n") ;
       RooArgList constPars = fitResult->constPars() ;
       for ( int pi=0; pi<constPars.getSize(); pi++ ) {
          constPars[pi].Print() ;
       } // pi.

       printf("\n\n----- Floating parameters:\n") ;
       RooArgList floatPars = fitResult->floatParsFinal() ;
       for ( int pi=0; pi<floatPars.getSize(); pi++ ) {
          floatPars[pi].Print() ;
       } // pi.
       printf("\n\n") ;



       ProfileLikelihoodCalculator plc_znn_sb(  *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsb ) ) ;
       ProfileLikelihoodCalculator plc_znn_sig( *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsig ) ) ;

       plc_znn_sb.SetTestSize(0.32) ;
       plc_znn_sig.SetTestSize(0.32) ;

       ConfInterval* sb_znn_interval = plc_znn_sb.GetInterval() ;
       float sbZnnLow  = ((LikelihoodInterval*) sb_znn_interval)->LowerLimit(*rv_mu_Znnsb) ;
       float sbZnnHigh = ((LikelihoodInterval*) sb_znn_interval)->UpperLimit(*rv_mu_Znnsb) ;
       printf("\n\n znn SB interval %6.1f to %6.1f\n", sbZnnLow, sbZnnHigh ) ;

       ConfInterval* sig_znn_interval = plc_znn_sig.GetInterval() ;
       float sigZnnLow  = ((LikelihoodInterval*) sig_znn_interval)->LowerLimit(*rv_mu_Znnsig) ;
       float sigZnnHigh = ((LikelihoodInterval*) sig_znn_interval)->UpperLimit(*rv_mu_Znnsig) ;
       printf("\n\n znn SIG interval %6.1f to %6.1f\n", sigZnnLow, sigZnnHigh ) ;



       TCanvas* c_prof_sb = new TCanvas("c_prof_sb","SB Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sb((LikelihoodInterval*)sb_znn_interval) ;
       plot_znn_sb.Draw() ;
       c_prof_sb->SaveAs("znn_sb_profile.png") ;

       TCanvas* c_prof_sig = new TCanvas("c_prof_sig","sig Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sig((LikelihoodInterval*)sig_znn_interval) ;
       plot_znn_sig.Draw() ;
       c_prof_sig->SaveAs("znn_sig_profile.png") ;


    }
コード例 #22
0
ファイル: ws_v05.C プロジェクト: gioveneziano/radiative
void ws_v05()
{
    gROOT->ProcessLine(".x ./mystyle.C");

    /*RooMsgService::instance().setSilentMode(true);*/
    /*RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ; //WAS WARNING*/

    // Variables definition

    Double_t xmin = 1000.;
    Double_t xmax = 2000.;
    Int_t nbins = 50;

    cout << "\n\n >>>> Importing shapes  \n\n" << endl;

    TFile *f1 = new TFile("K1_1270/ws_K1_1270.root");
    /*TFile *f2 = new TFile("K1_1400/ws_K1_1400.root");*/
    /*TFile *f3 = new TFile("K2_1430/ws_K2_1430.root");*/

    RooWorkspace* ws_K1_1270 = (RooWorkspace*) f1->Get("ws_K1_1270");
    /*RooWorkspace* ws_K1_1400 = (RooWorkspace*) f2->Get("ws_K1_1400");*/
    /*RooWorkspace* ws_K2_1430 = (RooWorkspace*) f3->Get("ws_K2_1430");*/
    ws_K1_1270->Print();
    /*ws_K1_1400->Print();*/
    /*ws_K2_1430->Print();*/

    // Importing variables from workspaces

    RooRealVar* m_Kpipi = ws_K1_1270 -> var("m_Kpipi");
    RooAbsPdf* totalPdf_K1_1270 = ws_K1_1270 -> pdf("histPdf_K1toKrho");
    RooAbsPdf* totalPdf_K1_1270_Kst0_1430 = ws_K1_1270 -> pdf("histPdf_Kstar1430pi");
    RooAbsPdf* totalPdf_K1_1270_Kst0_892 = ws_K1_1270 -> pdf("histPdf_Kstar892pi");
    /*RooAbsPdf* totalPdf_K1_1270 = ws_K1_1270 -> pdf("totalPdf_K1_1270");*/
    /*RooAbsData* data_K1_1270 = ws_K1_1270 -> data("totalPdf_K1_1270Data");*/
    /*RooHistPdf* pdf_K1_1270_to_Krho = ws_K1_1270 -> pdf("histPdf_K1toKrho");*/

///////
    /*TFile *MC = new TFile("radiativeVPG_MC11s20_B2K11270Gamma_magdown.root");*/
    /*TTree* t_tree = (TTree*)MC->Get("k1GammaMCStrip/DecayTree");*/
    /*TH1F* hist = new TH1F("hist","hist",nbins,xmin,xmax);*/
    /*Float_t mass = 0.;*/
    /*t_tree->SetBranchAddress("B_BMassFit_K_1_1270_plus_M",&mass);*/
    /*Int_t n2 = 0;*/
    /*for (int i=0;i<t_tree->GetEntries();i++)*/
    /*{*/
    /*t_tree->GetEntry(i);*/

    /*hist->Fill(mass);*/
    /*n2++;*/
    /*}*/
    /*RooDataHist datahist("datahist","datahist",*m_Kpipi,hist);*/
    /*RooHistPdf totalPdf_K1_1270("totalPdf_K1_1270","",*m_Kpipi,datahist,2);*/

//////
    /*RooRealVar* m_Kpipi = ws_K1_1400 -> var("m_Kpipi");*/
    /*RooAbsPdf* totalPdf_K1_1400 = ws_K1_1400 -> pdf("totalPdf_K1_1400");*/
    /*RooAbsData* data_K1_1400 = ws_K1_1400 -> data("totalPdf_K1_1400Data");*/
    /*RooHistPdf* pdf_K1_1400_to_Krho = ws_K1_1400 -> pdf("histPdf_K1_1400toKrho");*/

    /*RooRealVar* m_Kpipi = ws_K2_1430 -> var("m_Kpipi");*/
    /*RooAbsPdf* totalPdf_K2_1430 = ws_K2_1430 -> pdf("totalPdf_K2_1430");*/
    /*RooAbsData* data_K2_1430 = ws_K2_1430 -> data("totalPdf_K2_1430Data");*/
    /*RooHistPdf* pdf_K2_1430_to_Krho = ws_K2_1430 -> pdf("histPdf_K2_1430toKrho");*/

    // Plotting pdf

    /*TCanvas* c1 = new TCanvas("c1","canvas",20,20,1200,600);*/
    /*c1->Divide(3,1);*/
    /*c1->cd(1);*/
    /*RooPlot* frame_K1_1270 = m_Kpipi -> frame(Bins(200),Title("K1(1270) -> K#pi#pi"));*/
    /*data_K1_1270->plotOn(frame_K1_1270,DrawOption("C"));*/
    /*frame_K1_1270->Draw();*/
    /*c1->cd(2);*/
    /*RooPlot* frame_K1_1400 = m_Kpipi -> frame(Bins(200),Title("K1(1400) -> K#pi#pi"));*/
    /*data_K1_1400->plotOn(frame_K1_1400,DrawOption("C"));*/
    /*frame_K1_1400->Draw();*/
    /*c1->cd(3);*/
    /*RooPlot* frame_K2_1430= m_Kpipi -> frame(Bins(200),Title("K2*(1430) -> K#pi#pi"));*/
    /*data_K2_1430->plotOn(frame_K2_1430,DrawOption("C"));*/
    /*frame_K2_1430->Draw();*/

////////////////////////////////////////////////////////////////////////

    cout << "\n\n >>>> Importing sPlot  \n\n" << endl;

    TFile *Fworkspace = new TFile("workspace.root");

    RooWorkspace* wsp = (RooWorkspace*) Fworkspace->Get("wsp");
    wsp->Print();

    RooRealVar* B_postcalib_M = wsp -> var("B_postcalib_M");
    RooRealVar* nsig_sw = wsp-> var("nsig_sw");
    RooRealVar* nbkg_sw = wsp-> var("nbkg_sw");
    RooRealVar* B_M13_Subst3_gamma2pi0 = wsp-> var("B_M13_Subst3_gamma2pi0");
    RooRealVar* B_M023 = wsp -> var("B_M023");
    RooRealVar* K_1_1270_plus_M = wsp -> var("K_1_1270_plus_M");
    RooRealVar* K_1_1270_plus_SMALLESTDELTACHI2 = wsp -> var("K_1_1270_plus_SMALLESTDELTACHI2");
    RooRealVar* gamma_CL = wsp -> var("gamma_CL");
    RooRealVar* piminus_PIDK = wsp -> var("piminus_PIDK");
    RooRealVar* piplus_PIDK = wsp -> var("piplus_PIDK");
    RooRealVar* Kplus_PIDp = wsp -> var("Kplus_PIDp");
    RooRealVar* Kplus_PIDK = wsp -> var("Kplus_PIDK");
    RooRealVar* B_M02 = wsp -> var("B_M02");
    RooRealVar* L_nsig = wsp -> var("L_nsig");
    RooRealVar* L_nbkg = wsp -> var("L_nbkg");

    RooArgSet arg(*B_postcalib_M,*gamma_CL,*B_M13_Subst3_gamma2pi0,*B_M023,*piminus_PIDK,*piplus_PIDK,*Kplus_PIDK,*Kplus_PIDp);
    arg.add(*K_1_1270_plus_M);
    arg.add(*K_1_1270_plus_SMALLESTDELTACHI2);
    arg.add(*B_M02);
    arg.add(*nsig_sw);
    arg.add(*L_nsig);
    arg.add(*nbkg_sw);
    arg.add(*L_nbkg);

    arg.add(*m_Kpipi);


    RooDataSet* DataSWeights = (RooDataSet*) wsp -> data("DataSWeights");
    RooFormulaVar newMass("m_Kpipi", "m_Kpipi", "K_1_1270_plus_M", RooArgList(*(wsp->var("K_1_1270_plus_M"))));
    DataSWeights->addColumn(newMass);
    RooDataSet* splot = new RooDataSet(DataSWeights->GetName(),DataSWeights->GetTitle(),DataSWeights,RooArgSet(arg),"","nsig_sw");


    cout << "\n\n >>>> Defining components and fitting  \n\n" << endl;

    // Defining here pdfs for other resonances to be fitted

    // K1(1270)

    Double_t R = 0.0015; //  was 3.1 GeV-1
    RooRealVar mean_K1_1270("mean_K1_1270","",1272.,1262.,1282.);
    RooRealVar width_K1_1270("width_K1_1270","",90.,70.,110.);

    // K1(1270) -> K rho
    /*RooBreitWigner totalPdf_K1_1270("totalPdf_K1_1270","",*m_Kpipi,mean_K1_1270,width_K1_1270);*/
    /*RooRelBreitWigner totalPdf_K1_1270("totalPdf_K1_1270","totalPdf_K1_1270_rho",*m_Kpipi,mean_K1_1270,width_K1_1270,RooConst(0),RooConst(R),RooConst(770.),RooConst(493.7));*/

    // K1(1270) -> K*0(1430) pi
    /*RooBreitWigner totalPdf_K1_1270_Kst0_1430("totalPdf_K1_1270_Kst0_1430","totalPdf_K1_1270_Kst0_1430",*m_Kpipi,mean_K1_1270,width_K1_1270);*/
    /*RooRelBreitWigner totalPdf_K1_1270_Kst0_1430("totalPdf_K1_1270_Kst0_1430","totalPdf_K1_1270_Kst0_1430",*m_Kpipi,mean_K1_1270,width_K1_1270,RooConst(0),RooConst(R),RooConst(1425.),RooConst(139.6));*/

    // K1(1270) -> K*0(892) pi
    /*RooBreitWigner totalPdf_K1_1270_Kst0_892("totalPdf_K1_1270_Kst0_892","totalPdf_K1_1270_Kst0_892",*m_Kpipi,mean_K1_1270,width_K1_1270);*/
    /*RooRelBreitWigner totalPdf_K1_1270_Kst0_892("totalPdf_K1_1270_Kst0_892","totalPdf_K1_1270_Kst0_892",*m_Kpipi,mean_K1_1270,width_K1_1270,RooConst(0),RooConst(R),RooConst(895.5),RooConst(139.6));*/

    // K1(1400)

    RooRealVar mean_K1_1400("mean_K1_1400","",1403./*,1396.,1410.*/);
    RooRealVar width_K1_1400("width_K1_1400","",174./*,151.,197.*/);
    RooBreitWigner totalPdf_K1_1400("totalPdf_K1_1400","",*m_Kpipi,mean_K1_1400,width_K1_1400);
    /*[>RooRelBreitWigner totalPdf_K1_1400("totalPdf_K1_1400","totalPdf_K1_1400",*m_Kpipi,mean_K1_1400,width_K1_1400,RooConst(0),RooConst(R),RooConst(895.),RooConst(139.6)); //K*(892) pi is 93%<]*/

    // K2*(1430)

    RooRealVar mean_K2_1430("mean_K2_1430","",1432./*,1424.,1435.*/);
    RooRealVar width_K2_1430("width_K2_1430","",109./*,96.,114.*/);
    RooBreitWigner totalPdf_K2_1430("totalPdf_K2_1430","",*m_Kpipi,mean_K2_1430,width_K2_1430);

    // K3*(1780)

    RooRealVar mean_K3st_1780("mean_K3st_1780","mean_K3st_1780",1776./*,1765.,1785.*/);
    RooRealVar width_K3st_1780("width_K3st_1780","width_K3st_1780",159.7/*,150.,170.*/);
    RooBreitWigner K3st_1780("K3st_1780","K3st_1780",*m_Kpipi,mean_K3st_1780,width_K3st_1780);

    // K2(1770)

    RooRealVar mean_K2_1770("mean_K2_1770","mean_K2_1770",1773./*,1763.,1783.*/);
    RooRealVar width_K2_1770("width_K2_1770","width_K2_1770",186./*,176.,196.*/);
    RooBreitWigner K2_1770("K2_1770","K2_1770",*m_Kpipi,mean_K2_1770,width_K2_1770);

    // K2(1580)

    RooRealVar mean_K2_1580("mean_K2_1580","mean_K2_1580",1580.);
    RooRealVar width_K2_1580("width_K2_1580","width_K2_1580",110.);
    RooBreitWigner K2_1580("K2_1580","K2_1580",*m_Kpipi,mean_K2_1580,width_K2_1580);

    // K2*(1980)

    RooRealVar mean_K2st_1980("mean_K2st_1980","mean_K2st_1980",1973./*,1957.,1999.*/);
    RooRealVar width_K2st_1980("width_K2st_1980","width_K2st_1980",373./*,303.,443.*/);
    RooBreitWigner K2st_1980("K2st_1980","K2st_1980",*m_Kpipi,mean_K2st_1980,width_K2st_1980);

    // K*(1680)

    RooRealVar mean_Kst_1680("mean_Kst_1680","mean_K*_1680",1717./*,1690.,1744.*/);
    RooRealVar width_Kst_1680("width_Kst_1680","width_K*_1680",322./*,212.,432.*/);
    RooBreitWigner Kst_1680("Kst_1680","K*_1680",*m_Kpipi,mean_Kst_1680,width_Kst_1680);
    /*width_Kst_1680.setVal(322.);*/
    /*width_Kst_1680.setConstant(kTRUE);*/

    // K*(1410) mass 1414 +- 15 MeV , width 232 +- 21 MeV

    RooRealVar mean_Kst_1410("mean_Kst_1410","",1414./*,1399.,1429.*/);
    RooRealVar width_Kst_1410("width_Kst_1410","",232./*,253.,211.*/);
    RooBreitWigner Kst_1410("Kst_1410","",*m_Kpipi,mean_Kst_1410,width_Kst_1410);

    // Non resonant Kpipi

    RooRealVar c0("c0","c0",1.);
    RooRealVar c1("c1","c1",1.);
    RooRealVar c2("c2","c2",100.,200.);
    RooRealVar c3("c3","c3",-.1,+2.);
    RooRealVar c4("c4","c4",-2.,0.);
    RooGenericPdf non_resonant("non_resonant","non_resonant","(@0 + @1*@5)*exp(@2 + @3*@5 + @4*@5*@5)",RooArgList(c0,c1,c2,c3,c4,*m_Kpipi));
    /*RooRealVar par0("par0","par0",-2.,-100.,100.);*/
    /*RooRealVar par1("par1","par1",-2.,-100.,100.);*/
    /*RooRealVar par2("par2","par2",1.,-100.,100.);*/
    /*RooRealVar par3("par3","par3",1.,-100.,100.);*/
    /*RooChebychev non_resonant("non_resonant","non_resonant",*m_Kpipi,RooArgList(par0,par1,par2,par3));*/

    // defining the yields as the BR wrt K1(1270)

    RooRealVar K1_1270_Kst0_1430_br("K1_1270_Kst0_1430_br","K1_1270_Kst0_1430_br",0.41,0.,1.);
    RooRealVar K1_1270_Kst0_892_br("K1_1270_Kst0_892_br","K1_1270_Kst0_892_br",0.074,0.,1.);
    RooRealVar K1_1400_br("K1_1400_br","K1_1400_br",0.1226,0.,1.); // upper limit only
    /*RooRealVar K2_1430_br("K2_1430_br","K2_1430_br",0.07,0.,1.);*/
    /*RooRealVar K1_1400_br("K1_1400_br","K1_1400_br",0.1226,0.,0.13); // upper limit only*/
    RooRealVar K2_1430_br("K2_1430_br","K2_1430_br",0.07,0.05,0.09); // from Belle
    RooRealVar K3st_1780_br("K3st_1780_br","K3st_1780_br",0.1,0.,1.);
    RooRealVar K2_1770_br("K2_1770_br","K2_1770_br",0.1,0.,1.);
    RooRealVar K2_1580_br("K2_1580_br","K2_1580_br",0.1,0.,1.);
    RooRealVar K2st_1980_br("K2st_1980_br","K2st_1980_br",0.1,0.,1.);
    RooRealVar Kst_1680_br("Kst_1680_br","K*_1680_br",0.1,0.,1.);
    RooRealVar Kst_1410_br("Kst_1410_br","K*_1410_br",0.1,0.,.3);
    RooRealVar non_resonant_br("non_resonant_br","non_resonant_br",0.3,0.,2.);

    RooRealVar K1_1270_y("K1_1270_y","K1_1270_y",1000.,0.,10000.); // this is the yield of the K1(1270) TO rho
    RooFormulaVar K1_1270_Kst0_1430_y("K1_1270_Kst0_1430_y","K1_1270_Kst0_1430_y","@0*@1",RooArgList(K1_1270_Kst0_1430_br,K1_1270_y));
    RooFormulaVar K1_1270_Kst0_892_y("K1_1270_Kst0_892_y","K1_1270_Kst0_892_y","@0*@1",RooArgList(K1_1270_Kst0_892_br,K1_1270_y));
    RooFormulaVar K1_1400_y("K1_1400_y","K1_1400_y","@0*@1",RooArgList(K1_1400_br,K1_1270_y));
    RooFormulaVar K2_1430_y("K2_1430_y","K2_1430_y","@0*@1",RooArgList(K2_1430_br,K1_1270_y));
    RooFormulaVar K3st_1780_y("K3st_1780_y","K3st_1780_y","@0*@1",RooArgList(K3st_1780_br,K1_1270_y));
    RooFormulaVar K2_1770_y("K2_1770_y","K2_1770_y","@0*@1",RooArgList(K2_1770_br,K1_1270_y));
    RooFormulaVar K2_1580_y("K2_1580_y","K2_1580_y","@0*@1",RooArgList(K2_1580_br,K1_1270_y));
    RooFormulaVar K2st_1980_y("K2st_1980_y","K2st_1980_y","@0*@1",RooArgList(K2st_1980_br,K1_1270_y));
    RooFormulaVar Kst_1680_y("Kst_1680_y","Kst_1680_y","@0*@1",RooArgList(Kst_1680_br,K1_1270_y));
    RooFormulaVar Kst_1410_y("Kst_1410_y","Kst_1410_y","@0*@1",RooArgList(Kst_1410_br,K1_1270_y));
    RooFormulaVar non_resonant_y("non_resonant_y","non_resonant_y","@0*@1",RooArgList(non_resonant_br,K1_1270_y));

    // here add pdfs and FIT sum of pdf to splot
    //
    RooArgList shapes;
    RooArgList yields;
    shapes.add(*totalPdf_K1_1270);
    shapes.add(*totalPdf_K1_1270_Kst0_1430);
    shapes.add(*totalPdf_K1_1270_Kst0_892);
    shapes.add(totalPdf_K1_1400);
    shapes.add(totalPdf_K2_1430);
    shapes.add(K3st_1780);
    /*shapes.add(K2_1770);*/
    shapes.add(K2_1580);
    shapes.add(K2st_1980);
    shapes.add(Kst_1680);
    /*shapes.add(Kst_1410);*/
    /*shapes.add(non_resonant);*/

    yields.add(K1_1270_y);
    yields.add(K1_1270_Kst0_1430_y);
    yields.add(K1_1270_Kst0_892_y);
    yields.add(K1_1400_y);
    yields.add(K2_1430_y);
    yields.add(K3st_1780_y);
    /*yields.add(K2_1770_y);*/
    yields.add(K2_1580_y);
    yields.add(K2st_1980_y);
    yields.add(Kst_1680_y);
    /*yields.add(Kst_1410_y);*/
    /*yields.add(non_resonant_y);*/

    // Putting all pdfs together

    RooAddPdf PDF("PDF","total Pdf for the resonances considered", shapes,yields);

    /*PDF->fitTo(*splot,Extended(),SumW2Error(kFALSE),Range(1000,2000));*/
    PDF.fitTo(*splot,Extended(),SumW2Error(kTRUE),Range(xmin,xmax));

    // Defining frames for plotting

    cout << "\n\n >>>> Plotting  \n\n" << endl;

    RooPlot* frame_splot = m_Kpipi->frame(Title("sPlot of m_{K#pi#pi} [MeV/c^{2}]"),Range(xmin,xmax),Bins(nbins));
    splot->plotOn(frame_splot,Name("fitted_splot")/*,DataError(RooAbsData::SumW2)*/);

    PDF.paramOn(frame_splot,Layout(.65,.9,.99)); // Layout(xmin,ymin,ymax)
    PDF.plotOn(frame_splot,Components(*totalPdf_K1_1270),LineColor(kRed));
    PDF.plotOn(frame_splot,Components(*totalPdf_K1_1270_Kst0_1430),LineColor(kRed),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(*totalPdf_K1_1270_Kst0_892),LineColor(kRed));
    PDF.plotOn(frame_splot,Components(totalPdf_K1_1400),LineColor(1));
    PDF.plotOn(frame_splot,Components(totalPdf_K2_1430),LineColor(51),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(K3st_1780),LineColor(kOrange),LineStyle(kDashed));
    /*PDF.plotOn(frame_splot,Components(K2_1770),LineColor(5),LineStyle(kDashed));*/
    PDF.plotOn(frame_splot,Components(K2_1580),LineColor(12),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(K2st_1980),LineColor(16),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(Kst_1680),LineColor(32),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(Kst_1410),LineColor(3),LineStyle(kDashed));
    PDF.plotOn(frame_splot,Components(non_resonant),LineColor(5),LineStyle(kDashed));
    PDF.plotOn(frame_splot);

    // Plotting with residuals

    TCanvas* canvas_sPlot = new TCanvas("canvas_sPlot","sPlot with weights",40,20,1200,800);
    plot_with_residuals(*canvas_sPlot,*frame_splot,*m_Kpipi,nbins,xmin,xmax); // residuals(TCanvas& _canvas,RooPlot& _frame,RooRealVar& var,Int_t& _nbins,Double_t& r_min,Double_t& r_max)

    // CleanUp worspaces

    delete ws_K1_1270;
    /*delete ws_K1_1400;*/
    /*delete ws_K2_1430;*/
    delete wsp;

    cout << "\n\n >>>> THE END  \n\n" << endl;

    /*cout << gMinuit->GetStatus() << endl;*/

}
コード例 #23
0
ファイル: tnpTools5.C プロジェクト: bianchini/usercode
vector<Double_t*> simFit(bool makeSoupFit_ = false,
			 const string tnp_ = "etoTauMargLooseNoCracks70", 
			 const string category_ = "tauAntiEMVA",
			 const string bin_ = "abseta<1.5",
			 const float binCenter_ = 0.75,
			 const float binWidth_ = 0.75,
			 const float xLow_=60, 
			 const float xHigh_=120,
			 bool SumW2_ = false,
			 bool verbose_ = true){

  vector<Double_t*> out;
  //return out;

  //TFile *test = new TFile( outFile->GetName(),"UPDATE");
  // output file
  TFile *test = new TFile( Form("EtoTauPlotsFit_%s_%s_%f.root",tnp_.c_str(),category_.c_str(),binCenter_),"RECREATE");
  test->mkdir(Form("bin%f",binCenter_));

  TCanvas *c = new TCanvas("fitCanvas",Form("fitCanvas_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600);
  c->SetGrid(0,0);
  c->SetFillStyle(4000);
  c->SetFillColor(10);
  c->SetTicky();
  c->SetObjectStat(0);
  
  TCanvas *c2 = new TCanvas("fitCanvasTemplate",Form("fitCanvasTemplate_%s_%s",tnp_.c_str(),bin_.c_str()),10,30,650,600);
  c2->SetGrid(0,0);
  c2->SetFillStyle(4000);
  c2->SetFillColor(10);
  c2->SetTicky();
  c2->SetObjectStat(0);

  // input files
  TFile fsup("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup.root");
  TFile fbkg("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_bkg.root");
  TFile fsgn("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_soup_sgn.root");
  TFile fdat("/data_CMS/cms/lbianchini/tagAndProbe/trees/38XWcut/testNewWriteFromPAT_Data.root");
  // data from 2iter:
  //TFile fdat("/data_CMS/cms/lbianchini/35pb/testNewWriteFromPAT_Data.root");
  
  //********************** signal only tree *************************/

  TTree *fullTreeSgn = (TTree*)fsgn.Get((tnp_+"/fitter_tree").c_str());
  TH1F* hSall        = new TH1F("hSall","",1,0,150);
  TH1F* hSPall       = new TH1F("hSPall","",1,0,150);
  TH1F* hS           = new TH1F("hS","",1,0,150);
  TH1F* hSP          = new TH1F("hSP","",1,0,150);
  fullTreeSgn->Draw("mass>>hS",Form("weight*(%s && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5)",bin_.c_str(),xLow_,xHigh_));
  fullTreeSgn->Draw("mass>>hSall",Form("weight*(%s && mass>%f && mass<%f)",bin_.c_str(),xLow_,xHigh_));

  float SGNtrue = hS->Integral();
  float SGNall  = hSall->Integral();
 
  fullTreeSgn->Draw("mass>>hSP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && mcTrue && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));
  fullTreeSgn->Draw("mass>>hSPall",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));

  float SGNtruePass = hSP->Integral();
  float SGNallPass  = hSPall->Integral();

  //********************** background only tree *************************//

  TTree *fullTreeBkg = (TTree*)fbkg.Get((tnp_+"/fitter_tree").c_str());
  TH1F* hB = new TH1F("hB","",1,0,150);
  TH1F* hBP = new TH1F("hBP","",1,0,150);
  fullTreeBkg->Draw("mass>>hB",Form("weight*(%s && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),xLow_,xHigh_));
 
  float BKG           = hB->Integral();
  float BKGUnWeighted = hB->GetEntries();
  
  fullTreeBkg->Draw("mass>>hBP",Form("weight*(%s && %s>0 && mass>%f && mass<%f && signalPFChargedHadrCands<1.5 )",bin_.c_str(),category_.c_str(),xLow_,xHigh_));
  
  float BKGPass           = hBP->Integral();
  float BKGUnWeightedPass = hBP->GetEntries();
  float BKGFail           = BKG-BKGPass;
  cout << "*********** BKGFail " << BKGFail << endl;

  //********************** soup tree *************************//

  TTree *fullTreeSoup = (TTree*)fsup.Get((tnp_+"/fitter_tree").c_str());

  //********************** data tree *************************//

  TTree *fullTreeData = (TTree*)fdat.Get((tnp_+"/fitter_tree").c_str());

  //********************** workspace ***********************//

  RooWorkspace *w = new RooWorkspace("w","w");
  // tree variables to be imported
  w->factory("mass[30,120]");
  w->factory("weight[0,10000]");
  w->factory("abseta[0,2.5]");
  w->factory("pt[0,200]");
  w->factory("mcTrue[0,1]");
  w->factory("signalPFChargedHadrCands[0,10]");
  w->factory((category_+"[0,1]").c_str());
  // background pass pdf for MC
  w->factory("RooExponential::McBackgroundPdfP(mass,McCP[0,-10,10])");
  // background fail pdf for MC
  w->factory("RooExponential::McBackgroundPdfF(mass,McCF[0,-10,10])");
  // background pass pdf for Data
  w->factory("RooExponential::DataBackgroundPdfP(mass,DataCP[0,-10,10])");
  // background fail pdf for Data
  w->factory("RooExponential::DataBackgroundPdfF(mass,DataCF[0,-10,10])");
  // fit parameters for background
  w->factory("McEfficiency[0.04,0,1]");
  w->factory("McNumSgn[0,1000000]");
  w->factory("McNumBkgP[0,100000]");
  w->factory("McNumBkgF[0,100000]"); 
  w->factory("expr::McNumSgnP('McEfficiency*McNumSgn',McEfficiency,McNumSgn)");
  w->factory("expr::McNumSgnF('(1-McEfficiency)*McNumSgn',McEfficiency,McNumSgn)");
  w->factory("McPassing[pass=1,fail=0]");
  // fit parameters for data
  w->factory("DataEfficiency[0.1,0,1]");
  w->factory("DataNumSgn[0,1000000]");
  w->factory("DataNumBkgP[0,1000000]");
  w->factory("DataNumBkgF[0,10000]");
  w->factory("expr::DataNumSgnP('DataEfficiency*DataNumSgn',DataEfficiency,DataNumSgn)");
  w->factory("expr::DataNumSgnF('(1-DataEfficiency)*DataNumSgn',DataEfficiency,DataNumSgn)");
  w->factory("DataPassing[pass=1,fail=0]");

  RooRealVar  *weight = w->var("weight");
  RooRealVar  *abseta = w->var("abseta");
  RooRealVar  *pt     = w->var("pt");
  RooRealVar  *mass   = w->var("mass");
  mass->setRange(xLow_,xHigh_);
  RooRealVar  *mcTrue = w->var("mcTrue");
  RooRealVar  *cut    = w->var( category_.c_str() );
  RooRealVar  *signalPFChargedHadrCands = w->var("signalPFChargedHadrCands");
 
  // build the template for the signal pass sample:
  RooDataSet templateP("templateP","dataset for signal-pass template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) );
  // build the template for the signal fail sample:
  RooDataSet templateF("templateF","dataset for signal-fail template", RooArgSet(*mass,*weight,*abseta,*pt,*cut,*mcTrue,*signalPFChargedHadrCands), Import( *fullTreeSgn ), /*WeightVar( *weight ),*/ Cut( Form("(mcTrue && %s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()) ) );
  

  mass->setBins(24);
  RooDataHist templateHistP("templateHistP","",RooArgSet(*mass), templateP, 1.0);
  RooHistPdf TemplateSignalPdfP("TemplateSignalPdfP","",RooArgSet(*mass),templateHistP);
  w->import(TemplateSignalPdfP);

  mass->setBins(24);
  RooDataHist templateHistF("templateHistF","",RooArgSet(*mass),templateF,1.0);
  RooHistPdf TemplateSignalPdfF("TemplateSignalPdfF","",RooArgSet(*mass),templateHistF);
  w->import(TemplateSignalPdfF);

  mass->setBins(10000,"fft");

  RooPlot* TemplateFrameP = mass->frame(Bins(24),Title("Template passing"));
  templateP.plotOn(TemplateFrameP);
  w->pdf("TemplateSignalPdfP")->plotOn(TemplateFrameP);
  
  RooPlot* TemplateFrameF = mass->frame(Bins(24),Title("Template failing"));
  templateF.plotOn(TemplateFrameF);
  w->pdf("TemplateSignalPdfF")->plotOn(TemplateFrameF);

  //w->factory("RooFFTConvPdf::McSignalPdfP(mass,TemplateSignalPdfP,RooTruthModel::McResolModP(mass))");
  //w->factory("RooFFTConvPdf::McSignalPdfF(mass,TemplateSignalPdfF,RooTruthModel::McResolModF(mass))");

  // FOR GREGORY: PROBLEM WHEN TRY TO USE THE PURE TEMPLATE =>
  RooHistPdf McSignalPdfP("McSignalPdfP","McSignalPdfP",RooArgSet(*mass),templateHistP);
  RooHistPdf McSignalPdfF("McSignalPdfF","McSignalPdfF",RooArgSet(*mass),templateHistF);
  w->import(McSignalPdfP);
  w->import(McSignalPdfF);
  // FOR GREGORY: FOR DATA, CONVOLUTION IS OK =>
  w->factory("RooFFTConvPdf::DataSignalPdfP(mass,TemplateSignalPdfP,RooGaussian::DataResolModP(mass,DataMeanResP[0.0,-5.,5.],DataSigmaResP[0.5,0.,10]))");
  w->factory("RooFFTConvPdf::DataSignalPdfF(mass,TemplateSignalPdfF,RooGaussian::DataResolModF(mass,DataMeanResF[-5.,-10.,10.],DataSigmaResF[0.5,0.,10]))");
  //w->factory("RooCBShape::DataSignalPdfF(mass,DataMeanF[91.2,88,95.],DataSigmaF[3,0.5,8],DataAlfaF[1.8,0.,10],DataNF[1.0,1e-06,10])");
  //w->factory("RooFFTConvPdf::DataSignalPdfF(mass,RooVoigtian::DataVoigF(mass,DataMeanF[85,80,95],DataWidthF[2.49],DataSigmaF[3,0.5,10]),RooCBShape::DataResolModF(mass,DataMeanResF[0.5,0.,10.],DataSigmaResF[0.5,0.,10],DataAlphaResF[0.5,0.,10],DataNResF[1.0,1e-06,10]))");
  //w->factory("SUM::DataSignalPdfF(fVBP[0.5,0,1]*RooBifurGauss::bifF(mass,DataMeanResF[91.2,80,95],sigmaLF[10,0.5,40],sigmaRF[0.]), RooVoigtian::voigF(mass, DataMeanResF, widthF[2.49], sigmaVoigF[5,0.1,10]) )" );
  
  // composite model pass for MC
  w->factory("SUM::McModelP(McNumSgnP*McSignalPdfP,McNumBkgP*McBackgroundPdfP)");  
  w->factory("SUM::McModelF(McNumSgnF*McSignalPdfF,McNumBkgF*McBackgroundPdfF)");
  // composite model pass for data
  w->factory("SUM::DataModelP(DataNumSgnP*DataSignalPdfP,DataNumBkgP*DataBackgroundPdfP)");  
  w->factory("SUM::DataModelF(DataNumSgnF*DataSignalPdfF,DataNumBkgF*DataBackgroundPdfF)");  
  // simultaneous fir for MC
  w->factory("SIMUL::McModel(McPassing,pass=McModelP,fail=McModelF)");
  // simultaneous fir for data
  w->factory("SIMUL::DataModel(DataPassing,pass=DataModelP,fail=DataModelF)");
  w->Print("V");
  w->saveSnapshot("clean", w->allVars());

  w->loadSnapshot("clean");

  /****************** sim fit to soup **************************/

  ///////////////////////////////////////////////////////////////
  TFile *f = new TFile("dummySoup.root","RECREATE");
  TTree* cutTreeSoupP = fullTreeSoup->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
  TTree* cutTreeSoupF = fullTreeSoup->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
 
  RooDataSet McDataP("McDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeSoupP ) );
 
  RooDataSet McDataF("McDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeSoupF ) );
 
  RooDataHist McCombData("McCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("McPassing"))), Import("pass", *(McDataP.createHistogram("histoP",*mass)) ), Import("fail",*(McDataF.createHistogram("histoF",*mass)) ) ) ;

  RooPlot* McFrameP    = 0;
  RooPlot* McFrameF    = 0;
  RooRealVar* McEffFit = 0;

  if(makeSoupFit_){

    cout << "**************** N bins in mass " << w->var("mass")->getBins() << endl;

    RooFitResult* ResMcCombinedFit = w->pdf("McModel")->fitTo(McCombData, Extended(1), Minos(1), Save(1),  SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4) /*, ExternalConstraints( *(w->pdf("ConstrainMcNumBkgF")) )*/ );
    test->cd(Form("bin%f",binCenter_));
    ResMcCombinedFit->Write("McFitResults_Combined");

    RooArgSet McFitParam(ResMcCombinedFit->floatParsFinal());
    McEffFit     = (RooRealVar*)(&McFitParam["McEfficiency"]);
    RooRealVar* McNumSigFit  = (RooRealVar*)(&McFitParam["McNumSgn"]);
    RooRealVar* McNumBkgPFit = (RooRealVar*)(&McFitParam["McNumBkgP"]);
    RooRealVar* McNumBkgFFit = (RooRealVar*)(&McFitParam["McNumBkgF"]);

    McFrameP = mass->frame(Bins(24),Title("MC: passing sample"));
    McCombData.plotOn(McFrameP,Cut("McPassing==McPassing::pass"));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameP,Slice(*(w->cat("McPassing")),"pass"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfP"), LineColor(kGreen),Range(xLow_,xHigh_));
    
    McFrameF = mass->frame(Bins(24),Title("MC: failing sample"));
    McCombData.plotOn(McFrameF,Cut("McPassing==McPassing::fail"));
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), LineColor(kBlue),Range(xLow_,xHigh_));
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_)); 
    w->pdf("McModel")->plotOn(McFrameF,Slice(*(w->cat("McPassing")),"fail"), ProjWData(*(w->cat("McPassing")),McCombData), Components("McBackgroundPdfF"), LineColor(kGreen),Range(xLow_,xHigh_)); 
  }
  
  ///////////////////////////////////////////////////////////////

  /****************** sim fit to data **************************/

  ///////////////////////////////////////////////////////////////
  TFile *f2 = new TFile("dummyData.root","RECREATE");
  TTree* cutTreeDataP = fullTreeData->CopyTree(Form("(%s>0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
  TTree* cutTreeDataF = fullTreeData->CopyTree(Form("(%s<0.5 && %s && signalPFChargedHadrCands<1.5)",category_.c_str(),bin_.c_str()));
 
  RooDataSet DataDataP("DataDataP","dataset pass for the soup", RooArgSet(*mass), Import( *cutTreeDataP ) );
  RooDataSet DataDataF("DataDataF","dataset fail for the soup", RooArgSet(*mass), Import( *cutTreeDataF ) );
  RooDataHist DataCombData("DataCombData","combined data for the soup", RooArgSet(*mass), Index(*(w->cat("DataPassing"))), Import("pass",*(DataDataP.createHistogram("histoDataP",*mass))),Import("fail",*(DataDataF.createHistogram("histoDataF",*mass)))) ;

  RooFitResult* ResDataCombinedFit = w->pdf("DataModel")->fitTo(DataCombData, Extended(1), Minos(1), Save(1),  SumW2Error( SumW2_ ), Range(xLow_,xHigh_), NumCPU(4));
  test->cd(Form("bin%f",binCenter_));
  ResDataCombinedFit->Write("DataFitResults_Combined");

  RooArgSet DataFitParam(ResDataCombinedFit->floatParsFinal());
  RooRealVar* DataEffFit     = (RooRealVar*)(&DataFitParam["DataEfficiency"]);
  RooRealVar* DataNumSigFit  = (RooRealVar*)(&DataFitParam["DataNumSgn"]);
  RooRealVar* DataNumBkgPFit = (RooRealVar*)(&DataFitParam["DataNumBkgP"]);
  RooRealVar* DataNumBkgFFit = (RooRealVar*)(&DataFitParam["DataNumBkgF"]);

  RooPlot* DataFrameP = mass->frame(Bins(24),Title("Data: passing sample"));
  DataCombData.plotOn(DataFrameP,Cut("DataPassing==DataPassing::pass"));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfP"), LineColor(kRed),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameP,Slice(*(w->cat("DataPassing")),"pass"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfP"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_));
  
  RooPlot* DataFrameF = mass->frame(Bins(24),Title("Data: failing sample"));
  DataCombData.plotOn(DataFrameF,Cut("DataPassing==DataPassing::fail"));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), LineColor(kBlue),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataSignalPdfF"), LineColor(kRed),Range(xLow_,xHigh_));
  w->pdf("DataModel")->plotOn(DataFrameF,Slice(*(w->cat("DataPassing")),"fail"), ProjWData(*(w->cat("DataPassing")),DataCombData), Components("DataBackgroundPdfF"), LineColor(kGreen),LineStyle(kDashed),Range(xLow_,xHigh_));
  ///////////////////////////////////////////////////////////////

 
  if(makeSoupFit_) c->Divide(2,2);
  else c->Divide(2,1);
 
  c->cd(1);
  DataFrameP->Draw();
  c->cd(2);
  DataFrameF->Draw();

  if(makeSoupFit_){
    c->cd(3);
    McFrameP->Draw();
    c->cd(4);
    McFrameF->Draw();
  }
 
  c->Draw();
 
  test->cd(Form("bin%f",binCenter_));
 
  c->Write();
 
  c2->Divide(2,1);
  c2->cd(1);
  TemplateFrameP->Draw();
  c2->cd(2);
  TemplateFrameF->Draw();
  c2->Draw();
 
  test->cd(Form("bin%f",binCenter_));
  c2->Write();


  // MINOS errors, otherwise HESSE quadratic errors
  float McErrorLo = 0;
  float McErrorHi = 0;
  if(makeSoupFit_){
    McErrorLo = McEffFit->getErrorLo()<0 ? McEffFit->getErrorLo() : (-1)*McEffFit->getError();
    McErrorHi = McEffFit->getErrorHi()>0 ? McEffFit->getErrorHi() : McEffFit->getError();
  }
  float DataErrorLo = DataEffFit->getErrorLo()<0 ? DataEffFit->getErrorLo() : (-1)*DataEffFit->getError();
  float DataErrorHi = DataEffFit->getErrorHi()>0 ? DataEffFit->getErrorHi() : DataEffFit->getError();
  float BinomialError = TMath::Sqrt(SGNtruePass/SGNtrue*(1-SGNtruePass/SGNtrue)/SGNtrue);
 
  Double_t* truthMC = new Double_t[6];
  Double_t* tnpMC   = new Double_t[6];
  Double_t* tnpData = new Double_t[6];

  truthMC[0] = binCenter_;
  truthMC[1] = binWidth_;
  truthMC[2] = binWidth_;
  truthMC[3] = SGNtruePass/SGNtrue;
  truthMC[4] = BinomialError;
  truthMC[5] = BinomialError;
  if(makeSoupFit_){
    tnpMC[0] = binCenter_;
    tnpMC[1] = binWidth_;
    tnpMC[2] = binWidth_;
    tnpMC[3] = McEffFit->getVal();
    tnpMC[4] = (-1)*McErrorLo;
    tnpMC[5] = McErrorHi;
  }
  tnpData[0] = binCenter_;
  tnpData[1] = binWidth_;
  tnpData[2] = binWidth_;
  tnpData[3] = DataEffFit->getVal();
  tnpData[4] = (-1)*DataErrorLo;
  tnpData[5] = DataErrorHi;

  out.push_back(truthMC);
  out.push_back(tnpData);
  if(makeSoupFit_) out.push_back(tnpMC);

  test->Close();

  //delete c; delete c2;

  if(verbose_) cout << "returning from bin " << bin_ << endl;
  return out;

}
コード例 #24
0
void StandardFeldmanCousinsDemo(const char* infile = "",
                                const char* workspaceName = "combined",
                                const char* modelConfigName = "ModelConfig",
                                const char* dataName = "obsData"){

   // -------------------------------------------------------
   // 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;
   }


   // -------------------------------------------------------
   // Tutorial starts here
   // -------------------------------------------------------

   // 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;
   }

   // -------------------------------------------------------
   // 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
   FeldmanCousins fc(*data,*mc);
   fc.SetConfidenceLevel(0.95); // 95% interval
   //fc.AdditionalNToysFactor(0.1); // to speed up the result
   fc.UseAdaptiveSampling(true); // speed it up a bit
   fc.SetNBins(10); // set how many points per parameter of interest to scan
   fc.CreateConfBelt(true); // save the information in the belt for plotting

   // 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, 1, "workers=4", kFALSE);
   //  ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   //  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
   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
      interval->LowerLimit(*firstPOI) << ", "<<
      interval->UpperLimit(*firstPOI) <<"] "<<endl;

   // ---------------------------------------------
   // No nice plots yet, so plot the belt by hand

   // 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());

   // 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 arMin = belt->GetAcceptanceRegionMax(*tmpPoint);
      double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
      histOfThresholds->Fill(poiVal,arMax);
   }
   histOfThresholds->SetMinimum(0);
   histOfThresholds->Draw();

}
コード例 #25
0
void StandardProfileInspectorDemo(const char* infile = "",
		      const char* workspaceName = "combined",
		      const char* modelConfigName = "ModelConfig",
		      const char* dataName = "obsData"){

  /////////////////////////////////////////////////////////////
  // 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;
  }

  
  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // 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 use the profile inspector
  ProfileInspector p;
  TList* list = p.GetListOfProfilePlots(*data,mc);
  
  // now make plots
  TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo"); //,800,200);
  c1->Divide(4,4);

  //  const RooArgSet* nuis_params = mc->GetNuisanceParameters();
  
  for(int i=0; i<list->GetSize(); ++i){
    c1->cd(i+1);
    //RooRealVar* nuis = (RooRealVar*) nuis_params->At(i);
    TGraph* graph = (TGraph*) list->At(i);

    std::string y_title = graph->GetYaxis()->GetTitle();
    y_title = "Profiled value of: " + y_title;
    graph->GetYaxis()->SetTitle(y_title.c_str());
    graph->GetYaxis()->SetTitleSize(0.05);
    graph->GetYaxis()->SetTitleOffset(0.8);
    //std::string poi_name = graph->GetXaxis()->GetTitle();
    //graph->GetYaxis()->SetTitle(var->GetName());
    graph->GetXaxis()->SetTitleSize(0.05);
    graph->GetXaxis()->SetTitleOffset(0.8);
    graph->Draw("al");

    //list->At(i)->Draw("al");
  }

  c1->Print("ProfileInspector.eps");
  c1->Print("ProfileInspector.pdf");
  cout << endl;
}
コード例 #26
0
ファイル: RA4abcd.C プロジェクト: wa01/usercode
//
// scan over parameter space
//
void RA4Mult (const RA4WorkingPoint& muChannel,
	      const RA4WorkingPoint& eleChannel,
	      StatMethod method) {

  //
  // Prepare workspace
  //   no syst. parameters: efficiency / sig.cont. / kappa
  //
  bool noEffSyst(false);
  bool noSContSyst(false);
  bool noKappaSyst(false);
  RA4WorkSpace ra4WSpace("wspace",noEffSyst,noSContSyst,noKappaSyst);


  TFile* fYield[2];
  TFile* fKFactor[2];
  //
  // Muon channel
  //
  unsigned int nf(0);
  RA4WorkSpace::ChannelType channelTypes[2];
  const RA4WorkingPoint* workingPoints[2];
  addChannel(muChannel,RA4WorkSpace::MuChannel,ra4WSpace,fYield,fKFactor,
	     nf,channelTypes,workingPoints);
  addChannel(eleChannel,RA4WorkSpace::EleChannel,ra4WSpace,fYield,fKFactor,
	     nf,channelTypes,workingPoints);
  if ( nf==0 ) {
    std::cout << "No input file" << std::endl;
    return;
  }
  //
  // finish definition of model
  //
  ra4WSpace.finalize();
  RooWorkspace* wspace = ra4WSpace.workspace();
//   wspace->Print("v");
//   RooArgSet allVars = wspace->allVars();
//   // allVars.printLatex(std::cout,1);
//   TIterator* it = allVars.createIterator();
//   RooRealVar* var;
//   while ( var=(RooRealVar*)it->Next() ) {
//     var->Print("v");
//     var->printValue(std::cout);
//   }
  //
  // preparation of histograms with yields and k-factors
  //
  const char* cRegion = { "ABCD" };
  TH2* hYields[4][2];
  TH2* hYields05[4][2];
  TH2* hYields20[4][2];
  TH2* hYEntries[4][2];
  TH2* hYESmooth[4][2];
  for ( unsigned int j=0; j<nf; ++j ) {
    for ( unsigned int i=0; i<4; ++i ) {
      hYields[i][j] = 0;
      hYields05[i][j] = 0;
      hYields20[i][j] = 0;
      hYEntries[i][j] = 0;
      hYESmooth[i][j] = 0;
    }
  }
  TH2* hKF05[2];
  TH2* hKF10[2];
  TH2* hKF20[2];
  for ( unsigned int j=0; j<nf; ++j ) {
    hKF05[j] = 0;
    hKF10[j] = 0;
    hKF20[j] = 0;
  }
  //
  // Retrieval of histograms with k-factors
  //
  for ( unsigned int j=0; j<nf; ++j ) {
    hKF05[j] = (TH2*)fKFactor[j]->Get("hKF05D");
    hKF10[j] = (TH2*)fKFactor[j]->Get("hKF10D");
    hKF20[j] = (TH2*)fKFactor[j]->Get("hKF20D");
    if ( hKF05[j]==0 || hKF10==0 || hKF20==0 ) {
      std::cout << "Missing histogram for kfactor for channel " << j << std::endl;
      return;
    }
  }
  //
  // Retrieval of histograms with yields
  //
  std::string hName;
  for ( unsigned int j=0; j<nf; ++j ) {
    for ( unsigned int i=0; i<4; ++i ) {
      hName = "Events";
      hName += cRegion[i];

      hYields[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      hYields05[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      hYields20[i][j] = (TH2*)fYield[j]->Get(hName.c_str())->Clone();
      if ( hYields[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      hYields[i][j]->Multiply(hYields[i][j],hKF10[j]);
      hYields05[i][j]->Multiply(hYields05[i][j],hKF05[j]);
      hYields20[i][j]->Multiply(hYields20[i][j],hKF20[j]);

      hName = "Entries";
      hName += cRegion[i];
      hYEntries[i][j] = (TH2*)fYield[j]->Get(hName.c_str());
      if ( hYEntries[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      hName = "SmoothEntries";
      hName += cRegion[i];
      hYESmooth[i][j] = (TH2*)fYield[j]->Get(hName.c_str());
      if ( hYESmooth[i][j]==0 ) {
	std::cout << "Missing histogram for region " << cRegion[i] << std::endl;
	return;
      }
      // convert to efficiency (assume 10000 MC events/bin)
      hYEntries[i][j]->Scale(1/10000.);
      hYESmooth[i][j]->Scale(1/10000.);
      // convert yield to cross section
      hYields[i][j]->Divide(hYields[i][j],hYEntries[i][j]);
      hYields05[i][j]->Divide(hYields05[i][j],hYEntries[i][j]);
      hYields20[i][j]->Divide(hYields20[i][j],hYEntries[i][j]);
    }
  }
  //
  // histograms with exclusion and limits
  //
  gROOT->cd();
  TH2* hExclusion = (TH2*)hYields[0][0]->Clone("Exclusion");
  hExclusion->Reset();
  hExclusion->SetTitle("Exclusion");
  TH2* hLowerLimit = (TH2*)hYields[0][0]->Clone("LowerLimit");
  hLowerLimit->Reset();
  hLowerLimit->SetTitle("LowerLimit");
  TH2* hUpperLimit = (TH2*)hYields[0][0]->Clone("UpperLimit");
  hUpperLimit->Reset();
  hUpperLimit->SetTitle("UpperLimit");

  double yields[4][2];
  double yields05[4][2];
  double yields20[4][2];
  double entries[4][2];

//   double bkgs[4][2];

//   double kappa = (bkgs[0]*bkgs[3])/(bkgs[1]*bkgs[2]);
//   double sigma_kappa_base = 0.10;
//   double delta_kappa_abs = kappa - 1.;
//   double sigma_kappa = sqrt(sigma_kappa_base*sigma_kappa_base+delta_kappa_abs*delta_kappa_abs);
//   sigma_kappa = sqrt(0.129*0.129+0.1*0.1);

#ifndef DEBUG
  int nbx = hYields[0][0]->GetNbinsX();
  int nby = hYields[0][0]->GetNbinsY();
  for ( int ix=1; ix<=nbx; ++ix ) {
    for ( int iy=1; iy<=nby; ++iy ) {
#else
   { 
     int ix=40;
     {
       int iy=11;
#endif

      bool process(false);
      for ( unsigned int j=0; j<nf; ++j ) {
	ra4WSpace.setBackground(channelTypes[j],
				workingPoints[j]->bkg_[0],workingPoints[j]->bkg_[1],
				workingPoints[j]->bkg_[2],workingPoints[j]->bkg_[3]);
	ra4WSpace.setObserved(channelTypes[j],
			      workingPoints[j]->obs_[0],workingPoints[j]->obs_[1],
			      workingPoints[j]->obs_[2],workingPoints[j]->obs_[3]);
	for ( unsigned int i=0; i<4; ++i ) {
	  yields[i][j] = hYields[i][j]->GetBinContent(ix,iy);
	  yields05[i][j] = hYields05[i][j]->GetBinContent(ix,iy);
	  yields20[i][j] = hYields20[i][j]->GetBinContent(ix,iy);
	  entries[i][j] = hYESmooth[i][j]->GetBinContent(ix,iy);
	}
	if ( yields[3][j]>0.01 && yields[3][j]<10000 && entries[3][j]>0.0001 )  process = true;
	ra4WSpace.setSignal(channelTypes[j],
			    yields[0][j],yields[1][j],
			    yields[2][j],yields[3][j],
			    entries[0][j],entries[1][j],
			    entries[2][j],entries[3][j]);
#ifdef DEBUG
	std::cout << "yields for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << yields[i][j];
	std::cout << endl;
	std::cout << "effs for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << entries[i][j];
	std::cout << endl;
	std::cout << "backgrounds for channel " << j << " =";
	for ( unsigned int i=0; i<4; ++i )
	  std::cout << " " << workingPoints[j]->bkg_[i];
	std::cout << endl;
#endif
      }

      MyLimit limit(true,0.,999999999.);
      double sumD(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
	sumD += (yields[3][j]*entries[3][j]);
      }
      if ( !process || sumD<0.01 ) {
	hExclusion->SetBinContent(ix,iy,limit.isInInterval);
	hLowerLimit->SetBinContent(ix,iy,limit.lowerLimit);
	hUpperLimit->SetBinContent(ix,iy,limit.upperLimit);
#ifndef DEBUG
	continue;
#endif
      }

      double sigK(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
 	if ( workingPoints[j]->sigKappa_>sigK )
	  sigK = workingPoints[j]->sigKappa_;
// 	  sigK += workingPoints[j]->sigKappa_;
      }
//       sigK /= nf;
      double sigEffBase(0.15);
      double sigEffLept(0.05);
      double sigEffNLO(0.);
      for ( unsigned int j=0; j<nf; ++j ) {
	double sige = max(fabs(yields05[3][j]-yields[3][j]),
			  fabs(yields20[3][j]-yields[3][j]));
	sige /= yields[3][j];
	if ( sige>sigEffNLO )  sigEffNLO = sige;
      }
      double sigEff = sqrt(sigEffBase*sigEffBase+sigEffLept*sigEffLept+sigEffNLO*sigEffNLO);
      std::cout << "Systematics are " << sigK << " " << sigEff << std::endl;
      sigEff = 0.20;
      if ( !noKappaSyst ) 
	wspace->var("sigmaKappa")->setVal(sigK);
      if ( !noSContSyst )
	wspace->var("sigmaScont")->setVal(sigEff);
      if ( !noEffSyst )
	wspace->var("sigmaEff")->setVal(sigEff);
      
//       wspace->var("sigmaKappa")->setVal(sqrt(0.129*0.129+0.1*0.1)*0.967);
      // for the time being: work with yields
//       if ( muChannel.valid_ ) {
// 	wspace->var("effM")->setVal(1.);
//  	wspace->var("sadM")->setVal(0.);
//  	wspace->var("sbdM")->setVal(0.);
//  	wspace->var("scdM")->setVal(0.);
//       }
//       if ( eleChannel.valid_ ) {
// 	wspace->var("effE")->setVal(1.);
//  	wspace->var("sadE")->setVal(0.);
//  	wspace->var("sbdE")->setVal(0.);
//  	wspace->var("scdE")->setVal(0.);
//       }
#ifdef DEBUG
      wspace->Print("v");
      RooArgSet allVars = wspace->allVars();
      // allVars.printLatex(std::cout,1);
      TIterator* it = allVars.createIterator();
      RooRealVar* var;
      while ( var=(RooRealVar*)it->Next() ) {
	var->Print("v");
	var->printValue(std::cout);
	std::cout << std::endl;
      }
#endif
      std::cout << "Checked ( " << hExclusion->GetXaxis()->GetBinCenter(ix) << " , "
		<< hExclusion->GetYaxis()->GetBinCenter(iy) << " ) with signal " 
		<< yields[3][nf-1] << std::endl;
	

      RooDataSet data("data","data",*wspace->set("obs"));
      data.add(*wspace->set("obs"));
      data.Print("v");
      
      limit = computeLimit(wspace,&data,method);
      std::cout << "  Limit [ " << limit.lowerLimit << " , "
		<< limit.upperLimit << " ] ; isIn = " << limit.isInInterval << std::endl;
      

      double excl = limit.isInInterval;
      if ( limit.upperLimit<limit.lowerLimit )  excl = -1;
      hExclusion->SetBinContent(ix,iy,excl);
      hLowerLimit->SetBinContent(ix,iy,limit.lowerLimit);
      hUpperLimit->SetBinContent(ix,iy,limit.upperLimit);
//       return;
      
    }
  }
  
  TFile* out = new TFile("RA4abcd.root","RECREATE");
  hExclusion->SetDirectory(out);
  hExclusion->SetMinimum(); hExclusion->SetMaximum();
  hExclusion->SetContour(1); hExclusion->SetContourLevel(0,0.5);
  hLowerLimit->SetDirectory(out);
  hLowerLimit->SetMinimum(); hLowerLimit->SetMaximum();
  hUpperLimit->SetDirectory(out);
  hUpperLimit->SetMinimum(); hUpperLimit->SetMaximum();
  for ( unsigned int j=0; j<nf; ++j ) {
    hYields[3][j]->SetDirectory(out);
    hYields[3][j]->SetMinimum(); hYields[3][j]->SetMaximum();
  }
  out->Write();
  delete out;
}
コード例 #27
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 ----------------------------------------
コード例 #28
0
void fastEfficiencyNadir(unsigned int iEG, int iECAL1, int iColl1, int iECAL2, int iColl2,
			 TString dirIn="/home/llr/cms/ndaci/SKWork/macro/skEfficiency/tagAndProbe/EfficiencyStudy/SingEle-May10ReReco/UPDATE2/Tag80Probe95/", 
			 TString lumi="200 pb", int nCPU=4, 
			 int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
			 TString probe="WP80", TString tag="WP80", TString fileIn="tree_effi_TagProbe.root")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // EG THRESHOLDS //
  const int nEG = 71;
  double thres[nEG];
  for(int i=0 ; i<nEG ; i++) thres[i]=i;

  TString names[nEG];
  ostringstream ossi;
  for(int i=0;i<(int)nEG;i++) {
    ossi.str("");
    ossi << thres[i] ;
    names[i] = ossi.str();
  }

  // NAMES //
  const int nECAL=2;
  const int nColl=2;

  TString name_leg_ecal[nECAL] = {"Barrel","Endcaps"};
  TString name_leg_coll[nColl] = {"Online","Emulation"};  

  TString name_ecal[nECAL] = {"_EB","_EE"};
  TString name_coll[nColl] = {"_N","_M"};

  TString dirResults = dirIn + "/turnons/EG"+names[iEG]+"/" ;
  TString name_image = 
    dirResults + "eff_EG"+names[iEG]+"_tag"+tag+"_probe"+probe+name_ecal[iECAL1]+name_coll[iColl1]+"_vs"+name_ecal[iECAL2]+name_coll[iColl2] ;

  // Output log //
  ofstream fichier(name_image+".txt", ios::out);


  // BINNING //
  const int nbins[nEG] = {29,29,29,29,21,21,21,22,22,21,22,21,22,18,19,18,18,18,18,20,20,20,20,19,20,20,20,20,21,21,
			  21,21,21,21,21,21,21,21,21,21, //EG30
			  22,22,22,22,22,22,22,22,22,22, //EG40
			  29,29,29,29,29,29,29,29,29,29, //EG50
			  29,29,29,29,29,29,29,29,29,29};//EG60

  Double_t bins_0[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG0
  Double_t bins_1[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG1
  Double_t bins_2[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG2 
  Double_t bins_3[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG3

  Double_t bins_4[21] = {1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 27, 32, 41, 50, 60, 70, 150}; // EG4
  Double_t bins_5[21] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 31, 40, 50, 60, 70, 150}; // EG5
  Double_t bins_6[21] = {3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 21, 23, 27, 32, 41, 50, 60, 70, 150}; // EG6

  Double_t bins_7[22] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG7
  Double_t bins_8[22] = {3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 32, 41, 50, 60, 70, 150}; // EG8
  Double_t bins_9[21] = {4, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG9

  Double_t bins_10[22] = {5, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG10
  Double_t bins_11[21] = {6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 26, 28, 31, 40, 50, 60, 70, 150}; // EG11
  Double_t bins_12[22] = {5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG12

  Double_t bins_13[18] = {5, 7, 9, 11, 12, 13, 14, 15, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG13
  Double_t bins_14[19] = {6, 8, 10, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG14
  Double_t bins_15[18] = {5, 7, 9, 11, 13, 14, 15, 16, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG15

  Double_t bins_16[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG16
  Double_t bins_17[18] = {9, 11, 13, 15, 16, 17, 18, 19, 21, 23, 25, 30, 35, 40, 50, 60, 70, 150}; // EG17
  Double_t bins_18[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG18

  Double_t bins_19[20] = {9, 11, 13, 15, 17, 18, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG19
  Double_t bins_20[20] = {8, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 30, 35, 40, 45, 50, 60, 70, 100}; // EG20
  Double_t bins_21[20] = {9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG21

  Double_t bins_22[20] = {10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG22
  Double_t bins_23[19] = {11, 13, 15, 17, 19, 21, 22, 23, 24, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG23
  Double_t bins_24[20] = {10, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG24

  Double_t bins_25[20] = {11, 13, 15, 17, 19, 21, 23, 24, 25, 26, 27, 29, 30, 35, 40, 45, 50, 60, 70, 150}; // EG25
  Double_t bins_26[20] = {10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG26
  Double_t bins_27[20] = {11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 33, 35, 40, 45, 50, 60, 70, 150}; // EG27

  Double_t bins_28[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 29, 30, 32, 35, 40, 45, 50, 60, 70, 150}; // EG28
  Double_t bins_29[21] = {11, 13, 15, 17, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 35, 40, 45, 50, 60, 70, 150}; // EG29
  Double_t bins_30[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 29, 30, 31, 32, 35, 40, 45, 50, 60, 70, 150}; // EG30

  Double_t bins_40[22] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 39, 40, 42, 45, 50, 60, 70, 150}; // EG40
  Double_t bins_50[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG50
  Double_t bins_60[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG60

  vector< Double_t* > bins;
  bins.push_back( bins_0 ); bins.push_back( bins_1 ); bins.push_back( bins_2 ); bins.push_back( bins_3 ); bins.push_back( bins_4 ); 
  bins.push_back( bins_5 ); bins.push_back( bins_6 ); bins.push_back( bins_7 ); bins.push_back( bins_8 ); bins.push_back( bins_9 ); 
  bins.push_back( bins_10 ); bins.push_back( bins_11 ); bins.push_back( bins_12 ); bins.push_back( bins_13 ); bins.push_back( bins_14 ); 
  bins.push_back( bins_15 ); bins.push_back( bins_16 ); bins.push_back( bins_17 ); bins.push_back( bins_18 ); bins.push_back( bins_19 ); 
  bins.push_back( bins_20 ); bins.push_back( bins_21 ); bins.push_back( bins_22 ); bins.push_back( bins_23 ); bins.push_back( bins_24 ); 
  bins.push_back( bins_25 ); bins.push_back( bins_26 ); bins.push_back( bins_27 ); bins.push_back( bins_28 ); bins.push_back( bins_29 ); 

  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_30 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_40 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_50 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_60 );

  RooBinning binning = RooBinning(nbins[iEG]-1, bins[iEG], "binning");


  // INPUT DATA //
  TFile* f1 = TFile::Open(dirIn+"/"+fileIn);

  TTree* treenew;
  TTree* treenew_2;

  treenew = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL1]+name_coll[iColl1] ) ;
  treenew_2 = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL2]+name_coll[iColl2] ) ;

  TString name_scet[2], name_scdr[2], name_l1bin[2];
  name_scet[0] = "sc_et"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scet[1] = "sc_et"+name_ecal[iECAL2]+name_coll[iColl2];
  name_scdr[0] = "sc_dr"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scdr[1] = "sc_dr"+name_ecal[iECAL2]+name_coll[iColl2];
  
  name_l1bin[0] = "l1_"+names[iEG]+name_ecal[iECAL1]+name_coll[iColl1];
  name_l1bin[1] = "l1_"+names[iEG]+name_ecal[iECAL2]+name_coll[iColl2];

  RooRealVar et_plot(name_scet[0],name_scet[0],0,150) ;
  RooRealVar dr(name_scdr[0],name_scdr[0],0.5,1.5) ; 
  RooRealVar et_plot2(name_scet[1],name_scet[1],0,150) ;
  RooRealVar dr2(name_scdr[1],name_scdr[1],0.5,1.5) ;

  // Acceptance state cut (1 or 0)
  RooCategory cut(name_l1bin[0],name_l1bin[0]) ;
  cut.defineType("accept",1) ;
  cut.defineType("reject",0) ;
  RooCategory cut2(name_l1bin[1],name_l1bin[1]) ;
  cut2.defineType("accept",1) ;
  cut2.defineType("reject",0) ;
  
  // PARAMETRES ROOFIT CRYSTAL BALL
  RooRealVar norm("norm","N",1,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.671034,0.01,8);
  RooRealVar n("n","n",4.07846,1.1,35);
  RooRealVar mean("mean","mean",20.8,0,100);
  //mean.setVal(thres[iEG]);
  RooRealVar sigma("sigma","#sigma",0.972825,0.01,5);
  //RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  RooRealVar norm2("norm2","N",0.999069,0.6,1);
  RooRealVar alpha2("alpha2","#alpha",0.492303,0.01,8);
  RooRealVar n2("n2","n",11.6694,1.1,35);
  RooRealVar mean2("mean2","mean",21.4582,0,100);
  //mean2.setVal(thres[iEG]);
  RooRealVar sigma2("sigma2","#sigma",1.19,0.01,5);
  //RooRealVar pedestal2("pedestal2","pedestal",0.01,0,0.4);

  FuncCB cb("cb","Crystal Ball Integree",et_plot,mean,sigma,alpha,n,norm) ;
  FuncCB cb2("cb2","Crystal Ball Integree",et_plot2,mean2,sigma2,alpha2,n2,norm2) ;
  
  // EFFICIENCY //
  RooEfficiency eff("eff","efficiency",cb,cut,"accept");
  RooEfficiency eff2("eff2","efficiency",cb2,cut2,"accept");

  // DATASETS //
  RooDataSet dataSet("data","data",RooArgSet(et_plot, cut,dr),Import(*treenew)); 
  RooDataSet dataSet2("data2","data2",RooArgSet(et_plot2, cut2,dr2),Import(*treenew_2));

  dataSet.Print();
  dataSet2.Print();
  
  // PLOT //
  RooPlot* frame = et_plot.frame(Bins(18000),Title("Fitted efficiency")) ;
  RooPlot* frame2 = et_plot2.frame(Bins(18000),Title("Fitted efficiency")) ;

  dataSet.plotOn(frame, Binning(binning), Efficiency(cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSet2.plotOn(frame2, Binning(binning), Efficiency(cut2), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );


  /////////////////////// FITTING /////////////////////////////

  double fit_cuts_min = thres[iEG]-1.5 ;
  double fit_cuts_max = 150;

  et_plot.setRange("interesting",fit_cuts_min,fit_cuts_max);
  et_plot2.setRange("interesting",fit_cuts_min,fit_cuts_max);

  RooFitResult* roofitres1 = new RooFitResult("roofitres1","roofitres1");
  RooFitResult* roofitres2 = new RooFitResult("roofitres2","roofitres2");

  fichier << "Fit characteristics :"   << endl ;
  fichier << "EG "     << names[iEG] << endl ;
  fichier << "Fit Range , EB Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "Fit Range , EE Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "----------------------"  << endl ;

  // Fit #1 //
  roofitres1 = eff.fitTo(dataSet,ConditionalObservables(et_plot),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
  
  cb.plotOn(frame,LineColor(color1),LineWidth(2));

  double res_norm1  = norm.getVal();
  double err_norm1  = norm.getErrorLo();
  double res_mean1  = mean.getVal();
  double err_mean1  = mean.getError();
  double res_sigma1 = sigma.getVal();
  double err_sigma1 = sigma.getError();
  double res_n1     = n.getVal();
  double err_n1     = n.getError();
  double res_alpha1 = alpha.getVal();
  double err_alpha1 = alpha.getError();

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << res_mean1  << "; "
	  << "double res_sigma=" << res_sigma1 << "; "
          << "double res_alpha=" << res_alpha1 << "; "
          << "double res_n="     << res_n1     << "; "
          << "double res_norm="  << res_norm1  << "; "
	  << endl
	  << "double err_mean="  << err_mean1  << "; "
	  << "double err_sigma=" << err_sigma1 << "; "
          << "double err_alpha=" << err_alpha1 << "; "
          << "double err_n="     << err_n1     << "; "
          << "double err_norm="  << err_norm1  << "; "
	  << endl;

  // Fit #2 //
  roofitres2 = eff2.fitTo(dataSet2,ConditionalObservables(et_plot2),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
 
  cb2.plotOn(frame2,LineColor(color2),LineWidth(2));

  double res_norm2  = norm2.getVal();
  double err_norm2  = norm2.getErrorLo();
  double res_mean2  = mean2.getVal();
  double err_mean2  = mean2.getError();
  double res_sigma2 = sigma2.getVal();
  double err_sigma2 = sigma2.getError();
  double res_n2     = n2.getVal();
  double err_n2     = n2.getError();
  double res_alpha2 = alpha2.getVal();
  double err_alpha2 = alpha2.getError();

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << res_mean2  << "; "
	  << "double res_sigma=" << res_sigma2 << "; "
	  << "double res_alpha=" << res_alpha2 << "; "
	  << "double res_n="     << res_n2     << "; "
	  << "double res_norm="  << res_norm2  << "; "
	  << endl
	  << "double err_mean="  << err_mean2  << "; "
	  << "double err_sigma=" << err_sigma2 << "; "
	  << "double err_alpha=" << err_alpha2 << "; "
	  << "double err_n="     << err_n2     << "; "
	  << "double err_norm="  << err_norm2  << "; "
	  << endl;
    

  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,100.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  frame2->GetYaxis()->SetRangeUser(0,1.05);
  frame2->GetXaxis()->SetRangeUser(1,100.);
  frame2->GetYaxis()->SetTitle("Efficiency");
  frame2->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame2->Draw("same") ;

  TH1F *SCeta1 = new TH1F("SCeta1","SCeta1",50,-2.5,2.5);
  TH1F *SCeta2 = new TH1F("SCeta2","SCeta2",50,-2.5,2.5);

  SCeta1->SetLineColor(color1) ;
  SCeta1->SetMarkerColor(color1);
  SCeta1->SetMarkerStyle(style1);

  SCeta2->SetLineColor(color2) ;
  SCeta2->SetMarkerColor(color2);
  SCeta2->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.246,0.435,0.461,0.560,NULL,"brNDC"); // mid : x=353.5
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);
  leg->SetMargin(0.25);
  TLegendEntry *entry=leg->AddEntry("NULL","L1_SingleEG"+names[iEG],"h");
//   leg->AddEntry(SCeta1,name_leg_ecal[iECAL1]+" "+name_leg_coll[iColl1],"p");
//   leg->AddEntry(SCeta2,name_leg_ecal[iECAL2]+" "+name_leg_coll[iColl2],"p");
  leg->AddEntry(SCeta1,name_leg_ecal[iECAL1],"p");
  leg->AddEntry(SCeta2,name_leg_ecal[iECAL2],"p");
  leg->Draw();

  leg = new TLegend(0.16,0.725,0.58,0.905,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+names[iEG]+" GeV","h");
  leg->Draw();

  TPaveText *pt2 = new TPaveText(0.220,0.605,0.487,0.685,"brNDC"); // mid : x=353.5                                          
  pt2->SetLineColor(1);
  pt2->SetTextColor(1);
  pt2->SetTextFont(42);
  pt2->SetTextSize(0.03);
  pt2->SetFillColor(kWhite);
  pt2->SetShadowColor(kWhite);
  pt2->AddText("L1 E/Gamma Trigger");
  pt2->AddText("Electrons from Z");
  pt2->Draw();
  
  //TString name_image="eff_EG20_2012_12fb";

  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");
  ca->Print(name_image+".eps","eps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSet);
  w->import(dataSet2);
  
  w->import(*roofitres1,"roofitres1");
  w->import(*roofitres2,"roofitres2");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  //f1->Close();
}
コード例 #29
0
void buildModelUpsi2015(RooWorkspace& w, int signalModel, int bkgdModel){
   // C r e a t e   m o d e l  
   int nt=100000;
   // cout << "you're building a model for the quarkonium resonance of mass = "<< M1S <<" GeV/c^{2},"endl;
   RooRealVar *nsig1f   = new RooRealVar("N_{ #varUpsilon(1S)}","nsig1S",0,nt*10);
   RooRealVar* mass       = (RooRealVar*) w.var("invariantMass");

   RooRealVar *nsig2f = NULL;
   RooRealVar *nsig3f = NULL;


   RooRealVar  *mean = new RooRealVar("m_{ #varUpsilon(1S)}","#Upsilon mean",M1S,M1S-0.2,M1S+0.2);
   RooConstVar *rat2 = new RooConstVar("rat2", "rat2", M2S/M1S);
   RooConstVar *rat3 = new RooConstVar("rat3", "rat3", M3S/M1S);
   // scale mean and resolution by mass ratio
   RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",RooArgList(*mean));
   RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0*@1", RooArgList(*mean,*rat2));
   RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0*@1", RooArgList(*mean,*rat3));

   // //detector resolution ?? where is this coming from?
   RooRealVar    *sigma1  = new RooRealVar("#sigma_{CB1}","#sigma_{CB1}",0.01,0.1); // 
   RooFormulaVar *sigma1S = new RooFormulaVar("sigma1S","@0"   ,RooArgList(*sigma1));
   RooFormulaVar *sigma2S = new RooFormulaVar("sigma2S","@0*@1",RooArgList(*sigma1,*rat2));
   RooFormulaVar *sigma3S = new RooFormulaVar("sigma3S","@0*@1",RooArgList(*sigma1,*rat3));
   RooRealVar *alpha  = new RooRealVar("#alpha_{CB}","tail shift",0.1,10);    // MC 5tev 1S pol2 
   RooRealVar *npow   = new RooRealVar("n_{CB}","power order",0.1,10);    // MC 5tev 1S pol2 
   RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.,1.);
   // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.
   RooRealVar    *scaleWidth = new RooRealVar("#sigma_{CB2}/#sigma_{CB1}","scaleWidth",1.,2.5);
   RooFormulaVar *sigmaGaus = new RooFormulaVar("sigmaGaus","@0*@1", RooArgList(*sigma1,*scaleWidth));
   RooFormulaVar *sigmaGaus2 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat2));
   RooFormulaVar *sigmaGaus3 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat3));
   RooGaussian* gauss1 = new RooGaussian("gaus1s","gaus1s",
         *nsig1f,
         *mass,    //mean
         *sigmaGaus); //sigma
   RooGaussian* gauss1b = new RooGaussian("gaus1sb","gaus1sb",
         *nsig1f,
         *mean,    //mean
         *sigma1); //sigma

   // declarations
   RooAbsPdf  *cb1S_1   = NULL;
   RooAbsPdf  *cb1S_2   = NULL;
   RooAbsPdf  *cb2S_1   = NULL;
   RooAbsPdf  *cb2S_2   = NULL;
   RooAbsPdf  *cb3S_1   = NULL;
   RooAbsPdf  *cb3S_2   = NULL;
   RooAbsPdf  *sig1S   = NULL;
   RooAbsPdf  *sig2S   = NULL;
   RooAbsPdf  *sig3S   = NULL;

   switch(signalModel){    
      case 1: //crystal boule
         sig1S   = new RooCBShape("cb1S_1", "FSR cb 1s",
               *mass,*mean1S,*sigma1,*alpha,*npow);

         sig2S   = new RooCBShape ("cb2S_1", "FSR cb 1s",
               *mass,*mean2S,*sigma2S,*alpha,*npow);
         sig3S   = new RooCBShape ("cb3S_1", "FSR cb 1s",
               *mass,*mean3S,*sigma3S,*alpha,*npow);
         cout << "you're fitting each signal peak with a Crystal Ball function"<< endl;
         break;
      case 2: //Gaussein
         sig1S  = new RooGaussian ("g1", "gaus 1s",
               *mass,*mean1S,*sigma1);
         cout << "you're fitting 1 signal peak with a Gaussian function"<< endl;
         break;
      case 3: //Gaussein + crystal boule
         cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
               *mass,*mean1S,*sigma1,*alpha,*npow);
         sig1S  = new RooAddPdf ("cbg", "cbgaus 1s",
               RooArgList(*gauss1,*cb1S_1),*sigmaFraction);
         cout << "you're fitting 1 signal peak with a sum of a Gaussian and a Crystal Ball function"<< endl;
         break;
      case 4: //crystal boules
         cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
               *mass,*mean1S,*sigma1,*alpha,*npow);

         cb1S_2    = new RooCBShape ("cb1S_2", "FSR cb 1s",
               *mass,*mean1S,*sigmaGaus,*alpha,*npow);
         sig1S  = new RooAddPdf  ("cbcb","1S mass pdf",
               RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);
         // /// Upsilon 2S
         cb2S_1    = new RooCBShape ("cb2S_1", "FSR cb 2s", 
               *mass,*mean2S,*sigma2S,*alpha,*npow); 
         cb2S_2    = new RooCBShape ("cb2S_2", "FSR cb 2s", 
               *mass,*mean2S,*sigmaGaus2,*alpha,*npow); 
         sig2S  = new RooAddPdf  ("sig2S","2S mass pdf",
               RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);

         // /// Upsilon 3S
         cb3S_1    = new RooCBShape ("cb3S_1", "FSR cb 3s", 
               *mass,*mean3S,*sigma3S,*alpha,*npow); 
         cb3S_2    = new RooCBShape ("cb3S_2", "FSR cb 3s", 
               *mass,*mean3S,*sigmaGaus3,*alpha,*npow); 
         sig3S  = new RooAddPdf  ("sig3S","3S mass pdf",
               RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction); // = cb3S1*sigmaFrac + cb3S2*(1-sigmaFrac)
         cout << "you're fitting each signal peak with a Double Crystal Ball function"<< endl;
         break;

      case 5: //deux Gausseins
         sig1S  = new RooAddPdf ("cb1S_1", "cbgaus 1s",
               RooArgList(*gauss1,*gauss1b),*sigmaFraction);
         cout << "you're fitting each signal peak with a Double Gaussian function"<< endl;
         break;
   }
   // bkg Chebychev
   RooRealVar *nbkgd   = new RooRealVar("n_{Bkgd}","nbkgd",0,nt);
   RooRealVar *bkg_a1  = new RooRealVar("a1_bkg", "bkg_{a1}", 0, -5, 5);
   RooRealVar *bkg_a2  = new RooRealVar("a2_Bkg", "bkg_{a2}", 0, -2, 2);
   RooRealVar *bkg_a3  = new RooRealVar("a3_Bkg", "bkg_{a3}", 0, -0.9, 2);

   //  likesign
   RooRealVar *nLikesignbkgd = new RooRealVar("NLikesignBkg","nlikesignbkgd",nt*0.75,0,10*nt);
   // *************************************************** bkgModel

   RooRealVar turnOn("turnOn","turnOn", 0,10);
   RooRealVar width("width","width", 0.1,10);// MB 2.63
   RooRealVar decay("decay","decay",0,10);// MB: 3.39


   width.setConstant(false);
   decay.setConstant(false);
   turnOn.setConstant(false);


   alpha->setConstant(false);
   npow->setConstant(false);
   sigma1->setConstant(false);
   scaleWidth->setConstant(false);
   sigmaFraction->setConstant(false);

   //thisPdf: form of the bkg pdf
   //pdf_combinedbkgd; // total bkg pdf. usually form*normalization  (so that you can do extended ML fits)

   RooAbsPdf *pdf_combinedbkgd = NULL;;
   RooRealVar *fPol   = new RooRealVar("F_{pol}","fraction of polynomial distribution",0.0,1);
   RooAbsPdf *ChebPdf = NULL;
   RooAbsPdf *ErrPdf = NULL;
   RooAbsPdf* ExpPdf = NULL;

   switch (bkgdModel) 
   {
      case 3 : //use error function to fit the OS directly
         bkg_a3->setConstant(true);
         pdf_combinedbkgd            = new  RooGenericPdf("bkgPdf","bkgPdf",
               "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
               RooArgList(*mass,turnOn,width,decay));
         break;

      case 4 : //use pol 2+ErfExp to fit the OS directly

         ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
               *mass, RooArgList(*bkg_a1,*bkg_a2));
         ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
               "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
               RooArgList(*mass,turnOn,width,decay));
         pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
               RooArgList(*ChebPdf,*ErrPdf),
               RooArgList(*fPol));

         break;
      case 5 : //use ( error function + polynomial 1) to fit the OS directly

         bkg_a3->setConstant(true);
         bkg_a2->setConstant(true);
         ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
               *mass, RooArgList(*bkg_a1,*bkg_a2,*bkg_a3));
         ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
               "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
               RooArgList(*mass,turnOn,width,decay));
         pdf_combinedbkgd   = new RooAddPdf ("bkgPdf","total combined background pdf",
               RooArgList(*ChebPdf,*ErrPdf),
               RooArgList(*fPol));
         break;
      case 6: // NOT WORKING
         ChebPdf  = new RooChebychev("ChebPdf","ChebPdf",
               *mass, RooArgList(*bkg_a1,*bkg_a2));
         ExpPdf     = new  RooGenericPdf("ExpPdf","ExpPdf",
               "exp(-@0/decay)",
               RooArgList(*mass,decay));
         pdf_combinedbkgd  =  new RooAddPdf ("bkgPdf","total combined background pdf",
               RooArgList(*ChebPdf,*ExpPdf),
               RooArgList(*fPol));
         break;
      default :
         cout<<"Donno what you are talking about! Pick another fit option!"<<endl;
         break;
   }

   //###### the nominal fit with default pdf 

   // can remove the double crystal ball in pbpb: just commenting out and copying an appropriate version
   RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
         RooArgList(*sig1S,*sig2S,*sig3S,*pdf_combinedbkgd),
         RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
   //  nsig3f->setVal(0); nsig3f->setConstant();

   w.import(*pdf);
   w.Print();
}
コード例 #30
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 ----------------------------------------