Histogram::Histogram(
        boost::array< Length, 2 > max_value, Length max_dist, bool periodic
) : bin_size( max_dist ), periodic_boundary(periodic)
{
    Bins::Size size;
    for (int i = 0; i < Dim; ++i) {
        bin_size = std::min( bin_size, max_value[i] * ((periodic_boundary) ? 0.5f : 1.0f) );
        area_size[i] = max_value[i];
        /* Add two extra border cells for periodic boundary conditions */
        size[i] = ( ceil( max_value[i] / bin_size ) + 2 ) * camera::pixel;
    }
    max_distance_sq = bin_size * bin_size;
    bins = Bins( size );

    BOOST_STATIC_ASSERT( Dim == 2 );
    for (int i = 0; i < Dim_power_3_half; ++i)
        for (int j = 0; j < Dim; ++j)
            this->forward_scan[i][j] = forward_scan_elements[i][j] * camera::pixel;
}
Exemple #2
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS   = 50;
  const Double_t METMAX  = 100;
  
  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.1;

  // file format for output plots
  const TString format("png"); 

    
  // recoil correction
  RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC
                             //"../Recoil/WmpMC/fits.root",
			     //"../Recoil/WmmMC/fits.root",
			     //"../Recoil/ZmmMC/fits.root");
   
  // NNLO boson pT k-factors
  TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root");
  TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B");
  
  //
  // input ntuple file names
  //
  enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root");   typev.push_back(eWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root");  typev.push_back(eEWK);
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root");   typev.push_back(eAntiWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root");  typev.push_back(eAntiEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root");  typev.push_back(eAntiEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet   = new TH1D("hDataMet","",  NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm  = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp  = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2();
  TH1D *hEWKMet    = new TH1D("hEWKMet", "",  NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp   = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm   = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2();

  TH1D *hAntiDataMet   = new TH1D("hAntiDataMet","",  NBINS,0,METMAX); hAntiDataMet->Sumw2();
  TH1D *hAntiDataMetm  = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2();  
  TH1D *hAntiDataMetp  = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2();
  TH1D *hAntiWmunuMet  = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2();
  TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2();
  TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2();
  TH1D *hAntiEWKMet    = new TH1D("hAntiEWKMet", "",  NBINS,0,METMAX); hAntiEWKMet->Sumw2();
  TH1D *hAntiEWKMetp   = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2();
  TH1D *hAntiEWKMetm   = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // GEN W boson phi (signal MC)   
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);	      // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet);  RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1);
  RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1);
  RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWm,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  
  // Anti-Signal PDFs
  RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet);  RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1);
  RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1);
  RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); 
  
  // Anti-EWK+top PDFs
  RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet);  RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1);
  RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); 
  RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); 
  
  // Anti-QCD Pdfs
  CPepeModel1 aqcd("aqcd",pfmet,qcd.a1);
  CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1);
  CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1);
  
  // Anti-selection PDFs
  RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)),   RooArgList(nAntiSig,nAntiEWK,nAntiQCD));  
  RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp));
  RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm));
  
  // PDF for simultaneous fit
  RooCategory rooCat("rooCat","rooCat");
  rooCat.defineType("Select");
  rooCat.defineType("Anti");
  
  RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
  pdfTotal.addPdf(pdfMet, "Select");
  pdfTotal.addPdf(apdfMet,"Anti");
  
  RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat);
  pdfTotalp.addPdf(pdfMetp, "Select");
  pdfTotalp.addPdf(apdfMetp,"Anti");
  
  RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat);
  pdfTotalm.addPdf(pdfMetm, "Select");
  pdfTotalm.addPdf(apdfMetm,"Anti");
  
  //
  // Perform fits
  //

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kFALSE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotAntiMetDiff.SetYRange(-8,8);
  plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMet.SetName("fitantimetlog");
  plotAntiMet.SetLogy();
  plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum()));
  plotAntiMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wmpframe = pfmet.frame(Bins(NBINS));
  wmpframe->GetYaxis()->SetNdivisions(505);
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,LineColor(linecolorW));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wmpframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
plotMetp.SetYRange(0.1,4100);
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);

  RooPlot *awmpframe = pfmet.frame(Bins(NBINS));    
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,LineColor(linecolorW));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2));
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1));
  CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel);
  plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum()));
plotAntiMetp.SetYRange(0.1,1500);
  plotAntiMetp.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor);
  plotAntiMetpDiff.SetYRange(-8,8);
  plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetpDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetp.SetName("fitantimetplog");
  plotAntiMetp.SetLogy();
  plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum()));
  plotAntiMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); 
  wmmframe->GetYaxis()->SetNdivisions(505);
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,LineColor(linecolorW));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wmmframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
plotMetm.SetYRange(0.1,4100);
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

  RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); 
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,LineColor(linecolorW));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2));
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel);
  plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum()));
