예제 #1
0
   RooFitResult* GenericModel::fitTo(RooDataSet* data)
   {
      // Perform fit of the pseudo-PDF to the data
      // On multi-core machines, this automatically uses all available processor cores

      SafeDelete(fLastFit);
#ifdef WITH_MULTICORE_CPU
      fLastFit = fModelPseudoPDF->fitTo(*data, Save(), NumCPU(WITH_MULTICORE_CPU));
#else
      fLastFit = fModelPseudoPDF->fitTo(*data, Save());
#endif

      SafeDelete(fParamDataHist);
      fParamDataHist = new RooDataHist("params", "params", GetParameters());

      // store weights of component pdfs => distribution of parameters
      fWeights.removeAll();
      const RooArgList& coefs = fModelPseudoPDF->coefList();
      for (int i = 0; i < GetNumberOfDataSets(); i++) {
         RooAbsReal* coef = (RooAbsReal*)coefs.at(i);
         RooRealVar w(Form("w%d", i), Form("Fitted weight of kernel#%d", i), coef->getVal());
         if (coef->InheritsFrom(RooRealVar::Class())) {
            w.setError(((RooRealVar*)coef)->getError());
         } else {
            w.setError(coef->getPropagatedError(*fLastFit));
         }
         fWeights.addClone(w);
         fParamDataHist->set(*GetParametersForDataset(i), w.getVal(), w.getError());
      }

      SafeDelete(fParameterPDF);
      fParameterPDF = new RooHistPdf("paramPDF", "paramPDF", GetParameters(), *fParamDataHist);

      return fLastFit;
   }
