コード例 #1
0
ファイル: RA4abcd.C プロジェクト: wa01/usercode
//
// single measurement (LM0 or LM1)
//
void RA4Single (StatMethod method, double* sig, double* bkg) {

  // RooWorkspace* wspace = createWorkspace();
  RA4WorkSpace ra4WSpace("wspace",true,true,true);
  ra4WSpace.addChannel(RA4WorkSpace::MuChannel);
  ra4WSpace.finalize();

  double lm0_mc[4] = { 1.09, 7.68, 3.78, 21.13 };
  double lm1_mc[4] = { 0.05 , 0.34 , 1.12 , 3.43 };
  double* lm_mc = sig ? sig : lm0_mc;

  double bkg_mc[4] = {  14.73, 18.20, 8.48, 10.98 };

  ra4WSpace.setBackground(RA4WorkSpace::MuChannel,bkg_mc[0],bkg_mc[1],bkg_mc[2],bkg_mc[3]);
  ra4WSpace.setSignal(RA4WorkSpace::MuChannel,lm_mc[0],lm_mc[1],lm_mc[2],lm_mc[3],1.,1.,1.,1.);
  
  // setBackgrounds(wspace,bkg);
  // setSignal(wspace,lm_mc);

  RooWorkspace* wspace = ra4WSpace.workspace();
  // wspace->Print("v");
  // RooArgSet allVars = wspace->allVars();
  // // allVars.printLatex(std::cout,1);
  // TIterator* it = allVars.createIterator();
  // RooRealVar* var;
  // while ( var=(RooRealVar*)it->Next() ) {
  //   var->Print("v");
  //   var->printValue(std::cout);
  // }

  ////////////////////////////////////////////////////////////
  // Generate toy data
  // generate toy data assuming current value of the parameters
  // import into workspace. 
  // add Verbose() to see how it's being generated
  // wspace->var("s")->setVal(0.);
  // RooDataSet* data =   wspace->pdf("model")->generate(*wspace->set("obs"),1);
  // data->Print("v");
  // // wspace->import(*data);
  // wspace->var("s")->setVal(lm_mc[3]);
  RooDataSet* data = new RooDataSet("data","data",*wspace->set("obs"));
  data->add(*wspace->set("obs"));
  data->Print("v");

  MyLimit limit = computeLimit(wspace,data,method,true);
  std::cout << "Limit [ " << limit.lowerLimit << " , "
	    << limit.upperLimit << " ] ; isIn = " << limit.isInInterval << std::endl;
}
コード例 #2
0
ファイル: rf510_wsnamedsets.C プロジェクト: adevress/root-1
void rf510_wsnamedsets()
{
  // C r e a t e   m o d e l   a n d   d a t a s e t
  // -----------------------------------------------

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

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

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

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

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


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


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


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

}
コード例 #3
0
ファイル: RA4abcd.C プロジェクト: wa01/usercode
//
// scan over parameter space
//
void RA4Mult (const RA4WorkingPoint& muChannel,
	      const RA4WorkingPoint& eleChannel,
	      StatMethod method) {

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


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

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

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

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

//   double bkgs[4][2];

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

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

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

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

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

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

      double excl = limit.isInInterval;
      if ( limit.upperLimit<limit.lowerLimit )  excl = -1;
      hExclusion->SetBinContent(ix,iy,excl);
      hLowerLimit->SetBinContent(ix,iy,limit.lowerLimit);
      hUpperLimit->SetBinContent(ix,iy,limit.upperLimit);
//       return;
      
    }
  }
  
  TFile* out = new TFile("RA4abcd.root","RECREATE");
  hExclusion->SetDirectory(out);
  hExclusion->SetMinimum(); hExclusion->SetMaximum();
  hExclusion->SetContour(1); hExclusion->SetContourLevel(0,0.5);
  hLowerLimit->SetDirectory(out);
  hLowerLimit->SetMinimum(); hLowerLimit->SetMaximum();
  hUpperLimit->SetDirectory(out);
  hUpperLimit->SetMinimum(); hUpperLimit->SetMaximum();
  for ( unsigned int j=0; j<nf; ++j ) {
    hYields[3][j]->SetDirectory(out);
    hYields[3][j]->SetMinimum(); hYields[3][j]->SetMaximum();
  }
  out->Write();
  delete out;
}
コード例 #4
0
ファイル: IntervalExamples.C プロジェクト: Y--/root
void IntervalExamples()
{

   // Time this macro
   TStopwatch t;
   t.Start();


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

   // make a simple model via the workspace factory
   RooWorkspace* wspace = new RooWorkspace();
   wspace->factory("Gaussian::normal(x[-10,10],mu[-1,1],sigma[1])");
   wspace->defineSet("poi","mu");
   wspace->defineSet("obs","x");

   // specify components of model for statistical tools
   ModelConfig* modelConfig = new ModelConfig("Example G(x|mu,1)");
   modelConfig->SetWorkspace(*wspace);
   modelConfig->SetPdf( *wspace->pdf("normal") );
   modelConfig->SetParametersOfInterest( *wspace->set("poi") );
   modelConfig->SetObservables( *wspace->set("obs") );

   // create a toy dataset
   RooDataSet* data = wspace->pdf("normal")->generate(*wspace->set("obs"),100);
   data->Print();

   // for convenience later on
   RooRealVar* x = wspace->var("x");
   RooRealVar* mu = wspace->var("mu");

   // set confidence level
   double confidenceLevel = 0.95;

   // example use profile likelihood calculator
   ProfileLikelihoodCalculator plc(*data, *modelConfig);
   plc.SetConfidenceLevel( confidenceLevel);
   LikelihoodInterval* plInt = plc.GetInterval();

   // example use of Feldman-Cousins
   FeldmanCousins fc(*data, *modelConfig);
   fc.SetConfidenceLevel( confidenceLevel);
   fc.SetNBins(100); // number of points to test per parameter
   fc.UseAdaptiveSampling(true); // make it go faster

   // Here, we consider only ensembles with 100 events
   // The PDF could be extended and this could be removed
   fc.FluctuateNumDataEntries(false);

   // Proof
   //  ProofConfig pc(*wspace, 4, "workers=4", kFALSE);    // proof-lite
   //ProofConfig pc(w, 8, "localhost");    // proof cluster at "localhost"
   //  ToyMCSampler* toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler();
   //  toymcsampler->SetProofConfig(&pc);     // enable proof

   PointSetInterval* interval = (PointSetInterval*) fc.GetInterval();


   // example use of BayesianCalculator
   // now we also need to specify a prior in the ModelConfig
   wspace->factory("Uniform::prior(mu)");
   modelConfig->SetPriorPdf(*wspace->pdf("prior"));

   // example usage of BayesianCalculator
   BayesianCalculator bc(*data, *modelConfig);
   bc.SetConfidenceLevel( confidenceLevel);
   SimpleInterval* bcInt = bc.GetInterval();

   // example use of MCMCInterval
   MCMCCalculator mc(*data, *modelConfig);
   mc.SetConfidenceLevel( confidenceLevel);
   // special options
   mc.SetNumBins(200);        // bins used internally for representing posterior
   mc.SetNumBurnInSteps(500); // first N steps to be ignored as burn-in
   mc.SetNumIters(100000);    // how long to run chain
   mc.SetLeftSideTailFraction(0.5); // for central interval
   MCMCInterval* mcInt = mc.GetInterval();

   // for this example we know the expected intervals
   double expectedLL = data->mean(*x)
      + ROOT::Math::normal_quantile(  (1-confidenceLevel)/2,1)
      / sqrt(data->numEntries());
   double expectedUL = data->mean(*x)
      + ROOT::Math::normal_quantile_c((1-confidenceLevel)/2,1)
      / sqrt(data->numEntries()) ;

   // Use the intervals
   std::cout << "expected interval is [" <<
      expectedLL << ", " <<
      expectedUL << "]" << endl;

   cout << "plc interval is [" <<
      plInt->LowerLimit(*mu) << ", " <<
      plInt->UpperLimit(*mu) << "]" << endl;

   std::cout << "fc interval is ["<<
      interval->LowerLimit(*mu) << " , "  <<
      interval->UpperLimit(*mu) << "]" << endl;

   cout << "bc interval is [" <<
      bcInt->LowerLimit() << ", " <<
      bcInt->UpperLimit() << "]" << endl;

   cout << "mc interval is [" <<
      mcInt->LowerLimit(*mu) << ", " <<
      mcInt->UpperLimit(*mu) << "]" << endl;

   mu->setVal(0);
   cout << "is mu=0 in the interval? " <<
      plInt->IsInInterval(RooArgSet(*mu)) << endl;


   // make a reasonable style
   gStyle->SetCanvasColor(0);
   gStyle->SetCanvasBorderMode(0);
   gStyle->SetPadBorderMode(0);
   gStyle->SetPadColor(0);
   gStyle->SetCanvasColor(0);
   gStyle->SetTitleFillColor(0);
   gStyle->SetFillColor(0);
   gStyle->SetFrameFillColor(0);
   gStyle->SetStatColor(0);


   // some plots
   TCanvas* canvas = new TCanvas("canvas");
   canvas->Divide(2,2);

   // plot the data
   canvas->cd(1);
   RooPlot* frame = x->frame();
   data->plotOn(frame);
   data->statOn(frame);
   frame->Draw();

   // plot the profile likelihood
   canvas->cd(2);
   LikelihoodIntervalPlot plot(plInt);
   plot.Draw();

   // plot the MCMC interval
   canvas->cd(3);
   MCMCIntervalPlot* mcPlot = new MCMCIntervalPlot(*mcInt);
   mcPlot->SetLineColor(kGreen);
   mcPlot->SetLineWidth(2);
   mcPlot->Draw();

   canvas->cd(4);
   RooPlot * bcPlot = bc.GetPosteriorPlot();
   bcPlot->Draw();

   canvas->Update();

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

}
コード例 #5
0
ファイル: runBATCalculator.C プロジェクト: Kaoschuks/bat
void runBATCalculator()
{
    // Definiton of a RooWorkspace containing the statistics model. Later the
    // information for BATCalculator is retrieved from the workspace. This is
    // certainly a bit of overhead but better from an educative point of view.
    cout << "preparing the RooWorkspace object" << endl;

    RooWorkspace* myWS = new RooWorkspace("myWS", true);

    // combined prior for signal contribution
    myWS->factory("Product::signal({sigma_s[0,20],L[5,15],epsilon[0,1]})");
    myWS->factory("N_bkg[0,3]");
    // define prior functions
    // uniform prior for signal crosssection
    myWS->factory("Uniform::prior_sigma_s(sigma_s)");
    // (truncated) prior for efficiency
    myWS->factory("Gaussian::prior_epsilon(epsilon,0.51,0.0765)");
    // (truncated) Gaussian prior for luminosity
    myWS->factory("Gaussian::prior_L(L,10,1)");
    // (truncated) Gaussian prior for bkg crosssection
    myWS->factory("Gaussian::prior_N_bkg(N_bkg,0.52,0.156)");

    // Poisson distribution with mean signal+bkg
    myWS->factory("Poisson::model(n[0,300],sum(signal,N_bkg))");

    // define the global prior function
    myWS->factory("PROD::prior(prior_sigma_s,prior_epsilon,prior_L,prior_N_bkg)");

    // Definition of observables and parameters of interest
    myWS->defineSet("obsSet", "n");
    myWS->defineSet("poiSet", "sigma_s");
    myWS->defineSet("nuisanceSet", "N_bkg,L,epsilon");

    // ->model complete (Additional information can be found in the
    // RooStats manual)

    //  feel free to vary the parameters, but don't forget to choose reasonable ranges for the
    // variables. Currently the Bayesian methods will often not work well if the variable ranges
    // are either too short (for obvious reasons) or too large (for technical reasons).

    // A ModelConfig object is used to associate parts of your workspace with their statistical
    // meaning (it is also possible to initialize BATCalculator directly with elements from the
    // workspace but if you are sharing your workspace with others or if you want to use several
    // different methods the use of ModelConfig will most often turn out to be the better choice.)

    // setup the ModelConfig object
    cout << "preparing the ModelConfig object" << endl;

    ModelConfig modelconfig("modelconfig", "ModelConfig for this example");
    modelconfig.SetWorkspace(*myWS);

    modelconfig.SetPdf(*(myWS->pdf("model")));
    modelconfig.SetParametersOfInterest(*(myWS->set("poiSet")));
    modelconfig.SetPriorPdf(*(myWS->pdf("prior")));
    modelconfig.SetNuisanceParameters(*(myWS->set("nuisanceSet")));
    modelconfig.SetObservables(*(myWS->set("obsSet")));


    // use BATCalculator to the derive credibility intervals as a function of the observed number of
    // events in the hypothetical experiment

    // define vector with tested numbers of events
    TVectorD obsEvents;
    // define vectors which will be filled with the lower and upper limits for each tested number
    // of observed events
    TVectorD BATul;
    TVectorD BATll;

    // fix upper limit of tested observed number of events
    int obslimit = 10;

    obsEvents.ResizeTo(obslimit);
    BATul.ResizeTo(obslimit);
    BATll.ResizeTo(obslimit);


    cout << "starting the calculation of Bayesian credibility intervals with BATCalculator" << endl;
    // loop over observed number of events in the hypothetical experiment
    for (int obs = 1; obs <= obslimit; obs++) {

        obsEvents[obs - 1] = (static_cast<double>(obs));

        // prepare data input for the the observed number of events
        // adjust number of observed events in the workspace. This is communicated to ModelConfig!
        myWS->var("n")->setVal(obs);
        // create data
        RooDataSet data("data", "", *(modelconfig.GetObservables()));
        data.add( *(modelconfig.GetObservables()));

        // prepare BATCalulator
        BATCalculator batcalc(data, modelconfig);

        // give the BATCalculator a unique name (always a good idea in ROOT)
        TString namestring = "mybatc_";
        namestring += obs;
        batcalc.SetName(namestring);

        // fix amount of posterior probability in the calculated interval.
        // the name confidence level is incorrect here
        batcalc.SetConfidenceLevel(0.90);

        // fix length of the Markov chain. (in general: the longer the Markov chain the more
        // precise will be the results)
        batcalc.SetnMCMC(20000);

        // retrieve SimpleInterval object containing the information about the interval (this
        // triggers the actual calculations)
        SimpleInterval* interval = batcalc.GetInterval1D("sigma_s");

        std::cout << "BATCalculator: 90% credibility interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or 95% credibility upper limit\n";

        // add the interval borders for the current number of observed events to the vectors
        // containing the lower and upper limits
        BATll[obs - 1] = interval->LowerLimit();
        BATul[obs - 1] = interval->UpperLimit();

        // clean up for next loop element
        batcalc.CleanCalculatorForNewData();
        delete interval;
    }
    cout << "all limits calculated" << endl;

    // summarize the results in a plot

    TGraph* grBATll = new TGraph(obsEvents, BATll);
    grBATll->SetLineColor(kGreen);
    grBATll->SetLineWidth(200);
    grBATll->SetFillStyle(3001);
    grBATll->SetFillColor(kGreen);

    TGraph* grBATul = new TGraph(obsEvents, BATul);
    grBATul->SetLineColor(kGreen);
    grBATul->SetLineWidth(-200);
    grBATul->SetFillStyle(3001);
    grBATul->SetFillColor(kGreen);

    // create and draw multigraph
    TMultiGraph* mg = new TMultiGraph("BayesianLimitsBATCalculator", "BayesianLimitsBATCalculator");
    mg->SetTitle("example of Bayesian credibility intervals derived with BATCAlculator ");

    mg->Add(grBATll);
    mg->Add(grBATul);

    mg->Draw("AC");

    mg->GetXaxis()->SetTitle ("# observed events");
    mg->GetYaxis()->SetTitle("limits on signal S (size of test: 0.1)");

    mg->Draw("AC");
}
コード例 #6
0
void fillDatasets( TString fname, TString tname, TString outfname ) {

  TFile *inFile = TFile::Open( fname );
  TTree *tree = (TTree*)inFile->Get( tname );

  ULong64_t eventNumber;
  TString   *year = 0;
  double    B_s0_DTF_B_s0_M;
  int       itype;
  bool      pass_bdt;
  bool      pass_pid;
  bool      pass_rhokst;
  bool      pass_massveto;
  bool      pass_multcand;
  bool      B_s0_L0HadronDecision_TOS;
  bool      B_s0_L0Global_TIS;
  double    B_s0_DTF_KST1_M;
  double    B_s0_DTF_KST2_M;

  tree->SetBranchAddress(  "eventNumber"                 , &eventNumber                 );
  tree->SetBranchAddress(  "year"                        , &year                        );
  tree->SetBranchAddress(  "B_s0_DTF_B_s0_M"             , &B_s0_DTF_B_s0_M             );
  tree->SetBranchAddress(  "itype"                       , &itype                       );
  tree->SetBranchAddress(  "pass_bdt"                    , &pass_bdt                    );
  tree->SetBranchAddress(  "pass_pid"                    , &pass_pid                    );
  tree->SetBranchAddress(  "pass_rhokst"                 , &pass_rhokst                 );
  tree->SetBranchAddress(  "pass_massveto"               , &pass_massveto               );
  tree->SetBranchAddress(  "pass_multcand"               , &pass_multcand               );
  tree->SetBranchAddress(  "B_s0_L0HadronDecision_TOS"   , &B_s0_L0HadronDecision_TOS   );
  tree->SetBranchAddress(  "B_s0_L0Global_TIS"           , &B_s0_L0Global_TIS           );
  tree->SetBranchAddress(  "B_s0_DTF_KST1_M"             , &B_s0_DTF_KST1_M             );
  tree->SetBranchAddress(  "B_s0_DTF_KST2_M"             , &B_s0_DTF_KST2_M             );

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

  for (int ev=0; ev<tree->GetEntries(); ev++) {

    tree->GetEntry(ev);

    if ( ev%10000==0 ) cout << ev << " / " << tree->GetEntries() << endl;

    // cut events outside the mass window
    if ( B_s0_DTF_B_s0_M < 5000 || B_s0_DTF_B_s0_M > 5800 ) continue;
    if ( B_s0_DTF_KST1_M < 750  || B_s0_DTF_KST1_M > 1600 ) continue;
    if ( B_s0_DTF_KST2_M < 750  || B_s0_DTF_KST2_M > 1600 ) continue;

    // set workspace values
    w->var("B_s0_DTF_B_s0_M")->setVal( B_s0_DTF_B_s0_M );
    w->var("eventNumber")->setVal( eventNumber );
    if ( *year==TString("2011") ) {
      if ( B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("HadronTOS2011");
      else if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("GlobalTIS2011");
      else continue;
    }
    else if ( *year==TString("2012") ) {
      if ( B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("HadronTOS2012");
      else if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) w->cat("DataCat")->setLabel("GlobalTIS2012");
      else continue;
    }
    else continue;

    // for the most case we put the bdt and pid requirement in
    // for low stats MC samples we don't use it
    //
    // NO REQUIREMENT:
    // Lb2pKpipi MC
    if ( itype == -78 || itype == -88 ) {
      w->data("Lb2pKpipi")->add( *w->set("observables") );
    }
    // Lb2ppipipi MC
    else if ( itype == -79 || itype == -89 ) {
        w->data("Lb2ppipipi")->add( *w->set("observables") );
    }
    // Bd2PhiKst MC
    else if ( itype == -75 || itype == -85 ) {
      w->data("Bd2PhiKst")->add( *w->set("observables") );
    }
    // Bs2PhiKst MC
    else if ( itype == -76 || itype == -86 ) {
      w->data("Bs2PhiKst")->add( *w->set("observables") );
    }
    // Bd2RhoKst MC
    else if ( itype == -77 || itype == -87 ) {
      w->data("Bd2RhoKst")->add( *w->set("observables") );
    }

    // FROM HERE BDT, PID AND MASS VETO REQUIREMENTS
    //if ( pass_bdt && pass_pid && pass_multcand && !pass_rhokst && !pass_massveto) {
    if ( pass_bdt && pass_pid && pass_multcand && !pass_massveto) {
      // Data 2011
      if ( itype == 71 ) {
        w->data("Data")->add( *w->set("observables") );
        w->data("Data2011")->add( *w->set("observables") );
        if ( B_s0_L0HadronDecision_TOS ) {
          w->data("Data2011HadronTOS")->add( *w->set("observables") );
        }
        if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) {
          w->data("Data2011GlobalTIS")->add( *w->set("observables") );
        }
      }
      // Data 2012
      else if ( itype == 81 ) {
        w->data("Data")->add( *w->set("observables") );
        w->data("Data2012")->add( *w->set("observables") );
        if ( B_s0_L0HadronDecision_TOS ) {
          w->data("Data2012HadronTOS")->add( *w->set("observables") );
        }
        if ( B_s0_L0Global_TIS && !B_s0_L0HadronDecision_TOS ) {
          w->data("Data2012GlobalTIS")->add( *w->set("observables") );
        }
      }
      // Bs2KstKst MC
      else if ( itype == -70 || itype == -80 ) {
        w->data("Bs2KstKst")->add( *w->set("observables") );
      }
      // Bs2KstKst1430 MC
      else if ( itype == -71 || itype == -81 ) {
        w->data("Bs2KstKst1430")->add( *w->set("observables") );
      }
      // Bs2Kst1430Kst1430 MC
      else if ( itype == -72 || itype == -82 ) {
        w->data("Bs2Kst1430Kst1430")->add( *w->set("observables") );
      }
      // Bs2KPiKPi PhaseSpace
      else if ( itype == -73 || itype == -83 ) {
        w->data("Bs2KpiKpiPhaseSpace")->add( *w->set("observables") );
      }
      // Bd2KstKst MC
      else if ( itype == -74 || itype == -84 ) {
        w->data("Bd2KstKst")->add( *w->set("observables") );
      }
    }
  }

  // combined data
  map<string,RooDataSet*> dsetMap;
  dsetMap[ "HadronTOS2011" ] = (RooDataSet*)w->data("Data2011HadronTOS") ;
  dsetMap[ "GlobalTIS2011" ] = (RooDataSet*)w->data("Data2011GlobalTIS") ;
  dsetMap[ "HadronTOS2012" ] = (RooDataSet*)w->data("Data2012HadronTOS") ;
  dsetMap[ "GlobalTIS2012" ] = (RooDataSet*)w->data("Data2012GlobalTIS") ;

  RooDataSet *DataComb = new RooDataSet( "DataCombined", "DataCombined", *w->set("observables"), Index(*w->cat("DataCat")), Import(dsetMap) );
  w->import(*DataComb);
  delete DataComb;

  inFile->Close();
  delete inFile;
  delete year;

  w->writeToFile( outfname );

}
コード例 #7
0
ファイル: sig.C プロジェクト: cms-analysis/ZprimeDiLeptons
void makeModel(RooWorkspace& w) {

   TFile *_file0 = TFile::Open("plots/htotal_root_ZprimeRecomass.root");
   TH1F *Histo = (TH1F*)_file0->Get("htotaldata");
   RooRealVar invm("invm","invm",200.,4000.);    
   RooDataHist* data = new RooDataHist("data","data",invm,Import(*Histo)) ;
   

//   TTree* tree = new TTree("simple","data from ascii file");
//   Long64_t nlines = tree->ReadFile("list_mll_200_2016.txt","x1:x2:x3:invm:x5:x6");
//   Long64_t nlines = tree->ReadFile("a.txt","x1:x2:x3:invm:x5:x6");
//   printf(" found %lld pointsn",nlines);
//   tree->Write();
//   tree->GetEntries();

   RooRealVar mass("mass","mass", 300., 200., 1600.);
   RooRealVar nsig("nsig","Number of signal events", 0., 5000.);
   RooRealVar nbkg("nbkg","Number of background events", 0., 300000.);
   w.import(mass);
   w.import(nsig);
   w.import(nbkg);

//   RooRealVar invm("invm","Invariant mass", 200., 4000.);
//   RooDataSet* data = new RooDataSet("data", "Data", invm, RooFit::Import(*tree));

   data->Print("v");
   w.import(invm);
   w.import(*data);
 
   w.factory("expr::sigma('invm*(0.01292 + 0.00001835 * invm - 0.0000000002733 * invm*invm)',invm)");
   w.factory("expr::width('0.03*invm',invm)");
 
   w.factory("CEXPR::bkgpdf('exp(24.9327 - 2.39287e-03*invm + 3.19926e-07*invm*invm - 3.38799e-11*invm*invm*invm)*pow(invm,-3.3634)',invm)");
   w.factory("Voigtian::sigpdf(invm,mass,width,sigma)");

   w.factory("SUM::model(nbkg*bkgpdf, nsig*sigpdf)");

   RooAbsPdf* sigpdf = w.pdf("sigpdf");
   RooAbsPdf* bkgpdf = w.pdf("bkgpdf");
   RooAbsPdf* model  = w.pdf("model");

   RooStats::ModelConfig* mc = new ModelConfig("mc",&w);
   mc->SetPdf(*w.pdf("model"));
   mc->SetParametersOfInterest(*w.var("nsig"));
   mc->SetObservables(*w.var("invm"));
   w.defineSet("nuisParams","nbkg");

   mc->SetNuisanceParameters(*w.set("nuisParams"));
   w.var("mass")->setConstant(true);

   w.import(*mc);

   w.Print("tree");

   w.writeToFile("MyModel_workspace.root");
  
   TCanvas* c1 = new TCanvas("c1","Control Plots", 900, 700);
   RooPlot* plot = w.var("invm")->frame();
   w.data("data")->plotOn(plot);
   w.pdf("model")->plotOn(plot);
   w.pdf("model")->plotOn(plot, Components("bkgpdf"),LineStyle(kDashed));
   w.pdf("model")->plotOn(plot, Components("sigpdf"),LineColor(kRed));
   plot->Draw();

   return;

}
コード例 #8
0
void counting( void ) {
    //
    // this function implements the interval calculation for a counting experiment
    //

    // make model
    RooWorkspace * wspace = new RooWorkspace("myWS");
    wspace -> factory("Uniform::model_pdf_1(x[0,1])");
    wspace -> factory("Uniform::model_pdf_2(x)");
    wspace -> factory("SUM::model_pdf(s[0,15]*model_pdf_1,b[1,0,2]*model_pdf_2)");
    wspace -> factory("Lognormal::likelihood_b(b,1,3)");
    wspace -> factory("PROD::model_likelihood(model_pdf, likelihood_b)");
    wspace -> factory("Uniform::prior_pdf(s)");

    // define observables
    wspace -> defineSet("observables","x");

    // define parameters of interest
    wspace -> defineSet("poi","s");

    // define nuisance parameters
    wspace -> defineSet("nuisance_parameters","b");

    // load data
    RooArgList * observables = new RooArgList( *wspace->set("observables") );
    RooDataSet * data = RooDataSet::read("counting_data_3.ascii", *observables);
    data -> SetName("data");
    wspace -> import(*data);

    // model config
    ModelConfig modelConfig("counting_model_config");
    modelConfig . SetWorkspace(*wspace);
    modelConfig . SetPdf(*wspace->pdf("model_likelihood"));
    modelConfig . SetPriorPdf(*wspace->pdf("prior_pdf"));
    modelConfig . SetParametersOfInterest(*wspace->set("poi"));
    modelConfig . SetNuisanceParameters(*wspace->set("nuisance_parameters"));
    wspace -> import(modelConfig, "counting_model_config");

    // Bayesian Calculator
    BayesianCalculator bc(*data, modelConfig);
    bc.SetName("exostBayes");
    wspace -> import(bc);

    // inspect workspace
    wspace -> Print();

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

    // run Bayesian calculation
    bc.SetConfidenceLevel(0.95);
    SimpleInterval* bInt = 0;
    bInt = bc.GetInterval();

    // make plots
    TCanvas * c1 = new TCanvas("c1");
    RooPlot * bplot = bc.GetPosteriorPlot();
    bplot -> Draw();
    c1 -> SaveAs("posterior_pdf.png");

    // query interval
    std::cout << "Bayesian interval on s = [" <<
              bInt->LowerLimit( ) << ", " <<
              bInt->UpperLimit( ) << "]" << std::endl;
}