plotAntiMetm.SetYRange(0.1,1500);
  plotAntiMetm.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWm");
}
Exemple #3
0
/** Analyze NOEtypeArray */
void Action_NMRrst::AnalyzeNoeArray(NOEtypeArray& Narray, CpptrajFile* out) const {
  // Calculate <r^-6>^(-1/6) 
  for (NOEtypeArray::iterator my_noe = Narray.begin();
                              my_noe != Narray.end(); ++my_noe)
  {
    double r6Avg = pow( my_noe->R6_Avg() / (double)nframes_, -1.0/6.0 );
    my_noe->SetR6Avg( r6Avg );
  }
  // Sort by R6 avg.
  std::sort( Narray.begin(), Narray.end() );
  // Remove sets greater than the cutoff.
  NOEtypeArray::iterator bad_noe = Narray.begin();
  while (bad_noe != Narray.end() && bad_noe->R6_Avg() < max_cut_)
    ++bad_noe;
  size_t newSize = bad_noe - Narray.begin();
  for (NOEtypeArray::iterator my_noe = bad_noe;
                              my_noe != Narray.end(); ++my_noe)
  {
    if (debug_ > 0)
      mprintf("\tRemoving: %s (%g Ang)\n", my_noe->PrintNOE().c_str(), my_noe->R6_Avg());
    if (my_noe->Data() != 0)
      masterDSL_->RemoveSet( my_noe->Data() );
  }
  Narray.resize( newSize );
  // Print Final found NOEs. Calculate distances from d^2 if necessary.
  ViewRst VR;
  if (rsttop_ != 0)
    VR.Init(*rsttop_, ViewRst::BY_STRENGTH);
  std::vector<unsigned int> Bins(4, 0); // Strong, weak, medium, none
  double Cutoffs[3] = {strong_cut_, medium_cut_, weak_cut_};
  unsigned int current_cut = 0;
  const char* Labels[4] = {"STRONG", "MEDIUM", "WEAK", "NONE"};
  while (current_cut < 3 && Narray.front().R6_Avg() > Cutoffs[current_cut])
    ++current_cut;
  out->Printf("#Format: <r1>:{ @<a1X>(c1X) ... } -- <r2>:{ @<a2X>(c2X) ... }"
                 " <Avg Dist. (Ang)> <Label>\n"
                 "# r1, r2: Residue Numbers\n"
                 "# a1X, a2X: Group atom numbers\n"
                 "# c1X, c2X: Number of times atom was part of shortest distance.\n");
  out->Printf("#Final NOEs (%zu):\n#   %s\n", Narray.size(), Labels[current_cut]);
  for (NOEtypeArray::iterator my_noe = Narray.begin();
                              my_noe != Narray.end(); ++my_noe)
  {
    unsigned int old_cut = current_cut;
    while (current_cut < 3 && my_noe->R6_Avg() > Cutoffs[current_cut]) 
      current_cut++;
    if (old_cut != current_cut)
      out->Printf("#   %s\n", Labels[current_cut]);
    out->Printf("\t %s %g \"%s\"\n", my_noe->PrintNOE().c_str(),
                   my_noe->R6_Avg(), my_noe->legend());
    if (my_noe->Data() != 0) {
      DataSet_float& data = static_cast<DataSet_float&>( *(my_noe->Data()) );
      for (unsigned int i = 0; i != data.Size(); i++)
        data[i] = sqrt(data[i]);
    }
    // Bin
    if (my_noe->R6_Avg() < strong_cut_) {
      ++Bins[0];
      VR.AddRst(my_noe->Site1().Idx(0), my_noe->Site2().Idx(0), ViewRst::NOE_STRONG);
    } else if (my_noe->R6_Avg() < medium_cut_) {
      ++Bins[1];
      VR.AddRst(my_noe->Site1().Idx(0), my_noe->Site2().Idx(0), ViewRst::NOE_MEDIUM);
    } else if (my_noe->R6_Avg() < weak_cut_) {
     ++Bins[2];
      VR.AddRst(my_noe->Site1().Idx(0), my_noe->Site2().Idx(0), ViewRst::NOE_WEAK);
    } else {
     ++Bins[3];
      VR.AddRst(my_noe->Site1().Idx(0), my_noe->Site2().Idx(0), ViewRst::NOE_VERYWEAK);
    }
  }
  out->Printf("#Totals: %u strong, %u medium, %u weak, %u none.\n",
          Bins[0], Bins[1], Bins[2], Bins[3]);
  VR.WriteRstTop(viewrst_);
}
Exemple #4
0
int scaleSmearFit(TString RDFile, TString MCFile, char BaseName[30])
{
  cout<<"Processing "<<BaseName<<endl;
  gStyle->SetPalette(1);
  //Data and histograms
  TFile *f_RD = new TFile(RDFile);
  TFile *f_MC = new TFile(MCFile);
  TH1D *h1_ZmassDaughEtaRD = (TH1D*)f_RD->Get("h1_ZmassDaughEtaRD")->Clone();
  TH1D *h1_ZmassDaughEtaMC[ScaleBins][ScaleBins];
  //Variables
  char histName[30];
  RooRealVar zMass("zMass","zMass",60,120);
  RooRealVar *nMC;
  RooRealVar nBRD("nBRD","nBRD",5,2000);
  RooRealVar nSRD("nSRD","nSRD",1000,0,20000);
  RooRealVar nBMC("nBMC","nBMC",5,2000);
  RooRealVar nSMC("nSMC","nSMC",1000,0,20000);
  RooPlot *zmassframe;
  RooPlot *zmassframeMC;
  CPlot *plotFit;
  CPlot *plotFitMC;
  //zMass.setBins(50);
  RooFitResult* fitRes;
  RooFitResult* fitResMC;
  TCanvas *myCan = MakeCanvas("myCan","myCan",800,600);
  RooDataHist *ZmassMC;
  //RooHistPdf *pdfMC;
  RooAddPdf *pdfMC;
  RooAddPdf* pdfRD;
  //RD fitting
  RooDataHist *ZmassRD =
    new RooDataHist("ZmassRD","ZmassRD", RooArgSet(zMass),h1_ZmassDaughEtaRD);
  //CBreitWignerConvCrystalBall ZsignalPdf("ZsigPdf",zMass);
  //pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsignalPdf.model)),RooArgList(nRD));
  CVoigtian     ZsigRD("ZsigRD",zMass);
  CErfExpo ZbgRD("ZbgRD",zMass);
  //CQuadraticExp ZbgRD("ZbgRD",zMass);
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  fitRes=pdfRD->fitTo(*ZmassRD,Extended(),Minos(kTRUE),Save(kTRUE));
  //fitRes=ZsignalPdf.model->fitTo(*ZmassRD,Minos(kTRUE),Save(kTRUE));
  zmassframe=zMass.frame(Bins(60));
  ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
  //ZsignalPdf.model->plotOn(zmassframe,LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,LineColor(kBlack),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZsigRD.model))),LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZbgRD.model))),LineColor(kRed),DrawOption("l"));
  sprintf(histName,"ZmassRD_%s",BaseName);
  plotFit = new CPlot(histName,zmassframe,"","","Z mass");
  plotFit->setOutDir("Plot");
  plotFit->Draw(myCan,kTRUE,"png");

  //CErfExpo *pdfZbg;
  //double nLL[41][41];

  //                                 90 0.004
  double ScaleWidth = (ScaleH-ScaleL)/(ScaleBins-1);
  double SmearWidth = (SmearH-SmearL)/(ScaleBins-1);
  sprintf(histName,"h2_NLL_%s",BaseName);
  TH2D *h2_NLL = new TH2D(histName,histName,
      ScaleBins,ScaleL-ScaleWidth/2,ScaleH+ScaleWidth/2,
      ScaleBins,SmearL-SmearWidth/2,SmearH+SmearWidth/2);
  //TH2D *h2_NLL = new TH2D("h2_NLL","NLL",41,0.97,1.05,41,0.5,1.5);
  double x,prob;
  //RooAbsReal *nll;
  double nll;
  double binContent;
  //***
  CVoigtian ZsigMC("ZsigMC",zMass);
  RooArgSet allArgset(zMass);
  RooArgSet anaVar;
  //for(int i(0);i<=0;i++)for(int j(0);j<=0;j++)
  for(int i(0);i<=ScaleBins-1;i++)for(int j(0);j<=ScaleBins-1;j++)
  {
    sprintf(histName,"h1_ZmassDaughEta_%d_%d",i,j);
    h1_ZmassDaughEtaMC[i][j] = (TH1D*)f_MC->Get(histName)->Clone(histName);
    ZmassMC =
      new RooDataHist("ZmassMC","ZmassMC",RooArgSet(zMass),h1_ZmassDaughEtaMC[i][j]);
    //                                               interpolation order
    //pdfMC =new RooHistPdf ("pdfMC", "pdfMC", zMass,*ZmassMC, 1);
    //Using fitting MC
    nSMC.setVal(285);
    ZsigMC.mass->setVal(91.37);
    ZsigMC.sigma->setVal(0.42);
    ZsigMC.width->setVal(4.4);
    pdfMC = new RooAddPdf("pdfMC","pdfMC",RooArgList(*(ZsigMC.model)),RooArgList(nSMC));
    fitResMC = pdfMC->fitTo(*ZmassMC,Extended(),Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));//SumW2Error(kTRUE) default

    nll=0;
    //nll= h1_ZmassDaughEtaMC[i][j]->Chi2Test(h1_ZmassDaughEtaRD,"CHI2/NDF");
    // code 1000 dataHist sum
    int intCode = pdfMC->getAnalyticalIntegral(allArgset,anaVar);
    double norm = pdfMC->analyticalIntegral(intCode);
    cout<<"norm: code "<<norm<<" : "<<intCode<<"======================"<<endl;
    //double totalProb(0);
    //****
    for(int k(1);k<=60;k++)
    {
      x=h1_ZmassDaughEtaMC[i][j]->GetBinCenter(k);
    //  binContent = h1_ZmassDaughEtaRD->GetBinContent(k);
      //binContent = h1_ZmassDaughEtaMC[i][j]->GetBinContent(k);
      zMass=x;
      //prob = ZsignalPdf.model->evaluate();
      binContent = ZsigRD.model->evaluate()*(120-60)/60.*nSRD.getVal();
      prob = pdfMC->evaluate()*(120-60)/60.;
      //cout<<"binCont, prob "<<binContent<<" "<<prob<<endl;
      //totalProb +=prob;
      nll+=-binContent*log(prob);
      //cout<<" x: prob "<<x<<"  "<<prob<<endl;
    }
    h2_NLL->SetBinContent(i+1,j+1,nll);
    /***/
    //
    //
    if( j==0 || j==int(ScaleBins/2)|| j==(ScaleBins-1) )
    {
      //RD MCpdf RDpdf Plot
      zmassframe =zMass.frame(Bins(60));
      ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
      pdfRD->plotOn(zmassframe,LineColor(kBlack));
      pdfMC->plotOn(zmassframe,LineColor(kBlue));
      //pdfRD->plotOn(zmassframe,Components(RooArgSet(*(pdfZbg->model))),LineColor(kRed));
      sprintf(histName,"Zmass_%s_%d_%d",BaseName,i,j);
      plotFit = new CPlot(histName,zmassframe,"","","Z mass");
      plotFit->SetLegend(0.68,0.57,0.93,0.8);
      plotFit->GetLegend()->AddEntry(pdfRD,"RD","f");
      plotFit->GetLegend()->AddEntry(pdfMC,"MC","f");
      plotFit->setOutDir("Plot");
      plotFit->Draw(myCan,kTRUE,"png");
      //MC MCPdf Plot
      zmassframeMC = zMass.frame(Bins(60));
      ZmassMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("p"));
      pdfMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("l"));
      sprintf(histName,"ZmassMC_%s_%d_%d",BaseName,i,j);
      plotFitMC = new CPlot(histName,zmassframeMC,"","","Z mass MC");
      plotFitMC->setOutDir("Plot");
      plotFitMC->Draw(myCan,kTRUE,"png");
    }
  }
  //====
  //Plot
  //====
  //Zmass----------
  //CPlot *plotZmassRD=new CPlot("plotZmassRD","","zMass","Event");
  //plotZmassRD->setOutDir("Plot");
  //plotZmassRD->AddHist1D(h1_ZmassDaughEtaRD,"",kBlack);
  //plotZmassRD->SetLegend(0.68,0.57,0.93,0.8);
  //plotZmassRD->GetLegend()->AddEntry(h1_ZmassDaughEtaRD,"RD Ele","l");
  //plotZmassRD->AddTextBox("both lepton at the |Eta|<0.4",0.65,0.80,0.99,0.86,0);
  //plotZmassRD->Draw(myCan,kTRUE,"png");
  //NLL------------
  sprintf(histName,"plotNLL_%s",BaseName);
  CPlot *plotNll=new CPlot(histName,"","Scale","Smear");
  plotNll->setOutDir("Plot");
  //plotNll->AddHist2D(h2_NLL,"COLZ",kWhite,kBlack);
  plotNll->AddHist2D(h2_NLL,"SURF3",kWhite,kBlack);
  plotNll->Draw(myCan,kTRUE,"png");
  //****/
  return 0;
}
int main() {
    bool recutdata=false;
    bool recutmc=false;
    bool remakedatasets=false;
    std::vector<std::string> VariablesToCompare= {"gamma_CL","nSPDHits","Bu_DIRA_OWNPV","Bu_M01"};
    auto BranchesToKeepMC = ControlCuts::BranchesToKeep;
    for(auto branch : VariablesToCompare) {
        if (std::find(BranchesToKeepMC.begin(),BranchesToKeepMC.end(),branch)==std::end(BranchesToKeepMC)) {
            BranchesToKeepMC.push_back(std::move(branch));
        }
    }

    auto BranchesToKeep = ControlCuts::BranchesToKeep;
    for(auto branch : VariablesToCompare) {
        if (std::find(BranchesToKeep.begin(),BranchesToKeep.end(),branch)==std::end(BranchesToKeep)) {
            BranchesToKeep.push_back(std::move(branch));
        }
    }

    if(recutdata) {
        DataFile TwelA(std::getenv("BUKETAPDATAROOT"),Data,Twel,MagAll,buketap,"TriggerCut_SampleA");
        DataFile TwelB(std::getenv("BUKETAPDATAROOT"),Data,Twel,MagAll,buketap,"TriggerCut_SampleB");
        DataFile ElevA(std::getenv("BUKETAPDATAROOT"),Data,Elev,MagAll,buketap,"TriggerCut_SampleA");
        DataFile ElevB(std::getenv("BUKETAPDATAROOT"),Data,Elev,MagAll,buketap,"TriggerCut_SampleB");

        TreeReader* TwelReader = new TreeReader("DecayTree");
        TwelReader->AddFile(TwelA);
        TwelReader->AddFile(TwelB);

        TreeReader* ElevReader = new TreeReader("DecayTree");
        ElevReader->AddFile(ElevA);
        ElevReader->AddFile(ElevB);


        TwelReader->Initialize(BranchesToKeep,"names");
        ElevReader->Initialize(BranchesToKeep,"names");

        auto TwelMinimalFile=std::make_unique<TFile>("TwelMinimalFile.root","RECREATE");
        TTree* TwelMinimalTree=TwelReader->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        TwelMinimalTree->Write();

        auto ElevMinimalFile=std::make_unique<TFile>("ElevMinimalFile.root","RECREATE");
        TTree* ElevMinimalTree=ElevReader->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        ElevMinimalTree->Write();
    }
    if(recutmc) {
        DataFile MCTwel(std::getenv("BUKETAPMCROOT"),MC,Twel,MagAll,buketap,"TriggerCut");
        DataFile MCElev(std::getenv("BUKETAPMCROOT"),MC,Elev,MagAll,buketap,"TriggerCut");

        TreeReader* TwelReaderMC = new TreeReader("DecayTree");
        TwelReaderMC->AddFile(MCTwel);

        TreeReader* ElevReaderMC = new TreeReader("DecayTree");
        ElevReaderMC->AddFile(MCElev);


        TwelReaderMC->Initialize(BranchesToKeepMC,"names");
        ElevReaderMC->Initialize(BranchesToKeepMC,"names");

        auto TwelMinimalFileMC=std::make_unique<TFile>("TwelMinimalFileMC.root","RECREATE");
        TTree* TwelMinimalTreeMC=TwelReaderMC->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        TwelMinimalTreeMC->Write();

        auto ElevMinimalFileMC=std::make_unique<TFile>("ElevMinimalFileMC.root","RECREATE");
        TTree* ElevMinimalTreeMC=ElevReaderMC->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        ElevMinimalTreeMC->Write();
    }
    if(remakedatasets||recutmc||recutdata) {
        RooArgSet* MCVars= new RooArgSet("MCVars");
        RooArgSet* Vars= new RooArgSet("Vars");

        for(auto & Branch : BranchesToKeep) {
            Vars->add(*(HandyFunctions::CreateRealVar(Branch)));
        }

        for(auto & MCBranch:  BranchesToKeepMC) {
            MCVars->add(*(HandyFunctions::CreateRealVar(MCBranch)));
            std::cout<<MCBranch<<std::endl;
        }

        auto TwelMinimalFile = std::make_unique<TFile>("TwelMinimalFile.root");
        TTree* TwelMinimalTree=(TTree*)TwelMinimalFile->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<TwelMinimalTree->GetEntries()<<std::endl;
        RooDataSet* TwelData= new RooDataSet("TwelData","TwelData",*Vars,Import(*TwelMinimalTree));
        std::cout<<"Events in Dataset= "<<TwelData->sumEntries()<<std::endl;

        auto ElevMinimalFile = std::make_unique<TFile>("ElevMinimalFile.root");
        TTree* ElevMinimalTree=(TTree*)ElevMinimalFile->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<ElevMinimalTree->GetEntries()<<std::endl;
        RooDataSet* ElevData= new RooDataSet("ElevData","ElevData",*Vars,Import(*ElevMinimalTree));
        std::cout<<"Events in Dataset= "<<ElevData->sumEntries()<<std::endl;

        auto TwelMinimalFileMC = std::make_unique<TFile>("TwelMinimalFileMC.root");
        TTree* TwelMinimalTreeMC=(TTree*)TwelMinimalFileMC->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<TwelMinimalTreeMC->GetEntries()<<std::endl;
        RooDataSet* TwelDataMC= new RooDataSet("TwelDataMC","TwelDataMC",*Vars,Import(*TwelMinimalTreeMC));
        std::cout<<"Events in Dataset= "<<TwelDataMC->sumEntries()<<std::endl;
        auto ElevMinimalFileMC = std::make_unique<TFile>("ElevMinimalFileMC.root");
        TTree* ElevMinimalTreeMC=(TTree*)ElevMinimalFileMC->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<ElevMinimalTreeMC->GetEntries()<<std::endl;
        RooDataSet* ElevDataMC= new RooDataSet("ElevDataMC","ElevDataMC",*Vars,Import(*ElevMinimalTreeMC));
        std::cout<<"Events in Dataset= "<<ElevDataMC->sumEntries()<<std::endl;

        TwelMinimalFile->Close();
        ElevMinimalFile->Close();
        TwelMinimalFileMC->Close();
        ElevMinimalFileMC->Close();
        auto DataSetCache=std::make_unique<TFile>("DataSetCache.root","RECREATE");
        gDirectory->pwd();
        TwelData->Write();
        ElevData->Write();
        TwelDataMC->Write();
        ElevDataMC->Write();
    }

    TFile* DataSetCache= new TFile("DataSetCache.root");
    RooDataSet* Data12=SafeGetDataSet(DataSetCache,"TwelData");
    RooDataSet* Data11=SafeGetDataSet(DataSetCache,"ElevData");
    RooDataSet* MC12=SafeGetDataSet(DataSetCache,"TwelDataMC");
    RooDataSet* MC11=SafeGetDataSet(DataSetCache,"ElevDataMC");

    RooRealVar * BuMass= new RooRealVar("Bu_DTF_MF","Bu_DTF_MF",5000.0,5500.0);
    RooRealVar* BkgP1= new RooRealVar("BkgP1","BkgP1",-1.0,-10.0,10.0);
    RooRealVar* BkgP2= new RooRealVar("BkgP2","BkgP2",1.0,-10.0,10.0);
    RooChebychev* BkgPdf= new RooChebychev("BkgPdf","BkgPdf",*BuMass,RooArgList(*BkgP1,*BkgP2));

    BkgPdf->fitTo(*Data12,Range(5000.0,5200.));

    RooPlot* BFrame = BuMass->frame(Bins(50));
    Data12->plotOn(BFrame);
    BkgPdf->plotOn(BFrame);
    BkgPdf->paramOn(BFrame);
    TCanvas C;
    BFrame->Draw();

    C.SaveAs("BFrame.pdf");


}
Exemple #6
0
void drawMassFrom2DPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  map<string, string>  parIni,   // Variable containing all initial parameters
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the type of object to fit
                  bool incJpsi,         // Includes Jpsi model
                  bool incPsi2S,        // Includes Psi(2S) model
                  bool incBkg,          // Includes Background model                  
                  // Select the fitting options
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  double  binWidth,     // Bin width
                  bool paperStyle=false // if true, print less info
                  ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
  
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
  
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiPRName  = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiNoPRName  = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SPRName  = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SNoPRName  = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  bool isMC = (DSTAG.find("MC")!=std::string::npos);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  
  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

 
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
 
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                       FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed)
                                       );
  if (!paperStyle) {
    if (incJpsi) {
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
    }
    if (incPsi2S) {
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }      
    } 
  }
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  // Create the pull distribution of the fit 
  RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP");
  int nBinsTMP = nBins;
  RooHist *hpull = frameTMP->pullHist(0, 0, true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  frame2->addPlotable(hpull, "PX"); 
  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setMassFrom2DRange(myws, frame, dsOSName, setLogScale);
  if (paperStyle) {
     double Ydown = 0.;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } else {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;}
  else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;}
  t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); }
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); }
  if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); }
  if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); }
  if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  if (!paperStyle) {
     //---plot pull
     pad2->Draw();
     pad2->cd();

     frame2->SetTitle("");
     frame2->GetYaxis()->CenterTitle(kTRUE);
     frame2->GetYaxis()->SetTitleOffset(0.4);
     frame2->GetYaxis()->SetTitleSize(0.1);
     frame2->GetYaxis()->SetLabelSize(0.1);
     frame2->GetYaxis()->SetTitle("Pull");
     frame2->GetXaxis()->CenterTitle(kTRUE);
     frame2->GetXaxis()->SetTitleOffset(1);
     frame2->GetXaxis()->SetTitleSize(0.12);
     frame2->GetXaxis()->SetLabelSize(0.1);
     frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

     frame2->Draw(); 

     // *** Print chi2/ndof 
     printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false);

     pline->Draw("same");
     pad2->Update();
  }

  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
};
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================    
  TRandom3 *randomnumber = new TRandom3(seed);