예제 #2
0
void rf313_paramranges()
{

  // C r e a t e   3 D   p d f 
  // -------------------------

  // Define observable (x,y,z)
  RooRealVar x("x","x",0,10) ;
  RooRealVar y("y","y",0,10) ;
  RooRealVar z("z","z",0,10) ;

  // Define 3 dimensional pdf
  RooRealVar z0("z0","z0",-0.1,1) ;
  RooPolynomial px("px","px",x,RooConst(0)) ;
  RooPolynomial py("py","py",y,RooConst(0)) ;
  RooPolynomial pz("pz","pz",z,z0) ;
  RooProdPdf pxyz("pxyz","pxyz",RooArgSet(px,py,pz)) ;



  // D e f i n e d   n o n - r e c t a n g u l a r   r e g i o n   R   i n   ( x , y , z ) 
  // -------------------------------------------------------------------------------------

  //
  // R = Z[0 - 0.1*Y^2] * Y[0.1*X - 0.9*X] * X[0 - 10]
  //

  // Construct range parameterized in "R" in y [ 0.1*x, 0.9*x ]
  RooFormulaVar ylo("ylo","0.1*x",x) ;
  RooFormulaVar yhi("yhi","0.9*x",x) ;
  y.setRange("R",ylo,yhi) ;

  // Construct parameterized ranged "R" in z [ 0, 0.1*y^2 ]
  RooFormulaVar zlo("zlo","0.0*y",y) ;
  RooFormulaVar zhi("zhi","0.1*y*y",y) ;
  z.setRange("R",zlo,zhi) ;



  // C a l c u l a t e   i n t e g r a l   o f   n o r m a l i z e d   p d f   i n   R 
  // ----------------------------------------------------------------------------------

  // Create integral over normalized pdf model over x,y,z in "R" region
  RooAbsReal* intPdf = pxyz.createIntegral(RooArgSet(x,y,z),RooArgSet(x,y,z),"R") ;

  // Plot value of integral as function of pdf parameter z0
  RooPlot* frame = z0.frame(Title("Integral of pxyz over x,y,z in region R")) ;
  intPdf->plotOn(frame) ;



  new TCanvas("rf313_paramranges","rf313_paramranges",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.6) ; frame->Draw() ;

  return ;
}
// grab the initial normalization from a datacard converted in workspace
// with: scripts/text2workspace.py -b -o model.root datacards/hww-12.1fb.mH125.comb_0j1j2j_shape.txt
void fillInitialNorms(RooArgSet *args, std::map<std::string, std::pair<double,double> > &vals, std::string workspace){
  TFile *fw_ =  TFile::Open(workspace.c_str());
  RooWorkspace *ws = (RooWorkspace*)fw_->Get("w");
  TIterator* iter(args->createIterator());
  for (TObject *a = iter->Next(); a != 0; a = iter->Next()) {
    RooAbsReal *rar = (RooAbsReal*)ws->obj(a->GetName());
    std::string name = rar->GetName();
    std::pair<double,double> valE(rar->getVal(),0.0);
    vals.insert( std::pair<std::string,std::pair<double ,double> > (name,valE)) ;
  }
}
예제 #4
0
double NormalizedIntegral(RooAbsPdf & function, RooRealVar & integrationVar, double lowerLimit, double upperLimit){

  integrationVar.setRange("integralRange",lowerLimit,upperLimit);
  RooAbsReal* integral = function.createIntegral(integrationVar,NormSet(integrationVar),Range("integralRange"));


  double normlizedIntegralValue = integral->getVal();

  //  cout<<normlizedIntegralValue<<endl;


  return normlizedIntegralValue;


}
예제 #5
0
THSEventsPDF::THSEventsPDF(const char *name, const char *title, 
			   RooAbsReal& _x,
			   RooAbsReal& _alpha,
			   RooAbsReal& _offset,
			   RooAbsReal& _scale,
			   Int_t NAlphBins  ) :
  RooAbsPdf(name,title), 
  x("x","x",this,_x),
  offset("offset","offset",this,_offset),
  scale("scale","scale",this,_scale),
  alpha("alpha","alpha",this,_alpha),
  fx_off(0),
  falpha(0),
  fHist(0),
  fHistPdf(0),
  fRHist(0),
  fWeightHist(0),
  fTree(0)
{ 
  
  RooRealVar *rx=dynamic_cast<RooRealVar*>(&_x);
  RooRealVar *ra=dynamic_cast<RooRealVar*>(&_alpha);
  RooRealVar *rs=dynamic_cast<RooRealVar*>(&_scale);
  RooRealVar *ro=dynamic_cast<RooRealVar*>(&_offset);
  //Work out number of bins for x axis
  //Take bin width as being 1/10 of the alpha range (arbitrary!) or 100 whichever is larger
  // NbinX=40;
  Double_t rsmin=1;
  fOldScale=rs->getVal();
  if(rs->getMin()) rsmin=rs->getMin();
  else cout<<"THSEventsPDF::THSEventsPDF Warning no scale minimum set take = 1"<<endl;
  Double_t mid=(rx->getMax()+rx->getMin())/2;
  Double_t diff=(rx->getMax()-rx->getMin())/2;
  Double_t rMin=mid-diff/rsmin - ro->getMin(); //additional range for possible tranformation or scaling
  Double_t rMax=mid+diff/rsmin + ro->getMax();
  Int_t NbinX=200/rsmin;
  cout<<GetName()<<" hist ranges "<<rMin<<" to "<<rMax<<endl;
  if(NbinX<10) NbinX=10;
   fRHist=new TH2F(TString("hmc_model_")+_x.GetName()+name,TString("MC model for ")+_x.GetName(),NbinX,rMin,rMax,NAlphBins,ra->getMin(),ra->getMax());
  fRHist->Sumw2();
  //  fRHist=new TH2F(TString("hmc_model_")+_x.GetName()+name,TString("MC model for ")+_x.GetName(),NbinX,rx->getMin(),rx->getMax(),NAlphBins,ra->getMin(),ra->getMax());
  fx=new RooRealVar(_x.GetName(),"Vx",0,x.min(),x.max());
  fx_off=new RooRealVar(_x.GetName(),"Vx_off",0,rMin,rMax);
  falpha=new RooRealVar("Valpha","Valpha",0,alpha.min(),alpha.max());
  
  fNWdim=0;
} 
예제 #6
0
void fit( RooAbsReal & chi2, int numberOfBins, const char * outFileNameWithFitResult ){
  TFile * out_root_file = new TFile(outFileNameWithFitResult , "recreate");
  RooMinuit m_tot(chi2) ;
  m_tot.migrad();
  // m_tot.hesse();
  RooFitResult* r_chi2 = m_tot.save() ;
  cout << "==> Chi2 Fit results " << endl ;
  r_chi2->Print("v") ;
  //  r_chi2->floatParsFinal().Print("v") ;
  int NumberOfFreeParameters =  r_chi2->floatParsFinal().getSize() ;
  for (int i =0; i< NumberOfFreeParameters; ++i){
    r_chi2->floatParsFinal()[i].Print();
  }
  cout<<"chi2:" <<chi2.getVal() << ", numberOfBins: " << numberOfBins  << ", NumberOfFreeParameters: " << NumberOfFreeParameters << endl; 
  cout<<"Normalized Chi2   = " << chi2.getVal()/ (numberOfBins - NumberOfFreeParameters)<<endl; 
  r_chi2->Write( ) ;
  delete out_root_file;
}
예제 #7
0
///
/// Make an Asimov toy: set all observables set to truth values.
/// The Asimov point needs to be loaded in the combiner before.
/// \param c - combiner which should be set to an asimov toy
///
void GammaComboEngine::setAsimovObservables(Combiner* c)
{
    if ( !c->isCombined() ) {
        cout << "GammaComboEngine::setAsimovObservables() : ERROR : Can't set an Asimov toy before "
             "the combiner is combined. Call combine() first." << endl;
        exit(1);
    }

    // set observables to asimov values in workspace
    RooWorkspace* w = c->getWorkspace();
    TIterator* itObs = c->getObservables()->createIterator();
    while(RooRealVar* pObs = (RooRealVar*) itObs->Next()) {
        // get theory name from the observable name
        TString pThName = pObs->GetName();
        pThName.ReplaceAll("obs","th");
        // get the theory relation
        RooAbsReal* th = w->function(pThName);
        if ( th==0 ) {
            cout << "GammaComboEngine::setAsimovObservables() : ERROR : theory relation not found in workspace: " << pThName << endl;
            exit(1);
        }
        // set the observable to what the theory relation predicts
        pObs->setVal(th->getVal());
    }
    delete itObs;

    // write back the asimov values to the PDF object so that when
    // the PDF is printed, the asimov values show up
    for ( int i=0; i<c->getPdfs().size(); i++ ) {
        PDF_Abs* pdf = c->getPdfs()[i];
        pdf->setObservableSourceString("Asimov");
        TIterator* itObs = pdf->getObservables()->createIterator();
        while(RooRealVar* pObs = (RooRealVar*) itObs->Next()) {
            RooAbsReal* obs =  w->var(pObs->GetName());
            if ( obs==0 ) {
                cout << "GammaComboEngine::setAsimovObservables() : ERROR : observable not found in workspace: " << pObs->GetName() << endl;
                exit(1);
            }
            pdf->setObservable(pObs->GetName(), obs->getVal());
        }
        delete itObs;
    }
}
예제 #8
0
파일: Zbi_Zgamma.C 프로젝트: MycrofD/root
void Zbi_Zgamma() {

  // Make model for prototype on/off problem
  // Pois(x | s+b) * Pois(y | tau b )
  // for Z_Gamma, use uniform prior on b.
  RooWorkspace* w = new RooWorkspace("w",true);
  w->factory("Poisson::px(x[150,0,500],sum::splusb(s[0,0,100],b[100,0,300]))");
  w->factory("Poisson::py(y[100,0,500],prod::taub(tau[1.],b))");
  w->factory("Uniform::prior_b(b)");

  // construct the Bayesian-averaged model (eg. a projection pdf)
  // p'(x|s) = \int db p(x|s+b) * [ p(y|b) * prior(b) ]
  w->factory("PROJ::averagedModel(PROD::foo(px|b,py,prior_b),b)") ;

  // plot it, blue is averaged model, red is b known exactly
  RooPlot* frame = w->var("x")->frame() ;
  w->pdf("averagedModel")->plotOn(frame) ;
  w->pdf("px")->plotOn(frame,LineColor(kRed)) ;
  frame->Draw() ;

  // compare analytic calculation of Z_Bi
  // with the numerical RooFit implementation of Z_Gamma
  // for an example with x = 150, y = 100

  // numeric RooFit Z_Gamma
  w->var("y")->setVal(100);
  w->var("x")->setVal(150);
  RooAbsReal* cdf = w->pdf("averagedModel")->createCdf(*w->var("x"));
  cdf->getVal(); // get ugly print messages out of the way

  cout << "Hybrid p-value = " << cdf->getVal() << endl;
  cout << "Z_Gamma Significance  = " <<
    PValueToSignificance(1-cdf->getVal()) << endl;

  // analytic Z_Bi
  double Z_Bi = NumberCountingUtils::BinomialWithTauObsZ(150, 100, 1);
  std::cout << "Z_Bi significance estimation: " << Z_Bi << std::endl;

  // OUTPUT
  // Hybrid p-value = 0.999058
  // Z_Gamma Significance  = 3.10804
  // Z_Bi significance estimation: 3.10804
}
예제 #9
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();
}
// get effective sigma from culmalative distribution function
pair<double,double> getEffSigma(RooRealVar *mass, RooAbsPdf *pdf, double wmin=110., double wmax=130., double step=0.002, double epsilon=1.e-4){

  RooAbsReal *cdf = pdf->createCdf(RooArgList(*mass));
  cout << "Computing effSigma...." << endl;
  TStopwatch sw;
  sw.Start();
  double point=wmin;
  vector<pair<double,double> > points;
  
  while (point <= wmax){
    mass->setVal(point);
    if (pdf->getVal() > epsilon){
      points.push_back(pair<double,double>(point,cdf->getVal())); 
    }
    point+=step;
  }
  double low = wmin;
  double high = wmax;
  double width = wmax-wmin;
  for (unsigned int i=0; i<points.size(); i++){
    for (unsigned int j=i; j<points.size(); j++){
      double wy = points[j].second - points[i].second;
      if (TMath::Abs(wy-0.683) < epsilon){
        double wx = points[j].first - points[i].first;
        if (wx < width){
          low = points[i].first;
          high = points[j].first;
          width=wx;
        }
      }
    }
  }
  sw.Stop();
  cout << "effSigma: [" << low << "-" << high << "] = " << width/2. << endl;
  cout << "\tTook: "; sw.Print();
  pair<double,double> result(low,high);
  return result;
}
예제 #11
0
void combinedWorkspace_4WS(const char* name_pbpb_pass="******", const char* name_pbpb_fail="fitresult_pbpb_fail.root", const char* name_pp_pass="******", const char* name_pp_fail="fitresult_pp_fail.root", const char* name_out="fitresult_combo.root", const float systval = 0., const char* subDirName ="wsTest", int nCPU=2){
   // subdir: Directory to save workspaces under currentPATH/CombinedWorkspaces/subDir/

   // set things silent
   gErrorIgnoreLevel=kError;
   RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  
   bool dosyst = (systval > 0.);

   TString nameOut(name_out);
  
   RooWorkspace * ws = test_combine_4WS(name_pbpb_pass, name_pp_pass, name_pbpb_fail, name_pp_fail, false, nCPU);
   RooAbsData * data = ws->data("dOS_DATA");

   RooRealVar* RFrac2Svs1S_PbPbvsPP_P = ws->var("RFrac2Svs1S_PbPbvsPP_P");
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",-10);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",10);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*RFrac2Svs1S_PbPbvsPP_P, *leftEdge, *rightEdge));
   ws->import(step);
   ws->factory( "Uniform::flat(RFrac2Svs1S_PbPbvsPP_P)" );

   // systematics
   if (dosyst) {
     ws->factory( Form("kappa_syst[%f]",systval) );
     ws->factory( "expr::alpha_syst('kappa_syst*beta_syst',kappa_syst,beta_syst[0,-5,5])" );
     ws->factory( "Gaussian::constr_syst(beta_syst,glob_syst[0,-5,5],1)" );
     
     // add systematics into the double ratio
     ws->factory( "expr::RFrac2Svs1S_PbPbvsPP_P_syst('@0+@1',RFrac2Svs1S_PbPbvsPP_P,alpha_syst)" );
     
     // build the pbpb pdf
     RooRealVar* effjpsi_pp_P = (RooRealVar*)ws->var("effjpsi_pp_P");
     RooRealVar* effpsip_pp_P = (RooRealVar*)ws->var("effpsip_pp_P");
     RooRealVar* effjpsi_pp_NP = (RooRealVar*)ws->var("effjpsi_pp_NP");
     Double_t Npsi2SPbPbPass = npsip_pbpb_pass_from_doubleratio_prompt(ws, RooArgList(*effjpsi_pp_P,*effpsip_pp_P,*effjpsi_pp_NP),true); // Create and import N_Psi2S_PbPb_pass_syst
     
     ws->factory( "SUM::pdfMASS_Tot_PbPb_pass_syst(N_Jpsi_PbPb_pass * pdfMASS_Jpsi_PbPb_pass, N_Psi2S_PbPb_pass_syst * pdfMASS_Psi2S_PbPb_pass, N_Bkg_PbPb_pass * pdfMASS_Bkg_PbPb_pass)" );
     ws->factory( "PROD::pdfMASS_Tot_PbPb_pass_constr(pdfMASS_Tot_PbPb_pass_syst,constr_syst)" );
     
     // build the combined pdf
     ws->factory("SIMUL::simPdf_syst_noconstr(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass_syst,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
     RooSimultaneous *simPdf = (RooSimultaneous*) ws->pdf("simPdf_syst_noconstr");
     RooGaussian *constr_syst = (RooGaussian*) ws->pdf("constr_syst");
     RooProdPdf *simPdf_constr = new RooProdPdf("simPdf_syst","simPdf_syst",RooArgSet(*simPdf,*constr_syst));
     ws->import(*simPdf_constr);
     
   } else {
      ws->factory("SIMUL::simPdf_syst(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
   }

   ws->Print();

   if (dosyst) ws->var("beta_syst")->setConstant(kFALSE);


   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws->var("invMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws->cat("sample"));    
   //  /////////////////////////////////////////////////////////////////////

   if (dosyst) ws->var("glob_syst")->setConstant(true);
   RooArgSet globalObs("global_obs");
   if (dosyst) globalObs.add( *ws->var("glob_syst") );

   // ws->Print();

   RooArgSet poi("poi");
   poi.add( *ws->var("RFrac2Svs1S_PbPbvsPP_P") );



   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   if (dosyst) nuis.add( *ws->var("beta_syst") );

   // set parameters constant
   RooArgSet allVars = ws->allVars();
   TIterator* it = allVars.createIterator();
   RooRealVar *theVar = (RooRealVar*) it->Next();
   while (theVar) {
      TString varname(theVar->GetName());
//      if (varname != "RFrac2Svs1S_PbPbvsPP"
//            && varname != "invMass"
//            && varname != "sample"
//            )
//         theVar->setConstant();
     if ( varname.Contains("f_Jpsi_PP") || varname.Contains("f_Jpsi_PbPb") ||
           varname.Contains("rSigma21_Jpsi_PP") || 
           varname.Contains("m_Jpsi_PP") || varname.Contains("m_Jpsi_PbPb") || 
           varname.Contains("sigma1_Jpsi_PP") || varname.Contains("sigma1_Jpsi_PbPb") || 
           (varname.Contains("lambda")) ||
           (varname.Contains("_fail") && !varname.Contains("RFrac2Svs1S")))
         {
           theVar->setConstant();
         }
      if (varname=="glob_syst"
            || varname=="beta_syst"
         ) {
         cout << varname << endl;
         theVar->setConstant(!dosyst);
      }
      theVar = (RooRealVar*) it->Next();
   }

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


   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
  
   if (controlPlots)
   {
     RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,1),Title("LL and profileLL in RFrac2Svs1S_PbPbvsPP_P"));
     pNll->plotOn(framepoi,ShiftToZero());
     framepoi->SetMinimum(0);
     framepoi->SetMaximum(10);
     TCanvas *cpoi = new TCanvas();
     cpoi->cd(); framepoi->Draw();
     cpoi->SaveAs("cpoi.pdf");
   }
  
   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);
  
   if (controlPlots)
   {
     RooPlot* xframeSB_PP_pass = pObs->frame(Title("SBhypo_PP_pass"));
     data->plotOn(xframeSB_PP_pass,Cut("sample==sample::PP_pass"));
     RooAbsPdf *pdfSB_PP_pass = sbHypo.GetPdf();
     RooCategory *sample = ws->cat("sample");
     pdfSB_PP_pass->plotOn(xframeSB_PP_pass,Slice(*sample,"PP_pass"),ProjWData(*sample,*data));
     TCanvas *c1 = new TCanvas();
     c1->cd(); xframeSB_PP_pass->Draw();
     c1->SaveAs("c1.pdf");
    
     RooPlot* xframeSB_PP_fail = pObs->frame(Title("SBhypo_PP_fail"));
     data->plotOn(xframeSB_PP_fail,Cut("sample==sample::PP_fail"));
     RooAbsPdf *pdfSB_PP_fail = sbHypo.GetPdf();
     pdfSB_PP_fail->plotOn(xframeSB_PP_fail,Slice(*sample,"PP_fail"),ProjWData(*sample,*data));
     TCanvas *c2 = new TCanvas();
     c2->cd(); xframeSB_PP_fail->Draw();
     c2->SaveAs("c1.pdf");
    
     RooPlot* xframeB_PbPb_pass = pObs->frame(Title("SBhypo_PbPb_pass"));
     data->plotOn(xframeB_PbPb_pass,Cut("sample==sample::PbPb_pass"));
     RooAbsPdf *pdfB_PbPb_pass = sbHypo.GetPdf();
     pdfB_PbPb_pass->plotOn(xframeB_PbPb_pass,Slice(*sample,"PbPb_pass"),ProjWData(*sample,*data));
     TCanvas *c3 = new TCanvas();
     c3->cd(); xframeB_PbPb_pass->Draw();
     c3->SetLogy();
     c3->SaveAs("c2.pdf");
    
     RooPlot* xframeB_PbPb_fail = pObs->frame(Title("SBhypo_PbPb_fail"));
     data->plotOn(xframeB_PbPb_fail,Cut("sample==sample::PbPb_fail"));
     RooAbsPdf *pdfB_PbPb_fail = sbHypo.GetPdf();
     pdfB_PbPb_fail->plotOn(xframeB_PbPb_fail,Slice(*sample,"PbPb_fail"),ProjWData(*sample,*data));
     TCanvas *c4 = new TCanvas();
     c4->cd(); xframeB_PbPb_fail->Draw();
     c4->SetLogy();
     c4->SaveAs("c2.pdf");
   }
  
   delete pNll;
   delete pPoiAndNuisance;
   ws->import( sbHypo );
  
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   // RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   RooAbsReal * pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set RFrac2Svs1S_PbPbvsPP=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);


   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws);
   ws->import( bHypo );
  
   /////////////////////////////////////////////////////////////////////
   ws->Print();
   bHypo.Print();
   sbHypo.Print();

   // save workspace to file
   string mainDIR = gSystem->ExpandPathName(gSystem->pwd());
   string wsDIR = mainDIR + "/CombinedWorkspaces/";
   string ssubDirName="";
   if (subDirName) ssubDirName.append(subDirName);
   string subDIR = wsDIR + ssubDirName;
  
   void * dirp = gSystem->OpenDirectory(wsDIR.c_str());
   if (dirp) gSystem->FreeDirectory(dirp);
   else gSystem->mkdir(wsDIR.c_str(), kTRUE);

   void * dirq = gSystem->OpenDirectory(subDIR.c_str());
   if (dirq) gSystem->FreeDirectory(dirq);
   else gSystem->mkdir(subDIR.c_str(), kTRUE);
  
   const char* saveName = Form("%s/%s",subDIR.c_str(),nameOut.Data());
   ws->writeToFile(saveName);
}
예제 #12
0
prepDataFiles(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	int myIndex;	
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while ((file=(TSystemFile*)next())) {
		fname = file->GetName();
		if (fname.BeginsWith("TnP")&& fname.Contains("mc")) {
	
			ofstream myfile;

			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());
			TKey *key;
			while (key = (TKey*)nextkey()) {
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
				if ( theTypeClasse == "TDirectoryFile"){
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while (key2 = (TKey*)nextkey2()) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						myfile.open (theNomClasse2+".info");
						if ( theTypeClasse == "TDirectoryFile"){
							cout << "avant " << endl;
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2);
							cout << "apres " << endl;
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while (key3 = (TKey*)nextkey3()) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetTitle();	
								if ((theNomClasse3.Contains("FromMC"))) {

									TString localClasse3 = theNomClasse3;
									localClasse3.ReplaceAll("__","%");
									cout << "apres " << localClasse3 << endl;
									TObjArray* listBin = localClasse3.Tokenize('%');
									TString first = ((TObjString*)listBin->At(0))->GetString();
									TString second = ((TObjString*)listBin->At(2))->GetString();
									myfile << first;
									myfile << " " << second << " ";
									cout << "coucou la on va récupérer le rooFitResult " << endl;

									RooFitResult *theResults = (RooFitResult*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/"+theNomClasse3+"/fitresults");
									theResults->Print();
									RooArgList theParam = theResults->floatParsFinal();
									int taille = theParam.getSize();
									for (int m = 0 ; m < taille ; m++){
										cout << "m=" << m << endl;
									RooAbsArg *theArg = (RooAbsArg*) theParam.at(m);
									RooAbsReal *theReal = (RooAbsReal*) theArg;
										myfile << theReal->getVal() << " " ;
									}		
															
									myfile << "\n";

								}
							}
						}
						myfile.close();

					}
			
				}
			}
			delete myFile;
		}
	
	}

}
예제 #13
0
RooWorkspace* makeInvertedANFit(TTree* tree, float forceSigma=-1, bool constrainMu=false, float forceMu=-1) {
  RooWorkspace *ws = new RooWorkspace("ws","");

  std::vector< TString (*)(TString, RooRealVar&, RooWorkspace&) > bkgPdfList;
  bkgPdfList.push_back(makeSingleExp);
  bkgPdfList.push_back(makeDoubleExp);
#if DEBUG==0
  //bkgPdfList.push_back(makeTripleExp);
  bkgPdfList.push_back(makeModExp);
  bkgPdfList.push_back(makeSinglePow);
  bkgPdfList.push_back(makeDoublePow);
  bkgPdfList.push_back(makePoly2);
  bkgPdfList.push_back(makePoly3);
#endif



  RooRealVar mgg("mgg","m_{#gamma#gamma}",103,160,"GeV");
  mgg.setBins(38);

  mgg.setRange("sideband_low", 103,120);
  mgg.setRange("sideband_high",131,160);
  mgg.setRange("signal",120,131);

  RooRealVar MR("MR","",0,3000,"GeV");
  MR.setBins(60);
  
  RooRealVar Rsq("t1Rsq","",0,1,"GeV");
  Rsq.setBins(20);

  RooRealVar hem1_M("hem1_M","",-1,2000,"GeV");
  hem1_M.setBins(40);

  RooRealVar hem2_M("hem2_M","",-1,2000,"GeV");
  hem2_M.setBins(40);

  RooRealVar ptgg("ptgg","p_{T}^{#gamma#gamma}",0,500,"GeV");
  ptgg.setBins(50);

  RooDataSet data("data","",tree,RooArgSet(mgg,MR,Rsq,hem1_M,hem2_M,ptgg));

  RooDataSet* blind_data = (RooDataSet*)data.reduce("mgg<121 || mgg>130");

  std::vector<TString> tags;
  //fit many different background models
  for(auto func = bkgPdfList.begin(); func != bkgPdfList.end(); func++) {
    TString tag = (*func)("bonly",mgg,*ws);
    tags.push_back(tag);
    ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    RooFitResult* bres = ws->pdf("bonly_"+tag+"_ext")->fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
    bres->SetName(tag+"_bonly_fitres");
    ws->import(*bres);

    //make blinded fit
    RooPlot *fmgg_b = mgg.frame();
    blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
    TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
    blindBox.SetFillColor(kGray);
    fmgg_b->addObject(&blindBox);
    ws->pdf("bonly_"+tag+"_ext")->plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
    fmgg_b->SetName(tag+"_blinded_frame");
    ws->import(*fmgg_b);
    delete fmgg_b;
    

    //set all the parameters constant
    RooArgSet* vars = ws->pdf("bonly_"+tag)->getVariables();
    RooFIter iter = vars->fwdIterator();
    RooAbsArg* a;
    while( (a = iter.next()) ){
      if(string(a->GetName()).compare("mgg")==0) continue;
      static_cast<RooRealVar*>(a)->setConstant(kTRUE);
    }

    //make the background portion of the s+b fit
    (*func)("b",mgg,*ws);

    RooRealVar sigma(tag+"_s_sigma","",5,0,100);
    if(forceSigma!=-1) {
      sigma.setVal(forceSigma);
      sigma.setConstant(true);
    }
    RooRealVar mu(tag+"_s_mu","",126,120,132);
    if(forceMu!=-1) {
      mu.setVal(forceMu);
      mu.setConstant(true);
    }
    RooGaussian sig(tag+"_sig_model","",mgg,mu,sigma);
    RooRealVar Nsig(tag+"_sb_Ns","",5,0,100);
    RooRealVar Nbkg(tag+"_sb_Nb","",100,0,100000);
    

    RooRealVar HiggsMass("HiggsMass","",125.1);
    RooRealVar HiggsMassError("HiggsMassError","",0.24);
    RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);


    RooAddPdf fitModel(tag+"_sb_model","",RooArgList( *ws->pdf("b_"+tag), sig ),RooArgList(Nbkg,Nsig));

    RooFitResult* sbres;
    RooAbsReal* nll;
    if(constrainMu) {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    } else {
      fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
      sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
      nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
    }
    sbres->SetName(tag+"_sb_fitres");
    ws->import(*sbres);
    ws->import(fitModel);

    RooPlot *fmgg = mgg.frame();
    data.plotOn(fmgg);
    fitModel.plotOn(fmgg);
    ws->pdf("b_"+tag+"_ext")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
    fmgg->SetName(tag+"_frame");
    ws->import(*fmgg);
    delete fmgg;


    RooMinuit(*nll).migrad();

    RooPlot *fNs = Nsig.frame(0,25);
    fNs->SetName(tag+"_Nsig_pll");
    RooAbsReal *pll = nll->createProfile(Nsig);
    //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
    pll->plotOn(fNs);
    ws->import(*fNs);

    delete fNs;

    RooPlot *fmu = mu.frame(125,132);
    fmu->SetName(tag+"_mu_pll");
    RooAbsReal *pll_mu = nll->createProfile(mu);
    pll_mu->plotOn(fmu);
    ws->import(*fmu);

    delete fmu;

  }

  RooArgSet weights("weights");
  RooArgSet pdfs_bonly("pdfs_bonly");
  RooArgSet pdfs_b("pdfs_b");

  RooRealVar minAIC("minAIC","",1E10);
  //compute AIC stuff
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooAbsPdf *p_bonly = ws->pdf("bonly_"+*t);
    RooAbsPdf *p_b = ws->pdf("b_"+*t);
    RooFitResult *sb = (RooFitResult*)ws->obj(*t+"_bonly_fitres");
    RooRealVar k(*t+"_b_k","",p_bonly->getParameters(RooArgSet(mgg))->getSize());
    RooRealVar nll(*t+"_b_minNll","",sb->minNll());
    RooRealVar Npts(*t+"_b_N","",blind_data->sumEntries());
    RooFormulaVar AIC(*t+"_b_AIC","2*@0+2*@1+2*@1*(@1+1)/(@2-@1-1)",RooArgSet(nll,k,Npts));
    ws->import(AIC);
    if(AIC.getVal() < minAIC.getVal()) {
      minAIC.setVal(AIC.getVal());
    }
    //aicExpSum+=TMath::Exp(-0.5*AIC.getVal()); //we will need this precomputed  for the next step
    pdfs_bonly.add(*p_bonly);
    pdfs_b.add(*p_b);
  }
  ws->import(minAIC);
  //compute the AIC weight
  float aicExpSum=0;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    aicExpSum+=TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal())); //we will need this precomputed  for the next step    
  }
  std::cout << "aicExpSum: " << aicExpSum << std::endl;

  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = new RooRealVar(*t+"_b_AICWeight","",TMath::Exp(-0.5*(AIC->getVal()-minAIC.getVal()))/aicExpSum);
    if( TMath::IsNaN(AICw->getVal()) ) {AICw->setVal(0);}
    ws->import(*AICw);
    std::cout << *t << ":  " << AIC->getVal()-minAIC.getVal() << "    " << AICw->getVal() << std::endl;
    weights.add(*AICw);
  }
  RooAddPdf bonly_AIC("bonly_AIC","",pdfs_bonly,weights);
  RooAddPdf b_AIC("b_AIC","",pdfs_b,weights);

  //b_AIC.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //RooFitResult* bres = b_AIC.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::Range("sideband_low,sideband_high"));
  //bres->SetName("AIC_b_fitres");
  //ws->import(*bres);

  //make blinded fit
  RooPlot *fmgg_b = mgg.frame(RooFit::Range("sideband_low,sideband_high"));
  blind_data->plotOn(fmgg_b,RooFit::Range("sideband_low,sideband_high"));
  TBox blindBox(121,fmgg_b->GetMinimum()-(fmgg_b->GetMaximum()-fmgg_b->GetMinimum())*0.015,130,fmgg_b->GetMaximum());
  blindBox.SetFillColor(kGray);
  fmgg_b->addObject(&blindBox);
  bonly_AIC.plotOn(fmgg_b,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("sideband_low,sideband_high"));
  fmgg_b->SetName("AIC_blinded_frame");
  ws->import(*fmgg_b);
  delete fmgg_b;
    
