Exemplo n.º 1
0
void test01()
{
  // S e t u p   m o d e l 
  // ---------------------

	TFile *openFile = new TFile("/tmp/kyolee/dimuonTree_upsiMiniTree_pA5tev_14nb_Run210498-210909_trigBit1_allTriggers0_pt4.root");
	TTree* tree = (TTree*)openFile->Get("UpsilonTree");	

  // Declare variables with associated name, title, initial value and allowed range
  RooRealVar mass("invariantMass","M_{#mu#mu} [GeV/c]",9.4,7,14) ;
  RooRealVar muPlusPt("muPlusPt","muPlusPt",0,40) ;
  RooRealVar muMinusPt("muMinusPt","muMinusPt",0,40) ;
  RooRealVar mean("mean","mean of gaussian",9.4,8,11) ;
  RooRealVar sigma("sigma","width of gaussian",1,0.1,10) ;

	RooDataSet* data = new RooDataSet("data", "data", RooArgSet(mass,muPlusPt,muMinusPt), Import(*tree), Cut("muPlusPt>4 && muMinusPt>4"));

 	data->Print();

  // Build gaussian p.d.f in terms of x,mean and sigma
  RooGaussian gauss("gauss","gaussian PDF",mass,mean,sigma) ;  

  // Construct plot frame in 'x'
  RooPlot* xframe = mass.frame(Title("Gaussian p.d.f.")) ;

	data->plotOn(xframe);

	/*
  // P l o t   m o d e l   a n d   c h a n g e   p a r a m e t e r   v a l u e s
  // ---------------------------------------------------------------------------

  // Plot gauss in frame (i.e. in x) 
  gauss.plotOn(xframe) ;

  // Change the value of sigma to 3
  sigma.setVal(3) ;

  // Plot gauss in frame (i.e. in x) and draw frame on canvas
  gauss.plotOn(xframe,LineColor(kRed)) ;
*/  

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

  // Fit pdf to data
  gauss.fitTo(*data,Range(9,10)) ;
  gauss.plotOn(xframe) ;

  // Print values of mean and sigma (that now reflect fitted values and errors)
  mean.Print() ;
  sigma.Print() ;


  // Draw all frames on a canvas
  TCanvas* c = new TCanvas("rf101_basics","rf101_basics",800,400) ;
  c->cd(1) ; gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.6) ; xframe->Draw() ;
 
}
Exemplo n.º 2
0
void read() {

  // Open File
  
  //TFile *datafile = TFile::Open("~/Documents/uni/LHCb_CharmSummerProj/Gedcode/baryon-lifetimes-2015/data/run-II-data/datafileLambda_TAUmin200fs_max2200fs_Mmin2216_max2356.root");
 
  //TFile *datafile = TFile::Open("~/Documents/uni/LHCb_CharmSummerProj/Gedcode/baryon-lifetimes-2015/data/run-II-data/datafileLambda_TAUmin200fs_max2200fs_Mmin2216_max2356_CutIPCHI2lt3.root"); 

  TFile *datafile = TFile::Open("~/Documents/uni/LHCb_CharmSummerProj/learning_root/DataSetLambda_TAUmin0002_max0022.root"); 

  //TFile *datafile = TFile::Open("~/Documents/uni/LHCb_CharmSummerProj/learning_root/DataSetfromGed_fit_data_wSWeight.root"); 

  // Define dataset
  RooDataSet* ds = (RooDataSet*)datafile->Get("ds") ;

  // Define TAU variable, get limits.
  RooRealVar Lambda_cplus_TAU("Lambda_cplus_TAU","Lambda_cplus_TAU",0.0002 ,0.0022 ,"ns") ;  //real range of interest is [0.00025, 0.002], this is defined later.
  double highestTAU;
  double lowestTAU;
  ds->getRange(Lambda_cplus_TAU, lowestTAU, highestTAU);

  // Define Mass variable, get limits.
  RooRealVar Lambda_cplus_M("Lambda_cplus_M","Lambda_cplus_M",2216 ,2356, "GeV") ; 
  double highestM;
  double lowestM;
  ds->RooAbsData::getRange(Lambda_cplus_M, lowestM, highestM) ;
  
  // Define IPCHI2 variable
  RooRealVar Lambda_cplus_IPCHI2_OWNPV("Lambda_cplus_IPCHI2_OWNPV","Lambda_cplus_IPCHI2_OWNPV",-100 ,100) ; 
  double highestIPCHI2_OWNPV;
  double lowestIPCHI2_OWNPV;
  ds->RooAbsData::getRange(Lambda_cplus_IPCHI2_OWNPV, lowestIPCHI2_OWNPV, highestIPCHI2_OWNPV) ;

  //Lambda_cplus_TAU.setRange("R1",0.00018, 0.0012);




  // Print to Screen
  cout<<endl<<endl<<"************info************"<<endl;

  cout<< "Lowest lifetime value in dataset = "<<lowestTAU<<endl;
  cout<< "Highest lifetime value in dataset = "<<highestTAU<<endl;  
  cout<< "Lowest mass value in dataset (should be: 2216)= "<<lowestM<<endl;
  cout<< "Highest mass value in dataset (should be: 2356)= "<<highestM<<endl; 
  cout<< "Lowest IPCHI2_OWNPV value in dataset = "<<lowestIPCHI2_OWNPV<<endl;
  cout<< "Highest IPCHI2_OWNPV value in dataset = "<<highestIPCHI2_OWNPV<<endl;
 
  cout<<"number of events: "<<endl ; 
  ds->Print();  //number of events in dataset    
  //rmodel->Print(); //results  
  //cout<<"Chi squared ="<<chi2<<endl ;
  
}
Exemplo n.º 3
0
///////////////////////////////////////////////////////////////////////////////
//weightDS 
///////////////////////////////////////////////////////////////////////////////
RooDataSet* weightDS(RooDataSet* set, double wgt){

  RooRealVar wt("wt","wt",wgt);
  set->addColumn(wt);

  RooDataSet* wSet = new RooDataSet(set->GetName(),set->GetTitle(),set,*set->get(),0,wt.GetName()) ;
  std::cout << "Returning weighted d.s." << std::endl;
  std::cout << std::endl;
  wSet->Print();
  return wSet;
    
}
Exemplo n.º 4
0
//
// 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;
}
Exemplo n.º 5
0
exampleScript()
{
  gSystem->CompileMacro("betaHelperFunctions.h"      ,"kO") ;
  gSystem->CompileMacro("RooNormalFromFlatPdf.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaInverseCDF.cxx"      ,"kO") ;
  gSystem->CompileMacro("RooBetaPrimeInverseCDF.cxx" ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("RooCorrelatedBetaPrimeGeneratorHelper.cxx"  ,"kO") ;
  gSystem->CompileMacro("rooFitBetaHelperFunctions.h","kO") ;

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

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

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

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

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

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

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

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

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

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

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

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

  RooRealVar* correlatedParameter = workspace.var(correlatedName);

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

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

  data->addColumn(*normalFromFlat);

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

  data->Print("v");

  workspace.Print() ;

  //Setup Plotting Kluges:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  observableSet->Print();

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

  correlatedParameter->setVal(0.25);

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

  correlatedParameter->setVal(0.75);

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

  //Testing for extreme values!

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


}
Exemplo n.º 6
0
/*RooDataSet* fillHIWTauDataSet(const TString& pathName, const TString& fileName, RooArgSet& muonArgSet, double wt=1.0){
    
  RooDataSet* set = new RooDataSet(fileName,fileName,muonArgSet);
  // --- Load the MC tree ---
  TChain* tree = new TChain("tree","tree");
  int nFiles = tree->Add(pathName+fileName);
  
  std::cout << "Filling the RooDataSet for " << fileName << "... Number of files: " << nFiles << std::endl;
  int nmu;
  float mc_mt[50], mc_mptPhi,mc_mptPx,mc_mptPy,mc_mptPz,mc_mptPt,centrality;
  float  mc_pt[50],  mc_ptNominal[50],mc_eta[50],mc_phi[50],mc_pdgId[50],mc_charge[50];
  float mc_M[50];

  tree->SetBranchAddress("nTauMu",&nmu);
  tree->SetBranchAddress("mc_mt",&mc_mt);
  tree->SetBranchAddress("mc_mptPhi",&mc_mptPhi);
  tree->SetBranchAddress("mc_mptPt",&mc_mptPt);
  tree->SetBranchAddress("centrality",&centrality);
  tree->SetBranchAddress("mc_pt",&mc_pt);
  tree->SetBranchAddress("mc_eta",&mc_eta);
  tree->SetBranchAddress("mc_phi",&mc_phi);
  tree->SetBranchAddress("mc_pdgId",&mc_pdgId);
  tree->SetBranchAddress("mc_charge",&mc_charge);

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("nTauMu",1);
  tree->SetBranchStatus("mc_mt",1);
  tree->SetBranchStatus("mc_mptPhi",1);
  tree->SetBranchStatus("mc_mptPt",1);
  tree->SetBranchStatus("centrality",1);
  tree->SetBranchStatus("mc_pt",1);
  tree->SetBranchStatus("mc_eta",1);
  tree->SetBranchStatus("mc_phi",1);
  tree->SetBranchStatus("mc_pdgId",1);
  tree->SetBranchStatus("mc_charge",1);

  std::cout << "Number of entries: " << tree->GetEntries() << std::endl; 
  for ( int i = 0; i < tree->GetEntries(); i++ ) {
//     if (i>10000) break; // temp hack
    tree->LoadTree(i);
    tree->GetEntry(i);

    muonArgSet.setRealValue("missPt",mc_mptPt);
    muonArgSet.setRealValue("centrality",centrality);

    for (int imu = 0; imu<nmu; ++imu){

      muonArgSet.setRealValue("w",wt);
      muonArgSet.setRealValue("muonPt",mc_pt[imu]);
      muonArgSet.setRealValue("muonMt",mc_mt[imu]);
      muonArgSet.setRealValue("muonEta",mc_eta[imu]);

      if (mc_charge[imu] > 0. ) muonArgSet.setCatLabel("chargeCategory","muPlus");
      else if (mc_charge[imu] < 0.) muonArgSet.setCatLabel("chargeCategory","muMinus");

      set->add(muonArgSet);    
    }//imu
   }//i
   
  return set;
}
*/
void bkgWtauPlotter(){

    ///Switch for binning
    bool doEta = true;
    bool doCentrality = true;
    bool doSystematic = false;

    ///Open file with product of CwAw as fcn
    ///of eta/centrality
    //TFile* _fCwAw = new TFile("CorrectionFactorFiles/correctionFactorsW_binbybin_9EtaBins6CentBins.07.24.2013.root","read");
    TFile* _fCwAw = new TFile("CorrectionFactorFiles/correctionFactorsW_binbybin_9VarEtaBins6CentBins2Charges.PowPy8.11.27.2013.root","read");
    //cross-check w/o mpt cut
    //TFile* _fCwAw = new TFile("crossChecks/correctionFactorsW_noMptCut.12.10.2013.root","read");
    ///Open file with efficiencies for muons passing
    ///PS,Z veto, isolation, and pT>25
//    TFile* _fCutEff = new TFile("background/mcWEffForTauMuonStudy_07_23_2013.root","read");
//
    ///Use this file for systematic study
    TFile* _fCutEff = NULL;
    if(doSystematic){
        std::cout << "WARNING! WARNING! WARNING! " << std::endl;
        std::cout << "Using different efficiencies for systematic study." << std::endl;
        _fCutEff = new TFile("systematics/mcWEffForTauMuonStudy_Systematics_07_28_2013.root","read");
    }
    else _fCutEff = new TFile("background/mcWEffForTauMuonStudy_07_23_2013.root","read");
    ///Open custom embedded Wtau ntuple
//    TFile* _fWtau = new TFile("","read");

    TFile* outFile = new TFile("fractionTauEtaCent_9etaBins6centBins.root","recreate");
	TString baseString = "/usatlas/u/tbales/scratch/";
    TString fileNameIn = "MonteCarloFiles/Wtaumu/HIWtaumuNtuple.07.30.2013";

    std::vector<double> centralityBins;
    centralityBins.push_back(0.0);
    if(doCentrality){
        centralityBins.push_back(0.05);
        centralityBins.push_back(0.10);
        centralityBins.push_back(0.15);
        centralityBins.push_back(0.20);
        centralityBins.push_back(0.40);
    }
    centralityBins.push_back(0.80);

    const int nCentralityBins = centralityBins.size()-1;

    std::vector<double> ptBins;
    ptBins.push_back(0.0);
    ptBins.push_back(300.0);
    const int nPtBins = ptBins.size()-1;

    std::vector<double> etaBins;
    etaBins.push_back(0.1);
    if(doEta){
        etaBins.push_back(0.35);
        etaBins.push_back(0.6);
        etaBins.push_back(0.8);
        etaBins.push_back(1.05);
        etaBins.push_back(1.37);
        etaBins.push_back(1.52);
        etaBins.push_back(1.74);
        etaBins.push_back(2.1);
 
    }
    etaBins.push_back(2.4);
    const int nEtaBins = etaBins.size()-1;

    // --- declare cut variables --- //
    RooRealVar muonPt("muonPt","p_{T}",0.0,350.0,"GeV");
    RooRealVar  missPt("missPt","p_{T}^{miss}",0.0,350.0,"GeV");
    RooRealVar  muonMt("muonMt","m_{T}",0.0,350.0,"GeV");
    RooRealVar  muonCharge("muonCharge","charge",-2.0,+2.0);
    RooRealVar  centrality("centrality","centrality",0.,1.0);
    RooRealVar  muonEta("muonEta","muonEta",-3.0,+3.0);
    RooRealVar  w("w","w",0.0,10.0);

    TString sCutsSig = "";
    sCutsSig = "abs(muonEta)>0.1&&abs(muonEta)<2.4&&muonPt>25.0&&missPt>25.0&&missPt<9000.0&&muonMt>40.0&&centrality>0.&&centrality<0.8";
    //cross-check w/o mpt cut
    //sCutsSig = "abs(muonEta)>0.1&&abs(muonEta)<2.4&&muonPt>25.0&&missPt>0.0&&missPt<9000.0&&muonMt>40.0&&centrality>0.&&centrality<0.8";
    if(doSystematic) sCutsSig = "muonPt>25.0&&abs(muonEta)>0.1&&abs(muonEta)<2.4&&centrality>0.&&centrality<0.8";
    std::cout << " Signals cuts: "<< sCutsSig << std::endl;

    RooArgList muonTauArgList(muonEta,muonPt,missPt,muonMt,centrality);

	RooFormulaVar cutsSig("cutsSig", "cutsSig", sCutsSig, muonTauArgList);

    RooCategory chargeCategory("chargeCategory","chargeCategory") ;
    chargeCategory.defineType("muMinus",-1) ;
    chargeCategory.defineType("muPlus",1) ;
    chargeCategory.Print();

    RooArgSet muonArgSet(muonPt,missPt,muonMt,muonEta,centrality,chargeCategory,w);

    ///Fill dataset
    RooDataSet* mcTauSet = fillHIWTauDataSet(baseString,fileNameIn+".root",muonArgSet); mcTauSet->Print(); 
    ///apply selection cuts
	RooDataSet* mcTauCutSet = (RooDataSet*)mcTauSet->reduce(Cut(cutsSig)); mcTauCutSet->Print();
    ///Create subsets
    RooDataSet* mcTauSubSet[nPtBins][nEtaBins][nCentralityBins];
    TH1F* hMcTauSubSet[nPtBins][nEtaBins][nCentralityBins];
    RooDataSet* mcTauCutSubSet[nPtBins][nEtaBins][nCentralityBins];
    TH1F* hMcTauCutSubSet[nPtBins][nEtaBins][nCentralityBins];

  	RooBinning b = RooBinning(170,0.0,510.0); // 3 GeV per bin
    std::cout << "Creating subsets..." << std::endl;
    char cTauGen[50],cTauCut[50];
    float cutEff;
	for ( int i = 0; i < nPtBins; i++ ) {
	  for ( int j = 0; j < nEtaBins; j++ ) {
	    for ( int k = 0; k < nCentralityBins; k++ ){

            sprintf(cTauGen,"hTauGen_Eta%i_Cent_%i",j,k);
            sprintf(cTauCut,"hTauCut_Eta%i_Cent_%i",j,k);

            TString sCutEff = "effForTauStudy_cent"; sCutEff+= k;
            TGraphAsymmErrors* grCutEff = (TGraphAsymmErrors*)_fCutEff->Get(sCutEff);
            ///Differential in centrality and eta
            if(doCentrality&&doEta) cutEff = grCutEff->GetY()[j];
            ///Averaged over all centrality and eta
            else cutEff =0.738509 ;
            ///bin in pt,eta,and centrality
            mcTauSubSet[i][j][k] = selectPtEtaCentrality(mcTauSet,ptBins[i], ptBins[i+1], etaBins[j], etaBins[j+1],centralityBins[k], centralityBins[k+1], true);
	        hMcTauSubSet[i][j][k] = (TH1F*)mcTauSubSet[i][j][k]->createHistogram(cTauGen,muonMt,Binning(b));
            std::cout << "Number of entries at generator level after selection for eta and centrality: " <<
                hMcTauSubSet[i][j][k]->Integral() << std::endl;
            std::cout << "Consistency check: " << mcTauSubSet[i][j][k]->numEntries() << "=?" <<
                hMcTauSubSet[i][j][k]->Integral() << std::endl;

            mcTauCutSubSet[i][j][k] = selectPtEtaCentrality(mcTauCutSet,ptBins[i], ptBins[i+1], etaBins[j], etaBins[j+1],centralityBins[k], centralityBins[k+1], true);
            std::cout << "Number of entries in cut set before applying efficiency: " << mcTauCutSubSet[i][j][k]->numEntries() << std::endl;
            w.setVal(cutEff);
            std::cout << "Weighting d.s. by cut efficiency: " << w.getVal() << std::endl;
            ///apply cut efficiency
            mcTauCutSubSet[i][j][k] = weightDS(mcTauCutSubSet[i][j][k],cutEff); 
	        hMcTauCutSubSet[i][j][k] = (TH1F*)mcTauCutSubSet[i][j][k]->createHistogram(cTauCut,muonMt,Binning(b));
            std::cout << "Number of events in cut subset after weighting: " << hMcTauCutSubSet[i][j][k]->Integral() << std::endl;
            //mcTauSubSet[i][j][k]->Print();
        }//k
      }//j
    }//i

    ///TGraph of tau bkg fraction
    TList _fraction;
    float CwAw;
	for ( int i = 0; i < nPtBins; i++ ) {
	  for ( int icent = 0; icent < nCentralityBins; icent++ ){
         
         _fraction.Add(new TGraphAsymmErrors(nEtaBins));
	    for ( int ieta = 0; ieta < nEtaBins; ieta++ ) {

            std::cout << " bin "<<i<<":"<<ieta<<":"<<icent<<std::endl;
            TString sCwAw = "grCwAwEtaDistroCent"; sCwAw+=icent;
            TGraphAsymmErrors* grCwAw = (TGraphAsymmErrors*)_fCwAw->Get(sCwAw);
            ///get CwAw product
            ///Differential in centrality and eta
            if(doCentrality&&doEta) CwAw = grCwAw->GetY()[ieta];
            ///Averaged over all centrality and eta
            else CwAw = 0.359;

            //plotBkgFraction(mcTauCutSubSet[i][ieta][icent],mcTauSubSet[i][ieta][icent],CwAw, (TGraphAsymmErrors*)_fraction.At(icent), ieta, etaBins[ieta], etaBins[ieta+1]);
            plotBkgFraction(hMcTauCutSubSet[i][ieta][icent],hMcTauSubSet[i][ieta][icent],CwAw, (TGraphAsymmErrors*)_fraction.At(icent), ieta, etaBins[ieta], etaBins[ieta+1]);

        }//k
        TString sName = "tauBkgFractionCent"; sName+=icent;
        ((TGraphAsymmErrors*)_fraction.At(icent))->SetName(sName);
        outFile->cd();
        ((TGraphAsymmErrors*)_fraction.At(icent))->Write();
      }//j
    }//k
        
    std::cout << "Clean up." << std::endl;
    for(int i=0; i<_fraction.GetEntries(); ++i){

        delete _fraction.At(i);
    }
}
Exemplo n.º 7
0
void rf303_conditional()
{
   // S e t u p   c o m p o s e d   m o d e l   g a u s s ( x , m ( y ) , s )
   // -----------------------------------------------------------------------

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

   // Create function f(y) = a0 + a1*y
   RooRealVar a0("a0","a0",-0.5,-5,5) ;
   RooRealVar a1("a1","a1",-0.5,-1,1) ;
   RooPolyVar fy("fy","fy",y,RooArgSet(a0,a1)) ;

   // Create gauss(x,f(y),s)
   RooRealVar sigma("sigma","width of gaussian",0.5,0.1,2.0) ;
   RooGaussian model("model","Gaussian with shifting mean",x,fy,sigma) ;


   // Obtain fake external experimental dataset with values for x and y
   RooDataSet* expDataXY = makeFakeDataXY() ;



   // G e n e r a t e   d a t a   f r o m   c o n d i t i o n a l   p . d . f   m o d e l ( x | y )
   // ---------------------------------------------------------------------------------------------

   // Make subset of experimental data with only y values
   RooDataSet* expDataY= (RooDataSet*) expDataXY->reduce(y) ;

   // Generate 10000 events in x obtained from _conditional_ model(x|y) with y values taken from experimental data
   RooDataSet *data = model.generate(x,ProtoData(*expDataY)) ;
   data->Print() ;



   // F i t   c o n d i t i o n a l   p . d . f   m o d e l ( x | y )   t o   d a t a
   // ---------------------------------------------------------------------------------------------

   model.fitTo(*expDataXY,ConditionalObservables(y)) ;



   // P r o j e c t   c o n d i t i o n a l   p . d . f   o n   x   a n d   y   d i m e n s i o n s
   // ---------------------------------------------------------------------------------------------

   // Plot x distribution of data and projection of model on x = 1/Ndata sum(data(y_i)) model(x;y_i)
   RooPlot* xframe = x.frame() ;
   expDataXY->plotOn(xframe) ;
   model.plotOn(xframe,ProjWData(*expDataY)) ;


   // Speed up (and approximate) projection by using binned clone of data for projection
   RooAbsData* binnedDataY = expDataY->binnedClone() ;
   model.plotOn(xframe,ProjWData(*binnedDataY),LineColor(kCyan),LineStyle(kDotted)) ;


   // Show effect of projection with too coarse binning
   ((RooRealVar*)expDataY->get()->find("y"))->setBins(5) ;
   RooAbsData* binnedDataY2 = expDataY->binnedClone() ;
   model.plotOn(xframe,ProjWData(*binnedDataY2),LineColor(kRed)) ;


   // Make canvas and draw RooPlots
   new TCanvas("rf303_conditional","rf303_conditional",600, 460);
   gPad->SetLeftMargin(0.15) ; xframe->GetYaxis()->SetTitleOffset(1.2) ; xframe->Draw() ;

}
Exemplo n.º 8
0
void rf403_weightedevts()
{
  // C r e a t e   o b s e r v a b l e   a n d   u n w e i g h t e d   d a t a s e t 
  // -------------------------------------------------------------------------------

  // Declare observable
  RooRealVar x("x","x",-10,10) ;
  x.setBins(40) ;

  // Construction a uniform pdf
  RooPolynomial p0("px","px",x) ;

  // Sample 1000 events from pdf
  RooDataSet* data = p0.generate(x,1000) ;

 

  // C a l c u l a t e   w e i g h t   a n d   m a k e   d a t a s e t   w e i g h t e d 
  // -----------------------------------------------------------------------------------

  // Construct formula to calculate (fake) weight for events
  RooFormulaVar wFunc("w","event weight","(x*x+10)",x) ;

  // Add column with variable w to previously generated dataset
  RooRealVar* w = (RooRealVar*) data->addColumn(wFunc) ;

  // Dataset d is now a dataset with two observable (x,w) with 1000 entries
  data->Print() ;

  // Instruct dataset wdata in interpret w as event weight rather than as observable
  RooDataSet wdata(data->GetName(),data->GetTitle(),data,*data->get(),0,w->GetName()) ;

  // Dataset d is now a dataset with one observable (x) with 1000 entries and a sum of weights of ~430K
  wdata.Print() ;



  // U n b i n n e d   M L   f i t   t o   w e i g h t e d   d a t a 
  // ---------------------------------------------------------------

  // Construction quadratic polynomial pdf for fitting
  RooRealVar a0("a0","a0",1) ;
  RooRealVar a1("a1","a1",0,-1,1) ;
  RooRealVar a2("a2","a2",1,0,10) ;
  RooPolynomial p2("p2","p2",x,RooArgList(a0,a1,a2),0) ;

  // Fit quadratic polynomial to weighted data

  // NOTE: A plain Maximum likelihood fit to weighted data does in general 
  //       NOT result in correct error estimates, unless individual
  //       event weights represent Poisson statistics themselves.
  //       
  // Fit with 'wrong' errors
  RooFitResult* r_ml_wgt = p2.fitTo(wdata,Save()) ;
  
  // A first order correction to estimated parameter errors in an 
  // (unbinned) ML fit can be obtained by calculating the
  // covariance matrix as
  //
  //    V' = V C-1 V
  //
  // where V is the covariance matrix calculated from a fit
  // to -logL = - sum [ w_i log f(x_i) ] and C is the covariance
  // matrix calculated from -logL' = -sum [ w_i^2 log f(x_i) ] 
  // (i.e. the weights are applied squared)
  //
  // A fit in this mode can be performed as follows:

  RooFitResult* r_ml_wgt_corr = p2.fitTo(wdata,Save(),SumW2Error(kTRUE)) ;



  // P l o t   w e i g h e d   d a t a   a n d   f i t   r e s u l t 
  // ---------------------------------------------------------------

  // Construct plot frame
  RooPlot* frame = x.frame(Title("Unbinned ML fit, binned chi^2 fit to weighted data")) ;

  // Plot data using sum-of-weights-squared error rather than Poisson errors
  wdata.plotOn(frame,DataError(RooAbsData::SumW2)) ;

  // Overlay result of 2nd order polynomial fit to weighted data
  p2.plotOn(frame) ;



  // M L  F i t   o f   p d f   t o   e q u i v a l e n t  u n w e i g h t e d   d a t a s e t
  // -----------------------------------------------------------------------------------------
  
  // Construct a pdf with the same shape as p0 after weighting
  RooGenericPdf genPdf("genPdf","x*x+10",x) ;

  // Sample a dataset with the same number of events as data
  RooDataSet* data2 = genPdf.generate(x,1000) ;

  // Sample a dataset with the same number of weights as data
  RooDataSet* data3 = genPdf.generate(x,43000) ;

  // Fit the 2nd order polynomial to both unweighted datasets and save the results for comparison
  RooFitResult* r_ml_unw10 = p2.fitTo(*data2,Save()) ;
  RooFitResult* r_ml_unw43 = p2.fitTo(*data3,Save()) ;


  // C h i 2   f i t   o f   p d f   t o   b i n n e d   w e i g h t e d   d a t a s e t
  // ------------------------------------------------------------------------------------

  // Construct binned clone of unbinned weighted dataset
  RooDataHist* binnedData = wdata.binnedClone() ;
  binnedData->Print("v") ;

  // Perform chi2 fit to binned weighted dataset using sum-of-weights errors
  // 
  // NB: Within the usual approximations of a chi2 fit, a chi2 fit to weighted
  // data using sum-of-weights-squared errors does give correct error
  // estimates
  RooChi2Var chi2("chi2","chi2",p2,*binnedData,DataError(RooAbsData::SumW2)) ;
  RooMinuit m(chi2) ;
  m.migrad() ;
  m.hesse() ;

  // Plot chi^2 fit result on frame as well
  RooFitResult* r_chi2_wgt = m.save() ;
  p2.plotOn(frame,LineStyle(kDashed),LineColor(kRed)) ;



  // C o m p a r e   f i t   r e s u l t s   o f   c h i 2 , M L   f i t s   t o   ( u n ) w e i g h t e d   d a t a 
  // ---------------------------------------------------------------------------------------------------------------

  // Note that ML fit on 1Kevt of weighted data is closer to result of ML fit on 43Kevt of unweighted data 
  // than to 1Kevt of unweighted data, whereas the reference chi^2 fit with SumW2 error gives a result closer to
  // that of an unbinned ML fit to 1Kevt of unweighted data. 

  cout << "==> ML Fit results on 1K unweighted events" << endl ;
  r_ml_unw10->Print() ;
  cout << "==> ML Fit results on 43K unweighted events" << endl ;
  r_ml_unw43->Print() ;
  cout << "==> ML Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_ml_wgt->Print() ;
  cout << "==> Corrected ML Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_ml_wgt_corr->Print() ;
  cout << "==> Chi2 Fit results on 1K weighted events with a summed weight of 43K" << endl ;
  r_chi2_wgt->Print() ;


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


}
Exemplo n.º 9
0
//put very small data entries in a binned dataset to avoid unphysical pdfs, specifically for H->ZZ->4l
RooDataSet* makeData(RooDataSet* orig, RooSimultaneous* simPdf, const RooArgSet* observables, RooRealVar* firstPOI, double mass, double& mu_min)
{

  double max_soverb = 0;

  mu_min = -10e9;

  map<string, RooDataSet*> data_map;
  firstPOI->setVal(0);
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();
  TList* datalist = orig->split(*(RooAbsCategory*)cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  RooRealVar* weightVar = new RooRealVar("weightVar","weightVar",1);
  while ((ds = (RooAbsData*)dataItr->Next()))
  {
    string typeName(ds->GetName());
    cat->setLabel(typeName.c_str());
    RooAbsPdf* pdf = simPdf->getPdf(typeName.c_str());
    cout << "pdf: " << pdf << endl;
    RooArgSet* obs = pdf->getObservables(observables);
    cout << "obs: " << obs << endl;

    RooArgSet obsAndWeight(*obs, *weightVar);
    obsAndWeight.add(*cat);
    stringstream datasetName;
    datasetName << "newData_" << typeName;
    RooDataSet* thisData = new RooDataSet(datasetName.str().c_str(),datasetName.str().c_str(), obsAndWeight, WeightVar(*weightVar));

    RooRealVar* firstObs = (RooRealVar*)obs->first();
    //int ibin = 0;
    int nrEntries = ds->numEntries();
    for (int ib=0;ib<nrEntries;ib++)
    {
      const RooArgSet* event = ds->get(ib);
      const RooRealVar* thisObs = (RooRealVar*)event->find(firstObs->GetName());
      firstObs->setVal(thisObs->getVal());

      firstPOI->setVal(0);
      double b = pdf->expectedEvents(*firstObs)*pdf->getVal(obs);
      firstPOI->setVal(1);
      double s = pdf->expectedEvents(*firstObs)*pdf->getVal(obs) - b;

      if (s > 0)
      {
	mu_min = max(mu_min, -b/s);
	double soverb = s/b;
	if (soverb > max_soverb)
	{
	  max_soverb = soverb;
	  cout << "Found new max s/b: " << soverb << " in pdf " << pdf->GetName() << " at m = " << thisObs->getVal() << endl;
	}
      }

      if (b == 0 && s != 0)
      {
	cout << "Expecting non-zero signal and zero bg at m=" << firstObs->getVal() << " in pdf " << pdf->GetName() << endl;
      }
      if (s+b <= 0) 
      {
	cout << "expecting zero" << endl;
	continue;
      }


      double weight = ds->weight();
      if ((typeName.find("ATLAS_H_4mu") != string::npos || 
	   typeName.find("ATLAS_H_4e") != string::npos ||
	   typeName.find("ATLAS_H_2mu2e") != string::npos ||
	   typeName.find("ATLAS_H_2e2mu") != string::npos) && fabs(firstObs->getVal() - mass) < 10 && weight == 0)
      {
	cout << "adding event: " << firstObs->getVal() << endl;
	thisData->add(*event, pow(10., -9.));
      }
      else
      {
	//weight = max(pow(10.0, -9), weight);
	thisData->add(*event, weight);
      }
    }



    data_map[string(ds->GetName())] = (RooDataSet*)thisData;
  }

  
  RooDataSet* newData = new RooDataSet("newData","newData",RooArgSet(*observables, *weightVar), 
				       Index(*cat), Import(data_map), WeightVar(*weightVar));

  orig->Print();
  newData->Print();
  //newData->tree()->Scan("*");
  return newData;

}
Exemplo n.º 10
0
int main(int argc, const char** argv){
  bool ReDoCuts=false;

  TCut TwelveCut = "gamma_CL>0.1&&BDT_response>0.36&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  TCut ElevenCut = "gamma_CL>0.1&&BDT_response>0.30&&piplus_MC12TuneV3_ProbNNpi>0.2&&piminus_MC12TuneV3_ProbNNpi>0.2&&Kaon_MC12TuneV3_ProbNNk>0.4";
  
  //______________________________MAKE CUT FILE FOR 2012___________________________________
  if(ReDoCuts){
    DataFile MCA(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MCB(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    TreeReader* MC12Reader=  new TreeReader("DecayTree");
    MC12Reader->AddFile(MCA);
    MC12Reader->AddFile(MCB);
    MC12Reader->Initialize();
    
    TFile* MC12Cut = new TFile("CutFile12.root","RECREATE");
    TTree* MC12CutTree=MC12Reader->CopyTree(TwelveCut,-1,"DecayTree");
    TRandom3 *MCRand = new TRandom3(224);
    TH1I * MCnCands12= new TH1I("MCnCands12","MCnCands12",10,0,10);
    TTree*MC12SingleTree=HandyFunctions::GetSingleTree(MCRand,MC12CutTree,MCnCands12,NULL);
    MCnCands12->Write();
    MC12SingleTree->Write();
    MC12Cut->Close();
    
    //________________________________MAKE CUT FILE FOR 2011__________________________________
    
    DataFile MC11A(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleA");
    
    DataFile MC11B(std::getenv("BUKETAPMCBDTRESPROOT"),MC,Elev,MagAll,buketap,"BDTApplied_SampleB");
    
    TreeReader* MC11Reader= new TreeReader("DecayTree");
    MC11Reader->AddFile(MC11A);
    MC11Reader->AddFile(MC11B);
    MC11Reader->Initialize();
    
    TFile* MC11Cut = new TFile("CutFile11.root","RECREATE");
    TTree* MC11CutTree=MC11Reader->CopyTree(ElevenCut,-1,"DecayTree");

    TH1I * MCnCands11= new TH1I("MCnCands11","MCnCands11",10,0,10);
    TTree* MC11SingleTree=HandyFunctions::GetSingleTree(MCRand,MC11CutTree,MCnCands11,NULL);
    MCnCands11->Write();
    MC11SingleTree->Write();
    MC11Cut->Close();
  //_________________________________ MAKE FLAT TREES  ____________________________________
  
    TFile* MC12Input = new TFile("CutFile12.root");
    TTree* MC12InputTree=(TTree*)MC12Input->Get("DecayTree");
    Float_t MCEta_Mass12[20]; MC12InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass12);
    Int_t isSingle12; MC12InputTree->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MC12FlatOut = new TFile("MCMinimalFile12.root","RECREATE");
    TTree* MC12FlatTree = MC12InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF12; MC12FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=MC12InputTree->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      MC12InputTree->GetEntry(i);
      if(isSingle12==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF12=MCEta_Mass12[0];
      MC12FlatTree->Fill();
    }
    
    MC12FlatTree->Write();
    MC12FlatOut->Close();
    
    TFile* MC11Input = new TFile("CutFile11.root");
    TTree* MC11InputTree=(TTree*)MC11Input->Get("DecayTree");
    Float_t MCEta_Mass11[20]; MC11InputTree->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&MCEta_Mass11);
    Int_t isSingle11; MC11InputTree->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MC11FlatOut = new TFile("MCMinimalFile11.root","RECREATE");
    TTree* MC11FlatTree = MC11InputTree->CloneTree(0);
    Double_t MCBu_DTFNoFix_eta_Prime_MF11; MC11FlatTree->Branch("Bu_DTFNoFix_eta_prime_MF",&MCBu_DTFNoFix_eta_Prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=MC11InputTree->GetEntries();
    
    for(int i=0;i<Entries11;++i){
      MC11InputTree->GetEntry(i);
      if(isSingle11==0)continue;
      MCBu_DTFNoFix_eta_Prime_MF11=MCEta_Mass11[0];
      MC11FlatTree->Fill();
    }
    
    MC11FlatTree->Write();
    MC11FlatOut->Close();
  }
  
  //_____________________________________________LOAD ROODATASETS___________________________________

  TFile* MCFlatInput12= new TFile("MCMinimalFile12.root");
  TTree* MCFlatInputTree12=(TTree*)MCFlatInput12->Get("DecayTree");

  TFile* MCFlatInput11= new TFile("MCMinimalFile11.root");
  TTree* MCFlatInputTree11=(TTree*)MCFlatInput11->Get("DecayTree");

  RooRealVar MCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar MCEtaMass("eta_prime_MM","eta_prime_MM",700.0,1200.0);
  RooRealVar BDT_response("BDT_response","BDT_response",-1.0,1.0);
  RooRealVar gamma_CL("gamma_CL","gamma_CL",0.1,1.0);
  RooArgSet Args(MCBMass,MCEtaMass,BDT_response,gamma_CL);

  RooDataSet* MCData12 = new RooDataSet("MCData12","MCData12",Args,Import(*MCFlatInputTree12));
  
  std::cout <<" Data File 12 Loaded"<<std::endl;
  
  RooDataSet* MCData11 = new RooDataSet("MCData11","MCData11",Args,Import(*MCFlatInputTree11));

  std::cout<<" Data File 11 loaded"<<std::endl;

  RooDataSet* MCDataAll= new RooDataSet("MCDataAll","MCDataAll",Args);

  MCDataAll->append(*MCData12);
  MCDataAll->append(*MCData11);
  
  RooPlot* massFrame = MCBMass.frame(Title("Data Import Check"),Bins(50));
  MCDataAll->plotOn(massFrame);
  
  RooPlot *BDTFrame = BDT_response.frame(Title("BDT Cut Check"),Bins(50));
  MCDataAll->plotOn(BDTFrame);
  TCanvas C;
  C.Divide(2,1);
  C.cd(1);
  massFrame->Draw();
  C.cd(2);
  BDTFrame->Draw();
  C.SaveAs("ImportChecks.eps");

  //________________________________MAKE MCROODATACATEGORIES__________________________________

  RooDataSet* MCBData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCBMass));
  MCBData->Print("v");
  
  RooDataSet* MCEtaData=(RooDataSet*)MCDataAll->reduce(RooArgSet(MCEtaMass));
  MCEtaData->Print("v");

  RooCategory MCMassType("MCMassType","MCMassType") ;
  MCMassType.defineType("B") ;
  MCMassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet MCcombData("MCcombData","MC combined data",Args,Index(MCMassType),Import("B",*MCBData),Import("Eta",*MCEtaData));

  
  //=============================================== MC FIT MODEL===================================
  
  RooRealVar Mean("Mean","Mean",5279.29,5276.0,5284.00);
  RooRealVar Sigma("Sigma","Sigma",20.54,17.0,24.8);
  RooRealVar LAlpha("LAlpha","LAlpha",-1.064,-2.5,0.0);
  RooRealVar RAlpha("RAlpha","RAlpha",1.88,0.0,5.0);
  RooRealVar LN("LN","LN",13.0,0.0,40.0);
  RooRealVar RN("RN","RN",2.56,0.0,6.0);

  RooCBShape CBLeft("CBLeft","CBLeft",MCBMass,Mean,Sigma,LAlpha,LN);
  
  RooCBShape CBRight("CBRight","CBRight",MCBMass,Mean,Sigma,RAlpha,RN);

  RooRealVar FitFraction("FitFraction","FitFraction",0.5,0.0,1.0);
  RooAddPdf DCB("DCB","DCB",RooArgList(CBRight,CBLeft),FitFraction);

  RooRealVar SignalYield("SignalYield","SignalYield",4338.0,500.0,10000.0);
  //  RooExtendPdf ExtDCB("ExtDCB","ExtDCB",DCB,SignalYield);
  
  //==============================ETA DCB ++++++++++++++++++++++++++++++
  
  RooRealVar MCEtamean("MCEtamean","MCEtamean",958.0,955.0,960.0);
  RooRealVar MCEtasigma("MCEtasigma","MCEtasigma",9.16,8.0,14.0);
  RooRealVar EtaLAlpha("EtaLAlpha","EtaLAlpha",-1.45,-5.0,1.0);
  RooRealVar EtaRAlpha("EtaRAlpha","EtaRAlpha",1.76,0.0,4.0);
  RooRealVar EtaLN("EtaLN","EtaLN",0.1,0.0,20.0);
  RooRealVar EtaRN("EtaRN","EtaRN",0.1,0.0,20.0);

  RooCBShape EtaCBLeft("EtaCBLeft","EtaCBLeft",MCEtaMass,MCEtamean,MCEtasigma,EtaLAlpha,EtaLN);
  
  RooCBShape EtaCBRight("EtaCBRight","EtaCBRight",MCEtaMass,MCEtamean,MCEtasigma,EtaRAlpha,EtaRN);

  RooRealVar EtaFitFraction("EtaFitFraction","EtaFitFraction",0.22,0.1,1.0);
  RooAddPdf EtaDCB("EteaDCB","EtaDCB",RooArgList(EtaCBRight,EtaCBLeft),EtaFitFraction);

  RooProdPdf MCSignalPdf("MCSignalPdf","MCSignalPdf",RooArgSet(EtaDCB,DCB));
  
  RooExtendPdf ExtendedMCSignalPdf("ExtendedMCSignalPdf","ExtendedMCSignalPdf",MCSignalPdf,SignalYield);

  RooSimultaneous MCsimPdf("MCsimPdf","MC simultaneous pdf",MCMassType) ;
  //  MCsimPdf.addPdf(ExtDCB,"B");
  //  MCsimPdf.addPdf(ExtendedMCEtaDCB,"Eta"); 

  //============================== DO the MC FIT =======================================
  //MCsimPdf.fitTo(MCcombData,Extended(kTRUE),Minos(kTRUE));
  //ExtendedMCEtaDCB.fitTo(*MCEtaData,Extended(kTRUE),Minos(kTRUE));
  //ExtDCB.fitTo(*MCBData,Extended(
  ExtendedMCSignalPdf.fitTo(*MCDataAll,Extended(kTRUE),Minos(kTRUE));
  
  RooPlot* MCframe1 = MCBMass.frame(Range(5100.0,5500.0),Bins(50),Title("B mass projection"));
  MCDataAll->plotOn(MCframe1);
  ExtendedMCSignalPdf.plotOn(MCframe1);
  ExtendedMCSignalPdf.paramOn(MCframe1);
  
  RooPlot* MCframe2 = MCEtaMass.frame(Range(880.0,1020.0),Bins(50),Title("Eta mass projection")) ;
  MCDataAll->plotOn(MCframe2);
  ExtendedMCSignalPdf.plotOn(MCframe2);
  ExtendedMCSignalPdf.paramOn(MCframe2);
  
  TCanvas* MCc = new TCanvas("rf501_simultaneouspdf","rf403_simultaneouspdf",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; MCframe1->GetYaxis()->SetTitleOffset(1.4) ; MCframe1->Draw() ;
  MCc->SaveAs("MCSimulCanvas.pdf");

  TCanvas* MCcEta = new TCanvas(" Eta Canvas","Eta Canvas",1200,1000);
  gPad->SetLeftMargin(0.15) ; MCframe2->GetYaxis()->SetTitleOffset(1.4) ; MCframe2->Draw() ;
  MCcEta->SaveAs("MCEtaCanvas.pdf");

  TFile* MCFits= new TFile("MCFitResult.root","RECREATE");
  //  TCanvas* DecMCB=HandyFunctions::DecoratePlot(MCframe1);
  //  TCanvas* DecMCEta=HandyFunctions::DecoratePlot(MCframe2);
  //DecMCEta->Write();
  //  DecMCB->Write();
  MCc->Write();
  MCcEta->Write();

  std::cout<<"MC Eta Chi2 = "<<MCframe2->chiSquare()<<std::endl;
  std::cout<<"MC B Chi2 = "<<MCframe1->chiSquare()<<std::endl;

  //___________________________________ CUT DOWN COLLISION DATA ______________________________
  if(ReDoCuts){
    DataFile TwelveA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleA");

    DataFile TwelveB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
  
    DataFile ElevenA(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleA");

    DataFile ElevenB(std::getenv("BUKETAPDATABDTRESPROOT"),Data,Elev,MagAll,buketap,"BDTApplied_SampleB");		

    TRandom3* DataRand= new TRandom3(224);
    TH1I* DataNCand12= new TH1I("DataNCand12","DataNCand12",10,0,10);
    TH1I* DataNCand11= new TH1I("DataNCand11","DataNCand11",10,0,10);
    
    TreeReader* UncutDataReader12= new TreeReader("DecayTree");
    UncutDataReader12->AddFile(TwelveA);
    UncutDataReader12->AddFile(TwelveB);
    UncutDataReader12->Initialize();
    
    TFile* CutDataFile12 = new TFile("CutDataFile12.root","RECREATE");
    TTree* CutDataTree12 = UncutDataReader12->CopyTree(TwelveCut,-1,"DecayTree");
    TTree* SingleCutDataTree12=HandyFunctions::GetSingleTree(DataRand,CutDataTree12,DataNCand12,NULL);
    SingleCutDataTree12->Write();
    CutDataFile12->Close();
    
    TreeReader* UncutDataReader11= new TreeReader("DecayTree");
    UncutDataReader11->AddFile(ElevenB);
    UncutDataReader11->AddFile(ElevenA);
    UncutDataReader11->Initialize();
    
    TFile* CutDataFile11 = new TFile("CutDataFile11.root","RECREATE");
    TTree* CutDataTree11 = UncutDataReader11->CopyTree(ElevenCut,-1,"DecayTree");
    TTree* SingleCutDataTree11=HandyFunctions::GetSingleTree(DataRand,CutDataTree11,DataNCand11,NULL);
    SingleCutDataTree11->Write();
    CutDataFile11->Close();
  

    TFile* DataInput12 = new TFile("CutDataFile12.root");
    TTree* DataInputTree12=(TTree*)DataInput12->Get("DecayTree");
    DataInputTree12->SetBranchStatus("*",0);
    DataInputTree12->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree12->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree12->SetBranchStatus("eta_prime_MM",1);
    DataInputTree12->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass12[20]; DataInputTree12->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass12);
    Int_t isSingle12; DataInputTree12->SetBranchAddress("isSingle",&isSingle12);
    
    TFile* MinimalDataFile12 = new TFile("MinimalDataFile12.root","RECREATE");
    TTree* MinimalDataTree12= DataInputTree12->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF12; MinimalDataTree12->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF12,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries12=DataInputTree12->GetEntries();
    
    for(int i=0;i<Entries12;++i){
      DataInputTree12->GetEntry(i);
      if(isSingle12==0)continue;
      Bu_DTFNoFix_eta_prime_MF12=Eta_Mass12[0];
      MinimalDataTree12->Fill();
    }
    
    MinimalDataTree12->Write();
    MinimalDataFile12->Close();
    
    TFile* DataInput11 = new TFile("CutDataFile11.root");
    TTree* DataInputTree11=(TTree*)DataInput11->Get("DecayTree");
    DataInputTree11->SetBranchStatus("*",0);
    DataInputTree11->SetBranchStatus("Bu_DTF_MF",1);
    DataInputTree11->SetBranchStatus("Bu_DTFNoFix_eta_prime_M",1);
    DataInputTree11->SetBranchStatus("eta_prime_MM",1);
    DataInputTree11->SetBranchStatus("isSingle",1);
    Float_t Eta_Mass11[20]; DataInputTree11->SetBranchAddress("Bu_DTFNoFix_eta_prime_M",&Eta_Mass11);
    Int_t isSingle11; DataInputTree11->SetBranchAddress("isSingle",&isSingle11);
    
    TFile* MinimalDataFile11 = new TFile("MinimalDataFile11.root","RECREATE");
    TTree* MinimalDataTree11= DataInputTree11->CloneTree(0);
    Double_t Bu_DTFNoFix_eta_prime_MF11; MinimalDataTree11->Branch("Bu_DTFNoFix_eta_prime_MF",&Bu_DTFNoFix_eta_prime_MF11,"Bu_DTFNoFix_eta_prime_MF/D");
    
    Long64_t Entries11=DataInputTree11->GetEntries();
    
    for(int i=0;i<Entries11;++i){
    DataInputTree11->GetEntry(i);
    if(isSingle11==0)continue;
    Bu_DTFNoFix_eta_prime_MF11=Eta_Mass11[0];
    MinimalDataTree11->Fill();
    }
    MinimalDataTree11->Write();
    MinimalDataFile11->Close();
  }

  //___________________________________ LOAD DATA TO ROODATASET____________________________________
  
  RooRealVar BMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5600.0);
  RooRealVar EtaMass("eta_prime_MM","eta_prime_MM",870.0,1050.0);
  RooArgSet MassArgs(BMass,EtaMass);

  TFile* Data12File = new TFile("MinimalDataFile12.root");
  TTree* DataTree12=(TTree*)Data12File->Get("DecayTree");

  RooDataSet* Data12 = new RooDataSet("Data12","Data12",MassArgs,Import(*DataTree12));

  TFile* Data11File = new TFile("MinimalDataFile11.root");
  TTree* DataTree11=(TTree*)Data11File->Get("DecayTree");

  RooDataSet* Data11 = new RooDataSet("Data11","Data11",MassArgs,Import(*DataTree11));
  
  RooDataSet* AllData = new RooDataSet("AllData","AllData",MassArgs);
  AllData->append(*Data12);
  AllData->append(*Data11);
  TCanvas ImportC;
  RooPlot* ImportCheck = BMass.frame(Title("ImportCheck"),Bins(50));
  AllData->plotOn(ImportCheck);
  ImportCheck->Draw();
  ImportC.SaveAs("Alldataimport.pdf");

  std::cout<<" Data Loaded, Total Entries = "<<AllData->numEntries()<<std::endl;

  AllData->Print("v");

  RooDataSet* BData=(RooDataSet*)AllData->reduce(RooArgSet(BMass));
  BData->Print("v");

  RooDataSet* EtaData=(RooDataSet*)AllData->reduce(RooArgSet(EtaMass));
  EtaData->Print("v");

  //___________________________________Fit to Eta_Prime in BMass Sidebands______________________

  RooDataSet* BSidebands=(RooDataSet*)AllData->reduce(Cut("(Bu_DTF_MF>5000.0&&Bu_DTF_MF<5179.0)||(Bu_DTF_MF>5379.0&&Bu_DTF_MF<5800.0)"));

  TCanvas BSidebandCanvas;
  RooPlot* BSidebandPlot = EtaMass.frame(Title("B sidebands"),Bins(30));
  BSidebands->plotOn(BSidebandPlot);
  BSidebandPlot->Draw();
  BSidebandCanvas.SaveAs("BSidebandDataCheck.pdf");

  
  RooRealVar BsbMean(" Mean","BsbMean",958.0,900.0,1020.0);
  RooRealVar BsbSigma(" Sigma","BsbSigma",19.8,10.0,40.8);
  RooRealVar BsbLAlpha(" Alpha","BsbLAlpha",-1.63,-10.0,0.0);
  //  RooRealVar BsbRAlpha("BsbRAlpha","BsbRAlpha",1.47,0.0,10.0);
  RooRealVar BsbLN(" N","BsbLN",0.1,0.0,20.0);
  //  RooRealVar BsbRN("BsbRN","BsbRN",0.1,0.0,20.0);

  RooCBShape BsbCBLeft("BsbCBLeft","BsbCBLeft",EtaMass,BsbMean,BsbSigma,BsbLAlpha,BsbLN);
  
  //  RooCBShape BsbCBRight("BsbCBRight","BsbCBRight",EtaMass,BsbMean,BsbSigma,BsbRAlpha,BsbRN);

  //  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.5,0.0,1.0);
  //  RooAddPdf BsbDCB("BsbDCB","BsbDCB",RooArgList(BsbCBRight,BsbCBLeft),BsbFitFraction);
  RooRealVar Bsbslope("Bsbslope","Bsbslope",0.5,0.0,1.0);
  RooRealVar BsbP2("BsbP2","BsbP2",-0.5,-1.0,0.0);
  RooChebychev BsbLinear("BsbLinear","BsbLinear",EtaMass,RooArgSet(Bsbslope,BsbP2));

  RooRealVar BsbFitFraction("BsbFitFraction","BsbFitFraction",0.2,0.0,1.0);

  RooAddPdf BsbBackground("BsbBackground","BsbBackground",RooArgList(BsbLinear,BsbCBLeft),BsbFitFraction);
  
  RooRealVar BsbYield(" Yield","BsbYield",500.0,0.0,1000.0);
  RooExtendPdf BsbExtDCB("BsbExtDCB","BsbExtDCB",BsbCBLeft,BsbYield);

  BsbExtDCB.fitTo(*BSidebands,Extended(kTRUE),Minos(kTRUE));
  TCanvas BSBFitCanvas;
  RooPlot* BSBFitPlot = EtaMass.frame(Title("Eta fit in B Sidebands"),Bins(30));
  BSidebands->plotOn(BSBFitPlot);
  BsbExtDCB.plotOn(BSBFitPlot);
  BsbExtDCB.paramOn(BSBFitPlot);
  BSBFitPlot->Draw();
  BSBFitCanvas.SaveAs("BSidebandFit.pdf");
  TFile * SidebandFitFile= new TFile("SidebandFit.root","RECREATE");
  BSBFitCanvas.Write();
  SidebandFitFile->Close();
  
  //___________________________________DO THE 2D FIT TO DATA___________________________________


  const double PDGBMass= 5279.26;
  BMass.setRange("SignalWindow",PDGBMass-(3*Sigma.getVal()),PDGBMass+(3*Sigma.getVal()));
  RooRealVar DSignalYield("DSignalYield","DSignalYield",4000.0,0.0,10000.0);

  //================================= B MASS SIGNAL PDF==============================
  RooRealVar DMean("Mean","DMean",5279.29,5270.0,5290.00);
  RooRealVar DSigma("Sigma","DSigma",19.8,10.0,40.8);
  RooRealVar DLAlpha("DLAlpha","DLAlpha",LAlpha.getVal());
  RooRealVar DRAlpha("DRAlpha","DRAlpha",RAlpha.getVal());
  RooRealVar DLN("DLN","DLN",LN.getVal());
  RooRealVar DRN("DRN","DRN",RN.getVal());

  RooCBShape DCBLeft("DCBLeft","DCBLeft",BMass,DMean,DSigma,DLAlpha,DLN);
  
  RooCBShape DCBRight("DCBRight","DCBRight",BMass,DMean,DSigma,DRAlpha,DRN);

  RooRealVar DFitFraction("FitFraction","DFitFraction",0.5,0.0,1.0);
  RooAddPdf DDCB("DDCB","DDCB",RooArgList(DCBRight,DCBLeft),DFitFraction);
  
  //==============================B MASS BKG PDF==============================
  RooRealVar slope("slope","slope",-0.5,-1.0,0.0);
  RooChebychev bkg("bkg","Background",BMass,RooArgSet(slope));
  
  //==============================Eta mass signal pdf================================
  RooRealVar DEtamean("Etamean","DEtamean",958.0,945.0,980.0) ;
  RooRealVar DEtasigma("Etasigma","DEtasigma",15.0,5.0,65.0) ;
  RooRealVar DEtaLAlpha("DEtaLAlpha","DEtaLAlpha",EtaLAlpha.getVal());
  RooRealVar DEtaRAlpha("DEtaRAlpha","DEtaRAlpha",EtaRAlpha.getVal());
  RooRealVar DEtaLN("DEtaLN","DEtaLN",EtaLN.getVal());
  RooRealVar DEtaRN("DEtaRN","DEtaRN",EtaRN.getVal());
  
  RooCBShape EtaDCBLeft("EtaDCBLeft","EtaDCBLeft",EtaMass,DEtamean,DEtasigma,DEtaLAlpha,DEtaLN);
  
  RooCBShape EtaDCBRight("EtaDCBRight","EtaDCBRight",EtaMass,DEtamean,DEtasigma,DEtaRAlpha,DEtaRN);
  
  RooRealVar DEtaFitFraction("EtaFitFraction","DEtaFitFraction",0.5,0.0,1.0);
  RooAddPdf EtaDDCB("EtaDDCB","EtaDDCB",RooArgList(EtaDCBRight,EtaDCBLeft),DEtaFitFraction);

  RooProdPdf DSignalPdf("DSignalPdf","DSignalPdf",RooArgList(EtaDDCB,DDCB));
  
  RooExtendPdf DExtSignalPdf("DExtSignalPdf","DExtSignalPdf",DSignalPdf,DSignalYield);

  //=============================== Eta mass bkg pdf==================================
  
  RooRealVar EtaBkgMean("EtaBkgMean","EtaBkgMean",958.0,900.0,1020.0);
  RooRealVar EtaBkgSigma("EtaBkgSigma","EtaBkgSigma",19.8,10.0,40.8);
  RooRealVar EtaBkgLAlpha("EtaBkgLAlpha","EtaBkgLAlpha",BsbLAlpha.getVal());
  //  RooRealVar EtaBkgRAlpha("EtaBkgRAlpha","EtaBkgRAlpha",BsbRAlpha.getVal());
  RooRealVar EtaBkgLN("EtaBkgLN","EtaBkgLN",BsbLN.getVal());
  //  RooRealVar EtaBkgRN("EtaBkgRN","EtaBkgRN",BsbRN.getVal());

  RooCBShape EtaBkgCBLeft("EtaBkgCBLeft","EtaBkgCBLeft",EtaMass,DEtamean,EtaBkgSigma,EtaBkgLAlpha,EtaBkgLN);
  
  //  RooCBShape EtaBkgCBRight("EtaBkgCBRight","EtaBkgCBRight",EtaMass,DEtamean,EtaBkgSigma,EtaBkgRAlpha,EtaBkgRN);
  
  //  RooRealVar EtaBkgFitFraction("EtaBkgFitFraction","EtaBkgFitFraction",0.5,0.0,1.0);
  //  RooAddPdf EtaBkgDCB("EtaBkgDCB","EtaBkgDCB",RooArgList(EtaBkgCBRight,EtaBkgCBLeft),EtaBkgFitFraction);
  
  RooProdPdf DataBackgroundPDF("DataBackgroundPDF","DataBackgroundPDF",RooArgList(EtaBkgCBLeft,bkg));
  
  RooRealVar DataBackgroundYield("BackgroundYield","DataBackgroundYield",500.0,0.0,10000.0);
  
  RooExtendPdf ExtDataBackgroundPDF("ExtDataBackgroundPDF","ExtDataBackgroundPDF",DataBackgroundPDF,DataBackgroundYield);

  RooAddPdf TotalPDF("TotalPDF","TotalPDF",RooArgList(ExtDataBackgroundPDF,DExtSignalPdf));
  std::cout<<"Dependents = "<<std::endl;
  RooArgSet* Dependents=TotalPDF.getDependents(AllData);
  Dependents->Print("v");
  std::cout<<"parameters= "<<std::endl;
  RooArgSet* parameters=TotalPDF.getParameters(AllData);
  parameters->Print("v");
  RooCategory MassType("MassType","MassType") ;
  MassType.defineType("B") ;
  MassType.defineType("Eta") ;
  
  // Construct combined dataset in (x,sample)
  RooDataSet combData("combData","combined data",MassArgs,Index(MassType),Import("B",*BData),Import("Eta",*EtaData));

  RooSimultaneous simPdf("simPdf","simultaneous pdf",MassType) ;

  // Associate model with the physics state and model_ctl with the control state
  //  simPdf.addPdf(WholeFit,"B");
  //  simPdf.addPdf(WholeEtaFit,"Eta"); 

  //  simPdf.fitTo(combData,Extended(kTRUE)/*,Minos(kTRUE)*/);
  
  TotalPDF.fitTo(*AllData,Extended(kTRUE),Minos(kTRUE));

  RooPlot* frame1 = BMass.frame(Bins(50),Title("B mass projection"));
  AllData->plotOn(frame1);
  TotalPDF.plotOn(frame1,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame1);
  TotalPDF.paramOn(frame1);
  
  // The same plot for the control sample slice
  RooPlot* frame2 = EtaMass.frame(Bins(50),Title("Eta mass projection")) ;
  AllData->plotOn(frame2);
  TotalPDF.plotOn(frame2,Components(ExtDataBackgroundPDF),LineStyle(kDashed),LineColor(kRed));
  TotalPDF.plotOn(frame2);
  TotalPDF.paramOn(frame2);
  TCanvas* DecoratedCanvas =HandyFunctions::DecoratePlot(frame2);

  
  TCanvas* DataBC= new TCanvas("BCanvas","BCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
  TCanvas* EtaBC= new TCanvas("EtaCanvas","EtaCanvas",1200,1000) ;
  gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;
  DataBC->SaveAs("DataBC.pdf");
  EtaBC->SaveAs("EtaBC.pdf");
  
  TFile * DataSimulFit = new TFile("DataSimulFit.root","RECREATE");
  DataBC->Write();
  EtaBC->Write();
  DecoratedCanvas->Write();

  
		 
		  

  
}
int main(int argc, char* argv[]) {

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

    

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

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

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

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


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

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

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

  for (unsigned int i=1; i <= knots.size(); ++i){
    std::string number = boost::lexical_cast<std::string>(i);
    RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
    coeff->setRange(0,10000);
    coeff->setVal(1);
    coeff->setConstant(false);
    list->add( *coeff );
    }
  
  // create last coefficient
  RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
  coeff_last->setRange(0,10000);
  coeff_last->setVal(1);
  coeff_last->setConstant(false);
  list->add( *coeff_last );
  list->Print();
  // define Eta PDF
  doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
  
  //Berechne die Tagging Assymetrie
  epdf->Var("p0");
  epdf->Var("p0").setVal(0.369);
  epdf->Var("p0").setConstant(true);

  epdf->Var("p1");
  epdf->Var("p1").setVal(0.952);
  epdf->Var("p1").setConstant(true);

  epdf->Var("delta_p0");
  epdf->Var("delta_p0").setVal(0.019);
  epdf->Var("delta_p0").setConstant(true);

  epdf->Var("delta_p1");
  epdf->Var("delta_p1").setVal(-0.012);
  epdf->Var("delta_p1").setConstant(true);

  epdf->Var("etamean");
  epdf->Var("etamean").setVal(0.365);
  epdf->Var("etamean").setConstant(true);

  epdf->Formula("omega","@0 +@1/2 +(@2+@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
  epdf->Formula("omegabar","@0 -@1/2 +(@2-@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
      


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

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

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

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

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

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

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

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

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

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


  //FIT-PDF-Koeffizienten
  epdf->Var("asym_prodFit");
  epdf->Var("asym_prodFit").setVal(-0.0108);
  epdf->Var("asym_prodFit").setConstant(false);

  DecRateCoeff *coeff_cFit = new DecRateCoeff("coef_cosFit","coef_cosFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sFit = new DecRateCoeff("coef_sinFit","coef_sinFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_shFit = new DecRateCoeff("coef_sinhFit","coef_sinhFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_chFit = new DecRateCoeff("coef_coshFit","coef_coshFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_chFit);
  epdf->AddRealToStore(coeff_shFit);
  epdf->AddRealToStore(coeff_cFit);
  epdf->AddRealToStore(coeff_sFit);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  
  epdf->BDecay("pdfSigTimeFit",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_coshFit"),epdf->Real("coef_sinhFit"),epdf->Real("coef_cosFit"),epdf->Real("coef_sinFit"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

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

  epdf->Extend("pdfExtendFit", epdf->Pdf("pdfSigTimeFit"),epdf->Real("sig_yield"));
  
  
  RooFitResult* fit_result = epdf->Pdf("pdfExtendFit").fitTo(*data, RooFit::Save(true));
  tstudy.StoreFitResult(fit_result);
  //epdf->Pdf("pdfExtendFit").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
  //epdf->Pdf("pdfExtendFit").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");

  //Plotten auf lhcb
  /*using namespace doofit::plotting;

  PlotConfig cfg_plot("cfg_plot");
  cfg_plot.InitializeOptions();
  cfg_plot.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/time/");
  // plot PDF and directly specify components
  Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
  myplot.PlotItLogNoLogY();

  PlotConfig cfg_plotEta("cfg_plotEta");
  cfg_plotEta.InitializeOptions();
  cfg_plotEta.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/eta/");
  // plot PDF and directly specify components
  Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
  myplotEta.PlotIt();*/

 }
Exemplo n.º 12
0
   void constrained_scan( const char* wsfile = "outputfiles/ws.root",
                          const char* new_poi_name="mu_bg_4b_msig_met1",
                          double constraintWidth=1.5,
                          int npoiPoints = 20,
                          double poiMinVal = 0.,
                          double poiMaxVal = 10.0,
                          double ymax = 9.,
                          int verbLevel=1  ) {

      TString outputdir("outputfiles") ;

      gStyle->SetOptStat(0) ;

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

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;
      cout << "\n\n\n  ===== RooDataSet ====================\n\n" << endl ;
      rds->Print() ;
      rds->printMultiline(cout, 1, kTRUE, "") ;

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

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



      /////rv_sig_strength -> setConstant( kFALSE ) ;
      rv_sig_strength -> setVal(0.) ;
      rv_sig_strength -> setConstant( kTRUE ) ;

      likelihood->fitTo( *rds, Save(false), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //double minNllSusyFloat = fitResult->minNll() ;
      //double susy_ss_atMinNll = rv_sig_strength -> getVal() ;

      RooMsgService::instance().getStream(1).removeTopic(Minimization) ;
      RooMsgService::instance().getStream(1).removeTopic(Fitting) ;



     //-- Construct the new POI parameter.
      RooAbsReal* new_poi_rar(0x0) ;

      new_poi_rar = ws->var( new_poi_name ) ;
      if ( new_poi_rar == 0x0 ) {
         printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
         new_poi_rar = ws->function( new_poi_name ) ;
         if ( new_poi_rar == 0x0 ) {
            printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
            return ;
         } else {
            printf("\n Found it.\n\n") ;
         }
      } else {
         printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
      }

       double startPoiVal = new_poi_rar->getVal() ;


       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;


       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }


       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;


       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }


       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



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


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;




   } // constrained_scan.
Exemplo n.º 13
0
   void ws_constrained_profile3D( const char* wsfile = "rootfiles/ws-data-unblind.root",
                                   const char* new_poi_name = "n_M234_H4_3b",
                                   int npoiPoints = 20,
                                   double poiMinVal = 0.,
                                   double poiMaxVal = 20.,
                                   double constraintWidth = 1.5,
                                   double ymax = 10.,
                                   int verbLevel=0 ) {


     gStyle->SetOptStat(0) ;

     //--- make output directory.

     char command[10000] ;
     sprintf( command, "basename %s", wsfile ) ;
     TString wsfilenopath = gSystem->GetFromPipe( command ) ;
     wsfilenopath.ReplaceAll(".root","") ;
     char outputdirstr[1000] ;
     sprintf( outputdirstr, "outputfiles/scans-%s", wsfilenopath.Data() ) ;
     TString outputdir( outputdirstr ) ;


     printf("\n\n Creating output directory: %s\n\n", outputdir.Data() ) ;
     sprintf(command, "mkdir -p %s", outputdir.Data() ) ;
     gSystem->Exec( command ) ;


     //--- Tell RooFit to shut up about anything less important than an ERROR.
      RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;



       if ( verbLevel > 0 ) { printf("\n\n Verbose level : %d\n\n", verbLevel) ; }


       TFile* wstf = new TFile( wsfile ) ;

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

       if ( verbLevel > 0 ) { ws->Print() ; }






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

       if ( verbLevel > 0 ) {
          printf("\n\n\n  ===== RooDataSet ====================\n\n") ;
          rds->Print() ;
          rds->printMultiline(cout, 1, kTRUE, "") ;
       }





       ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
       RooAbsPdf* likelihood = modelConfig->GetPdf() ;

       RooRealVar* rrv_mu_susy_all0lep = ws->var("mu_susy_all0lep") ;
       if ( rrv_mu_susy_all0lep == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
          return ;
       }





       //-- do BG only.
       rrv_mu_susy_all0lep->setVal(0.) ;
       rrv_mu_susy_all0lep->setConstant( kTRUE ) ;










       //-- do a prefit.

       printf("\n\n\n ====== Pre fit with unmodified nll var.\n\n") ;

       RooFitResult* dataFitResultSusyFixed = likelihood->fitTo(*rds, Save(true),Hesse(false),Minos(false),Strategy(1),PrintLevel(verbLevel));
       int dataSusyFixedFitCovQual = dataFitResultSusyFixed->covQual() ;
       if ( dataSusyFixedFitCovQual < 2 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFixedFitCovQual ) ; return ; }
       double dataFitSusyFixedNll = dataFitResultSusyFixed->minNll() ;

       if ( verbLevel > 0 ) {
          dataFitResultSusyFixed->Print("v") ;
       }

       printf("\n\n Nll value, from fit result : %.3f\n\n", dataFitSusyFixedNll ) ;

       delete dataFitResultSusyFixed ;






       //-- Construct the new POI parameter.
       RooAbsReal* new_poi_rar(0x0) ;

       new_poi_rar = ws->var( new_poi_name ) ;
       if ( new_poi_rar == 0x0 ) {
          printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
          new_poi_rar = ws->function( new_poi_name ) ;
          if ( new_poi_rar == 0x0 ) {
             printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
             return ;
          }
       } else {
          printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
       }








       if ( npoiPoints <=0 ) {
          printf("\n\n Quitting now.\n\n" ) ;
          return ;
       }


       double startPoiVal = new_poi_rar->getVal() ;



      //--- The RooNLLVar is NOT equivalent to what minuit uses.
  //   RooNLLVar* nll = new RooNLLVar("nll","nll", *likelihood, *rds ) ;
  //   printf("\n\n Nll value, from construction : %.3f\n\n", nll->getVal() ) ;

      //--- output of createNLL IS what minuit uses, so use that.
       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;
   /// rrv_poiValue->setVal( poiMinVal ) ;
   /// rrv_poiValue->setConstant(kTRUE) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;




       if ( verbLevel > 0 ) {
          printf("\n\n ======= debug likelihood print\n\n") ;
          likelihood->Print("v") ;
          printf("\n\n ======= debug nll print\n\n") ;
          nll->Print("v") ;
       }






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

       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }



     //-------

       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;




       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }

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

       //-- If POI range is -1 to -1, automatically determine the range using the set value.

       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



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


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;

   }
Exemplo n.º 14
0
   void fitqual_plots( const char* wsfile = "outputfiles/ws.root", const char* plottitle="" ) {

      TText* tt_title = new TText() ;
      tt_title -> SetTextAlign(33) ;

      gStyle -> SetOptStat(0) ;
      gStyle -> SetLabelSize( 0.06, "y" ) ;
      gStyle -> SetLabelSize( 0.08, "x" ) ;
      gStyle -> SetLabelOffset( 0.010, "y" ) ;
      gStyle -> SetLabelOffset( 0.010, "x" ) ;
      gStyle -> SetTitleSize( 0.07, "y" ) ;
      gStyle -> SetTitleSize( 0.05, "x" ) ;
      gStyle -> SetTitleOffset( 1.50, "x" ) ;
      gStyle -> SetTitleH( 0.07 ) ;
      gStyle -> SetPadLeftMargin( 0.15 ) ;
      gStyle -> SetPadBottomMargin( 0.15 ) ;
      gStyle -> SetTitleX( 0.10 ) ;

      gDirectory->Delete("h*") ;

      TFile* wstf = new TFile( wsfile ) ;

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

      int bins_of_met = TMath::Nint( ws->var("bins_of_met")->getVal()  ) ;
      printf("\n\n Bins of MET : %d\n\n", bins_of_met ) ;

      int bins_of_nb = TMath::Nint( ws->var("bins_of_nb")->getVal()  ) ;
      printf("\n\n Bins of nb : %d\n\n", bins_of_nb ) ;

      int nb_lookup[10] ;
      if ( bins_of_nb == 2 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 4 ;
      } else if ( bins_of_nb == 3 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 3 ;
         nb_lookup[2] = 4 ;
      }

      TCanvas* cfq1 = (TCanvas*) gDirectory->FindObject("cfq1") ;
      if ( cfq1 == 0x0 ) {
         if ( bins_of_nb == 3 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 1000 ) ;
         } else if ( bins_of_nb == 2 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 750 ) ;
         } else {
            return ;
         }
      }

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

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

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;

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

      RooAbsPdf* likelihood = modelConfig->GetPdf() ;

      ///RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
      RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(3) ) ;
      fitResult->Print() ;


      char hname[1000] ;
      char htitle[1000] ;
      char pname[1000] ;




     //-- unpack observables.

      int obs_N_msig[10][50] ; // first index is n btags, second is met bin.
      int obs_N_msb[10][50]  ; // first index is n btags, second is met bin.

      const RooArgSet* dsras = rds->get() ;
      TIterator* obsIter = dsras->createIterator() ;
      while ( RooRealVar* obs = (RooRealVar*) obsIter->Next() ) {
         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", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msig[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
               sprintf( pname, "N_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msb[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
            } // mbi.
         } // nbi.
      } // obs iterator.


      printf("\n\n") ;
      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {
         printf(" nb=%d :  ", nb_lookup[nbi] ) ;
         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
            printf("  sig=%3d, sb=%3d  |", obs_N_msig[nbi][mbi], obs_N_msb[nbi][mbi] ) ;
         } // mbi.
         printf("\n") ;
      } // nbi.
      printf("\n\n") ;




      int pad(1) ;

      cfq1->Clear() ;
      cfq1->Divide( 2, bins_of_nb+1 ) ;

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


         sprintf( hname, "h_bg_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msig -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msig ) ;

         sprintf( hname, "h_bg_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msb -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msb ) ;

         sprintf( hname, "h_sig_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msig -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msig ) ;

         sprintf( hname, "h_sig_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msb -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msb ) ;

         sprintf( hname, "h_all_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_all_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_data_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msig -> SetLineWidth(2) ;
         hist_data_msig -> SetMarkerStyle(20) ;
         labelBins( hist_data_msig ) ;

         sprintf( hname, "h_data_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msb -> SetLineWidth(2) ;
         hist_data_msb -> SetMarkerStyle(20) ;
         labelBins( hist_data_msb ) ;

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



            sprintf( pname, "mu_bg_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msig = ws->function( pname ) ;
            if ( mu_bg_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msig = ws->function( pname ) ;
            if ( mu_sig_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msig -> SetBinContent( mbi+1, mu_sig_msig->getVal() ) ;

            hist_all_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() + mu_sig_msig->getVal() ) ;

            hist_data_msig -> SetBinContent( mbi+1, obs_N_msig[nbi][mbi] ) ;



            sprintf( pname, "mu_bg_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msb = ws->function( pname ) ;
            if ( mu_bg_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msb = ws->function( pname ) ;
            if ( mu_sig_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msb -> SetBinContent( mbi+1, mu_sig_msb->getVal() ) ;

            hist_all_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() + mu_sig_msb->getVal() ) ;

            hist_data_msb -> SetBinContent( mbi+1, obs_N_msb[nbi][mbi] ) ;



         } // mbi.

         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msig = new THStack( hname, htitle ) ;
         hstack_msig -> Add( hist_bg_msig ) ;
         hstack_msig -> Add( hist_sig_msig ) ;

         hist_data_msig -> Draw("e") ;
         hstack_msig -> Draw("same") ;
         hist_data_msig -> Draw("same e") ;
         hist_data_msig -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msb = new THStack( hname, htitle ) ;
         hstack_msb -> Add( hist_bg_msb ) ;
         hstack_msb -> Add( hist_sig_msb ) ;

         hist_data_msb -> Draw("e") ;
         hstack_msb -> Draw("same") ;
         hist_data_msb -> Draw("same e") ;
         hist_data_msb -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



      } // nbi.




      TH1F* hist_R_msigmsb = new TH1F( "h_R_msigmsb", "R msig/msb vs met bin", bins_of_met, 0.5, 0.5+bins_of_met ) ;
      hist_R_msigmsb -> SetLineWidth(2) ;
      hist_R_msigmsb -> SetMarkerStyle(20) ;
      hist_R_msigmsb -> SetYTitle("R msig/msb") ;
      labelBins( hist_R_msigmsb ) ;


      for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
         sprintf( pname, "R_msigmsb_met%d", mbi+1 ) ;
         RooRealVar* rrv_R = ws->var( pname ) ;
         if ( rrv_R == 0x0 ) { printf("\n\n *** Can't find %s in ws.\n\n", pname ) ; return ; }
         hist_R_msigmsb -> SetBinContent( mbi+1, rrv_R -> getVal() ) ;
         hist_R_msigmsb -> SetBinError( mbi+1, rrv_R -> getError() ) ;
      } // mbi.

      cfq1->cd( pad ) ;

      gPad->SetGridy(1) ;

      hist_R_msigmsb -> SetMaximum(0.35) ;
      hist_R_msigmsb -> Draw("e") ;

      tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

      pad++ ;



      cfq1->cd( pad ) ;

      scan_sigstrength( wsfile ) ;

      tt_title -> DrawTextNDC( 0.85, 0.25, plottitle ) ;



      TString pdffile( wsfile ) ;
      pdffile.ReplaceAll("ws-","fitqual-") ;
      pdffile.ReplaceAll("root","pdf") ;


      cfq1->SaveAs( pdffile ) ;



      TString histfile( wsfile ) ;
      histfile.ReplaceAll("ws-","fitqual-") ;

      saveHist( histfile, "h*" ) ;



   } // fitqual_plots
Exemplo n.º 15
0
float ComputeTestStat(TString wsfile, double mu_susy_sig_val) {

  gROOT->Reset();

  TFile* wstf = new TFile( wsfile ) ;

  RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
  ws->Print() ;
  
  ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
  
  modelConfig->Print() ;

  RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;
  
  rds->Print() ;
  rds->printMultiline(cout, 1, kTRUE, "") ;
  
  RooAbsPdf* likelihood = modelConfig->GetPdf() ;
  
  RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_all0lep") ;
  if ( rrv_mu_susy_sig == 0x0 ) {
    printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
    return ;
  } else {
    printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
    rrv_mu_susy_sig->setConstant(kFALSE) ;
  }

  /*
  // check the impact of varying the qcd normalization:

  RooRealVar *rrv_qcd_0lepLDP_ratioH1 = ws->var("qcd_0lepLDP_ratio_H1");
  RooRealVar *rrv_qcd_0lepLDP_ratioH2 = ws->var("qcd_0lepLDP_ratio_H2");
  RooRealVar *rrv_qcd_0lepLDP_ratioH3 = ws->var("qcd_0lepLDP_ratio_H3");
  
  rrv_qcd_0lepLDP_ratioH1->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH2->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH3->setVal(0.3);
  
  rrv_qcd_0lepLDP_ratioH1->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH2->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH3->setConstant(kTRUE);
  */
  
  printf("\n\n\n  ===== Doing a fit with SUSY component floating ====================\n\n") ;

  RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
  double logLikelihoodSusyFloat = fitResult->minNll() ;
  
  double logLikelihoodSusyFixed(0.) ;
  double testStatVal(-1.) ;
  if ( mu_susy_sig_val >= 0. ) {
    printf("\n\n\n  ===== Doing a fit with SUSY fixed ====================\n\n") ;
    printf(" fixing mu_susy_sig to %8.2f.\n", mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setVal( mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setConstant(kTRUE) ;
    
    fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
    logLikelihoodSusyFixed = fitResult->minNll() ;
    testStatVal = 2.*(logLikelihoodSusyFixed - logLikelihoodSusyFloat) ;
    printf("\n\n\n ======= test statistic : -2 * ln (L_fixed / ln L_max) = %8.3f\n\n\n", testStatVal ) ;
  }


  return testStatVal ;

}
int main(int argc, char* argv[]) {

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

     

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

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

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

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


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

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

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

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

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



            list->Print();

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



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

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


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


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


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



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





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

                 ws.Print();

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

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

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

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

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

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




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

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

          /*using namespace doofit::plotting;

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

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

 }
Exemplo n.º 17
0
void RooToyMCFit1Bin(const int _bin){
    if(_bin<1 || _bin>8){
        cout << "Bin number should be between 1 and 8" << endl;
        return;
    }
    stringstream out;
    out.str("");
    out << "toyMC_" << _sigma_over_tau << "_" << _purity << "_" << mistag_rate << ".root";
    TFile* file = TFile::Open(out.str().c_str());
    TTree* tree = (TTree*)file->Get("ToyTree");
    cout << "The tree has been readed from the file " << out.str().c_str() << endl;

    RooRealVar tau("tau","tau",_tau,"ps"); tau.setConstant(kTRUE);
    RooRealVar dm("dm","dm",_dm,"ps^{-1}"); dm.setConstant(kTRUE);
    RooRealVar sin2beta("sin2beta","sin2beta",_sin2beta,-5.,5.); if(constBeta) sin2beta.setConstant(kTRUE);
    RooRealVar cos2beta("cos2beta","cos2beta",_cos2beta,-5.,5.); if(constBeta) cos2beta.setConstant(kTRUE);
    RooRealVar dt("dt","#Deltat",-5.,5.,"ps");
    RooRealVar avgMisgat("avgMisgat","avgMisgat",mistag_rate,0.0,0.5); if(constMistag) avgMisgat.setConstant(kTRUE);
    RooRealVar delMisgat("delMisgat","delMisgat",0); delMisgat.setConstant(kTRUE);
    RooRealVar mu("mu","mu",0); mu.setConstant(kTRUE);
    RooRealVar moment("moment","moment",0.);  moment.setConstant(kTRUE);
    RooRealVar parity("parity","parity",-1.); parity.setConstant(kTRUE);

    cout << "Preparing coefficients..." << endl;
    RooRealVar*    K  = new RooRealVar("K","K",K8[_bin-1],0.,1.); if(constK) K->setConstant(kTRUE);
    RooFormulaVar* Kb = new RooFormulaVar("Kb","Kb","1-@0",RooArgList(*K));

    RooRealVar* C = new RooRealVar("C","C",_C[_bin-1]); C->setConstant(kTRUE);
    RooRealVar* S = new RooRealVar("S","S",_S[_bin-1]); S->setConstant(kTRUE);

    RooFormulaVar* a1  = new RooFormulaVar("a1","a1","-(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a1b = new RooFormulaVar("a1b","a1b","(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a2  = new RooFormulaVar("a2","a2","(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));
    RooFormulaVar* a2b = new RooFormulaVar("a2b","a2b","-(@0-@1)/(@0+@1)",RooArgList(*K,*Kb));

    RooFormulaVar* b1  = new RooFormulaVar("b1","b1","2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b1b = new RooFormulaVar("b1b","b1b","2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b2  = new RooFormulaVar("b2","b2","-2.*(@2*@4+@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));
    RooFormulaVar* b2b = new RooFormulaVar("b2b","b2b","-2.*(@2*@4-@3*@5)*TMath::Sqrt(@0*@1)/(@0+@1);",RooArgList(*K,*Kb,*C,*S,sin2beta,cos2beta));

    RooRealVar* dgamma = new RooRealVar("dgamma","dgamma",0.); dgamma->setConstant(kTRUE);
    RooRealVar* f0 = new RooRealVar("f0","f0",1.); f0->setConstant(kTRUE);
    RooRealVar* f1 = new RooRealVar("f1","f1",0.); f1->setConstant(kTRUE);

    RooCategory tag("tag","tag");
    tag.defineType("B0",1);
    tag.defineType("anti-B0",-1);

    RooCategory bin("bin","bin");
    bin.defineType("bin",_bin);
    bin.defineType("binb",-_bin);

    RooSuperCategory bintag("bintag","bintag",RooArgSet(bin,tag));

    RooDataSet d("data","data",tree,RooArgSet(dt,bin,tag));
    cout << "DataSet is ready." << endl;
    d.Print();

    RooRealVar mean("mean","mean",0.,"ps"); mean.setConstant(kTRUE);
    RooRealVar sigma("sigma","sigma",_sigma_over_tau*_tau,0.,_tau,"ps"); if(constSigma) sigma.setConstant(kTRUE);
    RooGaussModel rf("rf","rf",dt,mean,sigma);
//    RooTruthModel rf("rf","rf",dt);
    RooGaussian rfpdf("rfpdf","rfpdf",dt,mean,sigma);

    cout << "Preparing PDFs..." << endl;
    RooBDecay* sigpdf1  = new RooBDecay("sigpdf1","sigpdf1",dt,tau,*dgamma,*f0,*f1,*a1,*b1,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf2  = new RooBDecay("sigpdf2","sigpdf2",dt,tau,*dgamma,*f0,*f1,*a2,*b2,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf1b  = new RooBDecay("sigpdf1b","sigpdf1b",dt,tau,*dgamma,*f0,*f1,*a1b,*b1b,dm,rf,RooBDecay::DoubleSided);
    RooBDecay* sigpdf2b  = new RooBDecay("sigpdf2b","sigpdf2b",dt,tau,*dgamma,*f0,*f1,*a2b,*b2b,dm,rf,RooBDecay::DoubleSided);

    RooRealVar fsig("fsig","fsigs",_purity,0.,1.);  if(constFSig) fsig.setConstant(kTRUE);
    RooAddPdf* PDF1 = new RooAddPdf("PDF1","PDF1",RooArgList(*sigpdf1,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF2 = new RooAddPdf("PDF2","PDF2",RooArgList(*sigpdf2,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF1b= new RooAddPdf("PDF1b","PDF1b",RooArgList(*sigpdf1b,rfpdf),RooArgList(fsig));
    RooAddPdf* PDF2b= new RooAddPdf("PDF2b","PDF2b",RooArgList(*sigpdf2b,rfpdf),RooArgList(fsig));

    //Adding mistaging
    RooAddPdf* pdf1 = new RooAddPdf("pdf1","pdf1",RooArgList(*PDF2,*PDF1),RooArgList(avgMisgat));
    RooAddPdf* pdf2 = new RooAddPdf("pdf2","pdf2",RooArgList(*PDF1,*PDF2),RooArgList(avgMisgat));
    RooAddPdf* pdf1b= new RooAddPdf("pdf1b","pdf1b",RooArgList(*PDF2b,*PDF1b),RooArgList(avgMisgat));
    RooAddPdf* pdf2b= new RooAddPdf("pdf2b","pdf2b",RooArgList(*PDF1b,*PDF2b),RooArgList(avgMisgat));

    RooSimultaneous pdf("pdf","pdf",bintag);
    pdf.addPdf(*pdf1,"{bin;B0}");
    pdf.addPdf(*pdf2,"{bin;anti-B0}");
    pdf.addPdf(*pdf1b,"{binb;B0}");
    pdf.addPdf(*pdf2b,"{binb;anti-B0}");

    cout << "Fitting..." << endl;
    pdf.fitTo(d,Verbose(),Timer());

    cout << "Drawing plots." << endl;
    // Plus bin
    RooPlot* dtFrame = dt.frame();

    // B0
    out.str("");
    out << "tag == 1 && bin == " << _bin;
    cout << out.str() << endl;
    RooDataSet* ds = d.reduce(out.str().c_str());
    ds->Print();
    ds->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kBlue));
    bintag = "{bin;B0}";
    pdf.plotOn(dtFrame,ProjWData(RooArgSet(),*ds),Slice(bintag),LineColor(kBlue));
    double chi2 = dtFrame->chiSquare();

    // anti-B0
    out.str("");
    out << "tag == -1 && bin == " << _bin;
    cout << out.str() << endl;
    RooDataSet* dsb = d.reduce(out.str().c_str());
    dsb->Print();
    dsb->plotOn(dtFrame,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kRed));
    bintag = "{bin;anti-B0}";
    pdf.plotOn(dtFrame,ProjWData(RooArgSet(),*dsb),Slice(bintag),LineColor(kRed));
    double chi2b = dtFrame->chiSquare();

    // Canvas
    out.str("");
    out << "#Delta t, toy MC, bin == " << _bin;
    TCanvas* cm = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
    cm->cd();
    dtFrame->GetXaxis()->SetTitleSize(0.05);
    dtFrame->GetXaxis()->SetTitleOffset(0.85);
    dtFrame->GetXaxis()->SetLabelSize(0.05);
    dtFrame->GetYaxis()->SetTitleOffset(1.6);

    TPaveText *pt = new TPaveText(0.7,0.6,0.98,0.99,"brNDC");
    pt->SetFillColor(0);
    pt->SetTextAlign(12);
    out.str("");
    out << "bin = " << _bin;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(B^{0}) = " << chi2;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(#barB^{0}) = " << chi2b;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "#sigma/#tau = " << sigma.getVal()/tau.getVal();
    pt->AddText(out.str().c_str());
    out.str("");
    out << "purity = " << _purity;
    pt->AddText(out.str().c_str());
    out.str("");
    out << "mistag = " << mistag_rate;
    pt->AddText(out.str().c_str());

    dtFrame->Draw();
    pt->Draw();

    // Minus bin
    RooPlot* dtFrameB = dt.frame();

    // B0
    out.str("");
    out << "tag == 1 && bin == " << -_bin;
    cout << out.str() << endl;
    RooDataSet* ds2 = d.reduce(out.str().c_str());
    ds2->Print();
    ds2->plotOn(dtFrameB,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kBlue));
    bintag = "{binb;B0}";
    pdf.plotOn(dtFrameB,ProjWData(RooArgSet(),*ds2),Slice(bintag),LineColor(kBlue));
    chi2 = dtFrameB->chiSquare();

    //anti-B0
    out.str("");
    out << "tag == -1 && bin == " << -_bin;
    cout << out.str() << endl;
    RooDataSet* dsb2 = d.reduce(out.str().c_str());
    dsb2->Print();
    dsb2->plotOn(dtFrameB,DataError(RooAbsData::SumW2),MarkerSize(1),MarkerColor(kRed));
    bintag = "{binb;anti-B0}";
    pdf.plotOn(dtFrameB,ProjWData(RooArgSet(),*dsb2),Slice(bintag),LineColor(kRed));
    chi2b = dtFrameB->chiSquare();

    //Canvas
    out.str("");
    out << "#Delta t, toy MC, bin == " << -_bin;
    TCanvas* cm2 = new TCanvas(out.str().c_str(),out.str().c_str(),600,400);
    cm2->cd();
    dtFrameB->GetXaxis()->SetTitleSize(0.05);
    dtFrameB->GetXaxis()->SetTitleOffset(0.85);
    dtFrameB->GetXaxis()->SetLabelSize(0.05);
    dtFrameB->GetYaxis()->SetTitleOffset(1.6);

    TPaveText *ptB = new TPaveText(0.7,0.65,0.98,0.99,"brNDC");
    ptB->SetFillColor(0);
    ptB->SetTextAlign(12);
    out.str("");
    out << "bin = " << -_bin;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(B^{0}) = " << chi2;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#chi^{2}(#barB^{0}) = " << chi2b;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "#sigma/#tau = " << sigma.getVal()/tau.getVal();
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "purity = " << _purity;
    ptB->AddText(out.str().c_str());
    out.str("");
    out << "mistag = " << mistag_rate;
    ptB->AddText(out.str().c_str());

    dtFrameB->Draw();
    ptB->Draw();

    return;
}
Exemplo n.º 18
0
   void ws_profile_interval1( const char* wsfile = "ws-test1.root", const char* parName = "mu_susy_sig", double alpha = 0.10, double mu_susy_sig_val = 0., double xmax = -1. ) {




       TFile* wstf = new TFile( wsfile ) ;

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






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

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







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

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









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

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

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












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

       likelihood->fitTo( *rds ) ;

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






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

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

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

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








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

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

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



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



   }
Exemplo n.º 19
0
void rf401_importttreethx()
{
    // I m p o r t  m u l t i p l e   T H 1   i n t o   a   R o o D a t a H i s t
    // --------------------------------------------------------------------------

    // Create thee ROOT TH1 histograms
    TH1* hh_1 = makeTH1("hh1",0,3) ;
    TH1* hh_2 = makeTH1("hh2",-3,1) ;
    TH1* hh_3 = makeTH1("hh3",+3,4) ;

    // Declare observable x
    RooRealVar x("x","x",-10,10) ;

    // Create category observable c that serves as index for the ROOT histograms
    RooCategory c("c","c") ;
    c.defineType("SampleA") ;
    c.defineType("SampleB") ;
    c.defineType("SampleC") ;

    // Create a binned dataset that imports contents of all TH1 mapped by index category c
    RooDataHist* dh = new RooDataHist("dh","dh",x,Index(c),Import("SampleA",*hh_1),Import("SampleB",*hh_2),Import("SampleC",*hh_3)) ;
    dh->Print() ;

    // Alternative constructor form for importing multiple histograms
    map<string,TH1*> hmap ;
    hmap["SampleA"] = hh_1 ;
    hmap["SampleB"] = hh_2 ;
    hmap["SampleC"] = hh_3 ;
    RooDataHist* dh2 = new RooDataHist("dh","dh",x,c,hmap) ;
    dh2->Print() ;



    // I m p o r t i n g   a   T T r e e   i n t o   a   R o o D a t a S e t   w i t h   c u t s
    // -----------------------------------------------------------------------------------------

    TTree* tree = makeTTree() ;

    // Define observables y,z
    RooRealVar y("y","y",-10,10) ;
    RooRealVar z("z","z",-10,10) ;

    // Import only observables (y,z)
    RooDataSet ds("ds","ds",RooArgSet(x,y),Import(*tree)) ;
    ds.Print() ;

    // Import observables (x,y,z) but only event for which (y+z<0) is true
    RooDataSet ds2("ds2","ds2",RooArgSet(x,y,z),Import(*tree),Cut("y+z<0")) ;
    ds2.Print() ;



    // I m p o r t i n g   i n t e g e r   T T r e e   b r a n c h e s
    // ---------------------------------------------------------------

    // Import integer tree branch as RooRealVar
    RooRealVar i("i","i",0,5) ;
    RooDataSet ds3("ds3","ds3",RooArgSet(i,x),Import(*tree)) ;
    ds3.Print() ;

    // Define category i
    RooCategory icat("i","i") ;
    icat.defineType("State0",0) ;
    icat.defineType("State1",1) ;

    // Import integer tree branch as RooCategory (only events with i==0 and i==1
    // will be imported as those are the only defined states)
    RooDataSet ds4("ds4","ds4",RooArgSet(icat,x),Import(*tree)) ;
    ds4.Print() ;



    // I m p o r t  m u l t i p l e   R o o D a t a S e t s   i n t o   a   R o o D a t a S e t
    // ----------------------------------------------------------------------------------------

    // Create three RooDataSets in (y,z)
    RooDataSet* dsA = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"z<-5") ;
    RooDataSet* dsB = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"abs(z)<5") ;
    RooDataSet* dsC = (RooDataSet*) ds2.reduce(RooArgSet(x,y),"z>5") ;

    // Create a dataset that imports contents of all the above datasets mapped by index category c
    RooDataSet* dsABC = new RooDataSet("dsABC","dsABC",RooArgSet(x,y),Index(c),Import("SampleA",*dsA),Import("SampleB",*dsB),Import("SampleC",*dsC)) ;

    dsABC->Print() ;

}
Exemplo n.º 20
0
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();

}
Exemplo n.º 21
0
void splitws(string inFolderName, double mass, string channel) {
  cout << "Splitting workspace in " << channel << endl;

  int flatInterpCode = 4;
  int shapeInterpCode = 4;

  bool do2011 = 0;

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

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

  set<string> channelNames;

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

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

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

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

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

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

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

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

  // bool fix = 1;
  stringstream inFileName;

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

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

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

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

  RooArgSet allParams;

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

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

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

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

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

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

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

  catItr->Reset();

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

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

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

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

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

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

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

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

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

  // antiNuis.Print();

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

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

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

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

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

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

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

  decData->Print();

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

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

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

  // setup(mcInWs);
  // return;

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

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

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

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

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

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

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

  cout << "Done" << endl;

  // decPdf->fitTo(*decData, Hesse(0), Minos(0), PrintLevel(0));
}
Exemplo n.º 22
0
   void ws_cls_hybrid1_ag( const char* wsfile = "output-files/expected-ws-lm9-2BL.root", bool isBgonlyStudy=false, double poiVal = 150.0, int nToys=100, bool makeTtree=true, int verbLevel=0 ) {



       TTree* toytt(0x0) ;
       TFile* ttfile(0x0) ;

       int    tt_gen_Nsig ;
       int    tt_gen_Nsb ;
       int    tt_gen_Nsig_sl ;
       int    tt_gen_Nsb_sl ;
       int    tt_gen_Nsig_ldp ;
       int    tt_gen_Nsb_ldp ;
       int    tt_gen_Nsig_ee ;
       int    tt_gen_Nsb_ee ;
       int    tt_gen_Nsig_mm ;
       int    tt_gen_Nsb_mm ;

       double tt_testStat ;
       double tt_dataTestStat ;
       double tt_hypo_mu_susy_sig ;
       char ttname[1000] ;
       char tttitle[1000] ;

       if ( makeTtree ) {

          ttfile = gDirectory->GetFile() ;
          if ( ttfile == 0x0 ) { printf("\n\n\n *** asked for a ttree but no open file???\n\n") ; return ; }


          if ( isBgonlyStudy ) {
             sprintf( ttname, "toytt_%.0f_bgo", poiVal ) ;
             sprintf( tttitle, "Toy study for background only, mu_susy_sig = %.0f", poiVal ) ;
          } else {
             sprintf( ttname, "toytt_%.0f_spb", poiVal ) ;
             sprintf( tttitle, "Toy study for signal+background, mu_susy_sig = %.0f", poiVal ) ;
          }

          printf("\n\n Creating TTree : %s : %s\n\n", ttname, tttitle ) ;

          gDirectory->pwd() ;
          gDirectory->ls() ;

          toytt = new TTree( ttname, tttitle ) ;

          gDirectory->ls() ;

          toytt -> Branch(  "gen_Nsig"         ,       &tt_gen_Nsig         ,      "gen_Nsig/I"         ) ;
          toytt -> Branch(  "gen_Nsb"          ,       &tt_gen_Nsb          ,      "gen_Nsb/I"          ) ;
          toytt -> Branch(  "gen_Nsig_sl"      ,       &tt_gen_Nsig_sl      ,      "gen_Nsig_sl/I"      ) ;
          toytt -> Branch(  "gen_Nsb_sl"       ,       &tt_gen_Nsb_sl       ,      "gen_Nsb_sl/I"       ) ;
          toytt -> Branch(  "gen_Nsig_ldp"     ,       &tt_gen_Nsig_ldp     ,      "gen_Nsig_ldp/I"     ) ;
          toytt -> Branch(  "gen_Nsb_ldp"      ,       &tt_gen_Nsb_ldp      ,      "gen_Nsb_ldp/I"      ) ;
          toytt -> Branch(  "gen_Nsig_ee"      ,       &tt_gen_Nsig_ee      ,      "gen_Nsig_ee/I"      ) ;
          toytt -> Branch(  "gen_Nsb_ee"       ,       &tt_gen_Nsb_ee       ,      "gen_Nsb_ee/I"       ) ;
          toytt -> Branch(  "gen_Nsig_mm"      ,       &tt_gen_Nsig_mm      ,      "gen_Nsig_mm/I"      ) ;
          toytt -> Branch(  "gen_Nsb_mm"       ,       &tt_gen_Nsb_mm       ,      "gen_Nsb_mm/I"       ) ;

          toytt -> Branch(  "testStat"         ,       &tt_testStat         ,      "testStat/D"         ) ;
          toytt -> Branch(  "dataTestStat"     ,       &tt_dataTestStat     ,      "dataTestStat/D"     ) ;
          toytt -> Branch(  "hypo_mu_susy_sig" ,       &tt_hypo_mu_susy_sig ,      "hypo_mu_susy_sig/D" ) ;

       }


     //--- Tell RooFit to shut up about anything less important than an ERROR.
      RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;


       random_ng = new TRandom2(12345) ;

   /// char sel[100] ;
   /// if ( strstr( wsfile, "1BL" ) != 0 ) {
   ///    sprintf( sel, "1BL" ) ;
   /// } else if ( strstr( wsfile, "2BL" ) != 0 ) {
   ///    sprintf( sel, "2BL" ) ;
   /// } else if ( strstr( wsfile, "3B" ) != 0 ) {
   ///    sprintf( sel, "3B" ) ;
   /// } else if ( strstr( wsfile, "1BT" ) != 0 ) {
   ///    sprintf( sel, "1BT" ) ;
   /// } else if ( strstr( wsfile, "2BT" ) != 0 ) {
   ///    sprintf( sel, "2BT" ) ;
   /// } else {
   ///    printf("\n\n\n *** can't figure out which selection this is.  I quit.\n\n" ) ;
   ///    return ;
   /// }
   /// printf("\n\n selection is %s\n\n", sel ) ;




       TFile* wstf = new TFile( wsfile ) ;

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

       ws->Print() ;






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

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





       ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
       RooAbsPdf* likelihood = modelConfig->GetPdf() ;

       const RooArgSet* nuisanceParameters = modelConfig->GetNuisanceParameters() ;

       RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_sig") ;
       if ( rrv_mu_susy_sig == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_sig in workspace.  Quitting.\n\n\n") ;
          return ;
       }






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

 ////  RooFitResult* preFitResult = likelihood->fitTo( *rds, Save(true) ) ;
 ////  const RooArgList preFitFloatVals = preFitResult->floatParsFinal() ;
 ////  {
 ////    TIterator* parIter = preFitFloatVals.createIterator() ;
 ////    while ( RooRealVar* par = (RooRealVar*) parIter->Next() ) {
 ////       printf(" %20s : %8.2f\n", par->GetName(), par->getVal() ) ;
 ////    }
 ////  }







       //--- Get pointers to the model predictions of the observables.

       rfv_n_sig       = ws->function("n_sig") ;
       rfv_n_sb        = ws->function("n_sb") ;
       rfv_n_sig_sl    = ws->function("n_sig_sl") ;
       rfv_n_sb_sl     = ws->function("n_sb_sl") ;
       rfv_n_sig_ldp   = ws->function("n_sig_ldp") ;
       rfv_n_sb_ldp    = ws->function("n_sb_ldp") ;
       rfv_n_sig_ee    = ws->function("n_sig_ee") ;
       rfv_n_sb_ee     = ws->function("n_sb_ee") ;
       rfv_n_sig_mm    = ws->function("n_sig_mm") ;
       rfv_n_sb_mm     = ws->function("n_sb_mm") ;

       if ( rfv_n_sig         == 0x0 ) { printf("\n\n\n *** can't find n_sig       in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb          == 0x0 ) { printf("\n\n\n *** can't find n_sb        in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_sl      == 0x0 ) { printf("\n\n\n *** can't find n_sig_sl    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_sl       == 0x0 ) { printf("\n\n\n *** can't find n_sb_sl     in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_ldp     == 0x0 ) { printf("\n\n\n *** can't find n_sig_ldp   in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_ldp      == 0x0 ) { printf("\n\n\n *** can't find n_sb_ldp    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_ee      == 0x0 ) { printf("\n\n\n *** can't find n_sig_ee    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_ee       == 0x0 ) { printf("\n\n\n *** can't find n_sb_ee     in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_mm      == 0x0 ) { printf("\n\n\n *** can't find n_sig_mm    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_mm       == 0x0 ) { printf("\n\n\n *** can't find n_sb_mm     in workspace.  Quitting.\n\n\n") ; return ; }







       //--- Get pointers to the observables.

       const RooArgSet* dsras = rds->get() ;
       TIterator* obsIter = dsras->createIterator() ;
       while ( RooRealVar* obs = (RooRealVar*) obsIter->Next() ) {
          if ( strcmp( obs->GetName(), "Nsig"     ) == 0 ) { rrv_Nsig      = obs ; }
          if ( strcmp( obs->GetName(), "Nsb"      ) == 0 ) { rrv_Nsb       = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_sl"  ) == 0 ) { rrv_Nsig_sl   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_sl"   ) == 0 ) { rrv_Nsb_sl    = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_ldp" ) == 0 ) { rrv_Nsig_ldp  = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_ldp"  ) == 0 ) { rrv_Nsb_ldp   = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_ee"  ) == 0 ) { rrv_Nsig_ee   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_ee"   ) == 0 ) { rrv_Nsb_ee    = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_mm"  ) == 0 ) { rrv_Nsig_mm   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_mm"   ) == 0 ) { rrv_Nsb_mm    = obs ; }
       }

       if ( rrv_Nsig       == 0x0 ) { printf("\n\n\n *** can't find Nsig       in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb        == 0x0 ) { printf("\n\n\n *** can't find Nsb        in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_sl    == 0x0 ) { printf("\n\n\n *** can't find Nsig_sl    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_sl     == 0x0 ) { printf("\n\n\n *** can't find Nsb_sl     in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_ldp   == 0x0 ) { printf("\n\n\n *** can't find Nsig_ldp   in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_ldp    == 0x0 ) { printf("\n\n\n *** can't find Nsb_ldp    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_ee    == 0x0 ) { printf("\n\n\n *** can't find Nsig_ee    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_ee     == 0x0 ) { printf("\n\n\n *** can't find Nsb_ee     in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_mm    == 0x0 ) { printf("\n\n\n *** can't find Nsig_mm    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_mm     == 0x0 ) { printf("\n\n\n *** can't find Nsb_mm     in dataset.  Quitting.\n\n\n") ; return ; }






       printf("\n\n\n === Model values for observables\n\n") ;

       printObservables() ;



      //--- save the actual values of the observables.

       saveObservables() ;











       //--- evaluate the test stat on the data: fit with susy floating.

       rrv_mu_susy_sig->setVal( poiVal ) ;
       rrv_mu_susy_sig->setConstant( kTRUE ) ;

       printf("\n\n\n ====== Fitting the data with susy fixed.\n\n") ;

       RooFitResult* dataFitResultSusyFixed = likelihood->fitTo(*rds, Save(true));
       int dataSusyFixedFitCovQual = dataFitResultSusyFixed->covQual() ;
       if ( dataSusyFixedFitCovQual != 3 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFixedFitCovQual ) ; return ; }
       double dataFitSusyFixedNll = dataFitResultSusyFixed->minNll() ;


       rrv_mu_susy_sig->setVal( 0.0 ) ;
       rrv_mu_susy_sig->setConstant( kFALSE ) ;

       printf("\n\n\n ====== Fitting the data with susy floating.\n\n") ;

       RooFitResult* dataFitResultSusyFloat = likelihood->fitTo(*rds, Save(true));
       int dataSusyFloatFitCovQual = dataFitResultSusyFloat->covQual() ;
       if ( dataSusyFloatFitCovQual != 3 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFloatFitCovQual ) ; return ; }
       double dataFitSusyFloatNll = dataFitResultSusyFloat->minNll() ;

       double dataTestStat = 2.*( dataFitSusyFixedNll - dataFitSusyFloatNll) ;

       printf("\n\n\n Data value of test stat : %8.2f\n", dataTestStat ) ;












       printf("\n\n\n === Nuisance parameters\n\n") ;

       {
          int npi(0) ;
          TIterator* npIter = nuisanceParameters->createIterator() ;
          while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {

             np_initial_val[npi] = np_rrv->getVal() ; //--- I am assuming that the order of the NPs in the iterator does not change.

             TString npname( np_rrv->GetName() ) ;
             npname.ReplaceAll("_prim","") ;
             RooAbsReal* np_rfv = ws->function( npname ) ;

             TString pdfname( np_rrv->GetName() ) ;
             pdfname.ReplaceAll("_prim","") ;
             pdfname.Prepend("pdf_") ;
             RooAbsPdf* np_pdf = ws->pdf( pdfname ) ;
             if ( np_pdf == 0x0 ) { printf("\n\n *** Can't find nuisance parameter pdf with name %s.\n\n", pdfname.Data() ) ; }

             if ( np_rfv != 0x0 ) {
                printf(" %20s : %8.2f , %20s, %8.2f\n", np_rrv->GetName(), np_rrv->getVal(), np_rfv->GetName(), np_rfv->getVal() ) ;
             } else {
                printf(" %20s : %8.2f\n", np_rrv->GetName(), np_rrv->getVal() ) ;
             }

             npi++ ;
          } // np_rrv iterator.

          np_count = npi ;

       }







       tt_dataTestStat = dataTestStat ;
       tt_hypo_mu_susy_sig = poiVal ;














       printf("\n\n\n === Doing the toys\n\n") ;

       int nToyOK(0) ;
       int nToyWorseThanData(0) ;

       for ( int ti=0; ti<nToys; ti++ ) {

          printf("\n\n\n ======= Toy %4d\n\n\n", ti ) ;





          //--- 1) pick values for the nuisance parameters from the PDFs and fix them.

          {
             TIterator* npIter = nuisanceParameters->createIterator() ;
             while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {

                TString pdfname( np_rrv->GetName() ) ;
                pdfname.ReplaceAll("_prim","") ;
                pdfname.Prepend("pdf_") ;
                RooAbsPdf* np_pdf = ws->pdf( pdfname ) ;
                if ( np_pdf == 0x0 ) { printf("\n\n *** Can't find nuisance parameter pdf with name %s.\n\n", pdfname.Data() ) ; return ; }

                RooDataSet* nprds = np_pdf->generate( RooArgSet(*np_rrv) ,1) ;
                const RooArgSet* npdsras = nprds->get() ;
                TIterator* valIter = npdsras->createIterator() ;
                RooRealVar* val = (RooRealVar*) valIter->Next() ;

                //--- reset the value of the nuisance parameter and fix it for the toy model definition fit.
                np_rrv->setVal( val->getVal() ) ;
                np_rrv->setConstant( kTRUE ) ;


                TString npname( np_rrv->GetName() ) ;
                npname.ReplaceAll("_prim","") ;
                RooAbsReal* np_rfv = ws->function( npname ) ;

                if ( verbLevel > 0 ) {
                   if ( np_rfv != 0x0 ) {
                      printf(" %20s : %8.2f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal() ) ;
                   } else if ( strstr( npname.Data(), "eff_sf" ) != 0 ) {
                      np_rfv = ws->function( "eff_sf_sig" ) ;
                      RooAbsReal* np_rfv2 = ws->function( "eff_sf_sb" ) ;
                      printf(" %20s : %8.2f , %15s, %8.3f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal(), np_rfv2->GetName(), np_rfv2->getVal() ) ;
                   } else if ( strstr( npname.Data(), "sf_ll" ) != 0 ) {
                      np_rfv = ws->function( "sf_ee" ) ;
                      RooAbsReal* np_rfv2 = ws->function( "sf_mm" ) ;
                      printf(" %20s : %8.2f , %15s, %8.3f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal(), np_rfv2->GetName(), np_rfv2->getVal() ) ;
                   } else {
                      printf(" %20s : %8.2f\n", val->GetName(), val->getVal() ) ;
                   }
                }

                delete nprds ;

             } // np_rrv iterator
          }






          //--- 2) Fit the dataset with these values for the nuisance parameters.

          if ( isBgonlyStudy ) {
            //-- fit with susy yield fixed to zero.
             rrv_mu_susy_sig -> setVal( 0. ) ;
             if ( verbLevel > 0 ) { printf("\n Setting mu_susy_sig to zero.\n\n") ; }
          } else {
            //-- fit with susy yield fixed to predicted value.
             rrv_mu_susy_sig -> setVal( poiVal ) ;
             if ( verbLevel > 0 ) { printf("\n Setting mu_susy_sig to %8.1f.\n\n", poiVal) ; }
          }
          rrv_mu_susy_sig->setConstant( kTRUE ) ;

          if ( verbLevel > 0 ) {
             printf("\n\n") ;
             printf("  Fitting with these values for the observables to define the model for toy generation.\n") ;
             rds->printMultiline(cout, 1, kTRUE, "") ;
             printf("\n\n") ;
          }

          RooFitResult* toyModelDefinitionFitResult(0x0) ;
          if ( verbLevel < 2 ) {
             toyModelDefinitionFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
          } else {
             toyModelDefinitionFitResult = likelihood->fitTo(*rds, Save(true));
          }

          int toyModelDefFitCovQual = toyModelDefinitionFitResult->covQual() ;
          if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d\n\n", toyModelDefFitCovQual ) ; }
          if ( toyModelDefFitCovQual != 3 ) {
             printf("\n\n\n *** Bad toy model definition fit.  Cov qual %d.  Aborting this toy.\n\n\n", toyModelDefFitCovQual ) ;
             continue ;
          }

          delete toyModelDefinitionFitResult ;

          if ( verbLevel > 0 ) {
             printf("\n\n\n === Model values for observables.  These will be used to generate the toy dataset.\n\n") ;
             printObservables() ;
          }









          //--- 3) Generate a new set of observables based on this model.

          generateObservables() ;

          printf("\n\n\n   Generated dataset\n") ;
          rds->Print() ;
          rds->printMultiline(cout, 1, kTRUE, "") ;

          //--- Apparently, I need to make a new RooDataSet...  Resetting the
          //    values in the old one doesn't stick.  If you do likelihood->fitTo(*rds), it
          //    uses the original values, not the reset ones, in the fit.

          RooArgSet toyFitobservedParametersList ;
          toyFitobservedParametersList.add( *rrv_Nsig        ) ;
          toyFitobservedParametersList.add( *rrv_Nsb         ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_sl     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_sl      ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_ldp    ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_ldp     ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_ee     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_ee      ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_mm     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_mm      ) ;


          RooDataSet* toyFitdsObserved = new RooDataSet("toyfit_ra2b_observed_rds", "RA2b toy observed data values",
                                         toyFitobservedParametersList ) ;
          toyFitdsObserved->add( toyFitobservedParametersList ) ;





          //--- 4) Reset and free the nuisance parameters.

          {
             if ( verbLevel > 0 ) { printf("\n\n") ; }
             int npi(0) ;
             TIterator* npIter = nuisanceParameters->createIterator() ;
             while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {
                np_rrv -> setVal( np_initial_val[npi] ) ; // assuming that the order in the iterator does not change.
                np_rrv -> setConstant( kFALSE ) ;
                npi++ ;
                if ( verbLevel > 0 ) { printf("    reset %20s to %8.2f and freed it.\n", np_rrv->GetName() , np_rrv->getVal() ) ; }
             } // np_rrv iterator.
             if ( verbLevel > 0 ) { printf("\n\n") ; }
          }





          //--- 5a) Evaluate the test statistic: Fit with susy yield floating to get the absolute maximum log likelihood.

          if ( verbLevel > 0 ) { printf("\n\n  Evaluating the test statistic for this toy.  Fitting with susy floating.\n\n") ; }

          rrv_mu_susy_sig->setVal( 0.0 ) ;
          rrv_mu_susy_sig->setConstant( kFALSE ) ;

          if ( verbLevel > 0 ) {
             printf("\n toy dataset\n\n") ;
             toyFitdsObserved->printMultiline(cout, 1, kTRUE, "") ;
          }

     /////---- nfg.  Need to create a new dataset  ----------
     /////RooFitResult* maxLikelihoodFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
     /////RooFitResult* maxLikelihoodFitResult = likelihood->fitTo(*rds, Save(true));
     /////--------------

          RooFitResult* maxLikelihoodFitResult(0x0) ;
          if ( verbLevel < 2 ) {
             maxLikelihoodFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true), PrintLevel(-1));
          } else {
             maxLikelihoodFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true));
          }

          if ( verbLevel > 0 ) { printObservables() ; }

          int mlFitCovQual = maxLikelihoodFitResult->covQual() ;
          if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d , -log likelihood %f\n\n", mlFitCovQual, maxLikelihoodFitResult->minNll() ) ; }
          if ( mlFitCovQual != 3 ) {
             printf("\n\n\n *** Bad maximum likelihood fit (susy floating).  Cov qual %d.  Aborting this toy.\n\n\n", mlFitCovQual ) ;
             continue ;
          }
          double maxL_susyFloat = maxLikelihoodFitResult->minNll() ;
          double maxL_mu_susy_sig = rrv_mu_susy_sig->getVal() ;

          delete maxLikelihoodFitResult ;






          //--- 5b) Evaluate the test statistic: Fit with susy yield fixed to hypothesis value.
          //        This is only necessary if the maximum likelihood fit value of the susy yield
          //        is less than the hypothesis value (to get a one-sided limit).


          double testStat(0.0) ;
          double maxL_susyFixed(0.0) ;

          if ( maxL_mu_susy_sig < poiVal ) {

             if ( verbLevel > 0 ) { printf("\n\n  Evaluating the test statistic for this toy.  Fitting with susy fixed to %8.2f.\n\n", poiVal ) ; }

             rrv_mu_susy_sig->setVal( poiVal ) ;
             rrv_mu_susy_sig->setConstant( kTRUE ) ;

             if ( verbLevel > 0 ) {
                printf("\n toy dataset\n\n") ;
                rds->printMultiline(cout, 1, kTRUE, "") ;
             }

         ////--------- nfg.  need to make a new dataset  ---------------
         ////RooFitResult* susyFixedFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
         ////RooFitResult* susyFixedFitResult = likelihood->fitTo(*rds, Save(true));
         ////-----------------------------

             RooFitResult* susyFixedFitResult(0x0) ;
             if ( verbLevel < 2 ) {
                susyFixedFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true), PrintLevel(-1));
             } else {
                susyFixedFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true));
             }

             if ( verbLevel > 0 ) { printObservables() ; }

             int susyFixedFitCovQual = susyFixedFitResult->covQual() ;
             if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d , -log likelihood %f\n\n", susyFixedFitCovQual, susyFixedFitResult->minNll()  ) ; }
             if ( susyFixedFitCovQual != 3 ) {
                printf("\n\n\n *** Bad maximum likelihood fit (susy fixed).  Cov qual %d.  Aborting this toy.\n\n\n", susyFixedFitCovQual ) ;
                continue ;
             }
             maxL_susyFixed = susyFixedFitResult->minNll() ;
             testStat = 2. * (maxL_susyFixed - maxL_susyFloat) ;


             delete susyFixedFitResult ;


          } else {

             if ( verbLevel > 0 ) { printf("\n\n  Floating value of susy yield greater than hypo value (%8.2f > %8.2f).  Setting test stat to zero.\n\n", maxL_mu_susy_sig, poiVal ) ; }

             testStat = 0.0 ;

          }

          printf("   --- test stat for toy %4d : %8.2f\n", ti, testStat ) ;





          nToyOK++ ;

          if ( testStat > dataTestStat ) { nToyWorseThanData++ ; }


          if ( makeTtree ) {

             tt_testStat = testStat ;

             tt_gen_Nsig     = rrv_Nsig->getVal() ;
             tt_gen_Nsb      = rrv_Nsb->getVal() ;
             tt_gen_Nsig_sl  = rrv_Nsig_sl->getVal() ;
             tt_gen_Nsb_sl   = rrv_Nsb_sl->getVal() ;
             tt_gen_Nsig_ldp = rrv_Nsig_ldp->getVal() ;
             tt_gen_Nsb_ldp  = rrv_Nsb_ldp->getVal() ;
             tt_gen_Nsig_ee  = rrv_Nsig_ee->getVal() ;
             tt_gen_Nsb_ee   = rrv_Nsb_ee->getVal() ;
             tt_gen_Nsig_mm  = rrv_Nsig_mm->getVal() ;
             tt_gen_Nsb_mm   = rrv_Nsb_mm->getVal() ;

             toytt->Fill() ;

          }





          //--- *) reset things for the next toy.

          resetObservables() ;

          delete toyFitdsObserved ;




       } // ti.

       wstf->Close() ;

       printf("\n\n\n") ;

       if ( nToyOK == 0 ) { printf("\n\n\n *** All toys bad !?!?!\n\n\n") ; return ; }

       double pValue = (1.0*nToyWorseThanData) / (1.0*nToyOK) ;

       if ( isBgonlyStudy ) {
          printf("\n\n\n p-value result, BG-only , poi=%3.0f : %4d / %4d = %6.3f\n\n\n\n", poiVal, nToyWorseThanData, nToyOK, pValue ) ;
       } else {
          printf("\n\n\n p-value result, S-plus-B, poi=%3.0f : %4d / %4d = %6.3f\n\n\n\n", poiVal, nToyWorseThanData, nToyOK, pValue ) ;
       }


       if ( makeTtree ) {
          printf("\n\n Writing TTree : %s : %s\n\n", ttname, tttitle ) ;
          ttfile->cd() ;
          toytt->Write() ;
       }


   } // ws_cls_hybrid1