//   RooRealVar m("m","mass",60,130);

  RooCategory sample("sample","");
  sample.defineType("Pass",1);
  sample.defineType("Fail",2);

  //--------------------------------------------------------------------------------------------------------------
  //Load Workspace
  //==============================================================================================================    
  TFile *f = new TFile (workspaceFile.c_str(), "READ");
  RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace");

  //--------------------------------------------------------------------------------------------------------------
  //Setup output tree
  //==============================================================================================================    
  TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE");
  float varEff = 0;
  float varEffErrL = 0;
  float varEffErrH = 0;
  TTree *outTree = new TTree("eff","eff");
  outTree->Branch("eff",&varEff, "eff/F");
  outTree->Branch("efferrl",&varEffErrL, "efferrl/F");
  outTree->Branch("efferrh",&varEffErrH, "efferrh/F");
  
  //--------------------------------------------------------------------------------------------------------------
  //Load Model
  //==============================================================================================================    
  RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf");
  RooRealVar *m_default = (RooRealVar*)w->var("m");
  m_default->setRange("signalRange",85, 95);
  
  //get default models
  RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass");
  RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail");

  //get variables
  RooRealVar *Nsig = (RooRealVar*)w->var("Nsig");
  RooRealVar *eff = (RooRealVar*)w->var("eff");
  RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail");

  RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig));	 
  RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig));

  //get number of expected events
  Double_t npass = 100;
  Double_t nfail = 169;

  //*************************************************************************************
  //make alternative model
  //*************************************************************************************
  RooRealVar *tFail_default = (RooRealVar*)w->var("tFail");
  RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail");
 

  RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail");
  RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail");
  RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail");
  RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail");
  RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail");
  RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail");
  RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail");
  RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail");
  RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail");
  RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail");

  //shifted mean
  RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5);
  meanFail_shifted->setVal(meanFail_default->getVal());
  if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0);
  else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0);  
  else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0);
  else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0);  

  RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5);
  sigmaFail_shifted->setVal(sigmaFail_default->getVal());
  if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2);
  else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8);

  CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted");
  bkgFailModel->t->setVal(tFail_default->getVal());
  bkgFailModel->frac->setVal(fracFail_default->getVal());

  cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl;
  cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl;
  cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl;
  cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl;
  
  cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl;
  cout << "NbkgFail: " << NbkgFail->getVal() << endl;


  //make alternative fail model
  RooAddPdf *modelFail=0;
  RooExtendPdf *esignalFail=0, *ebackgroundFail=0;
  ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange");
  modelFail       = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail));



  cout << "*************************************\n";
  ebackgroundFail->Print();
  cout << "*************************************\n";
  ebackgroundFail_default->Print();
  cout << "*************************************\n";
  modelFail->Print();
  cout << "*************************************\n";
  modelFail_default->Print();
  cout << "*************************************\n";

  TCanvas *cv = new TCanvas("cv","cv",800,600);

  RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail_default->plotOn(mframeFail_default);
  modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
  modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail_default->GetYaxis()->SetTitle("");
  mframeFail_default->GetYaxis()->SetTitleOffset(1.2);
  mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail_default->GetXaxis()->SetTitleOffset(1.05);
  mframeFail_default->SetTitle("");
  mframeFail_default->Draw();

  cv->SaveAs("DefaultModel.gif");

  RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail->plotOn(mframeFail);
  modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
  modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail->GetYaxis()->SetTitle("");
  mframeFail->GetYaxis()->SetTitleOffset(1.2);
  mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail->GetXaxis()->SetTitleOffset(1.05);
  mframeFail->SetTitle("");
  mframeFail->Draw();
  cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


  //*************************************************************************************
  //Do Toys
  //*************************************************************************************
  for(uint t=0; t < NToys; ++t) {

    RooDataSet *pseudoData_pass    = modelPass_default->generate(*m_default, randomnumber->Poisson(npass));
    RooDataSet *pseudoData_fail  = 0;
    pseudoData_fail    = modelFail->generate(*m_default, randomnumber->Poisson(nfail));
    RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default),
                                                    RooFit::Index(sample),
                                                    RooFit::Import("Pass",*pseudoData_pass),
                                                    RooFit::Import("Fail",*pseudoData_fail));

    pseudoDataCombined->write(Form("toy%d.txt",t));

    RooFitResult *fitResult=0;
    fitResult = totalPdf->fitTo(*pseudoDataCombined,
                                RooFit::Extended(),
                                RooFit::Strategy(2),
                                //RooFit::Minos(RooArgSet(eff)),
                                RooFit::Save());

    cout << "\n\n";
    cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl;

    //Fill Tree
    varEff = eff->getVal();
    varEffErrL = fabs(eff->getErrorLo());
    varEffErrH = eff->getErrorHi();
    outTree->Fill();


//   //*************************************************************************************
//   //Plot Toys
//   //*************************************************************************************
//   TCanvas *cv = new TCanvas("cv","cv",800,600);
//   char pname[50];
//   char binlabelx[100];
//   char binlabely[100];
//   char yield[50];
//   char effstr[100];
//   char nsigstr[100];
//   char nbkgstr[100];
//   char chi2str[100];

//   //
//   // Plot passing probes
//   //

//   RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2));
//   modelFail_default->plotOn(mframeFail_default);
//   modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
//   modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
//   mframeFail_default->Draw();
//   cv->SaveAs("DefaultModel.gif");





//   RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2));
//   modelFail->plotOn(mframeFail);
//   modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
//   modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));

//   sprintf(yield,"%u Events",(Int_t)passTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult));
//     plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);
//     plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str);