#if 1

  RooRealVar sigma("AIC_s_sigma","",5,0,100);
  if(forceSigma!=-1) {
    sigma.setVal(forceSigma);
    sigma.setConstant(true);
  }
  RooRealVar mu("AIC_s_mu","",126,120,132);
  if(forceMu!=-1) {
    mu.setVal(forceMu);
    mu.setConstant(true);
  }
  RooGaussian sig("AIC_sig_model","",mgg,mu,sigma);
  RooRealVar Nsig("AIC_sb_Ns","",5,0,100);
  RooRealVar Nbkg("AIC_sb_Nb","",100,0,100000);
  
  
  RooRealVar HiggsMass("HiggsMass","",125.1);
  RooRealVar HiggsMassError("HiggsMassError","",0.24);
  RooGaussian HiggsMassConstraint("HiggsMassConstraint","",mu,HiggsMass,HiggsMassError);
  
  
  RooAddPdf fitModel("AIC_sb_model","",RooArgList( b_AIC, sig ),RooArgList(Nbkg,Nsig));

  RooFitResult* sbres;
  RooAbsReal *nll;

  if(constrainMu) {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE),RooFit::ExternalConstraints(RooArgSet(HiggsMassConstraint)));
  } else {
    fitModel.fitTo(data,RooFit::Strategy(0),RooFit::Extended(kTRUE));
    sbres = fitModel.fitTo(data,RooFit::Strategy(2),RooFit::Save(kTRUE),RooFit::Extended(kTRUE));
    nll = fitModel.createNLL(data,RooFit::NumCPU(4),RooFit::Extended(kTRUE));
  }

  assert(nll!=0);
  
  sbres->SetName("AIC_sb_fitres");
  ws->import(*sbres);
  ws->import(fitModel);
  
  RooPlot *fmgg = mgg.frame();
  data.plotOn(fmgg);
  fitModel.plotOn(fmgg);
  ws->pdf("b_AIC")->plotOn(fmgg,RooFit::LineColor(kRed),RooFit::Range("Full"),RooFit::NormRange("Full"));
  fmgg->SetName("AIC_frame");
  ws->import(*fmgg);
  delete fmgg;

  RooMinuit(*nll).migrad();
  
  RooPlot *fNs = Nsig.frame(0,25);
  fNs->SetName("AIC_Nsig_pll");
  RooAbsReal *pll = nll->createProfile(Nsig);
  //nll->plotOn(fNs,RooFit::ShiftToZero(),RooFit::LineColor(kRed));
  pll->plotOn(fNs);
  ws->import(*fNs);
  delete fNs;


  RooPlot *fmu = mu.frame(125,132);
  fmu->SetName("AIC_mu_pll");
  RooAbsReal *pll_mu = nll->createProfile(mu);
  pll_mu->plotOn(fmu);
  ws->import(*fmu);

  delete fmu;

  std::cout << "min AIC: " << minAIC.getVal() << std::endl;
  for(auto t = tags.begin(); t!=tags.end(); t++) {
    RooFormulaVar *AIC = (RooFormulaVar*)ws->obj(*t+"_b_AIC");
    RooRealVar *AICw = ws->var(*t+"_b_AICWeight");
    RooRealVar* k = ws->var(*t+"_b_k");
    printf("%s & %0.0f & %0.2f & %0.2f \\\\\n",t->Data(),k->getVal(),AIC->getVal()-minAIC.getVal(),AICw->getVal());
    //std::cout << k->getVal() << " " << AIC->getVal()-minAIC.getVal() << " " << AICw->getVal() << std::endl;
  }