//   mframeFail->Draw();
//   cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


 
//   //
//   // Plot failing probes
//   //
//   sprintf(pname,"fail%s_%i",name.Data(),ibin);
//   sprintf(yield,"%u Events",(Int_t)failTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult));
//   sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult));
//   sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail));
//   CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}");
//   plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1);
//   if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) {
//     plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1);    
//     plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   } else {
//     plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1);
//   }
//   plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);  
//   plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str);
//   plotFail.Draw(cfail,kTRUE,format);  




  } //for loop over all toys
  



  //*************************************************************************************
  //Save To File
  //*************************************************************************************
  outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete");

}
Exemple #8
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();

  
		 
		  

  
}
Exemple #9
0
void drawCtauFrom2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        map<string, string>  parIni,   // Variable containing all initial parameters
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                        // Select the type of object to fit
                        bool incJpsi,         // Includes Jpsi model
                        bool incPsi2S,        // Includes Psi(2S) model
                        bool incBkg,          // Includes Background model     
                        // Select the fitting options
                        // Select the drawing options
                        bool setLogScale,     // Draw plot with log scale
                        bool incSS,           // Include Same Sign data
                        double binWidth       // Bin width
                        ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string hOSName = Form("dhCTAUERRTot_Tot_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameBkg  = Form("dhCTAUERR_Bkg_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameJpsi = Form("dhCTAUERR_Jpsi_%s", (isPbPb?"PbPb":"PP"));
  string hOSNamePsi2S = Form("dhCTAUERR_Psi2S_%s", (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  vector<double> range; range.push_back(cut.dMuon.ctau.Min); range.push_back(cut.dMuon.ctau.Max);

  double minRange = -4.0;
  double maxRange = 7.0;
  Double_t outTot = myws.data(dsOSName.c_str())->numEntries();
  Double_t outErr = myws.data(dsOSName.c_str())->reduce(Form("(ctau>%.6f || ctau<%.6f)", range[1], range[0]))->numEntries();
  int nBins = min(int( round((maxRange - minRange)/binWidth) ), 1000);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  double normJpsi  = 1.0;  if (myws.data(hOSNameJpsi.c_str()))  { normJpsi  = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameJpsi.c_str())->sumEntries();  }
  double normPsi2S = 1.0;  if (myws.data(hOSNamePsi2S.c_str())) { normPsi2S = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNamePsi2S.c_str())->sumEntries(); }
  double normBkg   = 1.0;  if (myws.data(hOSNameBkg.c_str()))   { normBkg   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameBkg.c_str())->sumEntries();   }
  double normTot   = 1.0;  if (myws.data(hOSName.c_str()))  { normTot   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSName.c_str())->sumEntries();  }

  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(minRange, maxRange));
  frame->updateNormVars(RooArgSet(*myws.var("invMass"), *myws.var("ctau"), *myws.var("ctauErr"))) ;
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kViolet+6), VLines(), DrawOption("LF"), NumCPU(32), LineColor(kBlack)
                                       );
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))) )),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kAzure-9), VLines(), DrawOption("LF"), NumCPU(32)
                                       );
  if (incJpsi) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }
  if (incPsi2S) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SNo_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }  
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDFLINE"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent), 
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  
  // set the CMS style
  setTDRStyle();

  // Create the pull distribution of the fit 
  RooHist *hpull = frame->pullHist(0, "PDF", true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("ctau")->frame(Title("Pull Distribution"), Bins(nBins), Range(minRange, maxRange));
  frame2->addPlotable(hpull, "PX"); 
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cCtauFig_%s", (isPbPb?"PbPb":"PP")), "cCtauFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(minRange, 0.0, maxRange, 0.0);
  
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  frame->GetXaxis()->SetTitleSize(0.045);
  frame->GetXaxis()->SetTitleFont(42);
  frame->GetXaxis()->SetTitleOffset(3);
  frame->GetXaxis()->SetLabelOffset(3);
  frame->GetYaxis()->SetLabelSize(0.04);
  frame->GetYaxis()->SetTitleSize(0.04);
  frame->GetYaxis()->SetTitleOffset(1.7);
  frame->GetYaxis()->SetTitleFont(42);
  setCtauFrom2DRange(myws, frame, dsOSNameCut, setLogScale, range, outErr);
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printCtauFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
  if (isPbPb) {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } else {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } 
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq p_{T}^{#mu#mu} < %.1f GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.21, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  if (outErr>0.0) {
    t->DrawLatex(0.21, 0.86-dy, Form("Excl: (%.4f%%) %.0f evts", (outErr*100.0/outTot), outErr)); dy+=1.5*0.045;
  }

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if(frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","fl"); }
  if((incBkg && (incJpsi || incPsi2S)) && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background","fl");  }
  if(incBkg && incJpsi && frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"J/#psi Prompt","l"); }
  if(incBkg && incJpsi && frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"J/#psi Non-Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SPR")) { leg->AddEntry(frame->findObject("PSI2SPR"),"#psi(2S) Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SNOPR")) { leg->AddEntry(frame->findObject("PSI2SNOPR"),"#psi(2S) Non-Prompt","l"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  //CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  //---plot pull
  pad2->Draw();
  pad2->cd();
    
  frame2->SetTitle("");
  frame2->GetYaxis()->CenterTitle(kTRUE);
  frame2->GetYaxis()->SetTitleOffset(0.4);
  frame2->GetYaxis()->SetTitleSize(0.1);
  frame2->GetYaxis()->SetLabelSize(0.1);
  frame2->GetYaxis()->SetTitle("Pull");
  frame2->GetXaxis()->CenterTitle(kTRUE);
  frame2->GetXaxis()->SetTitleOffset(1);
  frame2->GetXaxis()->SetTitleSize(0.12);
  frame2->GetXaxis()->SetLabelSize(0.1);
  frame2->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

  frame2->Draw(); 
  
  // *** Print chi2/ndof 
  printChi2(myws, pad2, frame, "ctau", dsOSName.c_str(), pdfTotName.c_str(), nBins, false);
  
  pline->Draw("same");
  pad2->Update();
  
  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  

  cFig->Clear();
  cFig->Close();

}
Exemple #10
0
int main() {
    const double PDGLbMass=5619.51;
    const double RareUpperBlind=PDGLbMass+125.0;
    const double RareLowerBlind=PDGLbMass-125.0;
    const double Rare2UpperBlind=PDGLbMass+175.0;
    const double Rare2LowerBlind=PDGLbMass-175.0;
    bool blind=true;
    bool remakecc=false;
    bool remakerare=false;
    bool remakerare2=false;
    bool sweight=false;
    TRandom3* MultiCandRand=new TRandom3(224); //dont change seed
    TH1I* ControlChannelMultiCands= new TH1I("ControlChannelMultiCands","ControlChannelMultiCands",10,0,10);
    TH1I* RareChannelMultiCands= new TH1I("RareChannelMultiCands","RareChannelMultiCands",10,0,10);
    TH1I* Rare2ChannelMultiCands= new TH1I("RareChannel2MultiCands","RareChannel2MultiCands",10,0,10);

    //_______________________________________ MAKE CONTROL CHANNEL ROODATASET______________________________________
    if(remakecc) {
        std::string ControlDataPath=std::getenv("BUKETAPDATABDTRESPROOT");
        DataFile CC12A(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC12B(ControlDataPath,Data,Twel,MagAll,buketap,"BDTApplied_SampleB");
        DataFile CC11A(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleA");
        DataFile CC11B(ControlDataPath,Data,Elev,MagAll,buketap,"BDTApplied_SampleB");

        TreeReader* CC12Reader= new TreeReader("DecayTree");
        CC12Reader->AddFile(CC12A);
        CC12Reader->AddFile(CC12B);
        CC12Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalCC12.root","RECREATE");
        TTree* Minimal12Tree=CC12Reader->CopyTree(ControlCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* CC11Reader= new TreeReader("DecayTree");
        CC11Reader->AddFile(CC11A);
        CC11Reader->AddFile(CC11B);
        CC11Reader->Initialize(ControlCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalCC11.root","RECREATE");
        TTree* Minimal11Tree=CC11Reader->CopyTree(ControlCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,ControlChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalCC12.root");
        FlaggedReader->AddFile("MinimalCC11.root");
        FlaggedReader->Initialize();
        TFile* CCSingleFile= new TFile("CCSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        CCSingleFile->Close();
    }

    //_____________________________________Make Rare Mode One Data__________________________________________________
    if(remakerare) {
        std::string RareDataPath=std::getenv("LBPKETAPPIPIGDATABDTRESPROOT");
        DataFile Rare12A(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare12B(RareDataPath,Data,Twel,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");
        DataFile Rare11A(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleA_NB");
        DataFile Rare11B(RareDataPath,Data,Elev,MagAll,lbpketappipig,"BDTApplied_SampleB_NB");

        TreeReader* Rare12Reader= new TreeReader("DecayTree");
        Rare12Reader->AddFile(Rare12A);
        Rare12Reader->AddFile(Rare12B);
        Rare12Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare12.root","RECREATE");
        TTree* Minimal12Tree=Rare12Reader->CopyTree(pipigCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,RareChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare11Reader= new TreeReader("DecayTree");
        Rare11Reader->AddFile(Rare11A);
        Rare11Reader->AddFile(Rare11B);
        Rare11Reader->Initialize(pipigCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare11.root","RECREATE");
        TTree* Minimal11Tree=Rare11Reader->CopyTree(pipigCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,RareChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare12.root");
        FlaggedReader->AddFile("MinimalRare11.root");
        FlaggedReader->Initialize();
        TFile* RareSingleFile= new TFile("RareSingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        RareSingleFile->Close();

    }
    //___________________________________ Make Rare mode Two Data________________________________________________
    if(remakerare2) {
        std::string Rare2DataPath=std::getenv("LBPKETAPETADATABDTRESPROOT");
        DataFile Rare212A(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare212B(Rare2DataPath,Data,Twel,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");
        DataFile Rare211A(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleA_NB");
        DataFile Rare211B(Rare2DataPath,Data,Elev,MagAll,lbpketapeta,"BDTApplied_SampleB_NB");

        TreeReader* Rare212Reader= new TreeReader("DecayTree");
        Rare212Reader->AddFile(Rare212A);
        Rare212Reader->AddFile(Rare212B);
        Rare212Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal12File= new TFile("MinimalRare212.root","RECREATE");
        TTree* Minimal12Tree=Rare212Reader->CopyTree(etapetaCuts::AllCuts12,-1,"DecayTree");
        TTree* MinimalFlagged12Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal12Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged12Tree->Write();
        Minimal12File->Close();

        TreeReader* Rare211Reader= new TreeReader("DecayTree");
        Rare211Reader->AddFile(Rare211A);
        Rare211Reader->AddFile(Rare211B);
        Rare211Reader->Initialize(etapetaCuts::BranchesToKeep,"contains");
        TFile* Minimal11File= new TFile("MinimalRare211.root","RECREATE");
        TTree* Minimal11Tree=Rare211Reader->CopyTree(etapetaCuts::AllCuts11,-1,"DecayTree");
        TTree* MinimalFlagged11Tree=HandyFunctions::GetSingleTree(MultiCandRand,Minimal11Tree,Rare2ChannelMultiCands,NULL);
        MinimalFlagged11Tree->Write();
        Minimal11File->Close();

        TreeReader* FlaggedReader= new TreeReader("DecayTree");
        FlaggedReader->AddFile("MinimalRare212.root");
        FlaggedReader->AddFile("MinimalRare211.root");
        FlaggedReader->Initialize();
        TFile* Rare2SingleFile= new TFile("Rare2SingleFile.root","RECREATE");
        TTree* SingleTree=FlaggedReader->CopyTree("isSingle==1",-1,"DecayTree");
        SingleTree->Write();
        Rare2SingleFile->Close();
    }
    //____________________________________ Shared Parameters_______________________________________________________

    RooRealVar DataMCRatio("DataMCRatio","DataMCRatio",1.0,0.5,1.5);
    RooRealVar CCMean("CCMean","CCMean",5279.0,5250.0,5310.0);
    RooFormulaVar LambdabMean("LambdabMean","LambdabMean","@0+339.72",RooArgList(CCMean));
    //RooRealVar LambdabMean("LambdabMean","LambdabMean",5619.0,5615.0,5630.0);
    // RooFormulaVar CCMean("CCMean","CCMean","@0 - 339.72",RooArgList(LambdabMean));

    std::vector<RooRealVar*> FreeParameters;
    FreeParameters.push_back(&DataMCRatio);
    //  FreeParameters.push_back(&LambdabMean);

    //____________________________________ Control Channel PDF______________________________________________________

    TFile* CCInputFile = new TFile("CCSingleFile.root");
    TTree* CCInputTree=(TTree*)CCInputFile->Get("DecayTree");
    RooRealVar CCBMass("Bu_DTF_MF","Bu_DTF_MF",5000.0,5550.0);
    RooRealVar CCEtaMass("eta_prime_MM","eta_prime_MM",880.0,1040.0);
    RooArgSet CCArgs(CCBMass,CCEtaMass);
    RooDataSet* CCData=new RooDataSet("CCData","CCData",CCArgs,Import(*CCInputTree));


    //++++++++++++++++++++++++++++++Signal PDF+++++++++++++++++++++++++++++++++


    TFile *CCMCFitResultFile = new TFile("CCFitResult.root");
    RooFitResult* CCMCFitResult=NULL;
    try {
        CCMCFitResult=SafeGetFitResult(CCMCFitResultFile,"CCFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    CCMCFitResult->Print("v");
    RooRealVar* CCMCSigma=NULL;
    RooRealVar* CCMCLAlphaFix=NULL;
    RooRealVar* CCMCRAlphaFix=NULL;
    RooRealVar* CCMCLNFix=NULL;
    RooRealVar* CCMCRNFix=NULL;

    try {
        CCMCSigma=SafeGetVar(CCMCFitResult,"CCSigma");
        CCMCLAlphaFix=SafeGetVar(CCMCFitResult,"CCLAlpha");
        CCMCRAlphaFix=SafeGetVar(CCMCFitResult,"CCRAlpha");
        CCMCLNFix=SafeGetVar(CCMCFitResult,"CCLN");
        CCMCRNFix=SafeGetVar(CCMCFitResult,"CCRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCMCSigmaFix("CCMCSigmaFix","CCMCSigmaFix",CCMCSigma->getVal());
    CCMCSigmaFix.setConstant(kTRUE);
    RooFormulaVar CCSigma("CCSigma","CCSigma","@0*@1",RooArgList(DataMCRatio,CCMCSigmaFix));

    RooRealVar CCLAlpha("CCLAlpha","CCLAlpha",CCMCLAlphaFix->getVal());

    RooRealVar CCRAlpha("CCRAlpha","CCRAlpha",CCMCRAlphaFix->getVal());

    RooRealVar CCLN("CCLN","CCLN",CCMCLNFix->getVal());

    RooRealVar CCRN("CCRN","CCRN",CCMCRNFix->getVal());

    RooCBShape CCDCBLeft("CCDCBLeft","CCDCBLeft",CCBMass,CCMean,CCSigma,CCLAlpha,CCLN);

    RooCBShape CCDCBRight("CCDCBRight","CCDCBRight",CCBMass,CCMean,CCSigma,CCRAlpha,CCRN);

    RooRealVar CCFitFraction("CCFitFraction","CCFitFraction",0.5,0.0,1.0);
    FreeParameters.push_back(&CCFitFraction);
    RooAddPdf CCDCB("CCDCB","CCDCB",RooArgList(CCDCBRight,CCDCBLeft),CCFitFraction);

    RooRealVar CCEtamean("CCEtamean","CCEtamean",958.0,955.0,960.0);
    RooRealVar CCEtasigma("CCEtasigma","CCEtasigma",9.16,9.0,15.0);

    RooRealVar* CCMCEtaLAlpha=NULL;
    RooRealVar* CCMCEtaRAlpha=NULL;
    RooRealVar* CCMCEtaLN=NULL;
    RooRealVar* CCMCEtaRN=NULL;

    try {
        CCMCEtaLAlpha=SafeGetVar(CCMCFitResult,"CCEtaLAlpha");
        CCMCEtaRAlpha=SafeGetVar(CCMCFitResult,"CCEtaRAlpha");
        CCMCEtaLN=SafeGetVar(CCMCFitResult,"CCEtaLN");
        CCMCEtaRN=SafeGetVar(CCMCFitResult,"CCEtaRN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar CCEtaLAlpha("CCEtaLAlpha","CCEtaLAlpha",CCMCEtaLAlpha->getVal());

    RooRealVar CCEtaRAlpha("CCEtaRAlpha","CCEtaRAlpha",CCMCEtaRAlpha->getVal());

    RooRealVar CCEtaLN("CCEtaLN","CCEtaLN",CCMCEtaLN->getVal());

    RooRealVar CCEtaRN("CCEtaRN","CCEtaRN",CCMCEtaRN->getVal());

    RooCBShape CCEtaDCBLeft("CCEtaCBLeft","CCEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCEtaLAlpha,CCEtaLN);

    RooCBShape CCEtaDCBRight("CCEtaCBRight","CCEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCEtaRAlpha,CCEtaRN);

    RooRealVar CCEtaFitFraction("CCEtaFitFraction","CCEtaFitFraction",0.22,0.1,1.0);
    FreeParameters.push_back(&CCEtaFitFraction);

    RooAddPdf CCEtaDCB("CCEteaDCB","CCEtaDCB",RooArgList(CCEtaDCBRight,CCEtaDCBLeft),CCEtaFitFraction);

    RooProdPdf CCSignalPdf("CCSignalPdf","CCSignalPdf",RooArgSet(CCEtaDCB,CCDCB));
    RooRealVar CCSignalYield("CCSignalYield","CCSignalYield",10000.0,1000.0,20000.0);

    RooExtendPdf CCExtendedSignalPdf("CCExtendedSignalPdf","CCExtendedSignalPdf",CCSignalPdf,CCSignalYield);

    //+++++++++++++++++++++++++++++++++ COMB NO ETAP PDF++++++++++++++++++++++++++++++++++++++++

    RooRealVar CCNoEtaBSlope("CCNoEtaBSlope","CCNoEtaBSlope",-0.6,-0.8,-0.4);
    FreeParameters.push_back(&CCNoEtaBSlope);

    RooRealVar CCNoEtaBCurve("CCNoEtaBCurve","CCNoEtaBCurve",-0.1,-0.30,-0.05);
    FreeParameters.push_back(&CCNoEtaBCurve);

    RooChebychev CCNoEtaBLine("CCNoEtaBLine","CCNoEtaBLine",CCBMass,RooArgList(CCNoEtaBSlope,CCNoEtaBCurve));

    RooRealVar CCNoEtaEtaP1("CCNoEtaEtaP1","CCNoEtaEtaP1",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP1);

    RooRealVar CCNoEtaEtaP2("CCNoEtaEtaP2","CCNoEtaEtaP2",-0.1,-0.8,0.0);
    FreeParameters.push_back(&CCNoEtaEtaP2);

    RooChebychev CCNoEtaQuad("CCNoEtaQuad","CCNoEtaQuad",CCEtaMass,RooArgList(CCNoEtaEtaP1,CCNoEtaEtaP2));

    RooProdPdf CCNoEtaBkgPdf("CCNoEtaBkgPdf","CCNoEtaBkgPdf",RooArgSet(CCNoEtaQuad,CCNoEtaBLine));
    RooRealVar CCNoEtaBkgYield("CCNoEtaBkgYield","CCNoEtaBkgYield",2400.0,500.0,15000.0);

    RooExtendPdf ExtCCNoEtaBkgPdf("ExtCCNoEtaBkgPdf","ExtCCNoEtaBkgPdf",CCNoEtaBkgPdf,CCNoEtaBkgYield);


    //++++++++++++++++++++++++++++++++++ COMB TRUE ETAP PDF++++++++++++++++++++++++++++++++++

    RooRealVar CCTrueEtaBSlope("CCTrueEtaBSlope","CCTrueEtaBSlope",-0.1,-1.0,0.0);
    FreeParameters.push_back(&CCTrueEtaBSlope);

    RooChebychev CCTrueEtaBLine("CCTrueEtaBLine","CCTrueEtaBLine",CCBMass,RooArgList(CCTrueEtaBSlope));

    RooRealVar CCTrueEtaEtaLAlpha("CCTrueEtaEtaLAlpha","CCTrueEtaEtaLAlpha",CCMCEtaLAlpha->getVal());
    RooRealVar CCTrueEtaEtaRAlpha("CCTrueEtaEtaRAlpha","CCTrueEtaEtaRAlpha",CCMCEtaRAlpha->getVal());
    RooRealVar CCTrueEtaEtaLN("CCTrueEtaEtaLN","CCTrueEtaEtaLN",CCMCEtaLN->getVal());
    RooRealVar CCTrueEtaEtaRN("CCTrueEtaEtaRN","CCTrueEtaEtaRN",CCMCEtaRN->getVal());

    //RooCBShape CCTrueEtaEtaCBLeft("CCTrueEtaEtaCBLeft","CCTrueEtaEtaCBLeft",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaLAlpha,CCTrueEtaEtaLN);

    RooCBShape CCTrueEtaEtaCBRight("CCTrueEtaEtaCBRight","CCTrueEtaEtaCBRight",CCEtaMass,CCEtamean,CCEtasigma,CCTrueEtaEtaRAlpha,CCTrueEtaEtaRN);

    //  RooRealVar CCTrueEtaEtaFitFraction("CCTrueEtaEtaFitFraction","CCTrueEtaEtaFitFraction",0.4,0.0,1.0);
    //RooAddPdf CCTrueEtaEtaDCB("CCTrueEtaEtaDCB","CCTrueEtaEtaDCB",RooArgList(CCTrueEtaEtaCBRight,CCTrueEtaEtaCBLeft),CCTrueEtaEtaFitFraction);

    RooProdPdf CCTrueEtaEtaBkgPdf("CCTrueEtaEtaBkgPdf","CCTrueEtaEtaBkgPdf",RooArgSet(CCTrueEtaEtaCBRight,CCTrueEtaBLine));

    RooRealVar CCTrueEtaBkgYield("CCTrueEtaBkgYield","CCTrueEtaBkgYield",800.0,20.0,10000.0);

    RooExtendPdf ExtCCTrueEtaBkgPdf("ExtCCTrueEtaBkgPdf","ExtCCTrueEtaBkgPdf",CCTrueEtaEtaBkgPdf,CCTrueEtaBkgYield);

    RooAddPdf CCTotalPdf("CCTotalPdf","CCTotalPdf",RooArgList(ExtCCTrueEtaBkgPdf,ExtCCNoEtaBkgPdf,CCExtendedSignalPdf));



    //_________________________________Rare1 Fit_____________________________

    TFile * RareInputFile = new TFile("RareSingleFile.root");
    TTree* RareInputTree=NULL;
    try {
        RareInputTree=SafeGetTree(RareInputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar LbMass("Lambda_b0_DTF_MF","Lambda_b0_DTF_MF",5200.0,6000.0);
    RooRealVar RareLambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareLambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareProton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar RareKaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rareeta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet RareArgs(LbMass,RareLambda_b0_PE,RareLambda_b0_PX,RareLambda_b0_PY,RareLambda_b0_PZ,RareProton_PE,RareProton_PX,RareProton_PY,RareProton_PZ);
    RareArgs.add(RareKaon_PE);
    RareArgs.add(RareKaon_PX);
    RareArgs.add(RareKaon_PY);
    RareArgs.add(RareKaon_PZ);
    RareArgs.add(Rareeta_prime_PE);
    RareArgs.add(Rareeta_prime_PX);
    RareArgs.add(Rareeta_prime_PY);
    RareArgs.add(Rareeta_prime_PZ);
    RooDataSet* RareData= new RooDataSet("RareData","RareData",RareArgs,Import(*RareInputTree));


    TFile * RareFitResultFile = new TFile("RareFitResult.root");
    RooFitResult* RareMCFitResult=NULL;
    try {
        RareMCFitResult=SafeGetFitResult(RareFitResultFile,"RareFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RareMCFitResult->Print("v");
    RooRealVar* RareMCRAlpha=NULL;
    RooRealVar* RareMCFitFraction=NULL;
    RooRealVar* RareMCLAlpha=NULL;
    RooRealVar* RareMCLN=NULL;
    RooRealVar* RareMCRN=NULL;
    RooRealVar* RareMCSigma=NULL;
    try {
        RareMCRAlpha=SafeGetVar(RareMCFitResult,"RareAlpha");
        RareMCFitFraction=SafeGetVar(RareMCFitResult,"RareFitFraction");
        RareMCLAlpha=SafeGetVar(RareMCFitResult,"RareLAlpha");
        RareMCLN=SafeGetVar(RareMCFitResult,"RareLN");
        RareMCRN=SafeGetVar(RareMCFitResult,"RareRN");
        RareMCSigma=SafeGetVar(RareMCFitResult,"RareSigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Rare Signal PDF++++++++++++++++++++++++++++
    RooRealVar RareMCSigmaFix("RareMCSigmaFix","RareMCSigmaFix",RareMCSigma->getVal());
    RareMCSigmaFix.setConstant();

    RooFormulaVar RareSigma("RareSigma","RareSigma","@0*@1",RooArgSet(RareMCSigmaFix,DataMCRatio));
    RooRealVar RareLAlpha("RareLAlpha","RareLAlpha",RareMCLAlpha->getVal());
    RooRealVar RareRAlpha("RareRAlpha","RareRAlpha",RareMCRAlpha->getVal());
    RooRealVar RareRN("RareRN","RareRN",RareMCRN->getVal());
    RooRealVar RareLN("RareLN","RareLN",RareMCLN->getVal());
    RooRealVar RareFitFraction("RareFitFraction","RareFitFraction",RareMCFitFraction->getVal());

    RooCBShape RareDCBLeft("DCBLeft","DCBLeft",LbMass,LambdabMean,RareSigma,RareLAlpha,RareLN);

    RooCBShape RareDCBRight("DCBRight","DCBRight",LbMass,LambdabMean,RareSigma,RareRAlpha,RareRN);

    RooAddPdf RareDCB("RareDCB","RareDCB",RooArgList(RareDCBLeft,RareDCBRight),RareFitFraction);

    RooRealVar RareYield("RareYield","RareYield",40.0,-100.0,1000.0);
    RooExtendPdf RareSignalPdf("RareSignalPdf","RareSignalPdf",RareDCB,RareYield);
    //++++++++++++++++++++++++++++++Rare Combinatorial Bkg+++++++++++++++++++++++++++++++++++
    RooRealVar Rarep1("Rarep1","Rarep1",-1.1,-5.0,-0.1);
    FreeParameters.push_back(&Rarep1);

    RooRealVar Rarep2("Rarep2","Rarep2",0.5,0.001,10.0);
    FreeParameters.push_back(&Rarep2);

    RooChebychev RarePoly("RarePoly","RarePoly",LbMass,RooArgList(Rarep1,Rarep2));

    RooRealVar RareBkgYield("RareBkgYield","RareBkgYield",2000.0,0.0,10000.0);
    RooExtendPdf RareBkgPdf("RareBkgPdf","RareBkgPdf",RarePoly,RareBkgYield);

    //++++++++++++++++++++++++++++Rare PKPhi Bkg+++++++++++++++++++++++++++++++++
    TFile* PKPhiMCFitresultFile= new TFile("PkPhiFitResultFile.root");
    RooFitResult* PKPhiMCFitResult=NULL;
    try {
        PKPhiMCFitResult=SafeGetFitResult(PKPhiMCFitresultFile,"PkPhiFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    PKPhiMCFitResult->Print("v");
    RooRealVar* PkPhiMean=NULL;
    RooRealVar* PkPhiSigma=NULL;
    RooRealVar* PkPhiLAlpha=NULL;
    RooRealVar* PkPhiRAlpha=NULL;
    RooRealVar* PkPhiLN=NULL;
    RooRealVar* PkPhiRN=NULL;
    try {
        PkPhiMean=SafeGetVar(PKPhiMCFitResult,"PkPhiMean");
        PkPhiSigma=SafeGetVar(PKPhiMCFitResult,"PkPhiSigma");
        PkPhiLAlpha=SafeGetVar(PKPhiMCFitResult,"PkPhiLAlpha");
        PkPhiLN=SafeGetVar(PKPhiMCFitResult,"PkPhiLN");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar RarePkPhiMean("RarePkPhiMean","RarePkPhiMean",PkPhiMean->getVal());
    RooRealVar RarePkPhiSigma("RarePkPhiSigma","RarePkPhiSigma",PkPhiSigma->getVal());
    RooRealVar RarePkPhiLN("RarePkPhiLN","RarePkPhiLN",PkPhiLN->getVal());
    RooRealVar RarePkPhiLAlpha("RarePkPhiLAlpha","RarePkPhiLAlpha",PkPhiLAlpha->getVal());

    RooCBShape RarePkPhiModel("RarePkPhiModel","RarePkPhiModel",LbMass,RarePkPhiMean,RarePkPhiSigma,RarePkPhiLAlpha,RarePkPhiLN);

    RooRealVar RarePkPhiYield("RarePkPhiYield","RarePkPhiYield",50.0,1.0,150.0);
    RooExtendPdf RarePkPhiPdf("RarePkPhiPdf","RarePkPhiPdf",RarePkPhiModel,RarePkPhiYield);

    RooAddPdf RarePdf("RarePdf","RarePdf",RooArgList(RarePkPhiPdf,RareBkgPdf,RareSignalPdf));

    /*RarePdf.fitTo(*RareData,Extended(kTRUE));
    RooPlot* RareFrame=LbMass.frame(Bins(35),Range(5200.0,6100.0));
    TCanvas RareCanvas;
    RareData->plotOn(RareFrame);
    RarePdf.plotOn(RareFrame);
    RareFrame->Draw();
    RareCanvas.SaveAs("RareCanvas.pdf");*/

    //________________________________ Fit Rare 2_______________________________
    TFile* Rare2InputFile = new TFile("Rare2SingleFile.root");
    TTree* Rare2InputTree=NULL;
    try {
        Rare2InputTree=SafeGetTree(Rare2InputFile,"DecayTree");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }
    RooRealVar Rare2Lambda_b0_PE("Lambda_b0_PE","Lambda_b0_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PX("Lambda_b0_PX","Lambda_b0_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PY("Lambda_b0_PY","Lambda_b0_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Lambda_b0_PZ("Lambda_b0_PZ","Lambda_b0_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PE("Proton_PE","Proton_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PX("Proton_PX","Proton_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PY("Proton_PY","Proton_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Proton_PZ("Proton_PZ","Proton_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PE("Kaon_PE","Kaon_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PX("Kaon_PX","Kaon_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PY("Kaon_PY","Kaon_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2Kaon_PZ("Kaon_PZ","Kaon_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PE("eta_prime_PE","eta_prime_PE",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PX("eta_prime_PX","eta_prime_PX",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PY("eta_prime_PY","eta_prime_PY",-RooNumber::infinity(),RooNumber::infinity());
    RooRealVar Rare2eta_prime_PZ("eta_prime_PZ","eta_prime_PZ",-RooNumber::infinity(),RooNumber::infinity());
    RooArgSet Rare2Args(LbMass,Rare2Lambda_b0_PE,Rare2Lambda_b0_PX,Rare2Lambda_b0_PY,Rare2Lambda_b0_PZ,Rare2Proton_PE,Rare2Proton_PX,Rare2Proton_PY,Rare2Proton_PZ);
    Rare2Args.add(Rare2Kaon_PE);
    Rare2Args.add(Rare2Kaon_PX);
    Rare2Args.add(Rare2Kaon_PY);
    Rare2Args.add(Rare2Kaon_PZ);
    Rare2Args.add(Rare2eta_prime_PE);
    Rare2Args.add(Rare2eta_prime_PX);
    Rare2Args.add(Rare2eta_prime_PY);
    Rare2Args.add(Rare2eta_prime_PZ);

    RooDataSet* Rare2Data=new RooDataSet("Rare2Data","Rare2Data",Rare2Args,Import(*Rare2InputTree));

    TFile* Rare2MCFitResultFile= new TFile("RareTwoFitResult.root");
    RooFitResult* Rare2MCFitResult=NULL;
    try {
        Rare2MCFitResult=SafeGetFitResult(Rare2MCFitResultFile,"RareTwoFitResult");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    //++++++++++++++++++++++++++++++Signal PDF++++++++++++++++++++++++++++++++
    RooRealVar* Rare2MCFitFraction=NULL;
    RooRealVar* Rare2MCLAlpha=NULL;
    RooRealVar* Rare2MCLN=NULL;
    RooRealVar* Rare2MCRN=NULL;
    RooRealVar* Rare2MCRAlpha=NULL;
    RooRealVar* Rare2MCSigma=NULL;

    try {
        Rare2MCFitFraction=SafeGetVar(Rare2MCFitResult,"Rare2FitFraction");
        Rare2MCLAlpha=SafeGetVar(Rare2MCFitResult,"Rare2LAlpha");
        Rare2MCLN=SafeGetVar(Rare2MCFitResult,"Rare2LN");
        Rare2MCRN=SafeGetVar(Rare2MCFitResult,"Rare2RN");
        Rare2MCRAlpha=SafeGetVar(Rare2MCFitResult,"Rare2RAlpha");
        Rare2MCSigma=SafeGetVar(Rare2MCFitResult,"Rare2Sigma");
    } catch(std::exception &e) {
        std::cout<<e.what()<<std::endl;
        return 1;
    }

    RooRealVar Rare2SigmaFix("Rare2SigmaFix","Rare2SigmaFix",Rare2MCSigma->getVal());
    RooFormulaVar Rare2Sigma("Rare2Sigma","Rare2Sigma","@0*@1",RooArgList(Rare2SigmaFix,DataMCRatio));

    RooRealVar Rare2LN("Rare2LN","Rare2LN",Rare2MCLN->getVal());
    RooRealVar Rare2RN("Rare2RN","Rare2RN",Rare2MCRN->getVal());
    RooRealVar Rare2RAlpha("Rare2RAlpha","Rare2RAlpha",Rare2MCRAlpha->getVal());
    RooRealVar Rare2LAlpha("Rare2LAlpha","Rare2LAlpha",Rare2MCLAlpha->getVal());
    RooRealVar Rare2FitFraction("Rare2FitFraction","Rare2FitFraction",Rare2MCFitFraction->getVal());

    RooCBShape Rare2CBLeft("Rare2CBLeft","Rare2CBLeft",LbMass,LambdabMean,Rare2Sigma,Rare2LAlpha,Rare2LN);

    RooCBShape Rare2CBRight("Rare2CBRight","Rare2CBRight",LbMass,LambdabMean,Rare2Sigma,Rare2RAlpha,Rare2RN);

    RooAddPdf Rare2DCB("Rare2DCB","Rare2DCB",RooArgList(Rare2CBLeft,Rare2CBRight),Rare2FitFraction);

    RooRealVar Rare2SignalYield("Rare2SignalYield","Rare2SignalYield",100.0,-100.0,1000.0);
    RooExtendPdf Rare2SignalPdf("Rare2SignalPdf","Rare2SignalPdf",Rare2DCB,Rare2SignalYield);

    //++++++++++++++++++++++++++++++Rare 2 Bkg pdf++++++++++++++++++++++++++++++
    RooRealVar Rare2K("K","K",-0.003,-0.1,0.0);
    RooExponential Rare2BkgExp("Rare2BkgExp","Rare2BkgExp",LbMass,Rare2K);
    RooRealVar Rare2BkgYield("Rare2BkgYield","Rare2BkgYield",2000.0,0.0,100000.0);
    RooExtendPdf Rare2BkgPdf("Rare2BkgPdf","Rare2BkgPdf",Rare2BkgExp,Rare2BkgYield);

    RooAddPdf Rare2Pdf("Rare2Pdf","Rare2Pdf",RooArgList(Rare2SignalPdf,Rare2BkgPdf));

    //___________________________________ SImultaneous Part ________________________________________________________

    RooCategory Channel("Channel","Channel");
    Channel.defineType("Rare");
    Channel.defineType("Rare2");
    Channel.defineType("Control");

    RooDataSet* AllData = new RooDataSet("AllData","AllData",RooArgSet(LbMass,CCBMass,CCEtaMass),Index(Channel),Import("Rare",*RareData),Import("Rare2",*Rare2Data),Import("Control",*CCData));

    RooSimultaneous SimPdf("SimPdf","SimPdf",Channel);
    SimPdf.addPdf(Rare2Pdf,"Rare2");
    SimPdf.addPdf(RarePdf,"Rare");
    SimPdf.addPdf(CCTotalPdf,"Control");

    RooDataSet* BlindedData=NULL;
    RooFitResult* SimResult=NULL;
    if(blind) {
        LbMass.setRange("RLSB",5200.0,RareLowerBlind);
        LbMass.setRange("RUSB",RareUpperBlind,6000.0);
        LbMass.setRange("R2LSB",5200.0,Rare2LowerBlind);
        LbMass.setRange("R2USB",Rare2UpperBlind,6000.0);
        LbMass.setRange("RDLSB",5200.0,5493.33333);
        LbMass.setRange("RDUSB",RareUpperBlind,6000.0);

        std::string CutString="Lambda_b0_DTF_MF<"+std::to_string(RareLowerBlind)+"||Lambda_b0_DTF_MF>"+std::to_string(Rare2UpperBlind);
        BlindedData=(RooDataSet*)AllData->reduce(CutString.data());
        RooMsgService::instance().setSilentMode(kTRUE);
        RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL) ;
    }

    RooArgSet MinosPars(Rare2SignalYield,RareYield,CCSignalYield);
    SimResult = SimPdf.fitTo(*AllData,Save(kTRUE),Extended(kTRUE),Minos(MinosPars));
    SimPdf.Print("v");
    RooPlot* NominalLikelihoodRareYield=RareYield.frame(Title("Likelihood scan of RareYield"),Range(50,150));
    RooAbsReal* nll = SimPdf.createNLL(*AllData,NumCPU(2),Extended(kTRUE));
    TCanvas C;
    nll->plotOn(NominalLikelihoodRareYield,ShiftToZero());
    NominalLikelihoodRareYield->Draw();
    C.SaveAs("NominalLikelihood.pdf");
    //  HandyFunctions::SetlhcbStyle();
    //_______________________________ Plot B+ Canvas_____________________________________________________________
    RooPlot* CCBFrame= CCBMass.frame(Bins(50),Range(5000.0,5500.0),Title("Control Channel B+ Mass Projection"));
    AllData->plotOn(CCBFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCBFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCBCanvas=HandyFunctions::DecoratePlot(CCBFrame);
    /*(TCanvas* CCBCanvas= new TCanvas("CCBCanvas","CCBCanvas",1600,900);
    CCBFrame->Draw();
    CCBCanvas->SaveAs("CCBCanvas.eps");*/

    //________________________________Plot Eta Canvas_____________________________________________________________
    RooPlot* CCEtaFrame=CCEtaMass.frame(Bins(50),Range(880.0,1040.0),Title("Control Channel Eta' Projection"));
    AllData->plotOn(CCEtaFrame,Cut("Channel==Channel::Control"));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCTrueEtaBkgPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("ExtCCNoEtaBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),Components("CCExtendedSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
    SimPdf.plotOn(CCEtaFrame,Slice(Channel,"Control"),ProjWData(Channel,*AllData));
    TCanvas* CCEtaCanvas=HandyFunctions::DecoratePlot(CCEtaFrame);
    /*TCanvas* CCEtaCanvas=new TCanvas("CCEtaCanvas","CCEtaCanvas",1600,900);
    CCEtaFrame->Draw();
    CCEtaCanvas->Print("CCEtaCanvas.eps");*/


    //________________________________Plot Rare Canvas_____________________________________________________________
    RooPlot* RareFrame=LbMass.frame(Bins(30),Range(5200.0,6000.0),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #gamma) ;M(#Lambda_{b})"));
    if(blind) {
        double sidebandsN = RareData ->sumEntries("1","RLSB,RUSB");
        double LowsidebandsN = RareData ->sumEntries("1","RLSB");
        RareData->plotOn(RareFrame,CutRange("RDLSB,RDUSB"),Name("RareDataPlotted"));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RarePkPhiPdf"),Name("RarePkPhiBkg"),LineColor(kMagenta),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Components("RareBkgPdf"),Name("RareCombBkg"),LineColor(kGreen),LineStyle(kDashed),Normalization(sidebandsN,RooAbsReal::NumEvent));
        RarePdf.plotOn(RareFrame,Range("RLSB,RUSB"),Normalization(sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(RareFrame,Cut("Channel==Channel::Rare"));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RarePkPhiPdf"),LineColor(kMagenta),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareBkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),Components("RareSignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(RareFrame,Slice(Channel,"Rare"),ProjWData(Channel,*AllData));
    }
    int i=RareFrame->numItems();
    std::cout<<"_________________________________________"<<std::endl;
    for(int j=0; j<i; j++) {
        std::cout<<RareFrame->nameOf(j)<<std::endl;
    }
    TLegend * RareLegend = new TLegend(0.66,0.7,0.9,0.9);
    RareLegend->AddEntry(RareFrame->findObject("RarePkPhiBkg"),"#Lambda_{b} -> p K #phi bkg","l");
    RareLegend->AddEntry(RareFrame->findObject("RareCombBkg"),"Combinatorial Background","l");
    std::cout<<"++++++++++++++++++++++++++++++++++++++++++++"<<std::endl;
    RooHist* Pulls=RareFrame->pullHist(0,"RarePdf_Norm[Lambda_b0_DTF_MF]");
    TCanvas* RareCanvas=HandyFunctions::DecoratePlot(RareFrame,"DecoratedRareCanvas");
    RareCanvas->Print("RareCanvas.pdf");
    TCanvas * PullCanvas=new TCanvas("RarePullCanvas","RarePullCanvas",1200,1000);
    Pulls->Draw("AP");
    PullCanvas->SaveAs("RarePulls.pdf");
    TCanvas *RareNoPullCanvas = new TCanvas("RareFitCanvas","RareFitCanvas",1600,900);
    RareFrame->Draw();
    RareLegend->Draw();
    RareNoPullCanvas->Print("RareNoPullCanvasPrinted.eps");


    //_______________________________Plot Rare2 Canvas_____________________________________________________________
    RooPlot* Rare2Frame=LbMass.frame(Bins(25),Range(5200.0,6000.),Title("#Lambda_{b} -> p K (#eta' -> #pi #pi #eta);M(#Lambda_{b})"));
    if(blind) {
        double Rare2sidebandsN= Rare2Data->sumEntries("1","R2LSB,R2USB");
        Rare2Data->plotOn(Rare2Frame,CutRange("R2LSB,R2USB"));
        Rare2Pdf.plotOn(Rare2Frame,Range("R2LSB,R2USB"),Normalization(Rare2sidebandsN,RooAbsReal::NumEvent));
    } else {
        AllData->plotOn(Rare2Frame,Cut("Channel==Channel::Rare2"));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2BkgPdf"),LineColor(kGreen),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),Components("Rare2SignalPdf"),LineColor(kRed),LineStyle(kDashed),ProjWData(Channel,*AllData));
        SimPdf.plotOn(Rare2Frame,Slice(Channel,"Rare2"),ProjWData(Channel,*AllData));
    }
    TCanvas* NoPullRare2= new TCanvas("NoPullRare2","NoPullRare2",1800,1000);
    Rare2Frame->Draw();
    NoPullRare2->SaveAs("PiPiEtaFit.eps");
    TCanvas* Rare2Canvas=HandyFunctions::DecoratePlot(Rare2Frame,"DecoratedRare2Canvas");
    Rare2Canvas->SaveAs("Rare2Canvas.pdf");

    if(blind) {
        RooArgSet NotBlind(CCEtamean,CCSignalYield,DataMCRatio,CCNoEtaBkgYield,CCTrueEtaBkgYield,CCMean,RareBkgYield,Rare2BkgYield,RarePkPhiYield);
        cout << "Fit complete" << endl;
        cout << "covQual:" << SimResult->covQual() << endl;
        cout << "EDM:" << SimResult->edm() << endl;
        cout << "FCN at min:" << SimResult->minNll() << endl;
        NotBlind.Print("s");
    }


    TFile* DataFitResults= new TFile("DataFitResults.root","RECREATE");
    RareNoPullCanvas->Write();
    CCBCanvas->Write();
    CCEtaCanvas->Write();
    RareCanvas->Write();
    Rare2Canvas->Write();
    SimResult->Write("DataFitResult");
    DataFitResults->Close();

    RooWorkspace* Wkspc= new RooWorkspace("w","workspace");
    Wkspc->import(SimPdf);
    //  Wkspc->writeToFile("BigFitWorkspace.root");
    Wkspc->writeToFile("TestBigFitWorkspace.root");

    for(auto Var : FreeParameters) {
        Var->setConstant();
    }

    RooStats::SPlot* sDataMass;
    if(sweight) {
        sDataMass = new RooStats::SPlot("sData","An SPlot",*RareData,&RarePdf,RooArgList(RarePkPhiYield,RareYield,RareBkgYield));
        std::cout<<" Check SWeights: "<<std::endl;
        std::cout<<" BkgYield= "<<RareBkgYield.getVal()<<std::endl;
        std::cout<<" Bkg yield from sweights = "<<sDataMass->GetYieldFromSWeight("RareBkgYield")<<std::endl;
    }




}
Exemple #11
0
void fit2015(
             TString FileName ="/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root", 
             int  oniamode  = 2,        // oniamode-> 3: Z,  2: Upsilon and 1: J/Psi
             bool isData    = true,     // isData = false for MC, true for Data
             bool isPbPb    = false,    // isPbPb = false for pp, true for PbPb
	     bool doFit = false ,
             bool inExcStat = true      // if inExcStat is true, then the excited states are fitted
             ) {

  InputOpt opt;
  SetOptions(&opt, isData, isPbPb, oniamode,inExcStat);

  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
  }
    
  int nbins = 1; //ceil((opt.dMuon->M->Max - opt.dMuon->M->Min)/binw);
  if (oniamode==1){
    nbins = 140;
  } else if (oniamode==2) {
    nbins = 70; 
  } else if (oniamode==3) {
    nbins = 40;
  } 
 
  RooWorkspace myws;
  TH1F* hDataOS =  new TH1F("hDataOS","hDataOS", nbins, opt.dMuon.M.Min, opt.dMuon.M.Max);
  makeWorkspace2015(myws, FileName, opt, hDataOS);

  RooRealVar* mass      = (RooRealVar*) myws.var("invariantMass"); 
  RooDataSet* dataOS_fit = (RooDataSet*) myws.data("dataOS");
  RooDataSet* dataSS_fit = (RooDataSet*) myws.data("dataSS");
  RooAbsPdf*  pdf = NULL;

  if (oniamode==3) { doFit=false; }
  if (doFit) {
    int sigModel=0, bkgModel=0;  
    if (isData) {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3;
        bkgModel = 1;
      } else {
        sigModel = inExcStat ? 1 : 3; // gaussian   
        bkgModel = 2;
      }      
    } else {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 2;
      } else {
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 3;
      }
    }

    if (opt.oniaMode==1) buildModelJpsi2015(myws, sigModel, bkgModel,inExcStat);
    else if (opt.oniaMode==2) buildModelUpsi2015(myws, sigModel, bkgModel,inExcStat);

    pdf       =(RooAbsPdf*)  myws.pdf("pdf");
    RooFitResult* fitObject = pdf->fitTo(*dataOS_fit,Save(),Hesse(kTRUE),Extended(kTRUE)); // Fit
  }

  RooPlot* frame = mass->frame(Bins(nbins),Range(opt.dMuon.M.Min, opt.dMuon.M.Max));  
  RooPlot* frame2 = NULL;
  dataSS_fit->plotOn(frame, Name("dataSS_FIT"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  dataOS_fit->plotOn(frame, Name("dataOS_FIT"), MarkerColor(kBlue), LineColor(kBlue), MarkerSize(1.2));
  

  if (doFit) {
     pdf->plotOn(frame,Name("thePdf"),Normalization(dataOS_fit->sumEntries(),RooAbsReal::NumEvent));
     RooHist *hpull = frame -> pullHist(0,0,true);
     hpull -> SetName("hpull");
     frame2 = mass->frame(Title("Pull Distribution"),Bins(nbins),Range(opt.dMuon.M.Min,opt.dMuon.M.Max));
     frame2 -> addPlotable(hpull,"PX");  
     } 
  drawPlot(frame,frame2, pdf, opt, doFit,inExcStat);

  TString OutputFileName = "";
  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
    opt.RunNb.Start=262548;
    opt.RunNb.End=262893;
    if (oniamode==1) {OutputFileName = (TString)("JPSIPbPbDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YPbPbDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZPbPbDataset.root");}
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
    opt.RunNb.Start=262163;
    opt.RunNb.End=262328;
    if (oniamode==1) {OutputFileName = (TString)("JPSIppDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YppDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZppDataset.root");}
  }
  
  TFile* oFile =  new TFile(OutputFileName,"RECREATE");
  oFile->cd();
  hDataOS->Write("hDataOS");
  dataOS_fit->Write("dataOS_FIT");
  oFile->Write();
  oFile->Close();

}
Exemple #12
0
void fitWe(const TString  outputDir="test",   // output directory
           const Double_t lumi=18.7,        // integrated luminosity (/fb)
	   const Int_t    Ecm=8,         // center-of-mass energy
	   const Int_t    doPU=1         // option for PU-reweighting
) {
  gBenchmark->Start("fitWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS  = 50;
  const Double_t METMAX = 100;

  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.5;

  // file format for output plots
  const TString format("png"); 
    
  // file name with recoil correction
  TString recoilfname("../RecoilSyst/ZeeData/fits.root");
  
  // file name(s) with PU weights
  TString pufname("");
  if(doPU>0) {
    if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; }
    else        { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); }
  }
  
  //
  // input ntuple file names
  //
  enum { eData, eWenu, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root");   typev.push_back(eData);
  fnamev.push_back("../Selection/Wenu/ntuples/we_select.root");         typev.push_back(eWenu);
  fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root");        typev.push_back(eEWK);
  fnamev.push_back("../Selection/Wenu/ntuples/top_select.root");        typev.push_back(eEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // Get pile-up weights
  TFile *pufile    = 0;
  TH1D  *puWeights = 0;
  if(doPU>0) {
    pufile = new TFile(pufname);
    assert(pufile);
    puWeights = (TH1D*)pufile->Get("puWeights");
    assert(puWeights);
  }
  
  // Access recoil corrections
  //RecoilCorrector recoilCorr(recoilfname);
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet  = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWenuMet  = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2();
  TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2();
  TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2();
  TH1D *hEWKMet   = new TH1D("hEWKMet",  "",NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp  = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm  = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genWPt, genWPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  LorentzVector *sc=0;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genWPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genWPhi);   // GEN W boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);         // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("sc",       &sc);        // electron Supercluster 4-vector
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(mt< 40)  continue;	// LUCA ADD
      TLorentzVector muPosP, muNegP, JpsiP;
      muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon
      muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino
      JpsiP = muPosP + muNegP;
      
      // if(JpsiP.Pt() < 15 
      // || JpsiP.Pt() > 25 )  continue;	

      
      if(sc->Pt()        < PT_CUT)  continue;	
      if(fabs(sc->Eta()) > ETA_CUT) continue;
   
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
        if(puWeights)
	  weight *= puWeights->GetBinContent(npu+1);
	
	if(typev[ifile]==eWenu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi());
	
          hWenuMet->Fill(corrMet,weight);
	  if(q>0) { hWenuMetp->Fill(corrMet,weight); } 
	  else    { hWenuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  
  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet);  RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1);
  RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1);
  RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  //
  // Perform fits
  //
  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet);
  RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp);
  RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm);
  RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.18);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.18);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.400,"Y");
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi,Ecm);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *weframe = pfmet.frame(Bins(NBINS));    
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(weframe,LineColor(linecolorW));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",weframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
//  plotMet.Draw(c,kFALSE,format,1);
  plotMet.Draw(c,kTRUE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wepframe = pfmet.frame(Bins(NBINS));    
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wepframe,LineColor(linecolorW));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wepframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wemframe = pfmet.frame(Bins(NBINS)); 
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wemframe,LineColor(linecolorW));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wemframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl;  
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWe");
}
void drawCtauPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  int  nBins,           // Number of bins used for plotting
                  bool paperStyle=false,// if true, print less info
                  bool saveWS=true      // save the workspace into a file
                  ) 
{
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  
  // Create the main plot of the fit
  // RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(-1,3));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
    
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setRange(myws, frame, dsOSName, setLogScale, cut.dMuon.AbsRap.Min);
  if (paperStyle) {
     double Ydown = 0.1;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
     } else {
        t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.20, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  else {t->DrawLatex(0.20, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  t->DrawLatex(0.20, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.20, 0.86-dy, Form("%g < M^{#mu#mu} < %g GeV/c^{2}",cut.dMuon.M.Min,cut.dMuon.M.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.20, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  dy+=0.5*0.045; t->DrawLatex(0.20, 0.86-dy, "#mu in acceptance"); dy+=0.045;

  // Drawing the Legend
  double ymin = 0.7802;
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 


  // Save the plot in different formats
  gSystem->mkdir(Form("%splot/%s/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%splot/%s/root/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(),  "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%splot/%s/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/png/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%splot/%s/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/pdf/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
  
  // Save the workspace
  if (saveWS) {
     gSystem->mkdir(Form("%sresult/%s/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
     TFile *file = NULL;
     file = new TFile(Form("%sresult/%s/FIT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End), "RECREATE");  
     if (!file) { 
        cout << "[ERROR] Output root file with fit results could not be created!" << endl; 
     } else {
        file->cd();    
        myws.Write("workspace"); 
        file->Write(); file->Close(); delete file;
     }
  }
}
void Wpt_ZmassCompEtaBins_Gaus(const TString Mode,//Channel - Muon or Electron
    const TString corrName,
    const TString outputDir 
    )
{
  TString plotTitle;
  TString mu_etaRange[6];
  mu_etaRange[0] = "-2.1 #geq eta < -1.4";
  mu_etaRange[1] = "-1.4 #geq eta < -0.7";
  mu_etaRange[2] = "-0.7 #geq eta < 0";
  mu_etaRange[3] = "0 #geq eta < 0.7";
  mu_etaRange[4] = "0.7 #geq eta < 1.4";
  mu_etaRange[5] = "1.4 #geq eta < 2.1";

  TH1D* makeDiffHist(TH1D* h1, TH1D* h2, const TString name);
  const TString format("png"); 
  Int_t ratioColor = kGray+2;

  TFile *fname_MC;
  TFile *fname_RD;

  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;

  fname_MC = new TFile("Muon2012LoPU/Muon_DYToMuMu_S8.root");
  fname_RD = new TFile("Muon2012LoPU/Muon_RD_LowPU.root");

  if(Mode=="Electron")
  {
    fname_MC = new TFile("Electron2012LoPU/Ele_DYToEE_S8.root");
    fname_RD = new TFile("Electron2012LoPU/Ele_RD_LowPU.root");
  }

  CPlot *plotMllEtaBinP;
  CPlot *plotMllEtaBinM;
  CPlot *plotMllEtameanP;
  CPlot *plotMllEtameanM;
  CPlot *plotMllEtawidthP;
  CPlot *plotMllEtawidthM;

  TH1D *hMCetaBinP[ScaleBins];
  TH1D *hRDetaBinP[ScaleBins];
  TH1D *hMCetaBinM[ScaleBins];
  TH1D *hRDetaBinM[ScaleBins];

  RooDataHist *h1_MCetaBinP;
  RooDataHist *h1_RDetaBinP;
  RooDataHist *h1_MCetaBinM;
  RooDataHist *h1_RDetaBinM;

  TH1D *hMCmeanp = new TH1D("hMCmeanp","hMCmeanp",ScaleBins,-2.1,2.1);hMCmeanp->Sumw2();
  TH1D *hRDmeanp = new TH1D("hRDmeanp","hRDmeanp",ScaleBins,-2.1,2.1);hRDmeanp->Sumw2();
  TH1D *hMCmeanm = new TH1D("hMCmeanm","hMCmeanm",ScaleBins,-2.1,2.1);hMCmeanm->Sumw2();
  TH1D *hRDmeanm = new TH1D("hRDmeanm","hRDmeanm",ScaleBins,-2.1,2.1);hRDmeanm->Sumw2();

  TH1D *hMCwidthp = new TH1D("hMCwidthp","hMCwidthp",ScaleBins,-2.1,2.1);hMCwidthp->Sumw2();
  TH1D *hRDwidthp = new TH1D("hRDwidthp","hRDwidthp",ScaleBins,-2.1,2.1);hRDwidthp->Sumw2();
  TH1D *hMCwidthm = new TH1D("hMCwidthm","hMCwidthm",ScaleBins,-2.1,2.1);hMCwidthm->Sumw2();
  TH1D *hRDwidthm = new TH1D("hRDwidthm","hRDwidthm",ScaleBins,-2.1,2.1);hRDwidthm->Sumw2();

  char histName[50];
  char tmpName[50];

  TCanvas *myCan;
  myCan = MakeCanvas("myCan","myCan",800,600);

  myCan->SetPad(0,0,1.0,1.0);
  myCan->SetTopMargin(0.11);
  myCan->SetBottomMargin(0.15);
  myCan->SetLeftMargin(0.15);  
  myCan->SetRightMargin(0.05);  
  myCan->SetTickx(1);
  myCan->SetTicky(1);  

  //=============================
  //Read Zmass histograms for each pt bin
  //=============================
  for(int i(0);i<ScaleBins;i++){
    sprintf(tmpName,"h1_Zmass_muEtaP_%d",i);
    if(corrName=="CorrTotalRegion")
      sprintf(tmpName,"h1_ZmassCorr_muEtaP_%d",i);

    if(outputDir=="Wpt_ZmassPlotsEtaBins_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_muEtaP_%d",i);
    }

    sprintf(histName,"hMCetaBinP_%d",i);
    hMCetaBinP[i]= (TH1D*)fname_MC->Get(tmpName)->Clone(histName); hMCetaBinP[i]->Sumw2();
    sprintf(histName,"hRDetaBinP_%d",i);
    hRDetaBinP[i]= (TH1D*)fname_RD->Get(tmpName)->Clone(histName); hRDetaBinP[i]->Sumw2();

    sprintf(tmpName,"h1_Zmass_muEtaM_%d",i);
    if(corrName=="CorrTotalRegion")
      sprintf(tmpName,"h1_ZmassCorr_muEtaM_%d",i);

    if(outputDir=="Wpt_ZmassPlotsEtaBins_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_muEtaM_%d",i);
    }

    sprintf(histName,"hMCetaBinM_%d",i);
    hMCetaBinM[i]= (TH1D*)fname_MC->Get(tmpName)->Clone(histName); hMCetaBinM[i]->Sumw2();
    sprintf(histName,"hRDetaBinM_%d",i);
    hRDetaBinM[i]= (TH1D*)fname_RD->Get(tmpName)->Clone(histName); hRDetaBinM[i]->Sumw2();
    
    hMCetaBinP[i] -> SetMarkerSize(0.9);
    hMCetaBinP[i] -> SetMarkerColor(kRed);
    hMCetaBinP[i] -> SetLineColor(kRed);
    hRDetaBinP[i] -> SetMarkerSize(0.9);
    hRDetaBinP[i] -> SetMarkerColor(kBlack);
    hRDetaBinP[i] -> SetLineColor(kBlack);
    hMCetaBinM[i] -> SetMarkerSize(0.9);
    hMCetaBinM[i] -> SetMarkerColor(kRed);
    hMCetaBinM[i] -> SetLineColor(kRed);
    hRDetaBinM[i] -> SetMarkerSize(0.9);
    hRDetaBinM[i] -> SetMarkerColor(kBlack);
    hRDetaBinM[i] -> SetLineColor(kBlack);

    RooRealVar x("x", "x",80,100);
    x.setBins(40);
    x.setRange("R0",86,96);

    h1_MCetaBinP = new RooDataHist("h1_MCetaBinP","h1_MCetaBinP",RooArgSet(x),hMCetaBinP[i]);
    h1_MCetaBinM = new RooDataHist("h1_MCetaBinM","h1_MCetaBinM",RooArgSet(x),hMCetaBinM[i]);
    h1_RDetaBinP = new RooDataHist("h1_RDetaBinP","h1_RDetaBinP",RooArgSet(x),hRDetaBinP[i]);
    h1_RDetaBinM = new RooDataHist("h1_RDetaBinM","h1_RDetaBinM",RooArgSet(x),hRDetaBinM[i]);

    //=============================
    //Gauss function
    //=============================
    RooRealVar meanMCp("meanMCp","",91.2,80,100);
    RooRealVar meanRDp("meanRDp","",91.2,80,100);
    RooRealVar meanMCm("meanMCm","",91.2,80,100);
    RooRealVar meanRDm("meanRDm","",91.2,80,100);
    RooRealVar sigmaMCp("sigmaMCp","",5,-50.,50.);
    RooRealVar sigmaRDp("sigmaRDp","",5,-50.,50.);
    RooRealVar sigmaMCm("sigmaMCm","",5,-50.,50.);
    RooRealVar sigmaRDm("sigmaRDm","",5,-50.,50.);

    RooGaussian mcModelp("mcModelp", "",x,meanMCp,sigmaMCp);
    RooGaussian mcModelm("mcModelm", "",x,meanMCm,sigmaMCm);
    RooGaussian dataModelp("dataModelp", "",x,meanRDp,sigmaRDp);
    RooGaussian dataModelm("dataModelm", "",x,meanRDm,sigmaRDm);

    //==================================
    //Fit Zmass distribution with Gaussian function
    //=============================
    mcModelp.fitTo(*h1_MCetaBinP,Range("R0"));
    mcModelm.fitTo(*h1_MCetaBinM,Range("R0"));
    dataModelp.fitTo(*h1_RDetaBinP,Range("R0"));
    dataModelm.fitTo(*h1_RDetaBinM,Range("R0"));

    //==================================
    //Fill 2D plots: etaBins and mean values
    //=============================
    hMCmeanp->SetBinContent(i+1,meanMCp.getVal());
    hRDmeanp->SetBinContent(i+1,meanRDp.getVal());
    hMCmeanm->SetBinContent(i+1,meanMCm.getVal());
    hRDmeanm->SetBinContent(i+1,meanRDm.getVal());

    hMCmeanp->SetBinError(i+1,meanMCp.getError());
    hRDmeanp->SetBinError(i+1,meanRDp.getError());
    hMCmeanm->SetBinError(i+1,meanMCm.getError());
    hRDmeanm->SetBinError(i+1,meanRDm.getError());

    hMCwidthp->SetBinContent(i+1,sigmaMCp.getVal());
    hRDwidthp->SetBinContent(i+1,sigmaRDp.getVal());
    hMCwidthm->SetBinContent(i+1,sigmaMCm.getVal());
    hRDwidthm->SetBinContent(i+1,sigmaRDm.getVal());

    hMCwidthp->SetBinError(i+1,sigmaMCp.getError());
    hRDwidthp->SetBinError(i+1,sigmaRDp.getError());
    hMCwidthm->SetBinError(i+1,sigmaMCm.getError());
    hRDwidthm->SetBinError(i+1,sigmaRDm.getError());

    cout<<meanMCp.getVal()<<"\t"<<meanMCm.getVal()<<"\t"<<meanRDp.getVal()<<"\t"<<meanRDm.getVal()<<endl;
    RooPlot* pframe = x.frame(Bins(40));
    RooPlot* mframe = x.frame(Bins(40));

    //==================================
    //Draw muon plus
    //==================================
    sprintf(tmpName,"pFit_etaBin%d_noCorr",i);
    plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{+}, before correction";
    if(corrName=="CorrTotalRegion")
    {
      sprintf(tmpName,"pFit_etaBin%d_Corr",i);
      plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{+}, after correction";
    }
    sprintf(histName,"Events / %.1f",hMCetaBinP[i]->GetBinWidth(1));
    plotMllEtaBinP = new CPlot(tmpName,pframe,plotTitle,"M_{#mu#mu} [GeV]",histName);
    plotMllEtaBinP->setOutDir(CPlot::sOutDir);

    plotMllEtaBinP->SetLegend(0.7,0.7,0.88,0.82);
    h1_MCetaBinP->plotOn(pframe,LineColor(kRed),MarkerColor(kRed),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    mcModelp.plotOn(pframe,LineColor(kRed));
    h1_RDetaBinP->plotOn(pframe,LineColor(kBlack),MarkerColor(kBlack),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    dataModelp.plotOn(pframe,LineColor(kBlack));
    plotMllEtaBinP->GetLegend()->AddEntry(hMCetaBinP[i],"Z #rightarrow #mu#mu","pl");
    plotMllEtaBinP->GetLegend()->AddEntry(hRDetaBinP[i],"Data","pl");

    sprintf(tmpName,"MC: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanMCp.getVal(),meanMCp.getError(),sigmaMCp.getVal(),sigmaMCp.getError());
    plotMllEtaBinP->AddTextBox(tmpName,0.20,0.83,0.6,0.88,0);
    sprintf(tmpName,"Data: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanRDp.getVal(),meanRDp.getError(),sigmaRDp.getVal(),sigmaRDp.getError());
    plotMllEtaBinP->AddTextBox(tmpName,0.20,0.78,0.6,0.83,0);

    plotMllEtaBinP->SetYRange(0.,1.4*TMath::Max(hRDetaBinP[i]->GetMaximum(),hMCetaBinP[i]->GetMaximum()));

    plotMllEtaBinP->Draw(myCan,kTRUE,"png");

    //==================================
    //Draw muon minus
    //=============================
    sprintf(tmpName,"mFit_etaBin%d_noCorr",i);
    plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{-}, before correction";
    if(corrName=="CorrTotalRegion")
    {
      sprintf(tmpName,"mFit_etaBin%d_Corr",i);
      plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{-}, after correction";
    }
    sprintf(histName,"Events / %.1f",hMCetaBinM[i]->GetBinWidth(1));
    plotMllEtaBinM = new CPlot(tmpName,mframe,plotTitle,"M_{#mu#mu} [GeV]",histName);
    plotMllEtaBinM->setOutDir(CPlot::sOutDir);

    plotMllEtaBinM->SetLegend(0.7,0.7,0.88,0.82);
    h1_MCetaBinM->plotOn(mframe,LineColor(kRed),MarkerColor(kRed),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    mcModelm.plotOn(mframe,LineColor(kRed));
    h1_RDetaBinM->plotOn(mframe,LineColor(kBlack),MarkerColor(kBlack),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    dataModelm.plotOn(mframe,LineColor(kBlack));
    plotMllEtaBinM->GetLegend()->AddEntry(hMCetaBinM[i],"Z #rightarrow #mu#mu","pl");
    plotMllEtaBinM->GetLegend()->AddEntry(hRDetaBinM[i],"Data","pl");

    sprintf(tmpName,"MC: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanMCm.getVal(),meanMCm.getError(),sigmaMCm.getVal(),sigmaMCm.getError());
    plotMllEtaBinM->AddTextBox(tmpName,0.20,0.83,0.6,0.88,0);
    sprintf(tmpName,"Data: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanRDm.getVal(),meanRDm.getError(),sigmaRDm.getVal(),sigmaRDm.getError());
    plotMllEtaBinM->AddTextBox(tmpName,0.20,0.78,0.6,0.83,0);

    plotMllEtaBinM->SetYRange(0.,1.4*TMath::Max(hRDetaBinM[i]->GetMaximum(),hMCetaBinM[i]->GetMaximum()));

    plotMllEtaBinM->Draw(myCan,kTRUE,"png");
  }

  //==================================
  //Save Mean and Width histograms to root file
  //==================================
  TString filename = outputDir + "/Wpt_MeanWidth_Gaus_" + corrName + ".root";
  TFile *outfile = new TFile(filename,"RECREATE");
  hMCmeanp ->Write();
  hMCmeanm ->Write();
  hMCwidthp->Write();
  hMCwidthm->Write();
  hRDmeanp ->Write();
  hRDmeanm ->Write();
  hRDwidthp->Write();
  hRDwidthm->Write();
  outfile->Close();

  //==================================
  //Draw 2D plots
  //==================================
  TString histoName = "plusMean_" + corrName;
  plotTitle = "Wpt: mean at #eta of #mu^{+}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: mean at #eta of #mu^{+}, after correction";
  plotMllEtameanP= new CPlot(histoName,plotTitle,"#eta of #mu^{+}","Mean of M(#mu^{+}#mu^{-})");
  plotMllEtameanP->setOutDir(CPlot::sOutDir);
  plotMllEtameanP->AddHist1D(hMCmeanp,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtameanP->AddHist1D(hRDmeanp,"Data","E1",kBlack);
                
  plotMllEtameanP->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtameanP->SetYRange(90,92);
  plotMllEtameanP->Draw(myCan,kTRUE,format);

  histoName = "minusMean_" + corrName;
  plotTitle = "Wpt: mean at #eta of #mu^{-}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: mean at #eta of #mu^{-}, after correction";
  plotMllEtameanM= new CPlot(histoName,plotTitle,"#eta of #mu^{-}","Mean of M(#mu^{+}#mu^{-})");
  plotMllEtameanM->setOutDir(CPlot::sOutDir);
  plotMllEtameanM->AddHist1D(hMCmeanm,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtameanM->AddHist1D(hRDmeanm,"Data","E1",kBlack);
                
  plotMllEtameanM->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtameanM->SetYRange(90,92);
  plotMllEtameanM->Draw(myCan,kTRUE,format);

  histoName = "plusWidth_" + corrName;
  plotTitle = "Wpt: width at #eta of #mu^{+}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: width at #eta of #mu^{+}, after correction";
  plotMllEtawidthP= new CPlot(histoName,plotTitle,"#eta of #mu^{+}","Width of M(#mu^{+}#mu^{-})");
  plotMllEtawidthP->setOutDir(CPlot::sOutDir);
  plotMllEtawidthP->AddHist1D(hMCwidthp,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtawidthP->AddHist1D(hRDwidthp,"Data","E1",kBlack);
                 
  plotMllEtawidthP->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtawidthP->SetYRange(1.5,3);
  plotMllEtawidthP->Draw(myCan,kTRUE,format);

  histoName = "minusWidth_" + corrName;
  plotTitle = "Wpt: width at #eta of #mu^{-}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: width at #eta of #mu^{-}, after correction";
  plotMllEtawidthM= new CPlot(histoName,plotTitle,"#eta of #mu^{-}","Width of M(#mu^{+}#mu^{-})");
  plotMllEtawidthM->setOutDir(CPlot::sOutDir);
  plotMllEtawidthM->AddHist1D(hMCwidthm,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtawidthM->AddHist1D(hRDwidthm,"Data","E1",kBlack);
                 
  plotMllEtawidthM->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtawidthM->SetYRange(1.5,3);
  plotMllEtawidthM->Draw(myCan,kTRUE,format);
}
void fitEfficiency(float thres,
		   float mLow=45, float mHigh=70,
		   TString cutdef="pt_HLT>=20", TString cut_choice="HLT",
		   TString dirIn="/data_CMS/cms/ndaci/ndaci_2012/HTauTau/TriggerStudy/SingleMu/MuMu/Run2012A_PRV1/Pairs/", 
		   TString dirResults="/home//llr/cms/ndaci/SKWork/macro/HTauTau/results/TriggerStudies/MuMu/Run2012A_PRV1/",
		   TString lumi="200 pb", int nCPU=4, 
		   int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
		   TString fileIn="*.root", TString image="eff_HLT_MuTau")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // OUTPUT //
  TString name_image = dirResults+"/"+image;
  ofstream fichier(name_image+".txt", ios::out);

  // BINNING //
  const int nbinsEB = 14;
  Double_t binsEB[nbinsEB] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEB = RooBinning(nbinsEB-1, binsEB, "binningEB");

  const int nbinsEE = 14;
  Double_t binsEE[nbinsEE] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEE = RooBinning(nbinsEE-1, binsEE, "binningEE");

  // EB/EE eta cuts //
  TString etacutEB="eta>-1.479 && eta<1.479", etacutEE="eta<=-1.479 || eta>=1.479";
  TString cutdefEB, cutdefEE;
  if(cutdef=="") { 
    cutdefEB=etacutEB;
    cutdefEE=etacutEE;
  }
  else {
    cutdefEB=cutdef+" && "+etacutEB ;
    cutdefEB=cutdef+" && "+etacutEE ;
  }

  // INPUT DATA //
  TChain* treeTnP = new TChain("treeTnP");
  treeTnP->Add(dirIn+"/"+fileIn);

  RooRealVar xaxis("pt","P_{T} [GeV]",0,150) ;
  RooRealVar mass("mass","mass",mLow,mHigh) ;// consider only this mass range when importing data                                      
  RooRealVar eta("eta","eta",-3., 3) ;
  RooRealVar weight("weight","weight",-1,1000) ;
  RooRealVar pt_HLT_tag("pt_HLT_tag","P_{T} [GeV]",0,150) ;
  RooRealVar pt_HLT_tag_sanity("pt_HLT_tag_sanity","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L3("pt_L3","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L25("pt_L25","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L2("pt_L2","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1jet("et_L1_jet","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1tau("et_L1_tau","P_{T} [GeV]",0,150) ;

  // DEFINE EFFICIENCY CUT //
  RooCategory cutHLT("match","") ;
  cutHLT.defineType("accept",1) ;
  cutHLT.defineType("reject",0) ;

  RooCategory cutL1("L1match","") ;
  cutL1.defineType("accept",1) ;
  cutL1.defineType("reject",0) ;

  RooCategory cutL1L2("L1L2match","") ;
  cutL1L2.defineType("accept",1) ;
  cutL1L2.defineType("reject",0) ;

  RooCategory cutL1L2L25("L1L2L25match","") ;
  cutL1L2L25.defineType("accept",1) ;
  cutL1L2L25.defineType("reject",0) ;

  RooCategory cutL1L2L25L3("L1L2L25L3match","") ;
  cutL1L2L25L3.defineType("accept",1) ;
  cutL1L2L25L3.defineType("reject",0) ;

  RooCategory *cut;
  if(cut_choice=="HLT") cut = &cutHLT;
  if(cut_choice=="L1") cut = &cutL1;
  if(cut_choice=="L1L2") cut = &cutL1L2;
  if(cut_choice=="L1L2L25") cut = &cutL1L2L25;
  if(cut_choice=="L1L2L25L3") cut = &cutL1L2L25L3;

  RooDataSet dataSetEB("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEB) );
  
  RooDataSet dataSetEE("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEE) );
  
  dataSetEB.Print();
  dataSetEE.Print();

  // PLOT //
  RooPlot* frame = xaxis.frame(Bins(18000),Title("Fitted efficiency")) ;
  dataSetEB.plotOn(frame, Binning(binningEB), Efficiency(*cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSetEE.plotOn(frame, Binning(binningEE), Efficiency(*cut), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );

  // PARAMETRES ROOFIT CRYSTAL BALL //
  RooRealVar norm("norm","N",0.95,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.2,0.01,8);
  RooRealVar n("n","n",2,1.1,35);
  RooRealVar mean("mean","mean",10,5,30);
  mean.setVal(thres);
  RooRealVar sigma("sigma","#sigma",0.23,0.01,5);
  RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  FuncCB cb_EB("cb_EB","Fit function EB (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  FuncCB cb_EE("cb_EE","Fit function EE (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  
  RooEfficiency eff_EB("eff_EB","efficiency EB", cb_EB, *cut, "accept");
  RooEfficiency eff_EE("eff_EE","efficiency EE", cb_EE, *cut, "accept");  

  // FIT //
  double fit_cuts_min = thres-1.5 ;
  double fit_cuts_max = 150;
  xaxis.setRange("interesting",fit_cuts_min,fit_cuts_max);

  fichier << "Fit characteristics :" << endl
	  << "Threshold : "          << thres << endl 
	  << "Fit Range : ["         << fit_cuts_min << "," << fit_cuts_max << "]" << endl 
	  << endl << endl;

  RooFitResult* roofitres_EB = new RooFitResult("roofitres_EB","roofitres_EB");
  RooFitResult* roofitres_EE = new RooFitResult("roofitres_EE","roofitres_EE");

  // Fit #1 //
  roofitres_EB = eff_EB.fitTo(dataSetEB,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EB.plotOn(frame,LineColor(color1),LineWidth(2));

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;

  // Fit #2 //
  roofitres_EE = eff_EE.fitTo(dataSetEE,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EE.plotOn(frame,LineColor(color2),LineWidth(2));

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;


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

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

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

  TH1F *SCeta_EB = new TH1F("SCeta_EB","SCeta_EB",50,-2.5,2.5);
  TH1F *SCeta_EE = new TH1F("SCeta_EE","SCeta_EE",50,-2.5,2.5);

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

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

  TLegend *leg = new TLegend(0.40, 0.14, 0.63, 0.34, NULL, "brNDC");
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.0244755);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);  
  leg->AddEntry("NULL","e #tau electrons efficiency","h");
  //    entry->SetLineColor(1);
  //    entry->SetLineStyle(1);
  //    entry->SetLineWidth(1);
  //    entry->SetMarkerColor(1);
  //    entry->SetMarkerStyle(21);
  //    entry->SetMarkerSize(1);
  //    entry->SetTextFont(62);
  leg->AddEntry(SCeta_EB,"Barrel","p");
  leg->AddEntry(SCeta_EE,"Endcaps","p");
  leg->Draw(); 
  
  ostringstream ossi("");
  ossi << thres;
  TString tossi = ossi.str();

  leg = new TLegend(0.40, 0.30, 0.50, 0.50, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.0297203);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+tossi+" GeV","h");
  leg->Draw();
  
  ca->Print(name_image+".C","C");
  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");

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

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

  w->import(dataSetEB);
  w->import(dataSetEE);
  
  w->import(*roofitres_EB,"roofitres_EB");
  w->import(*roofitres_EE,"roofitres_EE");

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

  // DELETE POINTERS
  // int a=0;
//   cin >> a;
//   delete treeTnP; delete cut; delete frame; delete roofitres_EB; delete roofitres_EE; delete ca; delete SCeta_EB; delete SCeta_EE; delete leg; delete w;

}