#endif
  return ws;
}
예제 #14
0
void BackgroundPrediction(std::string pname,int rebin_factor,int model_number = 0,int imass=750, bool plotBands = false)
{
    rebin = rebin_factor;
    std::string fname = std::string("../fitFilesMETPT34/") + pname + std::string("/histos_bkg.root");
    
    stringstream iimass ;
    iimass << imass;
    std::string dirName = "info_"+iimass.str()+"_"+pname;
    
    
    gStyle->SetOptStat(000000000);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    
    setTDRStyle();
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetOptStat(0000);
    
    writeExtraText = true;       // if extra text
    extraText  = "Preliminary";  // default extra text is "Preliminary"
    lumi_13TeV  = "2.7 fb^{-1}"; // default is "19.7 fb^{-1}"
    lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
    
    
    double ratio_tau=-1;
    
    TFile *f=new TFile(fname.c_str());
    TH1F *h_mX_CR_tau=(TH1F*)f->Get("distribs_18_10_1")->Clone("CR_tau");
    TH1F *h_mX_SR=(TH1F*)f->Get("distribs_18_10_0")->Clone("The_SR");
    double maxdata = h_mX_SR->GetMaximum();
    double nEventsSR = h_mX_SR->Integral(600,4000);
    ratio_tau=(h_mX_SR->GetSumOfWeights()/(h_mX_CR_tau->GetSumOfWeights()));
    //double nEventsSR = h_mX_SR->Integral(600,4000);
    
    std::cout<<"ratio tau "<<ratio_tau<<std::endl;
    
    TH1F *h_SR_Prediction;
    TH1F *h_SR_Prediction2;
    
    if(blind) {
        h_SR_Prediction2 = (TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction2");
        h_mX_CR_tau->Rebin(rebin);
        h_mX_CR_tau->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction");
    } else {
        h_SR_Prediction2=(TH1F*)h_mX_SR->Clone("h_SR_Prediction2");
        h_mX_SR->Rebin(rebin);
        h_mX_SR->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_SR->Clone("h_SR_Prediction");
        
    }
    h_SR_Prediction->SetMarkerSize(0.7);
    h_SR_Prediction->GetYaxis()->SetTitleOffset(1.2);
    h_SR_Prediction->Sumw2();
    
    /*TFile *f_sig = new TFile((dirName+"/w_signal_"+iimass.str()+".root").c_str());
    RooWorkspace* xf_sig = (RooWorkspace*)f_sig->Get("Vg");
    RooAbsPdf *xf_sig_pdf = (RooAbsPdf *)xf_sig->pdf((std::string("signal_fixed_")+pname).c_str());
    
    RooWorkspace w_sig("w");
    w_sig.import(*xf_sig_pdf,RooFit::RenameVariable((std::string("signal_fixed_")+pname).c_str(),(std::string("signal_fixed_")+pname+std::string("low")).c_str()),RooFit::RenameAllVariablesExcept("low","x"));
    xf_sig_pdf = w_sig.pdf((std::string("signal_fixed_")+pname+std::string("low")).c_str());
   
    RooArgSet* biasVars = xf_sig_pdf->getVariables();
    TIterator *it = biasVars->createIterator();
    RooRealVar* var = (RooRealVar*)it->Next();
    while (var) {
        var->setConstant(kTRUE);
        var = (RooRealVar*)it->Next();
    }
    */
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    
    RooRealVar nBackground((std::string("bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    RooRealVar nBackground2((std::string("alt_bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    std::string blah = pname;
    //pname=""; //Antibtag=tag to constrain b-tag to the anti-btag shape
    
    
    /* RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 4.2, 0, 200.);
     RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", 4.5, 0, 300.);
     RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", 0.000047, 0, 10.1);
     RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(1-@0/13000,@1)/pow(@0/13000,@2+@3*log(@0/13000)))",RooArgList(x,bg_p0,bg_p1,bg_p2));
   */
    RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 0., -1000, 200.);
    RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", -13, -1000, 1000.);
    RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", -1.4, -1000, 1000.);
    bg_p0.setConstant(kTRUE);
    //RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
    RooGenericPdf bg = RooGenericPdf((std::string("bg_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
  

    /*TF1* biasFunc = new TF1("biasFunc","(0.63*x/1000-1.45)",1350,3600);
    TF1* biasFunc2 = new TF1("biasFunc2","TMath::Min(2.,2.3*x/1000-3.8)",1350,3600);
    double bias_term_s = 0;
    if ((imass > 2450 && blah == "antibtag") || (imass > 1640 && blah == "btag")) {
        if (blah == "antibtag") {
            bias_term_s = 2.7*biasFunc->Eval(imass);
        } else {
            bias_term_s = 2.7*biasFunc2->Eval(imass);
        }
       bias_term_s/=nEventsSR;
    }
    
    RooRealVar bias_term((std::string("bias_term_")+blah).c_str(), "bias_term", 0., -bias_term_s, bias_term_s);
    //bias_term.setConstant(kTRUE);
    RooAddPdf bg((std::string("bg_")+blah).c_str(), "bg_all", RooArgList(*xf_sig_pdf, bg_pure), bias_term);
    */
    string name_output = "CR_RooFit_Exp";
    
    std::cout<<"Nevents "<<nEventsSR<<std::endl;
    RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_SR_Prediction);
    RooFitResult *r_bg=bg.fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save(),RooFit::SumW2Error(kTRUE));
    std::cout<<" --------------------- Building Envelope --------------------- "<<std::endl;
    //std::cout<< "bg_p0_"<< pname << "   param   "<<bg_p0.getVal() <<  " "<<bg_p0.getError()<<std::endl;
    std::cout<< "bg_p1_"<< pname << "   param   "<<bg_p1.getVal() <<  " "<<100*bg_p1.getError()<<std::endl;
    std::cout<< "bg_p2_"<< pname << "   param   "<<bg_p2.getVal() <<  " "<<100*bg_p2.getError()<<std::endl;
    //std::cout<< "bias_term_"<< blah << "   param   0 "<<bias_term_s<<std::endl;
    
    RooPlot *aC_plot=x.frame();
    pred.plotOn(aC_plot, RooFit::MarkerColor(kPink+2));
    if (!plotBands) {
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 2), RooFit::FillColor(kYellow));
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 1), RooFit::FillColor(kGreen));
    }
    bg.plotOn(aC_plot, RooFit::LineColor(kBlue));
    //pred.plotOn(aC_plot, RooFit::LineColor(kBlack), RooFit::MarkerColor(kBlack));
    
    TGraph* error_curve[5]; //correct error bands
    TGraphAsymmErrors* dataGr = new TGraphAsymmErrors(h_SR_Prediction->GetNbinsX()); //data w/o 0 entries

    for (int i=2; i!=5; ++i) {
        error_curve[i] = new TGraph();
    }
    error_curve[2] = (TGraph*)aC_plot->getObject(1)->Clone("errs");
    int nPoints = error_curve[2]->GetN();
    
    error_curve[0] = new TGraph(2*nPoints);
    error_curve[1] = new TGraph(2*nPoints);
    
    error_curve[0]->SetFillStyle(1001);
    error_curve[1]->SetFillStyle(1001);
    
    error_curve[0]->SetFillColor(kGreen);
    error_curve[1]->SetFillColor(kYellow);
    
    error_curve[0]->SetLineColor(kGreen);
    error_curve[1]->SetLineColor(kYellow);
    
    if (plotBands) {
        RooDataHist pred2("pred2", "Prediction from SB", RooArgList(x), h_SR_Prediction2);

        error_curve[3]->SetFillStyle(1001);
        error_curve[4]->SetFillStyle(1001);
        
        error_curve[3]->SetFillColor(kGreen);
        error_curve[4]->SetFillColor(kYellow);
        
        error_curve[3]->SetLineColor(kGreen);
        error_curve[4]->SetLineColor(kYellow);
        
        error_curve[2]->SetLineColor(kBlue);
        error_curve[2]->SetLineWidth(3);
        
        double binSize = rebin;
        
        for (int i=0; i!=nPoints; ++i) {
            double x0,y0, x1,y1;
            error_curve[2]->GetPoint(i,x0,y0);
            
            RooAbsReal* nlim = new RooRealVar("nlim","y0",y0,-100000,100000);
            //double lowedge = x0 - (SR_hi - SR_lo)/double(2*nPoints);
            //double upedge = x0 + (SR_hi - SR_lo)/double(2*nPoints);
            
            double lowedge = x0 - binSize/2.;
            double upedge = x0 + binSize/2.;
            
            x.setRange("errRange",lowedge,upedge);
            
            RooExtendPdf* epdf = new RooExtendPdf("epdf","extpdf",bg, *nlim,"errRange");
            
            // Construct unbinned likelihood
            RooAbsReal* nll = epdf->createNLL(pred2,NumCPU(2));
            // Minimize likelihood w.r.t all parameters before making plots
            RooMinimizer* minim = new RooMinimizer(*nll);
            minim->setMinimizerType("Minuit2");
            minim->setStrategy(2);
            minim->setPrintLevel(-1);
            minim->migrad();
            
            minim->hesse();
            RooFitResult* result = minim->lastMinuitFit();
            double errm = nlim->getPropagatedError(*result);
            
            //std::cout<<x0<<" "<<lowedge<<" "<<upedge<<" "<<y0<<" "<<nlim->getVal()<<" "<<errm<<std::endl;
            
            error_curve[0]->SetPoint(i,x0,(y0-errm));
            error_curve[0]->SetPoint(2*nPoints-i-1,x0,y0+errm);
            
            error_curve[1]->SetPoint(i,x0,(y0-2*errm));
            error_curve[1]->SetPoint(2*nPoints-i-1,x0,(y0+2*errm));
            
            error_curve[3]->SetPoint(i,x0,-errm/sqrt(y0));
            error_curve[3]->SetPoint(2*nPoints-i-1,x0,errm/sqrt(y0));
            
            error_curve[4]->SetPoint(i,x0,-2*errm/sqrt(y0));
            error_curve[4]->SetPoint(2*nPoints-i-1,x0,2*errm/sqrt(y0));
            
        }
        
        int npois = 0;
        dataGr->SetMarkerSize(1.0);
        dataGr->SetMarkerStyle (20);
        
        const double alpha = 1 - 0.6827;
        
        for (int i=0; i!=h_SR_Prediction->GetNbinsX(); ++i){
            if (h_SR_Prediction->GetBinContent(i+1) > 0) {
                
                int N = h_SR_Prediction->GetBinContent(i+1);
                double L =  (N==0) ? 0  : (ROOT::Math::gamma_quantile(alpha/2,N,1.));
                double U =  ROOT::Math::gamma_quantile_c(alpha/2,N+1,1) ;
                
                dataGr->SetPoint(npois,h_SR_Prediction->GetBinCenter(i+1),h_SR_Prediction->GetBinContent(i+1));
                dataGr->SetPointEYlow(npois, N-L);
                dataGr->SetPointEYhigh(npois, U-N);
                npois++;
            }
        }
    }
    
    double xG[2] = {-10,4000};
    double yG[2] = {0.0,0.0};
    TGraph* unityG = new TGraph(2, xG, yG);
    unityG->SetLineColor(kBlue);
    unityG->SetLineWidth(1);

    double xPad = 0.3;
    TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 800*(1.-xPad), 600);
    c_rooFit->SetFillStyle(4000);
    c_rooFit->SetFrameFillColor(0);
    
    TPad *p_1=new TPad("p_1", "p_1", 0, xPad, 1, 1);
    p_1->SetFillStyle(4000);
    p_1->SetFrameFillColor(0);
    p_1->SetBottomMargin(0.02);
    TPad* p_2 = new TPad("p_2", "p_2",0,0,1,xPad);
    p_2->SetBottomMargin((1.-xPad)/xPad*0.13);
    p_2->SetTopMargin(0.03);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    
    int nbins = (int) (SR_hi- SR_lo)/rebin;
    x.setBins(nbins);
    
    std::cout << "chi2(data) " <<  aC_plot->chiSquare()<<std::endl;
    
    //std::cout << "p-value: data     under hypothesis H0:  " << TMath::Prob(chi2_data->getVal(), nbins - 1) << std::endl;
    
    aC_plot->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    aC_plot->GetXaxis()->SetLabelOffset(0.02);
    aC_plot->GetYaxis()->SetRangeUser(0.1, 1000.);
    h_SR_Prediction->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    string rebin_ = itoa(rebin);
    
    aC_plot->GetXaxis()->SetTitle("M_{Z#gamma} [GeV] ");
    aC_plot->GetYaxis()->SetTitle(("Events / "+rebin_+" GeV ").c_str());
    aC_plot->SetMarkerSize(0.7);
    aC_plot->GetYaxis()->SetTitleOffset(1.2);
    aC_plot->Draw();
    
    if (plotBands) {
        error_curve[1]->Draw("Fsame");
        error_curve[0]->Draw("Fsame");
        error_curve[2]->Draw("Lsame");
        dataGr->Draw("p e1 same");
    }
    
    aC_plot->SetTitle("");
    TPaveText *pave = new TPaveText(0.85,0.4,0.67,0.5,"NDC");
    pave->SetBorderSize(0);
    pave->SetTextSize(0.05);
    pave->SetTextFont(42);
    pave->SetLineColor(1);
    pave->SetLineStyle(1);
    pave->SetLineWidth(2);
    pave->SetFillColor(0);
    pave->SetFillStyle(0);
    char name[1000];
    sprintf(name,"#chi^{2}/n = %.2f",aC_plot->chiSquare());
    pave->AddText(name);
    //pave->Draw();
    
    TLegend *leg = new TLegend(0.88,0.65,0.55,0.90,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextSize(0.05);
    leg->SetTextFont(42);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(2);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    h_SR_Prediction->SetMarkerColor(kBlack);
    h_SR_Prediction->SetLineColor(kBlack);
    h_SR_Prediction->SetMarkerStyle(20);
    h_SR_Prediction->SetMarkerSize(1.0);
    //h_mMMMMa_3Tag_SR->GetXaxis()->SetTitleSize(0.09);
    if (blind)
        leg->AddEntry(h_SR_Prediction, "Data: sideband", "ep");
    else {
        if (blah == "antibtag" )
            leg->AddEntry(h_SR_Prediction, "Data: anti-b-tag SR", "ep");
        else
            leg->AddEntry(h_SR_Prediction, "Data: b-tag SR", "ep");
        
    }
    
    leg->AddEntry(error_curve[2], "Fit model", "l");
    leg->AddEntry(error_curve[0], "Fit #pm1#sigma", "f");
    leg->AddEntry(error_curve[1], "Fit #pm2#sigma", "f");
    leg->Draw();
    
    aC_plot->Draw("axis same");
    
    
    CMS_lumi( p_1, iPeriod, iPos );
    
    p_2->cd();
    RooHist* hpull;
    hpull = aC_plot->pullHist();
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetRangeUser(-7,7);
    frameP->GetYaxis()->SetNdivisions(505);
    frameP->GetYaxis()->SetTitle("#frac{(data-fit)}{#sigma_{stat}}");
    
    frameP->GetYaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    frameP->GetYaxis()->SetTitleOffset(1.0/((1.-xPad)/xPad));
    frameP->GetXaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    //frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    frameP->GetYaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    
    
    frameP->Draw();
    if (plotBands) {
        error_curve[4]->Draw("Fsame");
        error_curve[3]->Draw("Fsame");
        unityG->Draw("same");
        hpull->Draw("psame");
        
        frameP->Draw("axis same");
    }
    
    
    c_rooFit->SaveAs((dirName+"/"+name_output+".pdf").c_str());
    
    const int nModels = 9;
    TString models[nModels] = {
        "env_pdf_0_13TeV_dijet2", //0
        "env_pdf_0_13TeV_exp1", //1
        "env_pdf_0_13TeV_expow1", //2
        "env_pdf_0_13TeV_expow2", //3 => skip
        "env_pdf_0_13TeV_pow1", //4
        "env_pdf_0_13TeV_lau1", //5
        "env_pdf_0_13TeV_atlas1", //6
        "env_pdf_0_13TeV_atlas2", //7 => skip
        "env_pdf_0_13TeV_vvdijet1" //8
    };
    
    int nPars[nModels] = {
        2, 1, 2, 3, 1, 1, 2, 3, 2
    };
    
    TString parNames[nModels][3] = {
        "env_pdf_0_13TeV_dijet2_log1","env_pdf_0_13TeV_dijet2_log2","",
        "env_pdf_0_13TeV_exp1_p1","","",
        "env_pdf_0_13TeV_expow1_exp1","env_pdf_0_13TeV_expow1_pow1","",
        "env_pdf_0_13TeV_expow2_exp1","env_pdf_0_13TeV_expow2_pow1","env_pdf_0_13TeV_expow2_exp2",
        "env_pdf_0_13TeV_pow1_p1","","",
        "env_pdf_0_13TeV_lau1_l1","","",
        "env_pdf_0_13TeV_atlas1_coeff1","env_pdf_0_13TeV_atlas1_log1","",
        "env_pdf_0_13TeV_atlas2_coeff1","env_pdf_0_13TeV_atlas2_log1","env_pdf_0_13TeV_atlas2_log2",
        "env_pdf_0_13TeV_vvdijet1_coeff1","env_pdf_0_13TeV_vvdijet1_log1",""
    }
    
    if(bias){
        //alternative model
        gSystem->Load("libHiggsAnalysisCombinedLimit");
        gSystem->Load("libdiphotonsUtils");
        
        TFile *f = new TFile("antibtag_multipdf.root");
        RooWorkspace* xf = (RooWorkspace*)f->Get("wtemplates");
        RooWorkspace *w_alt=new RooWorkspace("Vg");
        for(int i=model_number; i<=model_number; i++){
            RooMultiPdf *alternative = (RooMultiPdf *)xf->pdf("model_bkg_AntiBtag");
            std::cout<<"Number of pdfs "<<alternative->getNumPdfs()<<std::endl;
            for (int j=0; j!=alternative->getNumPdfs(); ++j){
                std::cout<<alternative->getPdf(j)->GetName()<<std::endl;
            }
            RooAbsPdf *alt_bg = alternative->getPdf(alternative->getCurrentIndex()+i);//->clone();
            w_alt->import(*alt_bg, RooFit::RenameVariable(alt_bg->GetName(),("alt_bg_"+blah).c_str()));
            w_alt->Print("V");
            std::cerr<<w_alt->var("x")<<std::endl;
            RooRealVar * range_ = w_alt->var("x");
            range_->setRange(SR_lo,SR_hi);
            char* asd = ("alt_bg_"+blah).c_str()	;
            w_alt->import(nBackground2);
            std::cout<<alt_bg->getVal() <<std::endl;
            w_alt->pdf(asd)->fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());

    	    RooArgSet* altVars = w_alt->pdf(asd)->getVariables();
            TIterator *it2 = altVars->createIterator();
            RooRealVar* varAlt = (RooRealVar*)it2->Next();
            while (varAlt) {
               varAlt->setConstant(kTRUE);
               varAlt = (RooRealVar*)it2->Next();
            }



            alt_bg->plotOn(aC_plot, RooFit::LineColor(i+1), RooFit::LineStyle(i+2));
            p_1->cd();
            aC_plot->GetYaxis()->SetRangeUser(0.01, maxdata*50.);
            aC_plot->Draw("same");
            TH1F *h=new TH1F();
            h->SetLineColor(1+i);
            h->SetLineStyle(i+2);
            leg->AddEntry(h, alt_bg->GetName(), "l");
            
            
            w_alt->SaveAs((dirName+"/w_background_alternative.root").c_str());
        }
        leg->Draw();
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+blah+"_multipdf.pdf").c_str());
        
        for (int i=0; i!=nPars[model_number]; ++i) {
            std::cout<<parNames[model_number][i]<<" param "<< w_alt->var(parNames[model_number][i])->getVal()<<"   "<<w_alt->var(parNames[model_number][i])->getError()<<std::endl;
        }
        
        
    } else {
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+"_log.pdf").c_str());
    }
    
    RooWorkspace *w=new RooWorkspace("Vg");
    w->import(bg);
    w->import(nBackground);
    w->SaveAs((dirName+"/w_background_GaussExp.root").c_str());
    
    TH1F *h_mX_SR_fakeData=(TH1F*)h_mX_SR->Clone("h_mX_SR_fakeData");
    h_mX_SR_fakeData->Scale(nEventsSR/h_mX_SR_fakeData->GetSumOfWeights());
    RooDataHist data_obs("data_obs", "Data", RooArgList(x), h_mX_SR_fakeData);
    std::cout<<" Background number of events = "<<nEventsSR<<std::endl;
    RooWorkspace *w_data=new RooWorkspace("Vg");
    w_data->import(data_obs);
    w_data->SaveAs((dirName+"/w_data.root").c_str());
    
}
예제 #15
0
void rf308_normintegration2d()
{
  // S e t u p   m o d e l 
  // ---------------------

  // Create observables x,y
  RooRealVar x("x","x",-10,10) ;
  RooRealVar y("y","y",-10,10) ;

  // Create p.d.f. gaussx(x,-2,3), gaussy(y,2,2) 
  RooGaussian gx("gx","gx",x,RooConst(-2),RooConst(3)) ;
  RooGaussian gy("gy","gy",y,RooConst(+2),RooConst(2)) ;

  // Create gxy = gx(x)*gy(y)
  RooProdPdf gxy("gxy","gxy",RooArgSet(gx,gy)) ;



  // R e t r i e v e   r a w  &   n o r m a l i z e d   v a l u e s   o f   R o o F i t   p . d . f . s
  // --------------------------------------------------------------------------------------------------

  // Return 'raw' unnormalized value of gx
  cout << "gxy = " << gxy.getVal() << endl ;
  
  // Return value of gxy normalized over x _and_ y in range [-10,10]
  RooArgSet nset_xy(x,y) ;
  cout << "gx_Norm[x,y] = " << gxy.getVal(&nset_xy) << endl ;

  // Create object representing integral over gx
  // which is used to calculate  gx_Norm[x,y] == gx / gx_Int[x,y]
  RooAbsReal* igxy = gxy.createIntegral(RooArgSet(x,y)) ;
  cout << "gx_Int[x,y] = " << igxy->getVal() << endl ;

  // NB: it is also possible to do the following

  // Return value of gxy normalized over x in range [-10,10] (i.e. treating y as parameter)
  RooArgSet nset_x(x) ;
  cout << "gx_Norm[x] = " << gxy.getVal(&nset_x) << endl ;

  // Return value of gxy normalized over y in range [-10,10] (i.e. treating x as parameter)
  RooArgSet nset_y(y) ;
  cout << "gx_Norm[y] = " << gxy.getVal(&nset_y) << endl ;



  // I n t e g r a t e   n o r m a l i z e d   p d f   o v e r   s u b r a n g e
  // ----------------------------------------------------------------------------

  // Define a range named "signal" in x from -5,5
  x.setRange("signal",-5,5) ;
  y.setRange("signal",-3,3) ;
  
  // Create an integral of gxy_Norm[x,y] over x and y in range "signal"
  // This is the fraction of of p.d.f. gxy_Norm[x,y] which is in the
  // range named "signal"
  RooAbsReal* igxy_sig = gxy.createIntegral(RooArgSet(x,y),NormSet(RooArgSet(x,y)),Range("signal")) ;
  cout << "gx_Int[x,y|signal]_Norm[x,y] = " << igxy_sig->getVal() << endl ;




  // C o n s t r u c t   c u m u l a t i v e   d i s t r i b u t i o n   f u n c t i o n   f r o m   p d f
  // -----------------------------------------------------------------------------------------------------

  // Create the cumulative distribution function of gx
  // i.e. calculate Int[-10,x] gx(x') dx'
  RooAbsReal* gxy_cdf = gxy.createCdf(RooArgSet(x,y)) ;
  
  // Plot cdf of gx versus x
  TH1* hh_cdf = gxy_cdf->createHistogram("hh_cdf",x,Binning(40),YVar(y,Binning(40))) ;
  hh_cdf->SetLineColor(kBlue) ;

  new TCanvas("rf308_normintegration2d","rf308_normintegration2d",600,600) ;
  gPad->SetLeftMargin(0.15) ; hh_cdf->GetZaxis()->SetTitleOffset(1.8) ; 
  hh_cdf->Draw("surf") ;

}
예제 #16
0
void Raa3S_Workspace(const char* name_pbpb="chad_ws_fits/centFits/ws_PbPbData_262548_263757_0cent10_0.0pt50.0_0.0y2.4.root", const char* name_pp="chad_ws_fits/centFits/ws_PPData_262157_262328_-1cent1_0.0pt50.0_0.0y2.4.root", const char* name_out="fitresult_combo.root"){

   //TFile File(filename);

   //RooWorkspace * ws = test_combine(name_pbpb, name_pp);

   TFile *f = new TFile("fitresult_combo_333.root") ;
   RooWorkspace * ws1 = (RooWorkspace*) f->Get("wcombo");

   //File.GetObject("wcombo", ws);
   ws1->Print();
   RooAbsData * data = ws1->data("data"); //dataOS, dataSS

   // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus");
   // US_data->SetName("US_data");
   // ws->import(* US_data);
   // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi");
   // hi_data->SetName("hi_data");
   // ws->import(* hi_data);
   // hi_data->Print();

   RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,-1,1);
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge));
   ws1->import(step);
   ws1->factory( "Uniform::flat(raa3)" );

   //pp Luminosities, Taa and efficiency ratios Systematics

   ws1->factory( "Taa_hi[5.662e-9]" );
   ws1->factory( "Taa_kappa[1.062]" ); // was 1.057
   ws1->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" );
   ws1->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" );
   ws1->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" );

   ws1->factory( "lumipp_hi[5.4]" );
   ws1->factory( "lumipp_kappa[1.037]" ); // was 1.06
   ws1->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" );
   ws1->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" );
   ws1->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" );

   // ws->factory( "effRat1[1]" );
   // ws->factory( "effRat2[1]" );
   ws1->factory( "effRat3_hi[0.95]" );
   ws1->factory( "effRat_kappa[1.054]" );
   ws1->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" );
   // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" );
   ws1->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" );
   // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" );
   ws1->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" );
   //  
   ws1->factory("Nmb_hi[1.161e9]");
   ws1->factory("prod::denominator(Taa_nom,Nmb_hi)");
   ws1->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)");
   RooAbsReal *lumiOverTaaNmbmodified = ws1->function("lumiOverTaaNmbmodified"); //RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified");
   //  
   //  RooRealVar *raa1 = ws->var("raa1");
   //  RooRealVar* nsig1_pp = ws->var("nsig1_pp");
   //  RooRealVar* effRat1 = ws->function("effRat1_nom");
   //  RooRealVar *raa2 = ws->var("raa2");
   //  RooRealVar* nsig2_pp = ws->var("nsig2_pp");
   //  RooRealVar* effRat2 = ws->function("effRat2_nom");
   RooRealVar* nsig3_pp = ws1->var("R_{#frac{3S}{1S}}_pp"); //RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   cout << nsig3_pp << endl;
   RooAbsReal* effRat3 = ws1->function("effRat3_nom"); //RooRealVar* effRat3 = ws->function("effRat3_nom");
   //  
   //  RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));
   //  ws->import(nsig1_hi_modified);
   //  RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));
   //  ws->import(nsig2_hi_modified);
   RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));
   ws1->import(nsig3_hi_modified);

   //  // background yield with systematics
   ws1->factory( "nbkg_hi_kappa[1.10]" );
   ws1->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" );
   ws1->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" );
   ws1->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" );
   RooAbsPdf* sig1S_hi = ws1->pdf("sig1S_hi"); //RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi");
   RooAbsPdf* sig2S_hi = ws1->pdf("sig2S_hi");
   RooAbsPdf* sig3S_hi = ws1->pdf("sig3S_hi");
   RooAbsPdf* LSBackground_hi = ws1->pdf("nbkg_hi_nom");
   RooRealVar* nsig1_hi = ws1->var("N_{#Upsilon(1S)}_hi");
   RooRealVar* nsig2_hi = ws1->var("R_{#frac{2S}{1S}}_hi");
   RooAbsReal* nsig3_hi = ws1->function("nsig3_hi_modified"); //RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified");
   cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl;
   RooRealVar* norm_nbkg_hi = ws1->var("n_{Bkgd}_hi");

   RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);
   RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);

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

   ws1->factory( "nbkg_pp_kappa[1.03]" );
   ws1->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" );
   ws1->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" );
   ws1->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" );
   RooAbsPdf* sig1S_pp = ws1->pdf("sig1S_pp"); //RooAbsPdf* sig1S_pp = ws1->pdf("cbcb_pp");
   RooAbsPdf* sig2S_pp = ws1->pdf("sig2S_pp");
   RooAbsPdf* sig3S_pp = ws1->pdf("sig3S_pp");
   RooAbsPdf* LSBackground_pp = ws1->pdf("nbkg_pp_nom");
   RooRealVar* nsig1_pp = ws1->var("N_{#Upsilon(1S)}_pp");
   RooRealVar* nsig2_pp = ws1->var("R_{#frac{2S}{1S}}_pp"); //RooRealVar* nsig2_pp = ws1->var("N_{#Upsilon(2S)}_pp");
   // RooRealVar* nsig3_pp = ws1->var("N_{#Upsilon(3S)}_pp");
   RooRealVar* norm_nbkg_pp = ws1->var("n_{Bkgd}_pp");

   RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);
   RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);

   RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); 
   ws1->import(model_num);
   ws1->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)");

   RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); 
   ws1->import(model_den);
   ws1->factory("PROD::model_pp(model_den, constr_nbkg_pp)");

   ws1->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)");



   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws1->var("invariantMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws1->cat("dataCat"));    
   //  /////////////////////////////////////////////////////////////////////
   ws1->var("glob_lumipp")->setConstant(true);
   ws1->var("glob_Taa")->setConstant(true);
   ws1->var("glob_effRat")->setConstant(true);
   ws1->var("glob_nbkg_pp")->setConstant(true);
   ws1->var("glob_nbkg_hi")->setConstant(true);
   RooArgSet globalObs("global_obs");
   globalObs.add( *ws1->var("glob_lumipp") );
   globalObs.add( *ws1->var("glob_Taa") );
   globalObs.add( *ws1->var("glob_effRat") );
   globalObs.add( *ws1->var("glob_nbkg_hi") );
   globalObs.add( *ws1->var("glob_nbkg_pp") );
   cout << "66666" << endl;

   // ws1->Print();

   RooArgSet poi("poi");
   poi.add( *ws1->var("raa3") );



   cout << "77777" << endl;
   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   nuis.add( *ws1->var("beta_lumipp") );
   nuis.add( *ws1->var("beta_nbkg_hi") );
   nuis.add( *ws1->var("beta_nbkg_pp") );
   nuis.add( *ws1->var("beta_Taa") );
   nuis.add( *ws1->var("beta_effRat") );

   cout << "88888" << endl;
   ws1->var("#alpha_{CB}_hi")->setConstant(true);
   ws1->var("#alpha_{CB}_pp")->setConstant(true);
   ws1->var("#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB1}_pp")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true);
   //ws1->var("Centrality")->setConstant(true); //delete
   ws1->var("N_{#varUpsilon(1S)}_hi")->setConstant(true);
   ws1->var("N_{#varUpsilon(1S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_hi")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(3S)}_pp")->setConstant(true);

   ws1->var("R_{#frac{2S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{2S}{1S}}_pp")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_pp")->setConstant(true); //new

   ws1->var("Nmb_hi")->setConstant(true);
   // ws1->var("QQsign")->setConstant(true);
   ws1->var("Taa_hi")->setConstant(true);
   ws1->var("Taa_kappa")->setConstant(true);
   // ws1->var("beta_Taa")->setConstant(true);
   // ws1->var("beta_effRat")->setConstant(true);
   // ws1->var("beta_lumipp")->setConstant(true);
   // ws1->var("beta_nbkg_hi")->setConstant(true);
   // ws1->var("beta_nbkg_pp")->setConstant(true);
   // ws1->var("dataCat")->setConstant(true);
   ws1->var("decay_hi")->setConstant(true);
   ws1->var("decay_pp")->setConstant(true);
   ws1->var("effRat3_hi")->setConstant(true);
   ws1->var("effRat_kappa")->setConstant(true);
   // ws1->var("glob_Taa")->setConstant(true);
   // ws1->var("glob_effRat")->setConstant(true);
   // ws1->var("glob_lumipp")->setConstant(true);
   // ws1->var("glob_nbkg_hi")->setConstant(true);
   // ws1->var("glob_nbkg_pp")->setConstant(true);
   // ws1->var("invariantMass")->setConstant(true);
   ws1->var("leftEdge")->setConstant(true);
   ws1->var("lumipp_hi")->setConstant(true);
   ws1->var("lumipp_kappa")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_hi")->setConstant(true); //ws1->var("mass1S_hi")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_pp")->setConstant(true); //ws1->var("mass1S_pp")->setConstant(true);
   ws1->var("muMinusPt")->setConstant(true);
   ws1->var("muPlusPt")->setConstant(true);
   ws1->var("n_{Bkgd}_hi")->setConstant(true);
   ws1->var("n_{Bkgd}_pp")->setConstant(true);
   ws1->var("nbkg_hi_kappa")->setConstant(true);
   ws1->var("nbkg_pp_kappa")->setConstant(true);
   //ws1->var("n_{CB}")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_hi")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_pp")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   // ws1->var("raa3")->setConstant(true);
   ws1->var("rightEdge")->setConstant(true);
   ws1->var("sigmaFraction_hi")->setConstant(true);
   ws1->var("sigmaFraction_pp")->setConstant(true);
   ws1->var("turnOn_hi")->setConstant(true);
   ws1->var("turnOn_pp")->setConstant(true);
   ws1->var("dimuPt")->setConstant(true); //ws1->var("upsPt")->setConstant(true);
   ws1->var("dimuRapidity")->setConstant(true); //ws1->var("upsRapidity")->setConstant(true);
   ws1->var("vProb")->setConstant(true);
   ws1->var("width_hi")->setConstant(true);
   ws1->var("width_pp")->setConstant(true);
   // ws1->var("x3raw")->setConstant(true);
   //  RooArgSet fixed_again("fixed_again");
   //  fixed_again.add( *ws1->var("leftEdge") );
   //  fixed_again.add( *ws1->var("rightEdge") );
   //  fixed_again.add( *ws1->var("Taa_hi") );
   //  fixed_again.add( *ws1->var("Nmb_hi") );
   //  fixed_again.add( *ws1->var("lumipp_hi") );
   //  fixed_again.add( *ws1->var("effRat1_hi") );
   //  fixed_again.add( *ws1->var("effRat2_hi") );
   //  fixed_again.add( *ws1->var("effRat3_hi") );
   //  fixed_again.add( *ws1->var("nsig3_pp") );
   //  fixed_again.add( *ws1->var("nsig1_pp") );
   //  fixed_again.add( *ws1->var("nbkg_hi") );
   //  fixed_again.add( *ws1->var("alpha") );
   //  fixed_again.add( *ws1->var("nbkg_kappa") );
   //  fixed_again.add( *ws1->var("Taa_kappa") );
   //  fixed_again.add( *ws1->var("lumipp_kappa") );
   // fixed_again.add( *ws1->var("mean_hi") );
   // fixed_again.add( *ws1->var("mean_pp") );
   // fixed_again.add( *ws1->var("width_hi") );
   // fixed_again.add( *ws1->var("turnOn_hi") );
   // fixed_again.add( *ws1->var("bkg_a1_pp") );
   // fixed_again.add( *ws1->var("bkg_a2_pp") );
   // fixed_again.add( *ws1->var("decay_hi") );
   // fixed_again.add( *ws1->var("raa1") );
   // fixed_again.add( *ws1->var("raa2") );
   //  fixed_again.add( *ws1->var("nsig2_pp") );
   // fixed_again.add( *ws1->var("sigma1") );
   //  fixed_again.add( *ws1->var("nbkg_pp") );
   // fixed_again.add( *ws1->var("npow") );
   // fixed_again.add( *ws1->var("muPlusPt") );
   // fixed_again.add( *ws1->var("muMinusPt") );
   // fixed_again.add( *ws1->var("mscale_hi") );
   // fixed_again.add( *ws1->var("mscale_pp") );
   //  
   // ws1->Print();
   cout << "99999" << endl;

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

   // ws1->Print();
   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(10) );
   cout << "111111" << endl;
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   cout << "444444" << endl;
   RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3"));
   cout << "222222" << endl;
   pNll->plotOn(framepoi,ShiftToZero());
   cout << "333333" << endl;
   
   RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
   pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
   pProfile->plotOn(framepoi,LineColor(kRed));
   framepoi->SetMinimum(0);
   framepoi->SetMaximum(3);
   TCanvas *cpoi = new TCanvas();
   cpoi->cd(); framepoi->Draw();
   cpoi->SaveAs("cpoi.pdf");

   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
   // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeSB = pObs->frame(Title("SBhypo"));
   data->plotOn(xframeSB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfSB = sbHypo.GetPdf();
   RooCategory *dataCat = ws1->cat("dataCat");
   pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c1 = new TCanvas();
   c1->cd(); xframeSB->Draw();
   c1->SaveAs("c1.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;
   ws1->import( sbHypo );
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws1);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set raa3=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeB = pObs->frame(Title("Bhypo"));
   data->plotOn(xframeB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfB = bHypo.GetPdf();
   pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c2 = new TCanvas();
   c2->cd(); xframeB->Draw();
   c2->SaveAs("c2.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws1);
   ws1->import( bHypo );
   /////////////////////////////////////////////////////////////////////
   ws1->Print();
   bHypo.Print();
   sbHypo.Print();

   // save workspace to file
   ws1 -> SaveAs(name_out);

   return;
}
예제 #17
0
void results2tree(
      const char* workDirName, 
      bool isMC=false,
      const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg"
      ) {
   // workDirName: usual tag where to look for files in Output
   // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all

   TFile *f = new TFile(treeFileName(workDirName,isMC),"RECREATE");
   TTree *tr = new TTree("fitresults","fit results");


   // bin edges
   float ptmin, ptmax, ymin, ymax, centmin, centmax;
   // model names
   Char_t jpsiName[128], psipName[128], bkgName[128];
   // collision system
   Char_t collSystem[8];
   // goodness of fit
   float nll, chi2, normchi2; int npar, ndof;
   // parameters to store: make it a vector
   vector<poi> thePois;
   TString thePoiNamesStr(thePoiNames);
   TString t; Int_t from = 0;
   while (thePoiNamesStr.Tokenize(t, from , ",")) {
      poi p; strcpy(p.name, t.Data());
      cout << p.name << endl;
      thePois.push_back(p);
   }

   // create tree branches
   tr->Branch("ptmin",&ptmin,"ptmin/F");
   tr->Branch("ptmax",&ptmax,"ptmax/F");
   tr->Branch("ymin",&ymin,"ymin/F");
   tr->Branch("ymax",&ymax,"ymax/F");
   tr->Branch("centmin",&centmin,"centmin/F");
   tr->Branch("centmax",&centmax,"centmax/F");
   tr->Branch("jpsiName",jpsiName,"jpsiName/C");
   tr->Branch("psipName",psipName,"psipName/C");
   tr->Branch("bkgName",bkgName,"bkgName/C");
   tr->Branch("collSystem",collSystem,"collSystem/C");
   tr->Branch("nll",&nll,"nll/F");
   tr->Branch("chi2",&chi2,"chi2/F");
   tr->Branch("normchi2",&normchi2,"normchi2/F");
   tr->Branch("npar",&npar,"npar/I");
   tr->Branch("ndof",&ndof,"ndof/I");

   for (vector<poi>::iterator it=thePois.begin(); it!=thePois.end(); it++) {
      tr->Branch(Form("%s_val",it->name),&(it->val),Form("%s_val/F",it->name));
      tr->Branch(Form("%s_err",it->name),&(it->err),Form("%s_err/F",it->name));
   }

   // list of files
   vector<TString> theFiles = fileList(workDirName,"",isMC);

   int cnt=0;
   for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) {
      cout << "Parsing file " << cnt << " / " << theFiles.size() << ": " << *it << endl;

      // parse the file name to get info
      anabin thebin = binFromFile(*it);
      ptmin = thebin.ptbin().low();
      ptmax = thebin.ptbin().high();
      ymin = thebin.rapbin().low();
      ymax = thebin.rapbin().high();
      centmin = thebin.centbin().low();
      centmax = thebin.centbin().high();
      strcpy(collSystem, (it->Index("PbPb")>0) ? "PbPb" : "PP");

      // get the model names
      from = 0;
      bool catchjpsi=false, catchpsip=false, catchbkg=false;
      while (it->Tokenize(t, from, "_")) {
         if (catchjpsi) {strcpy(jpsiName, t.Data()); catchjpsi=false;}
         if (catchpsip) {strcpy(psipName, t.Data()); catchpsip=false;}
         if (catchbkg) {strcpy(bkgName, t.Data()); catchbkg=false;}
         if (t=="Jpsi") catchjpsi=true;
         if (t=="Psi2S") catchpsip=true;
         if (t=="Bkg") catchbkg=true;
      }

      TFile *f = new TFile(*it); RooWorkspace *ws = NULL;
      if (!f) {
         cout << "Error, file " << *it << " does not exist." << endl;
      } else {
         ws = (RooWorkspace*) f->Get("workspace");
         if (!ws) {
            cout << "Error, workspace not found in " << *it << "." << endl;
         }
      }

      nll=0; chi2=0; npar=0; ndof=0;
      if (f && ws) {
         // get the model for nll and npar
         RooAbsPdf *model = pdfFromWS(ws, Form("_%s",collSystem), "pdfMASS_Tot");
         if (model) {
            RooAbsData *dat = dataFromWS(ws, Form("_%s",collSystem), "dOS_DATA");
            if (dat) {
               RooAbsReal *NLL = model->createNLL(*dat);
               if (NLL) nll = NLL->getVal();
               npar = model->getParameters(dat)->selectByAttrib("Constant",kFALSE)->getSize();

               // compute the chi2 and the ndof
               RooPlot* frame = ws->var("invMass")->frame(Bins(nBins));
               dat->plotOn(frame);
               model->plotOn(frame);
               TH1 *hdatact = dat->createHistogram("hdatact", *(ws->var("invMass")), Binning(nBins));
               RooHist *hpull = frame->pullHist(0,0, true);
               double* ypulls = hpull->GetY();
               unsigned int nFullBins = 0;
               for (int i = 0; i < nBins; i++) {
                  if (hdatact->GetBinContent(i+1) > 0.0) {
                     chi2 += ypulls[i]*ypulls[i];
                     nFullBins++;
                  }
               }
               ndof = nFullBins - npar;
               normchi2 = chi2/ndof;
            }
         }

         // get the POIs
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            RooRealVar *thevar = poiFromWS(ws, Form("_%s",collSystem), itpoi->name);
            itpoi->val = thevar ? thevar->getVal() : 0;
            itpoi->err = thevar ? thevar->getError() : 0;
         }

         f->Close();
         delete f;
      } else {
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            itpoi->val = 0;
            itpoi->err = 0;
         }
      }

      // fill the tree
      tr->Fill();
      cnt++;
   } // loop on the files

   f->Write();
   f->Close();
}
예제 #18
0
void Purity_1d_fit(int type = 0){
  TChain* tree = new TChain("TEvent");
  if(!type) tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_gen_0-1_full.root");
  else      tree->Add("/home/vitaly/B0toDh0/TMVA/FIL_b2dh_data.root");

  RooCategory b0f("b0f","b0f");
  b0f.defineType("signal",1);
  b0f.defineType("fsr",10);
  b0f.defineType("bad_pi0",5);
  b0f.defineType("rho",3);
  b0f.defineType("comb",-1);

  RooArgSet argset;

  const double deMin = -0.15;
  const double deMax = 0.3;

  RooRealVar mbc("mbc","M_{bc}",mbc_min,mbc_max,"GeV"); argset.add(mbc);
  RooRealVar de("de","#DeltaE",deMin,deMax,"GeV"); argset.add(de);
  de.setRange("Signal",de_min,de_max);
  RooRealVar md("md","md",DMass-md_cut,DMass+md_cut,"GeV"); argset.add(md);
  RooRealVar mk("mk","mk",KMass-mk_cut,KMass+mk_cut,"GeV"); argset.add(mk);
  RooRealVar mpi0("mpi0","mpi0",Pi0Mass-mpi0_cut,Pi0Mass+mpi0_cut,"GeV"); argset.add(mpi0);
  RooRealVar bdtgs("bdtgs","bdtgs",bdtgs_cut,1.); argset.add(bdtgs);
  RooRealVar atckpi_max("atckpi_max","atckpi_max",0.,atckpi_cut); argset.add(atckpi_max);

  if(!type) argset.add(b0f);

  RooDataSet ds("ds","ds",tree,argset,"mbc>0||mbc<=0");
//  RooDataSet* ds0 = ds.reduce(RooArgSet(de));
  
  stringstream out;
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");

    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }

//  RooDataHist* dh = ds0->binnedClone();

//  ds0->Print();

  ////////////////
  // Signal PDF //
  ////////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar de0("de0","de0",m_de0,-0.1,0.1); if(cSig) de0.setConstant(kTRUE);
  RooRealVar s1("s1","s1",m_s1,0.,0.5); if(cSig) s1.setConstant(kTRUE);
  RooGaussian g1("g1","g1",de,de0,s1);

  RooRealVar deCBl("deCBl","deCBl",m_deCBl,-0.1,0.1); if(cSig) deCBl.setConstant(kTRUE);
  RooRealVar sCBl("sCBl","sCBl",m_sCBl,0.,0.5); if(cSig) sCBl.setConstant(kTRUE);
  RooRealVar nl("nl","nl",m_nl,0.,100.); if(cSig) nl.setConstant(kTRUE);
  RooRealVar alphal("alphal","alphal",m_alphal,-10.,10.); if(cSig) alphal.setConstant(kTRUE);

  RooRealVar deCBr("deCBr","deCBr",m_deCBr,-0.1,0.1); if(cSig) deCBr.setConstant(kTRUE);
  RooRealVar sCBr("sCBr","sCBr",m_sCBr,0.,0.5); if(cSig) sCBr.setConstant(kTRUE);
  RooRealVar nr("nr","nr",m_nr,0.,100.); if(cSig) nr.setConstant(kTRUE);
  RooRealVar alphar("alphar","alphar",m_alphar,-10.,10.); if(cSig) alphar.setConstant(kTRUE);

  RooCBShape CBl("CBl","CBl",de,deCBl,sCBl,alphal,nl);
  RooCBShape CBr("CBr","CBr",de,deCBr,sCBr,alphar,nr);

  RooRealVar fCBl("fCBl","fCBl",m_fCBl,0.,1.); if(cSig) fCBl.setConstant(kTRUE);
  RooRealVar fCBr("fCBr","fCBr",m_fCBr,0.,1.); if(cSig) fCBr.setConstant(kTRUE);

  RooAddPdf pdf_sig("pdf_sig","pdf_sig",RooArgList(CBl,CBr,g1),RooArgSet(fCBl,fCBr));

  //////////////
  // Comb PDF //
  //////////////
  ////////////
  // de pdf //
  ////////////
  RooRealVar c1("c1","c1",mc_c1_1d,-10.,10.); if(cComb) c1.setConstant(kTRUE);
  RooRealVar c2("c2","c2",mc_c2_1d,-10.,10.); if(cComb) c2.setConstant(kTRUE);
  RooChebychev pdf_comb("pdf_comb","pdf_comb",de,RooArgSet(c1,c2));

  /////////////
  // Rho PDF //
  /////////////
  ////////////
  // de pdf //
  ////////////
if(de_rho_param == 0){
  RooRealVar exppar("exppar","exppar",mr_exppar,-40.,-25.);// if(cRho) exppar.setConstant(kTRUE);
  RooExponential pdf_rho("pdf_rho","pdf_rho",de,exppar);
  }
  
  RooRealVar de0r("de0r","de0r",mr_de0r,-0.2,0.12); if(cRho) de0r.setConstant(kTRUE);
  
  if(de_rho_param == 1){
   RooRealVar slopel("slopel","slopel",mr_slopel,-1000,-500.); if(cRho) slopel.setConstant(kTRUE);
   RooRealVar sloper("sloper","sloper",mr_sloper,-10000,0.); if(cRho) sloper.setConstant(kTRUE);
   RooRealVar steep("steep","steep",mr_steep,7.,9.); if(cRho) steep.setConstant(kTRUE);
   RooRealVar p5("p5","p5",mr_p5,0.01,1000.); if(cRho) p5.setConstant(kTRUE);
   RooRhoDeltaEPdf pdf_rho("pdf_rho","pdf_rho",de,de0r,slopel,sloper,steep,p5);
  }
  
  if(de_rho_param == -1){
   RooRealVar x0("x0","x0",mr_x0_1d,-0.2,0.12); if(cRho) x0.setConstant(kTRUE);
   RooRealVar p1("p1","p1",mr_p1_1d,-1000.,100.); if(cRho) p1.setConstant(kTRUE);
   RooRealVar p2("p2","p2",mr_p2_1d,0.,100.); if(cRho) p2.setConstant(kTRUE);
   RooGenericPdf pdf_rho("pdf_rho","1+@0*@1-@2*TMath::Log(1+TMath::Exp(@2*(@0-@1)/@3))",RooArgSet(de,x0,p1,p2));
  }
  //////////////////
  // Complete PDF //
  //////////////////
  RooRealVar Nsig("Nsig","Nsig",700,100.,1500.);// fsig.setConstant(kTRUE);
  RooRealVar Nrho("Nrho","Nrho",400,100,1500.);// frho.setConstant(kTRUE);
  RooRealVar Ncmb("Ncmb","Ncmb",1000,100,100000);// frho.setConstant(kTRUE);
  RooAddPdf pdf("pdf","pdf",RooArgList(pdf_sig,pdf_rho,pdf_comb),RooArgList(Nsig,Nrho,Ncmb));

  pdf.fitTo(ds,Verbose(),Timer(true));

   RooAbsReal* intSig  = pdf_sig.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intRho  = pdf_rho.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   RooAbsReal* intCmb  = pdf_comb.createIntegral(RooArgSet(de),NormSet(RooArgSet(de)),Range("Signal"));
   const double nsig = intSig->getVal()*Nsig.getVal();
   const double nsig_err = intSig->getVal()*Nsig.getError();
   const double nsig_err_npq = TMath::Sqrt(nsig*(Nsig.getVal()-nsig)/Nsig.getVal());
   const double nsig_err_total = TMath::Sqrt(nsig_err*nsig_err+nsig_err_npq*nsig_err_npq);
   const double nrho = intRho->getVal()*Nrho.getVal();
   const double nrho_err = intRho->getVal()*Nrho.getError();
   const double nrho_err_npq = TMath::Sqrt(nrho*(Nrho.getVal()-nrho)/Nrho.getVal());
   const double nrho_err_total = TMath::Sqrt(nrho_err*nrho_err+nrho_err_npq*nrho_err_npq);
   const double ncmb = intCmb->getVal()*Ncmb.getVal();
   const double ncmb_err = intCmb->getVal()*Ncmb.getError();
   const double ncmb_err_npq = TMath::Sqrt(ncmb*(Ncmb.getVal()-ncmb)/Ncmb.getVal());
   const double ncmb_err_total = TMath::Sqrt(ncmb_err*ncmb_err+ncmb_err_npq*ncmb_err_npq);
   const double purity = nsig/(nsig+nrho+ncmb);
   const double purity_err = nsig_err_total/(nsig+nrho+ncmb);
   cout << "Nsig = " << nsig <<" +- " << nsig_err << endl;
   cout << "Nrho = " << nrho <<" +- " << nrho_err << endl;
   cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << endl;
   
  /////////////
  //  Plots  //
  /////////////
  // de //
  RooPlot* deFrame = de.frame();
  ds.plotOn(deFrame,DataError(RooAbsData::SumW2),MarkerSize(1));
  pdf.plotOn(deFrame,Components(pdf_sig),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_rho),LineStyle(kDashed));
  pdf.plotOn(deFrame,Components(pdf_comb),LineStyle(kDashed));
  pdf.plotOn(deFrame,LineWidth(2));

  RooHist* hdepull = deFrame->pullHist();
  RooPlot* dePull = de.frame(Title("#Delta E pull distribution"));
  dePull->addPlotable(hdepull,"P");
  dePull->GetYaxis()->SetRangeUser(-5,5);

  TCanvas* cm = new TCanvas("Delta E","Delta E",600,700);
  cm->cd();

  TPad *pad3 = new TPad("pad3","pad3",0.01,0.20,0.99,0.99);
  TPad *pad4 = new TPad("pad4","pad4",0.01,0.01,0.99,0.20);
  pad3->Draw();
  pad4->Draw();

  pad3->cd();
  pad3->SetLeftMargin(0.15);
  pad3->SetFillColor(0);

  deFrame->GetXaxis()->SetTitleSize(0.05);
  deFrame->GetXaxis()->SetTitleOffset(0.85);
  deFrame->GetXaxis()->SetLabelSize(0.04);
  deFrame->GetYaxis()->SetTitleOffset(1.6);
  deFrame->Draw();

  stringstream out1;
  TPaveText *pt = new TPaveText(0.6,0.75,0.98,0.9,"brNDC");
  pt->SetFillColor(0);
  pt->SetTextAlign(12);
  out1.str("");
  out1 << "#chi^{2}/n.d.f = " << deFrame->chiSquare();
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "S: " << (int)(nsig+0.5) << " #pm " << (int)(nsig_err_total+0.5);
  pt->AddText(out1.str().c_str());
  out1.str("");
  out1 << "Purity: " << std::fixed << std::setprecision(2) << purity*100. << " #pm " << purity_err*100;
  pt->AddText(out1.str().c_str());
  pt->Draw();

  TLine *de_line_RIGHT = new TLine(de_max,0,de_max,50);
  de_line_RIGHT->SetLineColor(kRed);
  de_line_RIGHT->SetLineStyle(1);
  de_line_RIGHT->SetLineWidth((Width_t)2.);
  de_line_RIGHT->Draw();
  TLine *de_line_LEFT = new TLine(de_min,0,de_min,50);
  de_line_LEFT->SetLineColor(kRed);
  de_line_LEFT->SetLineStyle(1);
  de_line_LEFT->SetLineWidth((Width_t)2.);
  de_line_LEFT->Draw();

  pad4->cd(); pad4->SetLeftMargin(0.15); pad4->SetFillColor(0);
  dePull->SetMarkerSize(0.05); dePull->Draw();
  TLine *de_lineUP = new TLine(deMin,3,deMax,3);
  de_lineUP->SetLineColor(kBlue);
  de_lineUP->SetLineStyle(2);
  de_lineUP->Draw();
  TLine *de_line = new TLine(deMin,0,deMax,0);
  de_line->SetLineColor(kBlue);
  de_line->SetLineStyle(1);
  de_line->SetLineWidth((Width_t)2.);
  de_line->Draw();
  TLine *de_lineDOWN = new TLine(deMin,-3,deMax,-3);
  de_lineDOWN->SetLineColor(kBlue);
  de_lineDOWN->SetLineStyle(2);
  de_lineDOWN->Draw();

  cm->Update();
  
  if(!type){
    out.str("");
    out << "de<" << de_max << " && de>" << de_min;
    Roo1DTable* sigtable = ds.table(b0f,out.str().c_str());
    sigtable->Print();
    sigtable->Print("v");
    
    Roo1DTable* fulltable = ds.table(b0f);
    fulltable->Print();
    fulltable->Print("v");
  }
  
  cout << "Nsig = " << nsig <<" +- " << nsig_err << " +- " << nsig_err_npq << " (" << nsig_err_total << ")" << endl;
  cout << "Nrho = " << nrho <<" +- " << nrho_err << " +- " << nrho_err_npq << " (" << nrho_err_total << ")" << endl;
  cout << "Ncmb = " << ncmb <<" +- " << ncmb_err << " +- " << ncmb_err_npq << " (" << ncmb_err_total << ")" << endl;
  cout << "Pury = " << purity << " +- " << purity_err << endl;
}
예제 #19
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 ----------------------------------------
예제 #20
0
   void build_hbb_workspace1( const char* infile = "outputfiles/input-file.txt", const char* outfile = "outputfiles/ws.root" ) {


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

     //-- Create workspace and other RooStats things.

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

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

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




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

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

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


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

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


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


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

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

      RooAbsReal* rv_Rsigsb_corr[bins_of_nb][max_bins_of_met]  ;

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

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

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

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

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

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

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

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


         } // mbi.

      } // nbi.

     //-- Finished reading input from file.

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

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

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

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

     //-- Define all floats.

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

      double R_msigmsb_initialval(0.15) ;

      RooRealVar* rv_R_msigmsb[50] ;

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

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

      } // mbi.

      printf("\n") ;

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

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

     //-- Define all mu parameters.

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

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

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

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

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

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



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

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

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


         } // mbi.

      } // nbi.

     //-- Finished defining mu parameters.

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

     //-- Defining small n's

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

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

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

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

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

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

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

         } // mbi.

      } // nbi.

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

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

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

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

      RooArgSet pdflist ;

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

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

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

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

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

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

         } // mbi.

      } // nbi.

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

     //-- Build the likelihood.

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

      pdflist.add( *allNuisancePdfs ) ;

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

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


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


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


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


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







     //-- Set up RooStats models.

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

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

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

      workspace.Print() ;

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

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

      delete pProfile ;
      delete pNll ;
      delete pPoiAndNuisance ;

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

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

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

      delete pProfile ;
      delete pNll ;
      delete pPoiAndNuisance ;

      workspace.Print() ;

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

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

      workspace.writeToFile( outfile ) ;




   } // build_hbb_workspace1.
예제 #21
0
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;
}
예제 #22
0
void rf506_msgservice()
{
  // C r e a t e   p d f 
  // --------------------

  // Construct gauss(x,m,s)
  RooRealVar x("x","x",-10,10) ;
  RooRealVar m("m","m",0,-10,10) ;
  RooRealVar s("s","s",1,-10,10) ;
  RooGaussian gauss("g","g",x,m,s) ;

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

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

  RooDataSet* data = model.generate(x,10) ;



  // P r i n t   c o n f i g u r a t i o n   o f   m e s s a g e   s e r v i c e
  // ---------------------------------------------------------------------------

  // Print streams configuration
  RooMsgService::instance().Print() ;
  cout << endl ;



  // A d d i n g   I n t e g r a t i o n   t o p i c   t o   e x i s t i n g   I N F O   s t r e a m
  // -----------------------------------------------------------------------------------------------

  // Print streams configuration
  RooMsgService::instance().Print() ;
  cout << endl ;

  // Add Integration topic to existing INFO stream
  RooMsgService::instance().getStream(1).addTopic(Integration) ;

  // Construct integral over gauss to demonstrate new message stream
  RooAbsReal* igauss = gauss.createIntegral(x) ;
  igauss->Print() ;

  // Print streams configuration in verbose, which also shows inactive streams
  cout << endl ;
  RooMsgService::instance().Print() ;
  cout << endl ;

  // Remove stream
  RooMsgService::instance().getStream(1).removeTopic(Integration) ;



  // E x a m p l e s   o f   p d f   v a l u e   t r a c i n g   s t r e a m
  // -----------------------------------------------------------------------
  
  // Show DEBUG level message on function tracing, trace RooGaussian only
  RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooGaussian")) ;

  // Perform a fit to generate some tracing messages
  model.fitTo(*data,Verbose(kTRUE)) ;

  // Reset message service to default stream configuration
  RooMsgService::instance().reset() ;



  // Show DEBUG level message on function tracing on all objects, redirect output to file
  RooMsgService::instance().addStream(DEBUG,Topic(Tracing),OutputFile("rf506_debug.log")) ;

  // Perform a fit to generate some tracing messages
  model.fitTo(*data,Verbose(kTRUE)) ;

  // Reset message service to default stream configuration
  RooMsgService::instance().reset() ;



  // E x a m p l e   o f   a n o t h e r   d e b u g g i n g   s t r e a m
  // ---------------------------------------------------------------------

  // Show DEBUG level messages on client/server link state management
  RooMsgService::instance().addStream(DEBUG,Topic(LinkStateMgmt)) ;
  RooMsgService::instance().Print("v") ;

  // Clone composite pdf g to trigger some link state management activity
  RooAbsArg* gprime = gauss.cloneTree() ;
  gprime->Print() ;

  // Reset message service to default stream configuration
  RooMsgService::instance().reset() ;



}
예제 #23
0
void new_RA4(){
  
  // let's time this challenging example
  TStopwatch t;
  t.Start();

  // set RooFit random seed for reproducible results
  RooRandom::randomGenerator()->SetSeed(4357);

  // make model
  RooWorkspace* wspace = new RooWorkspace("wspace");

  wspace->factory("Gaussian::sigCons(prime_SigEff[0,-5,5], nom_SigEff[0,-5,5], 1)");
  wspace->factory("expr::SigEff('1.0*pow(1.20,@0)',prime_SigEff)"); // // 1+-20%, 1.20=exp(20%)

  wspace->factory("Poisson::on(non[0,50], sum::splusb(prod::SigUnc(s[0,0,50],SigEff),mainb[8.8,0,50],dilep[0.9,0,20],tau[2.3,0,20],QCD[0.,0,10],MC[0.1,0,4]))");

  wspace->factory("Gaussian::mcCons(prime_rho[0,-5,5], nom_rho[0,-5,5], 1)");
  wspace->factory("expr::rho('1.0*pow(1.39,@0)',prime_rho)"); // // 1+-39%
  wspace->factory("Poisson::off(noff[0,200], prod::rhob(mainb,rho,mu_plus_e[0.74,0.01,10],1.08))");
  wspace->factory("Gaussian::mcCons2(mu_plus_enom[0.74,0.01,4], mu_plus_e, sigmatwo[.05])");

  wspace->factory("Gaussian::dilep_pred(dilep_nom[0.9,0,20], dilep, sigma3[2.2])");
  wspace->factory("Gaussian::tau_pred(tau_nom[2.3,0,20], tau, sigma4[0.5])");
  wspace->factory("Gaussian::QCD_pred(QCD_nom[0.0,0,10], QCD, sigma5[1.0])");
  wspace->factory("Gaussian::MC_pred(MC_nom[0.1,0.01,4], MC, sigma7[0.14])");

  wspace->factory("PROD::model(on,off,mcCons,mcCons2,sigCons,dilep_pred,tau_pred,QCD_pred,MC_pred)");

  RooArgSet obs(*wspace->var("non"), *wspace->var("noff"), *wspace->var("mu_plus_enom"), *wspace->var("dilep_nom"), *wspace->var("tau_nom"), "obs");
  obs.add(*wspace->var("QCD_nom"));  obs.add(*wspace->var("MC_nom"));
  RooArgSet globalObs(*wspace->var("nom_SigEff"), *wspace->var("nom_rho"), "global_obs");
  // fix global observables to their nominal values
  wspace->var("nom_SigEff")->setConstant();
  wspace->var("nom_rho")->setConstant();

  RooArgSet poi(*wspace->var("s"), "poi");
  RooArgSet nuis(*wspace->var("mainb"), *wspace->var("prime_rho"), *wspace->var("prime_SigEff"), *wspace->var("mu_plus_e"), *wspace->var("dilep"), *wspace->var("tau"), "nuis");
  nuis.add(*wspace->var("QCD"));  nuis.add(*wspace->var("MC"));


  wspace->factory("Uniform::prior_poi({s})");
  wspace->factory("Uniform::prior_nuis({mainb,mu_plus_e,dilep,tau,QCD,MC})");
  wspace->factory("PROD::prior(prior_poi,prior_nuis)");

  wspace->var("non")->setVal(8); //observed
  //wspace->var("non")->setVal(12); //expected observation
  wspace->var("noff")->setVal(7); //observed events in control region
  wspace->var("mu_plus_enom")->setVal(0.74);
  wspace->var("dilep_nom")->setVal(0.9);
  wspace->var("tau_nom")->setVal(2.3);
  wspace->var("QCD")->setVal(0.0);
  wspace->var("MC")->setVal(0.1);


  RooDataSet * data = new RooDataSet("data","",obs);
  data->add(obs);
  wspace->import(*data);


  /////////////////////////////////////////////////////
  // Now the statistical tests
  // model config
  ModelConfig* pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*wspace);
  pSbModel->SetPdf(*wspace->pdf("model"));
  pSbModel->SetPriorPdf(*wspace->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);
  wspace->import(*pSbModel);

  // set all but obs, poi and nuisance to const
  SetConstants(wspace, pSbModel);
  wspace->import(*pSbModel);


  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)wspace->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*wspace);
  wspace->import(*pBModel);


  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*data);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  //if(pSbModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  pNll = pBModel->GetPdf()->createNLL(*data);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  //if(pBModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  // inspect workspace
  wspace->Print();

  // save workspace to file
  wspace->writeToFile("tight.root");
  //wspace->writeToFile("tight_median.root");


  // clean up
  delete wspace;
  delete data;
  delete pSbModel;
  delete pBModel;

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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


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

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

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

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

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


  double CLb=0;
  double CLbinclusive=0;

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

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

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

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


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

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

    histOfUL->Fill(thisUL);

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

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

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

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

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

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

  delete profile;
  delete nll;

}
예제 #25
0
파일: LL.C 프로젝트: bellan/VVXAnalysis
void LL(){

  //y0 = 0.000135096401209 sigma_y0 = 0.000103896581837 x0 = 0.000446013873443 sigma_x0 =1.81384394011e-06
  //0.014108652249 0.0168368471049 0.0219755396247 0.000120423865262 1.5575931164 1.55759310722 3.41637854038
  //0.072569437325 0.084063541977 0.0376693978906 0.000284216132439 0.51908074913 0.519080758095 1.12037749267
 // double d = 0.014108652249;
 //  double sd = 0.0168368471049;
 //  double mc = 0.0219755396247;
 //  double smc = 0.000120423865262;
 //  double r0 = d/mc;

  double d = 0.072569437325;
  double sd =  0.084063541977;
  double mc =  0.0376693978906;
  double smc =  0.00028421613243;
  double r0 = d/mc;

  RooRealVar x("x","x",mc*0.9,mc*1.1);
  RooRealVar x0("x0","x0",mc);
  RooRealVar sx("sx","sx",smc);

  RooRealVar r("r","r",r0,0.,5.);
  RooRealVar y0("y0","y0",d); 
  RooRealVar sy("sy","sy",sd); 
  
  RooProduct rx("rx","rx",RooArgList(r,x));

  RooGaussian g1("g1","g1",x,x0,sx);
  RooGaussian g2("g2","g2",rx,y0,sy);

  RooProdPdf LL("LL","LL",g1,g2);

  RooArgSet obs(x0,y0); //observables
  RooArgSet poi(r); //parameters of interest
  RooDataSet data("data", "data", obs);
  data.add(obs); //actually add the data


  RooFitResult* res = LL.fitTo(data,RooFit::Minos(poi),RooFit::Save(),RooFit::Hesse(false));
  if(res->status()==0) {
    r.Print();
    x.Print();
    cout << r.getErrorLo() << " " << r.getErrorHi() << endl;
  } else {
    cout << "Likelihood maximization failed" << endl;
  }
  
  RooAbsReal* nll = LL.createNLL(data); 
  RooPlot* frame = r.frame();
  RooAbsReal* pll = nll->createProfile(poi);
  pll->plotOn(frame);//,RooFit::LineColor(ROOT::kRed));
  frame->Draw();

  r.setVal(0.);
  cout << pll->getVal() << endl; 

  return;
    
    


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

}
예제 #27
0
void rf105_funcbinding()
{

   // B i n d   T M a t h : : E r f   C   f u n c t i o n
   // ---------------------------------------------------

   // Bind one-dimensional TMath::Erf function as RooAbsReal function
   RooRealVar x("x","x",-3,3) ;
   RooAbsReal* errorFunc = bindFunction("erf",TMath::Erf,x) ;

   // Print erf definition
   errorFunc->Print() ;

   // Plot erf on frame 
   RooPlot* frame1 = x.frame(Title("TMath::Erf bound as RooFit function")) ;
   errorFunc->plotOn(frame1) ;


   // B i n d   R O O T : : M a t h : : b e t a _ p d f   C   f u n c t i o n
   // -----------------------------------------------------------------------

   // Bind pdf ROOT::Math::Beta with three variables as RooAbsPdf function
   RooRealVar x2("x2","x2",0,0.999) ;
   RooRealVar a("a","a",5,0,10) ;
   RooRealVar b("b","b",2,0,10) ;
   RooAbsPdf* beta = bindPdf("beta",ROOT::Math::beta_pdf,x2,a,b) ;

   // Perf beta definition
   beta->Print() ;

   // Generate some events and fit
   RooDataSet* data = beta->generate(x2,10000) ;
   beta->fitTo(*data) ;

   // Plot data and pdf on frame
   RooPlot* frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf")) ;
   data->plotOn(frame2) ;
   beta->plotOn(frame2) ;



   // B i n d   R O O T   T F 1   a s   R o o F i t   f u n c t i o n
   // ---------------------------------------------------------------

   // Create a ROOT TF1 function
   TF1 *fa1 = new TF1("fa1","sin(x)/x",0,10);

   // Create an observable 
   RooRealVar x3("x3","x3",0.01,20) ;

   // Create binding of TF1 object to above observable
   RooAbsReal* rfa1 = bindFunction(fa1,x3) ;

   // Print rfa1 definition
   rfa1->Print() ;

   // Make plot frame in observable, plot TF1 binding function
   RooPlot* frame3 = x3.frame(Title("TF1 bound as RooFit function")) ;
   rfa1->plotOn(frame3) ;



   TCanvas* c = new TCanvas("rf105_funcbinding","rf105_funcbinding",1200,400) ;
   c->Divide(3) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;

}
예제 #28
0
int DiagnosisMacro(int Nbins = 10, int Nsigma = 10, int CPUused = 1, TString Filename = "FIT_DATA_Psi2SJpsi_PPPrompt_Bkg_SecondOrderChebychev_pt65300_rap016_cent0200_262620_263757.root", TString Outputdir = "./")
//Nbins: Number of points for which to calculate profile likelihood. Time required is about (1/CPU) minutes per point per parameter. 0 means do plain likelihood only
//Nsigma: The range in which the scan is performed (value-Nsigma*sigma, value+Nsigma*sigma)
//CPUused: anything larger than 1 causes weird fit results on my laptop, runs fine on lxplus with more (16)

{
    // R e a d   w o r k s p a c e   f r o m   f i l e
    // -----------------------------------------------
    // Open input file with workspace

    //Filename = "FIT_DATA_Psi2SJpsi_PP_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev2_pt6590_rap016_cent0200.root";
    //Filename = "FIT_DATA_Psi2SJpsi_PbPb_Jpsi_DoubleCrystalBall_Psi2S_DoubleCrystalBall_Bkg_Chebychev1_pt6590_rap016_cent0200.root";

    TFile *f = new TFile(Filename);
    // Retrieve workspace from file
    RooWorkspace* w = (RooWorkspace*)f->Get("workspace");

    // Retrieve x,model and data from workspace
    RooRealVar* x = w->var("invMass");
    RooAbsPdf* model = w->pdf("simPdf_syst");
    if (model == 0) {
        model = w->pdf("simPdf");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PP");
    }
    if (model == 0) {
        model = w->pdf("pdfMASS_Tot_PbPb");
    }
    if (model == 0) {
        cout << "[ERROR] pdf failed to load from the workspace" << endl;
        return false;
    }

    RooAbsData* data = w->data("dOS_DATA");
    if (data == 0) {
        data = w->data("dOS_DATA_PP");
    }
    if (data == 0) {
        data = w->data("dOS_DATA_PbPb");
    }
    if (data == 0) {
        cout << "[ERROR] data failed to load from the workspace" << endl;
        return false;
    }

    // Print structure of composite p.d.f.
    model->Print("t");

    /*
    // P l o t   m o d e l
    // ---------------------------------------------------------
    // Plot data and PDF overlaid
    RooPlot* xframe = x->frame(Title("J/psi Model and Data"));
    data->plotOn(xframe);
    model->plotOn(xframe);

    // Draw the frame on the canvas
    TCanvas* c2 = new TCanvas("PlotModel", "PlotModel", 1000, 1000);
    gPad->SetLeftMargin(0.15);
    xframe->GetYaxis()->SetTitleOffset(2.0);
    xframe->Draw();//*/

    ///// Check parameters

    RooArgSet* paramSet1 = model->getDependents(data);
    paramSet1->Print("v");  // Just check
    RooArgSet* paramSet2 = model->getParameters(data);
    paramSet2->Print("v");
    int Nparams = paramSet2->getSize();
    cout << "Number of parameters: " << Nparams<<endl<<endl;


    // C o n s t r u c t   p l a i n   l i k e l i h o o d
    // ---------------------------------------------------
    // Construct unbinned likelihood
    RooAbsReal* nll = model->createNLL(*data, NumCPU(CPUused));
    // Minimize likelihood w.r.t all parameters before making plots
    RooMinuit(*nll).migrad();


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

    ///////////////////   L O O P   O V E R   P A R A M E T E R S

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

    /// Set up loop over parameters
    TString ParamName;
    double ParamValue;
    double ParamError;
    double ParamLimitLow;
    double ParamLimitHigh;
    double FitRangeLow;
    double FitRangeHigh;
    RooRealVar* vParam;
    int counter = 0;

    // Loop start
    TIterator* iter = paramSet2->createIterator();
    TObject* var = iter->Next();
    while (var != 0) {
        counter++;
        ParamName = var->GetName();
        vParam = w->var(ParamName);
        ParamValue = vParam->getVal();
        ParamError = vParam->getError();
        ParamLimitLow = vParam->getMin();
        ParamLimitHigh = vParam->getMax();
        cout << ParamName << " has value " << ParamValue << " with error: " << ParamError << " and limits: " << ParamLimitLow << " to " << ParamLimitHigh << endl << endl;

        if (ParamError == 0) {  //Skipping fixed parameters
            cout << "Parameter was fixed, skipping its fitting" << endl;
            cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
            var = iter->Next();
            continue;
        }

        // determining fit range: Nsigma sigma on each side unless it would be outside of parameter limits
        if ((ParamValue - Nsigma * ParamError) > ParamLimitLow) {
            FitRangeLow = (ParamValue - Nsigma * ParamError);
        }
        else {
            FitRangeLow = ParamLimitLow;
        }

        if ((ParamValue + Nsigma * ParamError) < ParamLimitHigh) {
            FitRangeHigh = (ParamValue + Nsigma * ParamError);
        }
        else {
            FitRangeHigh = ParamLimitHigh;
        }


        // P l o t    p l a i n   l i k e l i h o o d   a n d   C o n s t r u c t   p r o f i l e   l i k e l i h o o d
        // ---------------------------------------------------
        RooPlot* frame1;
        RooAbsReal* pll=NULL;

        if (Nbins != 0) {
            frame1 = vParam->frame(Bins(Nbins), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());

            pll = nll->createProfile(*vParam);
            // Plot the profile likelihood
            pll->plotOn(frame1, LineColor(kRed), RooFit::Precision(-1));
        }
        else { //Skip profile likelihood
            frame1 = vParam->frame(Bins(10), Range(FitRangeLow, FitRangeHigh), Title(TString::Format("LL and profileLL in %s", ParamName.Data())));
            nll->plotOn(frame1, ShiftToZero());
        }

        // D r a w   a n d   s a v e   p l o t s
        // -----------------------------------------------------------------------

        // Adjust frame maximum for visual clarity
        frame1->SetMinimum(0);
        frame1->SetMaximum(20);

        TCanvas* c = new TCanvas("CLikelihoodResult", "CLikelihoodResult", 800, 600);
        c->cd(1);
        gPad->SetLeftMargin(0.15);
        frame1->GetYaxis()->SetTitleOffset(1.4);
        frame1->Draw();
        TLegend* leg = new TLegend(0.70, 0.70, 0.95, 0.88, "");
        leg->SetFillColor(kWhite);
        leg->SetBorderSize(0);
        leg->SetTextSize(0.035);
        TLegendEntry *le1 = leg->AddEntry(nll, "Plain likelihood", "l");
        le1->SetLineColor(kBlue);
        le1->SetLineWidth(3);
        TLegendEntry *le2 = leg->AddEntry(pll, "Profile likelihood", "l");
        le2->SetLineColor(kRed);
        le2->SetLineWidth(3);
        leg->Draw("same");

        //Save plot
        TString StrippedName = TString(Filename(Filename.Last('/')+1,Filename.Length()));
        StrippedName = StrippedName.ReplaceAll(".root","");
        cout << StrippedName << endl;
        gSystem->mkdir(Form("%s/root/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/root/%s/Likelihood_scan_%s.root", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/pdf/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/pdf/%s/Likelihood_scan_%s.pdf", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));
        gSystem->mkdir(Form("%s/png/%s", Outputdir.Data(), StrippedName.Data()), kTRUE);
        c->SaveAs(Form("%s/png/%s/Likelihood_scan_%s.png", Outputdir.Data(), StrippedName.Data(), ParamName.Data()));


        delete c;
        delete frame1;
        if (pll) delete pll;

        cout << endl << "DONE WITH " << counter << " PARAMETER OUT OF " << Nparams << endl << endl;
        //if (counter == 2){ break; } //Exit - for testing
        var = iter->Next();
    }  // End of the loop

    return true;
}
예제 #29
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 ----------------------------------------
예제 #30
0
int main() {
// Construct gauss(x,m,s)
  RooRealVar x("x","x",-10,10) ;
  RooRealVar m("m","m",0,-10,10) ;
  RooRealVar s("s","s",1,-10,10) ;
  RooGaussian gauss("g","g",x,m,s) ;

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

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

  RooDataSet* data = model.generate(x,10);
  
// P r i n t   c o n f i g u r a t i o n   o f   m e s s a g e   s e r v i c e
  // ---------------------------------------------------------------------------

  // Print streams configuration
  RooMsgService::instance().Print() ;
  cout << endl ;



  // A d d i n g   I n t e g r a t i o n   t o p i c   t o   e x i s t i n g   I N F O   s t r e a m
  // -----------------------------------------------------------------------------------------------

  // Print streams configuration
  RooMsgService::instance().Print() ;
  cout << endl ;

  // Add Integration topic to existing INFO stream
  RooMsgService::instance().getStream(1).addTopic(Integration) ;

  // Construct integral over gauss to demonstrate new message stream
  RooAbsReal* igauss = gauss.createIntegral(x) ;
  igauss->Print() ;

  // Print streams configuration in verbose, which also shows inactive streams
  cout << endl ;
  RooMsgService::instance().Print() ;
  cout << endl ;

  // Remove stream
  RooMsgService::instance().getStream(1).removeTopic(Integration) ;



  // E x a m p l e s   o f   p d f   v a l u e   t r a c i n g   s t r e a m
  // -----------------------------------------------------------------------
  
  // Show DEBUG level message on function tracing, trace RooGaussian only
  RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooGaussian")) ;

  // Perform a fit to generate some tracing messages
  model.fitTo(*data,Verbose(kTRUE)) ;
  
  TH1 *histo = model.createHistogram("histo");
  
  
  return 0;
}