Example #1
0
bool TrGainDB::Save(const char* filename) {
  Init();
  TFile* rootfile = TFile::Open(filename,"recreate");
  if (rootfile==0) return false;
  rootfile->WriteTObject(GetHead());
  return true;
}
Example #2
0
void MakeHQTHiggsPtDistribution( string inputFilename ,  const string Label) {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
  string label = "";
  if (Label != "") label = "_" + Label;
 


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  ifstream infile(inputFilename.c_str());
  vector<double> lowEdges;
  vector<double> binContent;
  double x_min;
  double x_max;
  double y;
  Int_t binNumber = 1;
  while(infile >> x_min) {
    infile >> x_max >> y;
    lowEdges.push_back(x_min);
    binContent.push_back(y);
  }

  Double_t *xLowEdges = new Double_t[lowEdges.size()];
  for (UInt_t i=0; i < lowEdges.size();i++) {
    xLowEdges[i] = lowEdges[i];
  }


  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *bosonSystemPt = new TH1D((string("HiggsPt")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", lowEdges.size()-1, xLowEdges);

  for (UInt_t i=1;i<lowEdges.size();i++) {
    bosonSystemPt->SetBinContent(i,binContent[i]);
  }

  TFile *file = new TFile("HwwAcceptanceSystematics.root", "UPDATE");
  file->WriteTObject(bosonSystemPt, bosonSystemPt->GetName(), "WriteDelete");
  file->Close();

}
//#include <typeinfo.h>
void addFlatNuisances(std::string fi){
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
  TFile *fin = TFile::Open(fi.c_str());
  RooWorkspace *wspace = (RooWorkspace*)fin->Get("w_hmumu");

  wspace->Print("");

  RooStats::ModelConfig *mc = (RooStats::ModelConfig*)wspace->genobj("ModelConfig");
  RooArgSet *nuis = (RooArgSet*) mc->GetNuisanceParameters();
  std::cout << "Before...." << std::endl;
  nuis->Print();
  
  RooRealVar *mgg = (RooRealVar*)wspace->var("mmm");
  // Get all of the "flat" nuisances to be added to the nusiances:
  RooArgSet pdfs = (RooArgSet) wspace->allVars();
  RooAbsReal *pdf;
  TIterator *it_pdf = pdfs.createIterator();
  

  while ( (pdf=(RooAbsReal*)it_pdf->Next()) ){
  	  if (!(std::string(pdf->GetName()).find("zmod") != std::string::npos )) {
  	   if (!(std::string(pdf->GetName()).find("__norm") != std::string::npos )) {
	   	continue;
	   }
	  }
	  pdf->Print();
	  RooArgSet* pdfpars = (RooArgSet*)pdf->getParameters(RooArgSet(*mgg));
	  pdfpars->Print();

	  std::string newname_pdf = (std::string("unconst_")+std::string(pdf->GetName()));
	  wspace->import(*pdf,RooFit::RenameVariable(pdf->GetName(),newname_pdf.c_str()));
	  pdf->SetName(newname_pdf.c_str());
	  nuis->add(*pdf);
  }
 
  wspace->var("MH")->setVal(125.0);
  std::cout << "After..." << std::endl;
  nuis->Print();
  mc->SetNuisanceParameters(*nuis);
  //RooWorkspace *wspace_new = wspace->Clone();
  //mc->SetWorkspace(*wspace_new);
  //wspace_new->import(*mc,true);

  TFile *finew = new TFile((std::string(fin->GetName())+std::string("_unconst.root")).c_str(),"RECREATE");
  //wspace_new->SetName("w");
  finew->WriteTObject(wspace);
  finew->Close();
}
void PileUpMaker() {
  // Access data file
  TFile *file = TFile::Open("ZmumuGammaNtuple_Full2012_MuCorr.root");
  TTree *Datatree = (TTree*)file->Get("ZmumuGammaEvent");

  // Set up histogram for data pile up
  TH1F *pileupraw = new TH1F("pileup","",40,0,80);
 
  // Fill pile up distribution
  Int_t nentries = Datatree->GetEntriesFast();
  Int_t nbytes = 0; 
  for (Int_t i=0; i<nentries;i++) {
    nbytes += Datatree->GetEvent(i);
    UInt_t NVertices;
    Datatree->SetBranchAddress("NVertices",&NVertices);
    pileupraw->Fill(float(NVertices)/0.7);
  }

  // Normalize the distribution
  TH1F* PU = (TH1F*)pileupraw->Clone("pileup");
  PU->Scale(1./PU->Integral());

  // Plot both the normalized and unnormalized pile up
  TCanvas *cv = 0;
  cv= new TCanvas("cv","cv",800, 600);
  pileupraw->Draw("");
  cv->SaveAs("DataPU.pdf");

  cv= new TCanvas("cv","cv",800,600);
  PU->Draw("");
  cv->SaveAs("DataPU_normalized.pdf");

  // Save the normalized distribution to a root file for weighting MC
  TFile *file = TFile::Open("2012_PhosphorData_PileUp.root","UPDATE");
  file->cd();
  file->WriteTObject(PU,PU->GetName(),"WriteDelete");
  file->Close();
  delete file;
}
Example #5
0
//--------------------------------------------------------------------------------------------------
// Main of the macro
//--------------------------------------------------------------------------------------------------
void computeFakeRates(char *FakeRateFilename ) {

  string fakeTypeString = "";
  //Samples
  vector<string> madgraphDatasetFiles;
  vector<string> madgraphDatasetNames;
  vector<string> pythiaDatasetFiles;
  vector<string> pythiaDatasetNames;

  //*****************************************************************************************
  //Do FakeRate Computation 
  //*****************************************************************************************

  //Create root file to store fake rates
  TFile *file = new TFile(FakeRateFilename, "RECREATE");
  file->cd();

  //do both muon and electrons
  Double_t maxY = 1.0;
  for (int faketype=11 ; faketype <= 13; faketype+=2) {
    if (faketype == 11) {
      fakeTypeString = "Electron";
      maxY = 0.5;
    } else if (faketype == 13) {
      fakeTypeString = "Muon";
      maxY = 0.01;
    } else {
      cerr << "Error: faketype = " << faketype << " not recognized.\n";
      return;
    }
    
    //*****************************************************************************************
    //Load input histogram files
    //*****************************************************************************************
    madgraphDatasetFiles.clear(); 
    madgraphDatasetNames.clear();
    pythiaDatasetFiles.clear();
    pythiaDatasetNames.clear();
    
    //Madgraph WJets
    madgraphDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_f8-wjets-mg-id9.root");
    madgraphDatasetNames.push_back("f8-wjets-mg-id9");
    //Pythia WJets
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-we-id9.root");
    pythiaDatasetNames.push_back("s8-we-id9");
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-wm-id9.root");
    pythiaDatasetNames.push_back("s8-wm-id9");
    pythiaDatasetFiles.push_back("/home/sixie/hist/Compute" + fakeTypeString + "FakeRate/filler/006/Compute" + fakeTypeString + "FakeRate_s8-wtau-id9.root");
    pythiaDatasetNames.push_back("s8-wtau-id9");

    //*****************************************************************************************
    //Construct the fake rate Histgrams. Fit with function.
    //*****************************************************************************************
    vector<TH1F*> fakeRateHistograms; fakeRateHistograms.clear();
    vector<TF1*> fakeRateFits; fakeRateFits.clear();
    vector<string> fakeRateLegendNames; fakeRateLegendNames.clear();

    //pythia version
    TH1F *FakeRatePt_pythia = createFakeRatePtHist(pythiaDatasetFiles, pythiaDatasetNames, faketype,
                                                   (fakeTypeString + "FakeRate_Pt_pythia").c_str());
    FakeRatePt_pythia->GetYaxis()->SetTitle((fakeTypeString + " Fake Rate").c_str());    
    TF1 *FakeRateFitFunction_pythia = fitFakeRatePtHist(FakeRatePt_pythia);
    FakeRateFitFunction_pythia->SetName((fakeTypeString + "FakeRateFunction_Pt_pythia").c_str());
    
    fakeRateHistograms.push_back(FakeRatePt_pythia);
    fakeRateFits.push_back(FakeRateFitFunction_pythia);
    fakeRateLegendNames.push_back("Pythia W+Jets");

    //madgraph version
    TH1F *FakeRatePt_madgraph = createFakeRatePtHist(
      madgraphDatasetFiles, madgraphDatasetNames,faketype,
      (fakeTypeString + "FakeRate_Pt_madgraph").c_str());
    FakeRatePt_madgraph->GetYaxis()->SetTitle((fakeTypeString + " Fake Rate").c_str());    
    TF1 *FakeRateFitFunction_madgraph = fitFakeRatePtHist(FakeRatePt_madgraph);
    FakeRateFitFunction_madgraph->SetName(
      (fakeTypeString + "FakeRateFunction_Pt_madgraph").c_str());

    fakeRateHistograms.push_back(FakeRatePt_madgraph);
    fakeRateFits.push_back(FakeRateFitFunction_madgraph);
    fakeRateLegendNames.push_back("Madgraph W+Jets");

    cout << "pythia at x = 30 : " << FakeRateFitFunction_pythia->Eval(30.0) << endl;
    cout << "pythia at x = 30 : " << FakeRateFitFunction_madgraph->Eval(30.0) << endl;

    //*****************************************************************************************
    //Draw the plots
    //*****************************************************************************************
    drawFakeRatePlots(fakeRateHistograms,fakeRateFits,fakeRateLegendNames,
                      (fakeTypeString + "FakeRateEt").c_str(),maxY);

    //*****************************************************************************************
    //save them to the output file
    //*****************************************************************************************
    for (UInt_t i=0; i<fakeRateHistograms.size();i++) {
      fakeRateHistograms[i]->SetDirectory(file);
      file->WriteTObject(fakeRateFits[i]);
    }
  }

  file->Write();
  file->Close();
  return;

}
void computeOSWeights_CR(int erg_tev, int iCR, double m4l_low, double m4l_high){
//  if (iCR>2 || iCR==1) return;
  char TREE_NAME[]="SelectedTree";

  int EnergyIndex=0; if (erg_tev==8)EnergyIndex=1;
  double my_luminosity = luminosity[EnergyIndex];

  TString erg_dir;
  erg_dir.Form("LHC_%iTeV", erg_tev);
  TString comstring;
  comstring.Form("%iTeV", erg_tev);

  TChain* tc = new TChain(TREE_NAME);

  TString cinput_common_noSIP = user_dir_hep + "No_SIP/" + erg_dir + "/CR/";
  if (iCR<2){
    int sampleindex = kAllSamples-1 + iCR;
    TString cinput = cinput_common_noSIP;
    cinput = cinput + sample_FullSim[sampleindex] + ".root";
    tc->Add(cinput);
  }
  else{
    for (int smp=kGGSamples; smp<kQQBZZSamples; smp++){
      TString cinput = cinput_common_noSIP;
      cinput = cinput + sample_FullSim[smp] + "_CRZLLTree.root";
      tc->Add(cinput);
    }
  }

  if (tc->GetEntries() == 0){
    cout << "Could not find any files, aborting..." << endl; return;
  }
  else if (iCR==2) cout << "qqZZ CR: " << tc->GetEntries() << endl;

  TString coutput_common = user_dir_hep + "Analysis/Auxiliary/";

  TFile* frecord;
  TString fname = "OSfakeweights_";
  if (iCR==0) fname.Append("ZLL_");
  else if (iCR==1) fname.Append("ZL_");
  else if (iCR==2) fname.Append("QQBZZ_");
  fname += comstring;
  fname.Append(Form("_m4l_%.1f_%.1f%s", m4l_low, m4l_high, ".root"));
  fname.Prepend(coutput_common);
  frecord = new TFile(fname, "recreate");

  TFile* foutput[3];

  TH1F* hOS[4];
  TFile* fweight[2] ={
    new TFile(Form("./data/Zmu_OS_%iTeV.root", erg_tev)),
    new TFile(Form("./data/Ze_OS_%iTeV.root", erg_tev))
  };
  hOS[0] = (TH1F*)fweight[0]->Get("h1D_FRmu_EB");
  hOS[1] = (TH1F*)fweight[0]->Get("h1D_FRmu_EE");
  hOS[2] = (TH1F*)fweight[1]->Get("h1D_FRel_EB");
  hOS[3] = (TH1F*)fweight[1]->Get("h1D_FRel_EE");

  frecord->cd();

  TString hname = "htemp";

  float GenHMass;
  float ZXfake_weight,MC_weight,MC_weight_QQBZZEWK;
  int CRflag;
  float Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF;
  bool Lep1isID, Lep2isID, Lep3isID, Lep4isID;
  short Z1ids;
  short Z2ids;
  float PFMET;

  float Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP;
  float Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP;
  int Lep1ID, Lep2ID, Lep3ID, Lep4ID;

  float Z1Mass, Z2Mass, ZZMass, ZZPt, ZZEta, ZZPhi;
  float KalmanCandVtx_x, KalmanCandVtx_y, KalmanCandVtx_z, KalmanCandVtx_chi2;
  float OfflinePrimaryVtx_x, OfflinePrimaryVtx_y, OfflinePrimaryVtx_z;

  float Lep1Pt, Lep2Pt, Lep3Pt, Lep4Pt;
  float Lep1Eta, Lep2Eta, Lep3Eta, Lep4Eta;

  tc->SetBranchAddress("ZXfake_weight", &ZXfake_weight);
  tc->SetBranchAddress("CRflag", &CRflag);

  tc->SetBranchAddress("Z1ids", &Z1ids);
  tc->SetBranchAddress("Z2ids", &Z2ids);
  tc->SetBranchAddress("Lep1ID", &Lep1ID);
  tc->SetBranchAddress("Lep1isID", &Lep1isID);
  tc->SetBranchAddress("Lep1combRelIsoPF", &Lep1combRelIsoPF);
  tc->SetBranchAddress("Lep2ID", &Lep2ID);
  tc->SetBranchAddress("Lep2isID", &Lep2isID);
  tc->SetBranchAddress("Lep2combRelIsoPF", &Lep2combRelIsoPF);
  tc->SetBranchAddress("Lep3ID", &Lep3ID);
  tc->SetBranchAddress("Lep3isID", &Lep3isID);
  tc->SetBranchAddress("Lep3combRelIsoPF", &Lep3combRelIsoPF);

  tc->SetBranchAddress("PFMET", &PFMET);
  tc->SetBranchAddress("Z1Mass", &Z1Mass);
  tc->SetBranchAddress("Z2Mass", &Z2Mass);
  tc->SetBranchAddress("ZZMass", &ZZMass);
  tc->SetBranchAddress("ZZPt", &ZZPt);
  tc->SetBranchAddress("ZZEta", &ZZEta);
  tc->SetBranchAddress("ZZPhi", &ZZPhi);
  tc->SetBranchAddress("OfflinePrimaryVtx_x", &OfflinePrimaryVtx_x);
  tc->SetBranchAddress("OfflinePrimaryVtx_y", &OfflinePrimaryVtx_y);
  tc->SetBranchAddress("OfflinePrimaryVtx_z", &OfflinePrimaryVtx_z);
  tc->SetBranchAddress("KalmanCandVtx_x", &KalmanCandVtx_x);
  tc->SetBranchAddress("KalmanCandVtx_y", &KalmanCandVtx_y);
  tc->SetBranchAddress("KalmanCandVtx_z", &KalmanCandVtx_z);

  tc->SetBranchAddress("Lep1Pt", &Lep1Pt);
  tc->SetBranchAddress("Lep2Pt", &Lep2Pt);
  tc->SetBranchAddress("Lep3Pt", &Lep3Pt);
  tc->SetBranchAddress("Lep1Eta", &Lep1Eta);
  tc->SetBranchAddress("Lep2Eta", &Lep2Eta);
  tc->SetBranchAddress("Lep3Eta", &Lep3Eta);


  tc->SetBranchAddress("KalmanCandVtx_chi2", &KalmanCandVtx_chi2);
  tc->SetBranchAddress("Lep1_Z1SIP", &Lep1_Z1SIP);
  tc->SetBranchAddress("Lep2_Z1SIP", &Lep2_Z1SIP);
  tc->SetBranchAddress("Lep3_Z1SIP", &Lep3_Z1SIP);
  tc->SetBranchAddress("Lep1SIP", &Lep1SIP);
  tc->SetBranchAddress("Lep2SIP", &Lep2SIP);
  tc->SetBranchAddress("Lep3SIP", &Lep3SIP);

  if (iCR!=1){
    tc->SetBranchAddress("Lep4ID", &Lep4ID);
    tc->SetBranchAddress("Lep4isID", &Lep4isID);
    tc->SetBranchAddress("Lep4combRelIsoPF", &Lep4combRelIsoPF);
    tc->SetBranchAddress("Lep4_Z1SIP", &Lep4_Z1SIP);
    tc->SetBranchAddress("Lep4SIP", &Lep4SIP);
    tc->SetBranchAddress("Lep4Pt", &Lep4Pt);
    tc->SetBranchAddress("Lep4Eta", &Lep4Eta);
  }
  if (iCR==2){
    tc->SetBranchAddress("MC_weight", &MC_weight);
    tc->SetBranchAddress("GenHMass", &GenHMass);
  }

  for (int iwgt=0; iwgt<2; iwgt++){
    if (iCR==1 && iwgt==1) continue;
    for (int isocut=0; isocut<4; isocut++){
      if (iCR==1 && isocut>=2) continue;
      if (isocut<2) continue;

      for (int iM1cut=0; iM1cut<1; iM1cut++){
        if (iM1cut==2 && iCR!=1) continue;
        if (iwgt==0) cout << "Un-weighted";
        else cout << "Weighted";
        if (isocut>=1) cout << ", " << strLepIsoCut_label[isocut-1];
        cout << ", " << Z1masswidth_label[iM1cut] << endl;
        cout << "\t"; for (int icut=0; icut<nSIPCuts; icut++) cout << cutLabel[icut] << '\t' << cutLabel[icut] << " Error\t";
        cout << endl;
        for (int catZ1=0; catZ1<2; catZ1++){
          for (int catZ2=0; catZ2<(iCR!=1 ? 3 : 2); catZ2++){
//          for (int catZ2=0; catZ2<(iCR!=1 ? 6 : 2); catZ2++){
            cout << strZ1Category_label[catZ1] << " ";
            if (iCR!=1) cout << strZ2Category_label[catZ2];
            else cout << strLep3Category_label[catZ2];
            for (int icut=0; icut<nSIPCuts; icut++){
              gStyle->SetTitleFont(62, "t");
              gROOT->SetStyle(gStyle->GetName());
              gROOT->ForceStyle();

              TH1F* hsip = new TH1F(hname, "", 1, 0, 1000);
              hsip->Sumw2();

              double ptbins[9]={ 0, 5, 7, 10, 20, 30, 40, 50, 80 };
              double etabins[3]={ 0, 1.2, 2.5 };
              if ((iCR==1 && catZ2==1) || (iCR!=1 && (catZ2==2 || catZ2==3))) etabins[1]=1.45;

//              const int nbinsTxy = 60;
//              double Txybins[nbinsTxy+1];
//              for (int bin=0; bin<=nbinsTxy; bin++)Txybins[bin] = -1400.+2800.*bin/nbinsTxy;
              const int nbinsTxy = 7;
              double Txybins[nbinsTxy+1]={-2000,-500,-200,-50,50,200,500,2000};
/*              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 100, 140.6, 170, 250, m4l_high };
              const int nbinsmZ1 = 10;
              double mZ1bins[nbinsmZ1+1];
              for (int bin=0; bin<=nbinsmZ1; bin++)mZ1bins[bin] = 0.+120.*bin/nbinsmZ1;
              const int nbinsmZ2 = 6;
              double mZ2bins[nbinsmZ2+1];
              for (int bin=0; bin<=nbinsmZ2; bin++)mZ2bins[bin] = 12.+132.*bin/nbinsmZ2;
*/
              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 0, 100, 140, 170, 3000 };
              const int nbinsmZ1 = 5;
              double mZ1bins[nbinsmZ1+1]={ 0, 40, 62.5, 85, 97.5, 120 };
              const int nbinsmZ2 = 3;
              double mZ2bins[nbinsmZ2+1]={ 0, 35, 65, 150 };

              TH2F* hmZZTxyOS;
              TH2F* hmZZTxyOS_extra;
              TH3F* hmZZmZ1mZ2OS;
              TH3F* hmZZmZ1mZ2OS_extra;
              if (iCR!=1 && isocut>1 && catZ2<3){
                hmZZTxyOS = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                hmZZTxyOS->Sumw2();
                hmZZTxyOS->SetXTitle("m_{4l} (GeV)");
                hmZZTxyOS->SetYTitle("T_{xy} (#mum)");
                hmZZTxyOS->SetZTitle("Events / bin");
                hmZZTxyOS->SetOption("colz");

                hmZZmZ1mZ2OS = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                hmZZmZ1mZ2OS->Sumw2();
                hmZZmZ1mZ2OS->SetXTitle("m_{4l} (GeV)");
                hmZZmZ1mZ2OS->SetYTitle("m_{1} (GeV)");
                hmZZmZ1mZ2OS->SetZTitle("m_{2} (GeV)");
                hmZZmZ1mZ2OS->SetOption("box");
                if (isocut==2 && iwgt>0){
                  hmZZTxyOS_extra = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                  hmZZTxyOS_extra->Sumw2();
                  hmZZTxyOS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZTxyOS_extra->SetYTitle("T_{xy} (#mum)");
                  hmZZTxyOS_extra->SetZTitle("Events / bin");
                  hmZZTxyOS_extra->SetOption("colz");

                  hmZZmZ1mZ2OS_extra = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                  hmZZmZ1mZ2OS_extra->Sumw2();
                  hmZZmZ1mZ2OS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetYTitle("m_{1} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetZTitle("m_{2} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetOption("box");
                }
              }


              for (int ev=0; ev<tc->GetEntries(); ev++){
                MC_weight=1;
                MC_weight_QQBZZEWK=1;
                
                tc->GetEntry(ev);

                if (iCR==2){
                  MC_weight*=my_luminosity;
                  MC_weight_QQBZZEWK = getQQZZEWKCorrection(GenHMass);
                  MC_weight*=MC_weight_QQBZZEWK;
                  ZXfake_weight = ZXfake_weight*MC_weight;
                }

                int option[7]={
                  iCR, icut, catZ1, catZ2, iwgt, isocut, iM1cut
                };
                int LepID[4]={
                  Lep1ID, Lep2ID, Lep3ID, Lep4ID
                };
                float Lep_Z1SIP[4]={
                  Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP
                };
                float LepSIP[4]={
                  Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP
                };

                float wgt = applyCRselection(
                  option,

                  m4l_low, m4l_high,

                  CRflag,
                  Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF,
                  Lep1isID, Lep2isID, Lep3isID, Lep4isID,
                  Z1ids,
                  Z2ids,
                  PFMET,

                  Lep_Z1SIP,
                  KalmanCandVtx_chi2,
                  LepSIP,
                  LepID,

                  Z1Mass, ZZMass,

                  1
//                  ZXfake_weight
                  );
                if (wgt==0) continue;
                float wgterror=0;


                float strdraw = Z1Mass;

                float strdraw_Txy = ((KalmanCandVtx_x - OfflinePrimaryVtx_x)*cos(ZZPhi) + (KalmanCandVtx_x - OfflinePrimaryVtx_x)*sin(ZZPhi))*10000.0*ZZMass / ZZPt;
                float strdraw_mZZ = ZZMass;
                float strdraw_mZ1 = Z1Mass;
                float strdraw_mZ2 = Z2Mass;
                float strdraw_pteta_ld[2] ={
                  fabs(Lep3Eta), Lep3Pt
                };
                float strdraw_pteta_subld[2] ={
                  fabs(Lep4Eta), Lep4Pt
                };
                if (iCR!=1 && Lep3Pt<=Lep4Pt){
                  strdraw_pteta_ld[0] = fabs(Lep4Eta);
                  strdraw_pteta_ld[1] = fabs(Lep4Pt);
                  strdraw_pteta_subld[0] = fabs(Lep3Eta);
                  strdraw_pteta_subld[1] = fabs(Lep3Pt);
                }

                float OSSFweight[2] ={ 0 };
                float OSSFweighterror[2] ={ 0 };
                if (iCR!=1 && isocut>1 && catZ2<3 && wgt>0){

                  OSSFweight[0] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep3combRelIsoPF,
                    Lep3isID,

                    Lep3ID,
                    Lep3Pt,
                    Lep3Eta,

                    OSSFweighterror[0]
                    );

                  OSSFweight[1] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep4combRelIsoPF,
                    Lep4isID,

                    Lep4ID,
                    Lep4Pt,
                    Lep4Eta,

                    OSSFweighterror[1]
                    );

                  if (isocut==2 && (OSSFweight[0]==0 || OSSFweight[1]==0)) cout << "WARNING: 2p2f OSSF weights are not all positive!" << endl;
                  if (isocut==3 && (OSSFweight[0]==0 && OSSFweight[1]==0)) cout << "WARNING: 3p1f OSSF weights are all zero!" << endl;
                  if (isocut==3 && (OSSFweight[0]!=0 && OSSFweight[1]!=0)) cout << "WARNING: 3p1f OSSF weights are all non-zero!" << endl;

                  float totalOS = 1;
                  float sumOS = 0;

                  float totalOSerror=0;
                  float sumOSerror=0;

                  if (iwgt>0){
                    if (OSSFweight[0]>0){
                      totalOS *= OSSFweight[0];
                      totalOSerror += pow(OSSFweighterror[0]/OSSFweight[0], 2);
                    }
                    if (OSSFweight[1]>0){
                      totalOS *= OSSFweight[1];
                      totalOSerror += pow(OSSFweighterror[1]/OSSFweight[1], 2);
                    }
                    totalOSerror = sqrt(totalOSerror) * totalOS;
                    if (isocut==2){
                      sumOS = OSSFweight[0] + OSSFweight[1];
                      sumOSerror = sqrt(pow(OSSFweighterror[0], 2) + pow(OSSFweighterror[1], 2));
                    }
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                      totalOSerror*=MC_weight;
                      sumOSerror*=MC_weight;
                    }
                    wgt = totalOS;
                    wgterror = totalOSerror;
                  }
                  else{
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                    }
                  }

                  hmZZTxyOS->Fill(strdraw_mZZ, strdraw_Txy, totalOS);
                  hmZZmZ1mZ2OS->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, totalOS);

                  if (iwgt>0){
/*
                    int binx = hmZZTxyOS->GetXaxis()->FindBin(strdraw_mZZ);
                    int biny = hmZZTxyOS->GetYaxis()->FindBin(strdraw_Txy);
                    hmZZTxyOS->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS->GetBinError(binx, biny), 2)+pow(totalOSerror, 2)));

                    binx = hmZZmZ1mZ2OS->GetXaxis()->FindBin(strdraw_mZZ);
                    biny = hmZZmZ1mZ2OS->GetYaxis()->FindBin(strdraw_mZ1);
                    int binz = hmZZmZ1mZ2OS->GetZaxis()->FindBin(strdraw_mZ2);
                    hmZZmZ1mZ2OS->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS->GetBinError(binx, biny, binz), 2)+pow(totalOSerror, 2)));
*/
                    if (isocut==2){
                      hmZZTxyOS_extra->Fill(strdraw_mZZ, strdraw_Txy, sumOS);
                      hmZZmZ1mZ2OS_extra->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, sumOS);
/*
                      int binx = hmZZTxyOS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      int biny = hmZZTxyOS_extra->GetYaxis()->FindBin(strdraw_Txy);
                      hmZZTxyOS_extra->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS_extra->GetBinError(binx, biny), 2)+pow(sumOSerror, 2)));

                      binx = hmZZmZ1mZ2OS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      biny = hmZZmZ1mZ2OS_extra->GetYaxis()->FindBin(strdraw_mZ1);
                      int binz = hmZZmZ1mZ2OS_extra->GetZaxis()->FindBin(strdraw_mZ2);
                      hmZZmZ1mZ2OS_extra->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS_extra->GetBinError(binx, biny, binz), 2)+pow(sumOSerror, 2)));
*/
                    }
                  }

                }

                hsip->Fill(strdraw, wgt);
                if (iwgt>0){
                  int binx = hsip->GetXaxis()->FindBin(strdraw);
                  hsip->SetBinError(binx, sqrt(pow(hsip->GetBinError(binx), 2)+pow(wgterror, 2)));
                }

              }

              if (iCR!=1 && isocut>1 && catZ2<3){
                frecord->WriteTObject(hmZZTxyOS);
                delete hmZZTxyOS;
                frecord->WriteTObject(hmZZmZ1mZ2OS);
                delete hmZZmZ1mZ2OS;
                if (isocut==2 && iwgt>0){
                  frecord->WriteTObject(hmZZTxyOS_extra);
                  delete hmZZTxyOS_extra;
                  frecord->WriteTObject(hmZZmZ1mZ2OS_extra);
                  delete hmZZmZ1mZ2OS_extra;
                }
              }

              double totalerror = 0;
              double totalintegral = hsip->IntegralAndError(1,hsip->GetNbinsX(),totalerror);

              cout << '\t' << totalintegral << '\t' << totalerror;

              delete hsip;
            }
            cout << endl;
          }
        }
        cout << endl;
      }
      cout << endl;
    }
    cout << endl;
  }
  delete tc;

  for (int ww=0; ww<2; ww++) fweight[ww]->Close();
  frecord->Close();
}
Example #7
0
void FitLeptonResponseModels(const string Label = "ZZ", Int_t Option = 0, Int_t PtBin = -1, Int_t EtaBin = -1) {

  string label = Label;
  if (Label != "") label = "_" + Label;
  TFile *fileInput = new TFile(("FakeRate" + label + ".root").c_str(), "READ");

  //********************************************************
  // Bins
  //********************************************************
  const UInt_t NPtBins = 4;
  const UInt_t NEtaBins = 3;
  double ptBins[NPtBins+1] = { 5, 7, 10, 15, 25 };
  double etaBins[NEtaBins+1] = { 0.0, 1.2, 2.2, 2.4 };

  
  //********************************************************
  // Output
  //********************************************************
  TFile *fileOutput = new TFile(("FakeMuonPtResolutionModel" + label + ".root").c_str(), "UPDATE");
  
  TH2F* GaussParamArray_Muons_mean = (TH2F*)fileOutput->Get("GaussParamArray_Muons_mean");
  TH2F* GaussParamArray_Muons_sigma = (TH2F*)fileOutput->Get("GaussParamArray_Muons_sigma");


  if (!GaussParamArray_Muons_mean) {
    GaussParamArray_Muons_mean = new TH2F( "GaussParamArray_Muons_mean", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0.0);
      }
    }
  }
  if (!GaussParamArray_Muons_sigma) {
    GaussParamArray_Muons_sigma = new TH2F( "GaussParamArray_Muons_sigma", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0.0);
      }
    }
  }

  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }
    }
  }

  //********************************************************
  // Fit for resolution function 
  //******************************************************** 
  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {

      if (PtBin >= 0 && EtaBin >= 0) {
        if (!(i==PtBin && j==EtaBin)) continue;
      }
      
      TH1F* hist = (TH1F*)fileInput->Get(Form("LeptonPtResolution_Muons_PtBin%d_EtaBin%d",i,j));
      assert(hist);

      RooRealVar leptonPtRes("leptonPtRes","leptonPtRes",-1.0,0.25);
      leptonPtRes.setRange("range",-1.00,0.25);
      leptonPtRes.setBins(100);
      RooDataHist *data=0;
      data = new RooDataHist("data","data",RooArgSet(leptonPtRes),hist);

      RooRealVar     *mean  = new RooRealVar("mean","mean",-0.25,-10,10);
      RooRealVar     *sigma = new RooRealVar("sigma","sigma",0.05,0.00001,0.5);

      RooGaussian *model = new RooGaussian("LeptonPtResModel","LeptonPtResModel",leptonPtRes,*mean,*sigma);

      RooFitResult *fitResult=0;
      fitResult = model->fitTo(*data,
                               RooFit::Binned(true),
                               RooFit::Strategy(1),
                               RooFit::Save());

      cout << "Fitted parameters\n";
      cout << mean->getVal() << endl;
      cout << sigma->getVal() << endl;
     
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,mean->getVal());
        GaussParamArray_Muons_sigma->SetBinContent(i,j,sigma->getVal());
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }




      //Save Workspace
      RooWorkspace *w = new RooWorkspace(Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j),Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j));
      w->import(*model);
      w->import(*data);
      //w->Print();

      //Make Plot
      RooPlot *frame = leptonPtRes.frame(RooFit::Bins(100));
      data->plotOn(frame,RooFit::MarkerStyle(kFullCircle),RooFit::MarkerSize(0.8),RooFit::DrawOption("ZP"));    
      model->plotOn(frame);

      TCanvas *cv = new TCanvas("cv","cv",800,600);
      
      frame->Draw();
      cv->SaveAs(Form("LeptonPtResolution_Muons%s_PtBin%d_EtaBin%d.gif",label.c_str(),i,j)); 

      fileOutput->WriteTObject(model, Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(cv, Form("LeptonPtResolutionFit_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(w, w->GetName(), "WriteDelete");

      fileOutput->WriteTObject(GaussParamArray_Muons_mean, "GaussParamArray_Muons_mean", "WriteDelete");
      fileOutput->WriteTObject(GaussParamArray_Muons_sigma, "GaussParamArray_Muons_sigma", "WriteDelete");


    }
  }

  //********************************************************
  // Produce output lookup table
  //******************************************************** 
  ofstream outf_e("FakeMuonResponseMap.h");

  outf_e << "UInt_t FindFakeMuonResponseBin( double value, double bins[], UInt_t nbins) {" << endl;
  outf_e << "  UInt_t nbinboundaries = nbins+1;" << endl;
  outf_e << "  UInt_t bin = 0;" << endl;
  outf_e << "  for (uint i=0; i < nbinboundaries; ++i) {" << endl;
  outf_e << "    if (i < nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i] && value < bins[i+1]) {" << endl;
  outf_e << "        bin = i+1;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    } else if (i == nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i]) {" << endl;
  outf_e << "        bin = nbinboundaries;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    }    " << endl;
  outf_e << "  }" << endl;
  outf_e << "  return bin;" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseMeanPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseMean[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_mean->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseMean[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseSigmaPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseSigma[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_sigma->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseSigma[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;


  outf_e.close();


  fileInput->Close();
  delete fileInput;
  fileOutput->Close();

  gBenchmark->Show("WWTemplate");       
}
void fit_JVBF(int erg_tev=8, float mSample=0){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "TestTree";

  TString cinput;
  if (mSample>0) cinput = Form("HZZ4lTree_jvbfMELA_H%.0f_%iTeV.root", mSample, erg_tev);
  else cinput = Form("HZZ4lTree_jvbfMELA_HAll_%iTeV.root", erg_tev);

  TFile* foutput;
  if (mSample>0) foutput = new TFile(Form("jvbfMELA_Fits_H%.0f_%iTeV.root", mSample, erg_tev), "recreate");
  else foutput = new TFile(Form("jvbfMELA_fits_wide_%iTeV.root", erg_tev), "recreate");

  TLorentzVector nullFourVector(0, 0, 0, 0);

  float MC_weight_noxsec;

  float pjvbf_VAJHU;
  float pjvbf_VAJHU_first;
  float pjvbf_VAJHU_second;

  float jet1Pt, jet2Pt;
  float jet1Eta, jet2Eta;
  float jet1Phi, jet2Phi;
  float jet1E, jet2E;
  float jet1Pt_Fake, jet2Pt_Fake;
  float jet1Eta_Fake, jet2Eta_Fake;
  float jet1Phi_Fake, jet2Phi_Fake;
  float jet1E_Fake, jet2E_Fake;
  float jet1px, jet1py, jet1pz;
  float jet2px, jet2py, jet2pz;
  float ZZPx, ZZPy, ZZPz, ZZE, dR;
  short NJets30;

  float ZZMass;

  TChain* tree = new TChain(TREE_NAME);
  tree->Add(cinput);
  tree->SetBranchAddress("MC_weight_noxsec", &MC_weight_noxsec);
  tree->SetBranchAddress("ZZMass", &ZZMass);
  tree->SetBranchAddress("pjvbf_VAJHU", &pjvbf_VAJHU);
  tree->SetBranchAddress("pjvbf_VAJHU_first", &pjvbf_VAJHU_first);
  tree->SetBranchAddress("pjvbf_VAJHU_second", &pjvbf_VAJHU_second);
  tree->SetBranchAddress("NJets30", &NJets30);
  tree->SetBranchAddress("jet1Pt", &jet1Pt);
  tree->SetBranchAddress("jet1Eta", &jet1Eta);
  tree->SetBranchAddress("jet1Phi", &jet1Phi);
  tree->SetBranchAddress("jet1E", &jet1E);
  tree->SetBranchAddress("jet2Pt", &jet2Pt);
  tree->SetBranchAddress("jet2Eta", &jet2Eta);
  tree->SetBranchAddress("jet2Phi", &jet2Phi);
  tree->SetBranchAddress("jet2E", &jet2E);
  tree->SetBranchAddress("jet1_Fake_Pt", &jet1Pt_Fake);
  tree->SetBranchAddress("jet1_Fake_Eta", &jet1Eta_Fake);
  tree->SetBranchAddress("jet1_Fake_Phi", &jet1Phi_Fake);
  tree->SetBranchAddress("jet1_Fake_E", &jet1E_Fake);
  tree->SetBranchAddress("jet2_Fake_Pt", &jet2Pt_Fake);
  tree->SetBranchAddress("jet2_Fake_Eta", &jet2Eta_Fake);
  tree->SetBranchAddress("jet2_Fake_Phi", &jet2Phi_Fake);
  tree->SetBranchAddress("jet2_Fake_E", &jet2E_Fake);


  const int nbinsx=6;
  double bins_mzz[nbinsx+1]={70, 140, 190, 240, 340, 520, 20000};
  double sum_w[nbinsx]={ 0 };
  double sum_mzz[nbinsx][2]={ { 0 } };
  const int nbins_eta = 8;
  double bins_eta[nbins_eta+1]={ 0, 0.75, 1.5, 2.25, 3, 4, 5.5, 10.5, 12 };

  TProfile* hProb[nbinsx];
  TH1D* hProb_all;
  TProfile* hEta[nbinsx+1];
  TH1D* hDist[nbinsx+1];
  for (int bin=0; bin<nbinsx+1; bin++){
    if (bin<nbinsx) hProb[bin] = new TProfile(Form("njets1_pjvbf_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hProb_all = new TH1D("njets1_pjvbf_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hEta[bin] = new TProfile(Form("njets1_eta_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hEta[bin] = new TProfile("njets1_eta_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hDist[bin] = new TH1D(Form("njets1_dist_bin_%i", bin+1), Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[bin], bins_mzz[bin+1]), nbins_eta, bins_eta);
    else hDist[bin] = new TH1D("njets1_dist_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]), nbins_eta, bins_eta);
    if (bin<nbinsx) hProb[bin]->Sumw2();
    else hProb_all->Sumw2();
    hEta[bin]->Sumw2();
    hDist[bin]->Sumw2();
  }

  int nEntries = tree->GetEntries();
  cout << nEntries << endl;
  for (int ev = 0; ev < nEntries; ev++){
    tree->GetEntry(ev);

    int massbin=-1;
    for (int bin=0; bin<nbinsx; bin++){
      if (ZZMass>=bins_mzz[bin] && ZZMass<bins_mzz[bin+1]){
        massbin=bin;
      }
    }
    if (NJets30==1){
      hProb[massbin]->Fill(fabs(jet2Eta_Fake), pjvbf_VAJHU_second, MC_weight_noxsec);
      hEta[massbin]->Fill(fabs(jet2Eta_Fake), fabs(jet2Eta_Fake), MC_weight_noxsec);
      hDist[massbin]->Fill(fabs(jet2Eta_Fake), MC_weight_noxsec);

      hEta[nbinsx]->Fill(fabs(jet2Eta_Fake), fabs(jet2Eta_Fake), MC_weight_noxsec);
      hDist[nbinsx]->Fill(fabs(jet2Eta_Fake), MC_weight_noxsec);
    }
  }

  for (int bin=0; bin<nbinsx; bin++){
    hProb[bin]->Scale(1./hProb[bin]->Integral("width"));
  }
  for (int bin=0; bin<nbinsx+1; bin++){
    for (int bineta=1; bineta<=nbins_eta; bineta++){
      double bincontent = hDist[bin]->GetBinContent(bineta);
      double binerror = hDist[bin]->GetBinError(bineta);
      double binwidth = hDist[bin]->GetXaxis()->GetBinWidth(bineta);

      bincontent /= binwidth;
      binerror /= binwidth;

      hDist[bin]->SetBinContent(bineta, bincontent);
      hDist[bin]->SetBinError(bineta, binerror);
    }
    hDist[bin]->Scale(1./hDist[bin]->Integral("width"));
  }
  for (int bineta=1; bineta<=nbins_eta; bineta++){
    double sum_invwsq=0;
    double sum_prob_invwsq=0;
    for (int bin=0; bin<nbinsx; bin++){
      double bincontent = hProb[bin]->GetBinContent(bineta);
      double binerror = hProb[bin]->GetBinError(bineta);

      double invwsq = 0, prob_invwsq = 0;
      if (binerror!=0){
        invwsq = 1./pow(binerror, 2);
        prob_invwsq = bincontent*invwsq;
      }
      sum_invwsq += invwsq;
      sum_prob_invwsq += prob_invwsq;
    }

    if (sum_invwsq>0){
      sum_prob_invwsq /= sum_invwsq;
      sum_invwsq = 1./sqrt(sum_invwsq);
    }
    hProb_all->SetBinContent(bineta, sum_prob_invwsq);
    hProb_all->SetBinError(bineta, sum_invwsq);
  }
  hProb_all->Scale(1./hProb_all->Integral("width"));


  double eta_center_all[nbins_eta];
  double prob_center_all[nbins_eta];
  double eta_center_all_err[nbins_eta];
  double prob_center_all_err[nbins_eta];
  int nNonEmpty_all = 0;
  for (int bineta=1; bineta<=nbins_eta; bineta++){
    if (hProb_all->GetBinError(bineta)>0){
      eta_center_all[nNonEmpty_all] = hEta[nbinsx]->GetBinContent(bineta);
      eta_center_all_err[nNonEmpty_all] = hEta[nbinsx]->GetBinError(bineta);
      prob_center_all[nNonEmpty_all] = hProb_all->GetBinContent(bineta);
      prob_center_all_err[nNonEmpty_all] = hProb_all->GetBinError(bineta);
      cout << nNonEmpty_all << '\t' << prob_center_all[nNonEmpty_all] << '\t' << prob_center_all_err[nNonEmpty_all] << endl;
      nNonEmpty_all++;
    }
  }

  TGraphErrors* tg_all = new TGraphErrors(nNonEmpty_all, eta_center_all, prob_center_all, eta_center_all_err, prob_center_all_err);
  tg_all->SetNameTitle("tg_njets1_pjvbf_all", Form("m_{4l}: [%.0f, %.0f] GeV", bins_mzz[0], bins_mzz[nbinsx]));
  tg_all->GetXaxis()->SetTitle("#eta");
  tg_all->GetYaxis()->SetTitle("<P_{VBF}>");
  
  TF1* fit_tg_all = new TF1("fit_tg_njets1_pjvbf_all", "gaus*(1+gaus(3))", bins_eta[0], bins_eta[nbins_eta]);
  const int npars = 6;
  double mypars[npars]={ 0.155, 5.193, 1.46, 0.362, 3.524, 0.715 };
  fit_tg_all->SetParameters(mypars);
  fit_tg_all->SetParLimits(0, 0, 1);
  fit_tg_all->SetParLimits(3, 0, 1);
  fit_tg_all->SetParLimits(1, 0, 20);
  fit_tg_all->SetParLimits(4, 0, 20);
  fit_tg_all->SetParLimits(2, 0, 20);
  fit_tg_all->SetParLimits(5, 0, 20);
  tg_all->Fit(fit_tg_all);

  double* par_postfit = fit_tg_all->GetParameters();
  double* parerr_postfit = fit_tg_all->GetParErrors();
  double parIndex[npars];
  double parIndexErr[npars]={ 0 };
  for (int ip=0; ip<npars; ip++) parIndex[ip] = (double)ip;

  double integral = 0.5*par_postfit[0]*(1.+TMath::Erf(par_postfit[1]/par_postfit[2]/TMath::Sqrt(2)));
  double integral2 = 1./(2.*TMath::Sqrt(2.*TMath::Pi()*(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2))));
  integral2 *= par_postfit[0]*par_postfit[3]*TMath::Exp(-0.5*pow(par_postfit[1]-par_postfit[4], 2)/(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2)))*
    (1.+TMath::Erf((TMath::Power(par_postfit[2], 2)*par_postfit[4]+TMath::Power(par_postfit[5], 2)*par_postfit[1]) / (par_postfit[2]*par_postfit[5]*TMath::Sqrt(2.*(TMath::Power(par_postfit[2], 2)+TMath::Power(par_postfit[5], 2))))));
  integral += integral2;

  cout << integral << endl;
  par_postfit[0] /= integral;
  parerr_postfit[0] /= integral;

  TGraphErrors* tg_pars = new TGraphErrors(npars, parIndex, par_postfit, parIndexErr, parerr_postfit);
  tg_pars->SetNameTitle("njets1_pjvbf_pars", "gaus*(1+gaus(3))");
  tg_pars->GetXaxis()->SetTitle("Parameter index");
  tg_pars->GetYaxis()->SetTitle("Parameter");
  foutput->WriteTObject(tg_pars);
  delete tg_pars;

  foutput->WriteTObject(tg_all);
  delete tg_all;

  for (int bin=0; bin<nbinsx+1; bin++){
    if (bin<nbinsx) foutput->WriteTObject(hProb[bin]);
    else foutput->WriteTObject(hProb_all);
    foutput->WriteTObject(hEta[bin]);
    foutput->WriteTObject(hDist[bin]);
    delete hDist[bin];
    delete hEta[bin];
    if (bin<nbinsx) delete hProb[bin];
    else delete hProb_all;
  }
  delete tree;

  foutput->Close();
}
Example #9
0
int EffAndCross(char* name)
{
 
  char line[1000];
  TFile *file = new TFile("cross.root","recreate");


  ifstream inbescross("cross.txt_665p01");
  double xbes[22];
  double xebes[22];
  double ybes[22];
  double yebes[22];
  inbescross.getline(line,1000);
  int idbes=0;
  while (!inbescross.eof() && idbes<21){
    double tmpe, tmpeff, tmpcross, tmpcrosse, tmp;
    inbescross >> tmpe >> tmp >> tmp>> tmpeff >> tmp >> tmp >> tmpcross >> tmpcrosse >> tmp >> tmp >> tmp ;
    xbes[idbes] = tmpe;
    xebes[idbes] = 0;
    ybes[idbes] = tmpcross;
    yebes[idbes] = tmpcrosse;
    idbes++;
  }

  TGraphErrors *gbes = new TGraphErrors(idbes,xbes,ybes,xebes,yebes);
  gbes->SetLineColor(2);
  gbes->SetMarkerColor(2);
  gbes->SetFillColor(0);
  //gbes->Draw("P");








  double xx[1000];
  double xxe[1000];
  double yy[1000];
  double yye[1000];
  double emat[1000][1000];

  int n2=0;
  ifstream infile2("KKBabar.txt");
  if (!infile2.is_open()) return -100;
  while (!infile2.eof())
  { 
    double energy1, energy2;
    double obs, obse;

    infile2.getline(line,1000);
    istringstream iss;
    iss.str(line);
  //if (iss.peek()<48 || iss.peek()>57) // not a number
  //{
  //  continue;  
  //}
    //else 
    {
      char a;
      iss >> energy1 >> a >> energy2;
      iss >> obs >> obse;
    }
    //std::cout<<"E1: "<< energy1 << "\tE2: "<< energy2 << "\tsigma: "<< obs <<"\terr: "<<obse<<std::endl;

    xx[n2] = (energy2+energy1)/2.;
    xxe[n2] = (energy2-energy1)/2.;
    yy[n2] = obs;
    yye[n2] = 0;
    n2 ++;
  }

  ifstream infile3("epapsFileKpKm.txt");
  if (!infile3.is_open()) return -200;
  int xid=0,yid=0;
  while(!infile3.eof())
  {
    infile3.getline(line,1000);
    istringstream iss;
    iss.str(line);
    if ((iss.peek()<48 || iss.peek()>57) && iss.peek()!='-') // not a number
    {
      continue;  
     }
    iss >> emat[xid][yid];
    yid++;
     if (yid==159){
      xid++;
      yid=0;
    }
    if (xid==159) break;
  }
  //std::cout<<"xid: "<<xid<<"\tyid: "<<yid<<std::endl;
  for (int i=0; i<159;i++)
  {
    yye[i] = sqrt(emat[i][i]);
  }

  //---------------------------
  //add bes result
  for (int i=0;i<21;i++){
    xx[n2] = xbes[i];
    xxe[n2] = 0.001;
    yy[n2] = ybes[i];
    yye[n2] = yebes[i];
    n2 ++; 
  }
  //----------------------------

  TCanvas *c2 = new TCanvas();
  TGraphErrors *graph1 = new TGraphErrors(n2,xx,yy,xxe,yye);
  graph1->GetXaxis()->SetTitle("#sqrt{s} (GeV)");
  graph1->GetYaxis()->SetTitle("#sigma (nb)");
  graph1->SetTitle("Cross section");
  //graph1->SetMarkerStyle(5);
  graph1->SetFillColor(0);
  graph1->Draw("AP");

  ofstream fitxs("fitxsbabar.txt");
  double gap = 0.01;
  TF1 *fit;
  for (int i=0; xx[i]<1.1-0.0000001;i++){
    double xs = yy[i];
    //fitxs<<xx[i]<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << xx[i] << ");\tyy.push_back("<< yy[i] << ");\t er.push_back(0);" <<endl;
  }
 
//fit = new TF1("f0","[0]/(pow(x-[1],2)+pow([2],2))",0.99,1.05);
//fit->SetParameter(0,1.0);
//fit->SetParameter(1,1.02);
//fit->SetParameter(2,0.005);
//graph1->Fit(fit,"R","",0.99,1.05);
//for (double x=0.99; x<1.05-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}


  fit = new TF1("f1","pol2",1.1,1.6);
  graph1->Fit(fit,"R+","",1.1,1.6);
  for (double x=1.1; x<1.6-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }
  
  fit = new TF1("f2","pol2",1.6,1.76);
  graph1->Fit(fit,"R+","",1.6,1.779);
  for (double x=1.6; x<1.779-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }
  
//fit = new TF1("f3","pol2",1.8,2.16);
//graph1->Fit(fit,"R+","",1.8,2.16);
//for (double x=1.8; x<2.16-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
  
  
//
//fit = new TF1("f4","gaus",2.16,2.35);
//graph1->Fit(fit,"R+","",2.16,2.4);
//for (double x=2.16; x<2.4-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
//
//fit = new TF1("f5","expo",2.35,5);
//graph1->Fit(fit,"R+","",2.4,5);
//for (double x=2.4; x<5-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
  
//fit = new TF1("f4",GausInvx,2.,5,6);
//fit->SetNpx(1000);
//fit->SetParameters(1,2.25,0.05,0.03,1.8,1.5);
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.05);
//fit->SetParLimits(3, 0.02,  10);
//fit->SetParLimits(4, 1.5,    2);
//fit->SetParLimits(5, 1,    2);
  
//fit = new TF1("f4",DGausInvx,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.03,  1.8,  5,
//                   0.1,   2.0,  0.05);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.3);
//fit->SetParLimits(2, 0.03, 0.05);
//
//fit->SetParLimits(3, 0.02, 10);
//fit->SetParLimits(4, -1,    2);
//fit->SetParLimits(5, 5,    20);
//
//fit->SetParLimits(6, 0.1,  0.2);
//fit->SetParLimits(7, 1.9,  2.05);
//fit->SetParLimits(8, 0.04, 0.08);
//graph1->Fit(fit,"R+","",1.8,5);

//fit = new TF1("f4",DGausExp,2.,5,8);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.052);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  9);
//fit->SetParLimits(7, 0,    1.8);
//
//graph1->Fit(fit,"R+","",1.75,5);
 
//fit = new TF1("f4",TGaus,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8,  1.0);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.052);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  90);
////fit->SetParLimits(7, -10,    2);
//fit->SetParLimits(7, -10,    2.4);
//fit->SetParLimits(8, 0.2,    2);
  
//fit = new TF1("f4",DGausAExp,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.5,   2.2,  30,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8,  1.0);
//
//fit->SetParLimits(0, 0.1,  100);
//fit->SetParLimits(1, 2.1,  2.3);
//fit->SetParLimits(2, 10,   60);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  90);
//fit->SetParLimits(7, -10,    2.4);
//fit->SetParLimits(8, 0.2,    2);
 
  fit = new TF1("f4",AGausDExp,2.,5,9);
  fit->SetNpx(1000);
  fit->SetParameters(50,   2.2,  30,
                     0.1,  2.0,  0.06,
                     0.1,  2.2,  1.8);
  
  fit->SetParLimits(0, 0.1,  100);
  fit->SetParLimits(1, 2.1,  2.3);
  fit->SetParLimits(2, 10,   60);
  
  fit->SetParLimits(3, 0.1,  1.0);
  fit->SetParLimits(4, 1.9,    2.1);
  fit->SetParLimits(5, 0.06,   0.1);
  
  fit->SetParLimits(6, 0.02,  90);
  fit->SetParLimits(7, -10,    2.4);
  fit->SetParLimits(8, 0.2,    2);
  
  graph1->Fit(fit,"R+","",1.77,5);



  for (double x=1.77; x<5-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }

  gbes->Draw("P");


  file->WriteTObject(c2);
  graph1->GetXaxis()->SetRangeUser(1.6,3.5);
  graph1->GetYaxis()->SetRangeUser(0,0.5);
  c2->Print("cross.pdf");

  return 0;
}
void compareplots_noRatio(){
  vector<TFile*> files; 
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/ttbarMergedFxFx8TeVCTEQ6M-extracted.root"));
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_30/ttbarMergedFxFxMS30GeVMECut10GeV8TeVCTEQ6M-extracted.root"));   
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbarMergedMS100GeV8TeVCTEQ6M-extracted.root"));   
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbarMergedMS100GeVMCCut50GeV8TeVCTEQ6M-extracted.root"));   
  


  
  vector<TString> names;
  names.push_back("ttbar +0/1 Jet, #mu_{Q}=10 GeV #mu_{ME} = 10 GeV");
  names.push_back("ttbar +0/1 Jet, #mu_{Q}=30 GeV #mu_{ME} = 10 GeV");
  names.push_back("ttbar +0/1 Jet, #mu_{Q}=100 GeV #mu_{ME} = 10 GeV");
  names.push_back("ttbar +0/1 Jet, #mu_{Q}=100 GeV #mu_{ME} = 50 GeV");
  
  
  vector<TString> titles;
  titles.push_back("Gen-Jet p_{T}  with pos weights (GeV)");
  titles.push_back("Gen-Jet p_{T} with neg weights (GeV)");
  titles.push_back("Gen-Jet p_{T} (GeV)");
  titles.push_back("Gen_Jet #phi with pos. weights");
  titles.push_back("Gen_Jet #phi with neg. weights");
  titles.push_back("Gen_Jet #phi");
  titles.push_back("Gen Jet #theta with pos weights");
  titles.push_back("Gen Jet #theta with neg weights");
  titles.push_back("Gen Jet #theta");
  titles.push_back("Gen Jet Energy with pos weights (GeV) ");
  titles.push_back("Gen Jet Energy with neg weights (GeV)");
  titles.push_back("Gen Jet Energy (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet with pos weights (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet with neg weights (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet with pos weights (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet with neg weights (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet (GeV)");
  titles.push_back("#eta of hardest Gen-Jets with pos weights");
  titles.push_back("#eta of hardest Gen-Jets with neg weights");
  titles.push_back("#eta of hardest Gen-Jets");
  titles.push_back("Number of Gen-Jets with pos. weights");
  titles.push_back("Number of Gen-Jets with neg. weights");
  titles.push_back("Number of Gen-Jets");

  TFile *vergleich = new TFile("vergleich_ttbar_0Jet.root","RECREATE");

// Show no statistics box
gStyle->SetOptStat(0);

TH1::SetDefaultSumw2();

// Main program part
  TIter nextkey(files.at(0)->GetListOfKeys());
  TKey *key;
  bool first=true;
  TCanvas* c = new TCanvas();
  c->Print("plots.pdf[");

  // Save also as pictures
  int pictureNumber = 0;

  int run = 0;
  while (key = (TKey*)nextkey()) {
    pictureNumber++;
    TString pictureName = TString::Format("%d.png",pictureNumber);


    vector<TH1F*> histos;
    histos.push_back((TH1F*)key->ReadObj());
    for(size_t i=1;i<files.size();i++){
      histos.push_back((TH1F*)files.at(i)->Get(histos.at(0)->GetName()));
    }
		       
    for(size_t i=0;i<histos.size();i++){
      if(i == 0){
	histos.at(i)->SetLineColor(kBlack);
      }
      if(i == 1){
	histos.at(i)->SetLineColor(kRed);
      }
      if(i == 2){
	histos.at(i)->SetLineColor(kBlue);
      }
      if(i == 3){
	histos.at(i)->SetLineColor(kGreen+2);
      }
      if(i == 4){
	histos.at(i)->SetLineColor(kMagenta-7);
      }
      if(i == 5){
	histos.at(i)->SetLineColor(kOrange+7);
      }
    }
   
    for(size_t i=0;i<histos.size();i++){
      histos.at(i)->Sumw2();
      histos.at(i)->Scale(1./histos.at(i)->Integral(),"width");
    }

// Set axis title
histos.at(0)->GetYaxis()->SetTitle("Normalized units"); 
std::string const histogramName = histos.at(1)->GetName();
histos.at(0)->GetXaxis()->SetLabelSize(0.05);
histos.at(0)->GetXaxis()->SetLabelOffset(0.006);
histos.at(0)->GetYaxis()->SetLabelSize(0.05);
histos.at(0)->GetYaxis()->SetLabelOffset(0.006);
histos.at(0)->GetXaxis()->SetTitleSize(0.06);
histos.at(0)->GetXaxis()->SetTitleOffset(1.1);
histos.at(0)->GetYaxis()->SetTitleSize(0.06);
histos.at(0)->GetYaxis()->SetTitleOffset(1.15);
	

 histos.at(0)->GetXaxis()->SetTitle(titles.at(run));
 run = run+1;
 if(run == (3*8)){
   run = 0;
 }

// If only two histograms per plot make a ratio plot
if(histos.size() == 2)
{

//create main pad  
                                                                                                                                                          
           TPad *mainPad = new TPad("","",0.0,0.0,1.0,1.0);
           mainPad->SetNumber(1);
           mainPad->SetBottomMargin(0.15);
           mainPad->SetRightMargin(0.04);
	   mainPad->SetLeftMargin(0.13);
           mainPad->Draw();
	   gStyle->SetOptTitle(0);
           //create ratio pad                                                                                                                                                           
           /*TPad *ratioPad = new TPad("","",0.0,0.0,1.0,0.3);
           ratioPad->SetTopMargin(0.0);
           ratioPad->SetBottomMargin(0.4);
           ratioPad->SetLeftMargin(0.13);                                                                                                                                             
           ratioPad->SetRightMargin(0.04);
           gStyle->SetOptTitle(0);
           ratioPad->SetFillColor(0);
           ratioPad->SetNumber(2);
           ratioPad->SetGridy();                                                                                                                                                      
           ratioPad->Draw();*/

// Draw both histograms first
c->cd(1);

histos.at(0)->Draw("histo E");
histos.at(1)->Draw("histo same E");

// Show legend and statistical tests in first pad
    for(size_t i=0;i<histos.size()-1;i=i+2){

      double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1));
      ksresult=floor(ksresult*1000+0.5)/1000;
      double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW");
      chi2result=floor(chi2result*1000+0.5)/1000;

      stringstream ss;
      //ss << "     KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result << " Private Work"; 
      ss << "            Private Work";
      const char * ch = & ss.str().c_str();;
      TLatex * ks = new TLatex(0.1, 0.9-0.03*i, ch );
      ks->SetTextColor(histos.at(i)->GetLineColor());
      ks->SetNDC();
      ks->Draw("");      

    }

    TLegend* l = new TLegend(0.40,0.9,0.69,0.99);
    // Options for legend
    l->SetBorderSize(0);
    l->SetLineStyle(0);
    l->SetTextSize(0.049);
    l->SetFillStyle(0);
    for(size_t i=0;i<names.size();i++){
      l->AddEntry(histos.at(i),names.at(i),"L");
    }
    l->Draw("same");

/*
// Clone histograms and draw ratio plot
c->cd(2);
 TH1F* ratioHisto = (TH1F*)histos.at(0)->Clone();
ratioHisto->Divide(histos.at(1));
ratioHisto->SetLineColor(kBlue);
ratioHisto->SetStats(false);
ratioHisto->GetYaxis()->SetTitle("Ratio #frac{noFxFx}{FxFx}");
// Same Size like in histogram
ratioHisto->SetLabelSize(histos.at(0)->GetLabelSize() * 0.7 / 0.3);
ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("Y") * 0.3 / 0.7), "Y");
ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("Y") * 0.7 / 0.3), "Y");
ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("X")), "X");
ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("X") * 0.7 / 0.3), "X");
// Use nicer range
ratioHisto->GetYaxis()->SetRangeUser(0, 2.2);
ratioHisto->GetYaxis()->SetNdivisions(503);
ratioHisto->GetYaxis()->SetLabelSize(0.06 * 0.7 / 0.3);
ratioHisto->Draw();*/
}
else
{
        TPad *mainPad = new TPad("","",0.0,0.0,1.0,1.0);
        mainPad->SetNumber(1);
        mainPad->SetBottomMargin(0.15);
        mainPad->SetRightMargin(0.04);
        mainPad->SetLeftMargin(0.13);
        mainPad->Draw();
        gStyle->SetOptTitle(0);
        //mainPad->SetLogx(1);
	c->cd(1);

    histos.at(0)->Draw("histo E");
    for(size_t i=0;i<histos.size();i++){
      histos.at(i)->Draw("histo same E");
    }


    for(size_t i=0;i<histos.size()-1;i=i+2){
      /*
      double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1));
      ksresult=floor(ksresult*1000+0.5)/1000;
      double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW");
      chi2result=floor(chi2result*1000+0.5)/1000;

      stringstream ss;
      ss << "KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result; 
      const char * ch = & ss.str().c_str();;
      TText * ks = new TText(0.1, 0.9-0.03*i, ch );
      ks->SetTextColor(histos.at(i)->GetLineColor());
      ks->SetNDC();
      ks->Draw("");      
      */
    }

    TLegend* l = new TLegend(0.65,0.5,0.9,0.7);
    l->SetBorderSize(0);
    l->SetLineStyle(0);
    //    l->SetTextSize(0.039);
    l->SetFillStyle(0);
    for(size_t i=0;i<names.size();i++){
      l->AddEntry(histos.at(i),names.at(i),"L");
    }
    l->Draw("same");
}

    c->Print("plots.pdf");
    c->SaveAs(pictureName);
    vergleich->WriteTObject(c);

}
  c->Print("plots.pdf]");


}
void buildPlotAxial_DD(){

	TH2F *dummyHist = new TH2F("dum","",1,1,900,1,6E-43,1E-37);
	dummyHist->GetYaxis()->SetTitle("#sigma_{SD} (cm^{2})");
	dummyHist->GetXaxis()->SetTitle("m_{DM} (GeV)");
	dummyHist->GetYaxis()->SetTitleOffset(1.5);
	dummyHist->GetYaxis()->SetTitleSize(0.046);
	dummyHist->GetXaxis()->SetTitleSize(0.046);
	dummyHist->GetYaxis()->SetTitleOffset(1.5);
	dummyHist->GetXaxis()->SetTitleOffset(1.25);
	dummyHist->GetYaxis()->SetTitleSize(0.045);
	dummyHist->GetXaxis()->SetTitleSize(0.045);
	dummyHist->GetYaxis()->SetLabelSize(0.04);
	dummyHist->GetXaxis()->SetLabelSize(0.04);


	gROOT->ProcessLine(".x paperStyle.C"); 
	gStyle->SetOptStat(0);
	gStyle->SetPalette(51);
	
	TFile *fiDD = TFile::Open("MassLimit_1_801_0_Both_updatePICO.root");
	TGraph *DDF = (TGraph*)fiDD->Get("DD");

	TFile *fi = TFile::Open("MassLimit_1_801_0_Both.root");

	TCanvas *can = new TCanvas();
	dummyHist->Draw("AXIS");
	
	TGraph *combinedD 	= makeOBV(combined_obs); combinedD->SetLineColor(1); combinedD->SetName("EXP");
	TGraph *combined_obsD 	= makeOBV(combined); combined_obsD->SetLineColor(1);combined_obsD->SetName("OBS");
	TGraph *monojetD 	= makeOBV(monojet); monojetD->SetLineColor(kBlue); monojetD->SetName("mjet");
	// Phil swapped boosted and resolved
	TGraph *boostedD 	= makeOBV(resolved); boostedD->SetLineColor(kMagenta); boostedD->SetName("bjet");
	TGraph *resolvedD 	= makeOBV(boosted); resolvedD->SetLineColor(kGreen); resolvedD->SetName("rjet");
	TGraph *monovD 		= makeOBV(monov); monovD->SetLineColor(kRed); monovD->SetName("MV");

	/* other lines */
	combinedD->Draw("lsame"); 
	combined_obsD->Draw("lsame"); 
	monojetD->Draw("lsame"); 
	boostedD->Draw("lsame"); 
	resolvedD->Draw("lsame"); 
	monovD->Draw("lsame"); 
	DDF->Draw("lsame");
	

	TLegend *leg = new TLegend(0.19,0.40,0.51,0.63,NULL,"brNDC");
	leg->SetFillStyle(0);
	leg->AddEntry(combinedD,"Median Expected","L");
	leg->AddEntry(combined_obsD,"Observed","L");
	leg->AddEntry(monojetD,"Monojet","L");
	leg->AddEntry(boostedD,"Boosted","L");
	leg->AddEntry(resolvedD,"Resolved","L");
	leg->AddEntry(monovD,"V-tagged","L");
	leg->AddEntry(DDF,"PICO-2L","L");
	leg->Draw();
	
   	TLatex *   texCMS = new TLatex(0.20,0.84,"#bf{CMS}");
	//TLegend *WHITEBOX = new TLegend(0.18,0.83,0.3,0.89);
   	//TLatex *   texCMS = new TLatex(0.20,0.84,"#bf{CMS}#it{Preliminary}");
	TLegend *WHITEBOX = new TLegend(0.18,0.83,0.42,0.89);
	WHITEBOX->SetFillColor(kWhite);
	//WHITEBOX->Draw();
	texCMS->SetNDC();
   	texCMS->SetTextFont(42);
   	texCMS->SetLineWidth(2);
   	texCMS->SetTextSize(0.042); texCMS->Draw();
	//tex->SetFillColor(kWhite);
	TLatex * tex = new TLatex();
	tex->SetNDC();
   	tex->SetTextFont(42);
   	tex->SetLineWidth(2);
   	tex->SetTextSize(0.035);
	tex->Draw();
   	tex->DrawLatex(0.69,0.94,"19.7 fb^{-1} (8 TeV)");
   	tex->DrawLatex(0.20,0.8,"g_{DM}=g_{SM}=1");
   	tex->DrawLatex(0.20,0.7,"Axial");
	
	can->SetRightMargin(0.11);
	can->SetLogx();
	can->SetLogy();
	can->RedrawAxis();	

	can->SaveAs("MassLimit_1_801_0_Both_DD.pdf");
	
        TFile *rout = new TFile("axialDD_out.root","RECREATE");
        rout->WriteTObject(combined_obsD,"combined");
        rout->WriteTObject(combinedD,"combined_expected"); 
        rout->WriteTObject(DDF,"DD_mass");
	rout->Close();
	
/*
 KEY: TCanvas	A;1	A
  KEY: TGraph	DD_mass;1	DD_mass
  KEY: TGraph	DD;1	DD
  KEY: TGraph	monojet;1	monojet
  KEY: TGraph	resolved;1	resolved
  KEY: TGraph	boosted;1	boosted
  KEY: TGraph	monov;1	monov
  KEY: TGraph	combined;1	combined
  KEY: TGraph	combinedUp;1	combinedUp
  KEY: TGraph	combinedDown;1	combinedDown
  KEY: TGraph	monojet_obs;1	monojet_obs
  KEY: TGraph	resolved_obs;1	resolved_obs
  KEY: TGraph	boosted_obs;1	boosted_obs
  KEY: TGraph	monov_obs;1	monov_obs
  KEY: TGraph	combined_obs;1	combined_obs
  KEY: TGraph2D	2D;1	2D	
*/	

}
void plot_BSM_MCFM(int SignalOnly=0){
  gROOT->ProcessLine(".x tdrstyle.cc");
  double mPOLE = 125.6;

  TString OUTPUT_NAME;
  OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMPlots";
  if (SignalOnly==0) OUTPUT_NAME.Append(".root");
  else OUTPUT_NAME.Append("_SignalOnly.root");
  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/Plots/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  foutput->cd();

  float ZZMass = 0;
  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;
  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TChain* tc[2][3][4];
  TH1F* hfill[4][9];
  int nbinsx = 73;
  double xlimits[2]={ 160, 1620 };
  if (SignalOnly==1){
    xlimits[0]=100;
    nbinsx = 76;
  }
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      hfill[t][ac]= new TH1F(Form("hSum_BSI%i_Hypo%i", t, ac), "", nbinsx, xlimits[0], xlimits[1]);
      hfill[t][ac]->SetXTitle("m_{4l} (GeV)");
      hfill[t][ac]->SetYTitle(Form("Events / %.0f GeV", (xlimits[1]-xlimits[0])/nbinsx));
    }
  }
  double nCounted[2][3][9]={ { { 0 } } };
  double nCountedScaled[2][3][9]={ { { 0 } } };
  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%iTeV", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);

      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/";
      cinput_common.Append(+erg_dir);
      cinput_common += user_folder[folder] + "/";
      cout << cinput_common << endl;
      for (int t=0; t<4; t++){
        TString INPUT_NAME;
        INPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
        INPUT_NAME += sample_suffix[t] + ".root";
        INPUT_NAME.Prepend(cinput_common);

        tc[EnergyIndex][folder][t] = new TChain("GenTree");
        if (t!=3) tc[EnergyIndex][folder][t]->Add(INPUT_NAME);
        tc[EnergyIndex][folder][t]->SetBranchAddress("ZZMass", &ZZMass);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0plus_VAJHU", &p0plus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0hplus_VAJHU", &p0hplus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0minus_VAJHU", &p0minus_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g2_VAJHU", &pg1g2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g4_VAJHU", &pg1g4_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
        tc[EnergyIndex][folder][t]->SetBranchAddress("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);
      }

      double nsig_counted[9] ={ 0 };
      for (int ev=0; ev<tc[EnergyIndex][folder][0]->GetEntries(); ev++){
        tc[EnergyIndex][folder][0]->GetEntry(ev);
        if (fabs(ZZMass-mPOLE)<0.1){
          nsig_counted[0] += p0plus_VAJHU;
          nsig_counted[1] += p0hplus_VAJHU;
          nsig_counted[2] += p0minus_VAJHU;
          nsig_counted[3] += p0_g1prime2_VAJHU;
          nsig_counted[4] += p0_g1prime4_VAJHU;
          nsig_counted[5] += (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU);
          nsig_counted[6] += pg1g4_VAJHU;
          nsig_counted[7] += pg1g1prime2_VAJHU;
          nsig_counted[8] += pg1g1prime4_VAJHU;
        }
      }

      for (int ac=0; ac<9; ac++) nCounted[EnergyIndex][folder][ac] = nsig_counted[ac];

    }
  }


  for (int erg_tev=7; erg_tev<9; erg_tev++){
    for (int folder=0; folder<3; folder++){
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;

      double nsig_SM = nSM_ScaledPeak[EnergyIndex][folder];
      double SMscale = nsig_SM/nCounted[EnergyIndex][folder][0];
      double scale=1;
      for (int t=0; t<4; t++){
        for (int ev=0; ev<tc[EnergyIndex][folder][t]->GetEntries(); ev++){
          tc[EnergyIndex][folder][t]->GetEntry(ev);
          if (ZZMass<xlimits[0]) continue;
          if (ZZMass>=xlimits[1]) ZZMass=xlimits[1]*0.999;

          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][0] = nCounted[EnergyIndex][folder][0]*scale;
          hfill[t][0]->Fill(ZZMass, p0plus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][1] = nCounted[EnergyIndex][folder][1]*scale;
          hfill[t][1]->Fill(ZZMass, p0hplus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][2] = nCounted[EnergyIndex][folder][2]*scale;
          hfill[t][2]->Fill(ZZMass, p0minus_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][3] = nCounted[EnergyIndex][folder][3]*scale;
          hfill[t][3]->Fill(ZZMass, p0_g1prime2_VAJHU*scale);
          scale = SMscale;
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][4] = nCounted[EnergyIndex][folder][4]*scale;
          hfill[t][4]->Fill(ZZMass, p0_g1prime4_VAJHU*scale);
          scale = SMscale;
          if (t>0){
            hfill[t][5]->Fill(ZZMass, pg1g2_VAJHU*scale);
          }
          else{
            scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][5]+nCounted[1][2][5]);
            hfill[t][5]->Fill(ZZMass, (2.*(p0plus_VAJHU+p0hplus_VAJHU)-pg1g2_VAJHU)*scale);
          }
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][5] = nCounted[EnergyIndex][folder][5]*scale;
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][6]+nCounted[1][2][6]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][6] = nCounted[EnergyIndex][folder][6]*scale;
          hfill[t][6]->Fill(ZZMass, pg1g4_VAJHU*scale);
          scale = SMscale;
          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][7]+nCounted[1][2][7]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][7] = nCounted[EnergyIndex][folder][7]*scale;
          hfill[t][7]->Fill(ZZMass, pg1g1prime2_VAJHU*scale);
          scale = SMscale;
          //          if (t==0) scale *= (nCounted[0][2][0]+nCounted[1][2][0])/(nCounted[0][2][8]+nCounted[1][2][8]);
          if (t==0 && ev==0) nCountedScaled[EnergyIndex][folder][8] = nCounted[EnergyIndex][folder][8]*scale;
          hfill[t][8]->Fill(ZZMass, pg1g1prime4_VAJHU*scale);
        }
        delete tc[EnergyIndex][folder][t];
      }
    }
  }
  for (int ac=1; ac<9; ac++){
    double nTotal[2]={ 0 };
    for (int erg_tev=7; erg_tev<9; erg_tev++){
      for (int folder=0; folder<3; folder++){
        int EnergyIndex = 1;
        if (erg_tev == 7) EnergyIndex = 0;

        nTotal[0] += nCountedScaled[EnergyIndex][folder][0];
        nTotal[1] += nCountedScaled[EnergyIndex][folder][ac];
      }
    }
    if (ac!=8) hfill[0][ac]->Scale(nTotal[0]/nTotal[1]);
    else hfill[0][ac]->Scale(0.5);
  }


  double maxplot=0;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<9; ac++){
      if (SignalOnly==0 && ac<5) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      else if (SignalOnly==1 && !(ac<5 && ac>0) && t==0) maxplot = max(maxplot, hfill[t][ac]->GetMaximum());
      hfill[t][ac]->SetLineWidth(2);
      if (t==0 && ac>=5){
        hfill[t][ac]->SetLineStyle(7);
        //        hfill[t][ac]->Add(hfill[1][ac]);
      }
      if (t==1) hfill[t][ac]->SetLineStyle(3);
      if (t==3) hfill[t][ac]->SetLineStyle(9);
      hfill[t][ac]->GetXaxis()->SetLabelFont(42);
      hfill[t][ac]->GetXaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetXaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetXaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetXaxis()->SetTitleOffset(0.9);
      hfill[t][ac]->GetXaxis()->SetTitleFont(42);
      hfill[t][ac]->GetYaxis()->SetNdivisions(505);
      hfill[t][ac]->GetYaxis()->SetLabelFont(42);
      hfill[t][ac]->GetYaxis()->SetLabelOffset(0.007);
      hfill[t][ac]->GetYaxis()->SetLabelSize(0.04);
      hfill[t][ac]->GetYaxis()->SetTitleSize(0.06);
      hfill[t][ac]->GetYaxis()->SetTitleOffset(1.1);
      hfill[t][ac]->GetYaxis()->SetTitleFont(42);
    }
  }

  TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
  pt->SetBorderSize(0);
  pt->SetFillStyle(0);
  pt->SetTextAlign(12);
  pt->SetTextFont(42);
  pt->SetTextSize(0.045);
  TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
  text->SetTextSize(0.044);
  text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
  text->SetTextSize(0.0315);
  TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
  text = pt->AddText(0.537, 0.45, cErgTev);
  text->SetTextSize(0.0315);

  float lxmin = 0.22;
  float lxwidth = 0.38;
  float lymax = 0.9;
  float lywidth = 0.3;
  float lxmax = lxmin + lxwidth;
  float lymin = lymax;
  if (SignalOnly==0) lymin -= lywidth*4./5.;
  else lymin -= lywidth;

  float lxmin2 = 0.22+0.39;
  float lymax2 = lymax;
  float lxmax2 = lxmin2 + lxwidth;
  float lymin2 = lymax2;
  if (SignalOnly==0) lymin2 -= lywidth*2./5.;
  else lymin2 -= lywidth*4./5.;

  if (SignalOnly==1){
    float lxmin3 = lxmin2;
    float lymax3 = lymax2;
    float lxmax3 = lxmax2;
    float lymin3 = lymin2;

    lxmin2 = lxmin;
    lxmax2 = lxmax;
    lymin2 = lymin;
    lymax2 = lymax;
    lxmin = lxmin3;
    lxmax = lxmax3;
    lymin = lymin3;
    lymax = lymax3;
  }

  float pxmin = 0.756;
  float pymin = 0.76;
  float pxmax = 0.85;
  if (SignalOnly==1){
    pymin -= 0.12;
  }
  float pymax = pymin+0.05;
  TPaveText* ptx = new TPaveText(pxmin, pymin, pxmax, pymax, "brNDC");
  ptx->SetBorderSize(0);
  ptx->SetTextFont(42);
  ptx->SetTextSize(0.04);
  ptx->SetLineColor(1);
  ptx->SetLineStyle(1);
  ptx->SetLineWidth(1);
  ptx->SetFillColor(0);
  ptx->SetFillStyle(0);
  text = ptx->AddText(0.01, 0.01, "gg#rightarrow4l");
  text->SetTextSize(0.04);

  TString canvasname = "cCanvas_MCFMBSM_GenLevel";
  if (SignalOnly==1) canvasname.Append("_SignalOnly");
  TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
  cc->cd();
  gStyle->SetOptStat(0);
  cc->SetFillColor(0);
  cc->SetBorderMode(0);
  cc->SetBorderSize(2);
  cc->SetTickx(1);
  cc->SetTicky(1);
  cc->SetLeftMargin(0.17);
  cc->SetRightMargin(0.05);
  cc->SetTopMargin(0.07);
  cc->SetBottomMargin(0.13);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetFrameFillStyle(0);
  cc->SetFrameBorderMode(0);
  cc->SetLogy();

  TLegend* ll;
  TLegend* ll2;

  ll = new TLegend(lxmin2, lymin2, lxmax2, lymax2);
  ll2 = new TLegend(lxmin, lymin, lxmax, lymax);

  ll->SetBorderSize(0);
  ll->SetTextFont(42);
  ll->SetTextSize(0.04);
  ll->SetLineColor(1);
  ll->SetLineStyle(1);
  ll->SetLineWidth(1);
  ll->SetFillColor(0);
  ll->SetFillStyle(0);
  ll2->SetBorderSize(0);
  ll2->SetTextFont(42);
  ll2->SetTextSize(0.04);
  ll2->SetLineColor(1);
  ll2->SetLineStyle(1);
  ll2->SetLineWidth(1);
  ll2->SetFillColor(0);
  ll2->SetFillStyle(0);

  TString strACtitle[9]={ "",
    "f_{a2}=1", "f_{a3}=1", "f_{#Lambda1}=1", "f_{#LambdaQ}=1",
    "f_{a2}=0.5, #phi_{#lower[-0.2]{a2}}=#pi", "f_{a3}=0.5", "f_{#Lambda1}=0.5", "f_{#LambdaQ}=0.5"
  };

  int iDraw = 2 - 2*SignalOnly;

  if (SignalOnly==0) hfill[iDraw][0]->GetYaxis()->SetRangeUser(7e-3, maxplot*15.);
  else{
    double histmin = 7e-3;
    if (hfill[iDraw][0]->GetMinimum()>0) histmin = hfill[iDraw][0]->GetMinimum();
    hfill[iDraw][0]->GetYaxis()->SetRangeUser(histmin, maxplot*2000.);
  }
  hfill[iDraw][0]->GetXaxis()->SetRangeUser(xlimits[0], 800.);

  hfill[iDraw][0]->SetLineColor(kBlack);
  if (SignalOnly==0){
    hfill[iDraw][0]->SetFillColor(kAzure-2);
    hfill[iDraw][0]->SetFillStyle(1001);
  }
  hfill[iDraw][0]->Draw("hist");

  hfill[iDraw][1]->SetLineColor(kBlue);
  hfill[iDraw][1]->Draw("histsame");

  hfill[iDraw][2]->SetLineColor(kRed);
  hfill[iDraw][2]->Draw("histsame");

  hfill[iDraw][3]->SetLineColor(kViolet);
  hfill[iDraw][3]->Draw("histsame");

  hfill[iDraw][4]->SetLineColor(kGreen+2);
  hfill[iDraw][4]->Draw("histsame");

  if (SignalOnly==1){
    hfill[iDraw][5]->SetLineColor(kBlue);
    hfill[iDraw][5]->Draw("histsame");

    hfill[iDraw][6]->SetLineColor(kRed);
    hfill[iDraw][6]->Draw("histsame");

    hfill[iDraw][7]->SetLineColor(kViolet);
    hfill[iDraw][7]->Draw("histsame");

    hfill[iDraw][8]->SetLineColor(kGreen+2);
    hfill[iDraw][8]->Draw("histsame");
  }

  if (SignalOnly==0){
    hfill[1][0]->SetLineColor(kBlack);
    hfill[1][0]->SetLineStyle(3);
    hfill[1][0]->Draw("histsame");
  }

  hfill[iDraw][0]->Draw("histsame");

  TLegendEntry* legendtext;
  if (SignalOnly==0){
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM total", "f");
    legendtext = ll->AddEntry(hfill[1][0], "SM bkg.", "f");
    legendtext->SetFillStyle(1001);
    legendtext->SetFillColor(hfill[1][0]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][0], "SM signal", "f");
    legendtext->SetFillStyle(3001);
  }

  if (SignalOnly==0){
    legendtext = ll2->AddEntry(hfill[iDraw][4], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[4].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][2], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[2].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][1], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[1].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][3], Form("#Gamma_{H}=#Gamma^{SM}_{H}, %s", strACtitle[3].Data()), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  else{
    legendtext = ll->AddEntry(hfill[iDraw][4], strACtitle[4].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][4]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][2], strACtitle[2].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][2]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][1], strACtitle[1].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][1]->GetFillColor());
    legendtext = ll->AddEntry(hfill[iDraw][3], strACtitle[3].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][3]->GetFillColor());
  }
  if (SignalOnly==1){
    legendtext = ll2->AddEntry(hfill[iDraw][8], strACtitle[8].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][8]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][5], strACtitle[5].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][5]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][7], strACtitle[7].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][7]->GetFillColor());
    legendtext = ll2->AddEntry(hfill[iDraw][6], strACtitle[6].Data(), "f");
    legendtext->SetFillStyle(3001);
    legendtext->SetFillColor(hfill[iDraw][6]->GetFillColor());
  }

  ll->Draw("same");
  ll2->Draw("same");
  ptx->Draw();
  pt->Draw();
  cc->RedrawAxis();
  cc->Update();

  canvasname.Prepend(coutput_common);
  TString canvasname_pdf = canvasname;
  TString canvasname_eps = canvasname;
  TString canvasname_png = canvasname;
  TString canvasname_root = canvasname;
  TString canvasname_c = canvasname;
  canvasname_pdf.Append(".pdf");
  canvasname_eps.Append(".eps");
  canvasname_png.Append(".png");
  canvasname_root.Append(".root");
  canvasname_c.Append(".C");
  cc->SaveAs(canvasname_pdf);
  cc->SaveAs(canvasname_eps);
  cc->SaveAs(canvasname_png);
  cc->SaveAs(canvasname_root);
  cc->SaveAs(canvasname_c);

  foutput->WriteTObject(cc);
  delete ll2;
  delete ll;
  cc->Close();
  delete ptx;
  delete pt;
  for (int t=0; t<4; t++){
    for (int ac=0; ac<5; ac++){
      foutput->WriteTObject(hfill[t][ac]);
      delete hfill[t][ac];
    }
  }
  foutput->Close();
}
void makeBSM_MCFM_single(int folder, int erg_tev){
  //  if (erg_tev==7) return;
  //  char TREE_NAME[] = "SelectedTree";
  char TREE_NAME[] = "GenTree";
  TString INPUT_NAME = "HZZ4l-125_6-";
  int tFitD = 0;
  TString comstring;
  comstring.Form("%iTeV", erg_tev);
  TString erg_dir;
  erg_dir.Form("LHC_%iTeV/", erg_tev);
  INPUT_NAME.Append(comstring);
  INPUT_NAME.Append("-");

  double mPOLE = 125.6;
  Mela mela(erg_tev, mPOLE);

  TString cinput_common = "/scratch0/hep/usarical/WidthSamples/" + erg_dir + "/";
  if (erg_tev!=7) cinput_common = cinput_common + user_folder[folder] + "/";

  int EnergyIndex = 1;
  if (erg_tev == 7) EnergyIndex = 0;

  float templateWeight = 1;
  float MC_weight;
  float ZZMass = 0;
  float Z1Mass = 0;
  float Z2Mass = 0;

  float GenHMass = 0;
  float GenZ1Mass = 0;
  float GenZ2Mass = 0;
  float GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;
  float GenLep1Mass, GenLep2Mass, GenLep3Mass, GenLep4Mass;
  float GenLep1Pt, GenLep2Pt, GenLep3Pt, GenLep4Pt;
  float GenLep1Phi, GenLep2Phi, GenLep3Phi, GenLep4Phi;
  float GenLep1Eta, GenLep2Eta, GenLep3Eta, GenLep4Eta;
  float GenLep1E, GenLep2E, GenLep3E, GenLep4E;

  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;

  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/" + erg_dir;
  coutput_common += user_folder[folder] + "/";
  gSystem->Exec("mkdir -p " + coutput_common);

  TString cinput_KDFactor = "./data/HZZ4l-KDFactorGraph";
  if (EnergyIndex == 0) cinput_KDFactor = cinput_KDFactor + "_7TeV";
  cinput_KDFactor = cinput_KDFactor + ".root";
  TFile* finput_KDFactor = new TFile(cinput_KDFactor, "read");
  TString tgkfname = "KDScale_";
  tgkfname = tgkfname + "AllFlavors_UnNormalized";
  TGraphAsymmErrors* tgkf = (TGraphAsymmErrors*)finput_KDFactor->Get(tgkfname);
  TGraph* tg_interf = make_HZZ_LeptonInterferenceGraph();

  cout<<endl;
  cout<<"==============================="<<endl;
  cout<<"CoM Energy: "<<erg_tev<<" TeV"<<endl;
  cout<<"Decay Channel: "<<user_folder[folder]<<endl;
  cout<<"==============================="<<endl;
  cout<<endl;


  const int kNumTemplates = 4;
  TString templatenames[kNumTemplates] ={ "ggF Sig", "gg Bkg", "ggF BSI", "ggF BSI25" };

  int nEntries;
  float fitYval = 0;
  MC_weight = 1;
  ZZMass = 0;

  double selfDHvvcoupl[SIZE_HVV][2] ={ { 0 } };
  double ggvvcoupl[2]={ 0, 0 };

  //Template and tree filler
  for (int t = 0; t < kNumTemplates; t++){
    TString OUTPUT_NAME;
    OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
    OUTPUT_NAME += sample_suffix[t] + ".root";
    TString coutput = coutput_common + OUTPUT_NAME;
    TFile* foutput = new TFile(coutput, "recreate");

    foutput->cd();

    TChain* tree = new TChain(TREE_NAME);
    TTree* templateTree = new TTree(TREE_NAME, TREE_NAME);

    float wPOLE=4.15e-3;
    if (t==3) wPOLE*=25;

    TString cinput = cinput_common + sample_suffix[t] + "/" + INPUT_NAME + sample_suffix[t] + ".root";
    tree->Add(cinput);

    templateTree->Branch("MC_weight", &templateWeight);
    templateTree->Branch("ZZMass", &ZZMass);
    templateTree->Branch("Z1Mass", &Z1Mass);
    templateTree->Branch("Z2Mass", &Z2Mass);
    //    templateTree->Branch("GenHMass", &GenHMass);
    templateTree->Branch("p0plus_VAJHU", &p0plus_VAJHU);
    templateTree->Branch("p0hplus_VAJHU", &p0hplus_VAJHU);
    templateTree->Branch("p0minus_VAJHU", &p0minus_VAJHU);
    templateTree->Branch("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
    templateTree->Branch("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
    templateTree->Branch("pg1g2_VAJHU", &pg1g2_VAJHU);
    templateTree->Branch("pg1g4_VAJHU", &pg1g4_VAJHU);
    templateTree->Branch("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
    templateTree->Branch("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);

    //Making templates using appropriate weights
    //    tree->SetBranchAddress("ZZMass", &ZZMass);
    //    tree->SetBranchAddress("MC_weight", &MC_weight);
    tree->SetBranchAddress("GenZZMass", &GenHMass);
    tree->SetBranchAddress("GenLep1Id", &GenLep1Id);
    tree->SetBranchAddress("GenLep2Id", &GenLep2Id);
    tree->SetBranchAddress("GenLep3Id", &GenLep3Id);
    tree->SetBranchAddress("GenLep4Id", &GenLep4Id);
    tree->SetBranchAddress("GenLep1Pt", &GenLep1Pt);
    tree->SetBranchAddress("GenLep2Pt", &GenLep2Pt);
    tree->SetBranchAddress("GenLep3Pt", &GenLep3Pt);
    tree->SetBranchAddress("GenLep4Pt", &GenLep4Pt);
    tree->SetBranchAddress("GenLep1Phi", &GenLep1Phi);
    tree->SetBranchAddress("GenLep2Phi", &GenLep2Phi);
    tree->SetBranchAddress("GenLep3Phi", &GenLep3Phi);
    tree->SetBranchAddress("GenLep4Phi", &GenLep4Phi);
    tree->SetBranchAddress("GenLep1Eta", &GenLep1Eta);
    tree->SetBranchAddress("GenLep2Eta", &GenLep2Eta);
    tree->SetBranchAddress("GenLep3Eta", &GenLep3Eta);
    tree->SetBranchAddress("GenLep4Eta", &GenLep4Eta);
    tree->SetBranchAddress("GenLep1E", &GenLep1E);
    tree->SetBranchAddress("GenLep2E", &GenLep2E);
    tree->SetBranchAddress("GenLep3E", &GenLep3E);
    tree->SetBranchAddress("GenLep4E", &GenLep4E);

    if (tFitD != 0){
      if (tree->GetBranchStatus(strFitDim[tFitD])){
        tree->SetBranchAddress("Dgg10_VAMCFM", &fitYval);
        templateTree->Branch(strFitDim[tFitD], &fitYval);
      }
      else{
        cerr << "Could NOT find branch named " << strFitDim[tFitD] << "!!! Setting strFitDim[" << tFitD << "] = 0." << endl;
        fitYval = 0;
      }
    }

    nEntries = tree->GetEntries();
    double xsec = 1./nEntries;
    if (t==0) xsec *= xsec_ggHZZ_MCFM[EnergyIndex];
    else if (t==1) xsec *= xsec_ggZZ_MCFM[EnergyIndex];
    else if (t==2) xsec *= xsec_ggHZZ_BSI_MCFM[EnergyIndex];
    else if (t==3) xsec *= xsec_ggHZZ_BSI25_MCFM[EnergyIndex];
    else xsec = 1;
    if (folder<2) xsec *= 0.25;
    else xsec *= 0.5;

    //    for (int ev = 0; ev < 100; ev++){

    for (int ev = 0; ev < nEntries; ev++){
      tree->GetEntry(ev);
      ZZMass = GenHMass;
      MC_weight = xsec;

      if (fitYval != fitYval) continue;
      // Protect against any KD exceeding boundaries
      if (tFitD!=0 && fitYval>=1){
        cout << "Found fitYval == " << fitYval;
        fitYval = 0.999;
        cout << ". Fixed to " << fitYval << endl;
      }
      if (tFitD!=0 && fitYval<0) fitYval = 0;

      if (t < 4 && erg_tev==7){
        if (folder==1){
          GenLep1Id=11;
          GenLep2Id=-11;
          GenLep3Id=11;
          GenLep4Id=-11;
        }
        else if (folder==0){
          GenLep1Id=13;
          GenLep2Id=-13;
          GenLep3Id=13;
          GenLep4Id=-13;
        }
      }

      double weight = MC_weight;
      if (t < 4) weight *= tgkf->Eval(GenHMass);
      if (t < 4
        && abs(GenLep1Id)==abs(GenLep2Id)
        && abs(GenLep1Id)==abs(GenLep3Id)
        && abs(GenLep1Id)==abs(GenLep4Id)
        ) weight *= tg_interf->Eval(GenHMass);
      templateWeight = weight;

      float mzz = mPOLE;
      float m1 = 0;
      float m2 = 0;
      float h1 = 0;
      float h2 = 0;
      float phi = 0;
      float hs = 0;
      float phi1 = 0;

      GenLep1Mass = findLeptonMass(GenLep1Id);
      GenLep2Mass = findLeptonMass(GenLep2Id);
      GenLep3Mass = findLeptonMass(GenLep3Id);
      GenLep4Mass = findLeptonMass(GenLep4Id);

      TLorentzVector p1, p2, p3, p4;
      p1.SetPtEtaPhiE(GenLep1Pt, GenLep1Eta, GenLep1Phi, GenLep1E);
      p2.SetPtEtaPhiE(GenLep2Pt, GenLep2Eta, GenLep2Phi, GenLep2E);
      p3.SetPtEtaPhiE(GenLep3Pt, GenLep3Eta, GenLep3Phi, GenLep3E);
      p4.SetPtEtaPhiE(GenLep4Pt, GenLep4Eta, GenLep4Phi, GenLep4E);
      TLorentzVector pZ1 = p1+p2;
      TLorentzVector pZ2 = p3+p4;
      TLorentzVector pZ1p = p1+p4;
      TLorentzVector pZ2p = p3+p2;
      TLorentzVector pZZ = pZ1+pZ2;
      mzz=pZZ.M();
      m1=pZ1.M();
      m2=pZ2.M();
      Z1Mass = m1;
      Z2Mass=m2;
      if (Z1Mass>=120 || Z1Mass<=40) continue;
      if (Z2Mass>=120 || Z2Mass<=12) continue;
      if (!passAcceptance(GenLep1Pt, GenLep1Eta, (int)GenLep1Id)) continue;
      if (!passAcceptance(GenLep2Pt, GenLep2Eta, (int)GenLep2Id)) continue;
      if (!passAcceptance(GenLep3Pt, GenLep3Eta, (int)GenLep3Id)) continue;
      if (!passAcceptance(GenLep4Pt, GenLep4Eta, (int)GenLep4Id)) continue;
      if (pZ1.M()<=4 ||pZ2.M()<=4 ||pZ1p.M()<=4 ||pZ2p.M()<=4) continue;
      TLorentzVector pp[4] ={ p1, p2, p3, p4 };
      int pass20=-1;
      int pass10=-1;
      for (int vv=0; vv<4; vv++){
        if (pp[vv].Pt()>20){
          pass20=vv; break;
        }
      }
      for (int vv=0; vv<4; vv++){
        if (vv==pass20) continue;
        if (pp[vv].Pt()>10){
          pass10=vv; break;
        }
      }
      if (pass20<0 || pass10<0) continue;

      mela::computeAngles(p1, GenLep1Id,
        p2, GenLep2Id,
        p3, GenLep3Id,
        p4, GenLep4Id,
        hs,
        h1,
        h2,
        phi,
        phi1);
      int lepIdOrdered[4] ={ (int)GenLep1Id, (int)GenLep2Id, (int)GenLep3Id, (int)GenLep4Id };
      float angularOrdered[8] ={ mzz, m1, m2, hs, h1, h2, phi, phi1 };

      if (t==0) mela.setProcess(TVar::HSMHiggs, TVar::MCFM, TVar::ZZGG);
      if (t==2 || t==3) mela.setProcess(TVar::bkgZZ_SMHiggs, TVar::MCFM, TVar::ZZGG);
      if (t!=1){
        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0plus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[1][0]=1.638;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0hplus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[3][0]=2.521;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0minus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[11][0]=-12046.01;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0_g1prime2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[13][0]=-pow(10000.0/mPOLE, 2);
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0_g1prime4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);


        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[1][0]=1.638;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[3][0]=2.521;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[11][0]=-12046.01;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g1prime2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[13][0]=-pow(10000.0/mPOLE, 2);
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g1prime4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        if (p0plus_VAJHU!=0){
          p0hplus_VAJHU/=p0plus_VAJHU;
          p0minus_VAJHU/=p0plus_VAJHU;
          p0_g1prime2_VAJHU/=p0plus_VAJHU;
          p0_g1prime4_VAJHU/=p0plus_VAJHU;

          pg1g2_VAJHU/=p0plus_VAJHU;
          pg1g4_VAJHU/=p0plus_VAJHU;
          pg1g1prime2_VAJHU/=p0plus_VAJHU;
          pg1g1prime4_VAJHU/=p0plus_VAJHU;
          p0plus_VAJHU=1;
        }
        else{
          p0plus_VAJHU=0;
          p0hplus_VAJHU=0;
          p0minus_VAJHU=0;
          p0_g1prime2_VAJHU=0;
          p0_g1prime4_VAJHU=0;

          pg1g2_VAJHU=0;
          pg1g4_VAJHU=0;
          pg1g1prime2_VAJHU=0;
          pg1g1prime4_VAJHU=0;
        }
      }
      else{
        p0plus_VAJHU=1;
        p0hplus_VAJHU=1;
        p0minus_VAJHU=1;
        p0_g1prime2_VAJHU=1;
        p0_g1prime4_VAJHU=1;

        pg1g2_VAJHU=1;
        pg1g4_VAJHU=1;
        pg1g1prime2_VAJHU=1;
        pg1g1prime4_VAJHU=1;
      }

      p0plus_VAJHU*=templateWeight;
      p0hplus_VAJHU*=templateWeight;
      p0minus_VAJHU*=templateWeight;
      p0_g1prime2_VAJHU*=templateWeight;
      p0_g1prime4_VAJHU*=templateWeight;

      pg1g2_VAJHU*=templateWeight;
      pg1g4_VAJHU*=templateWeight;
      pg1g1prime2_VAJHU*=templateWeight;
      pg1g1prime4_VAJHU*=templateWeight;

      templateTree->Fill();
    }

    foutput->WriteTObject(templateTree);
    delete tree;
    delete templateTree;
    foutput->Close();
  }

  delete tg_interf;
  delete tgkf;
  finput_KDFactor->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");

}
//------------------------------------------------------------------------------
// PlotHiggsRes_LP
//------------------------------------------------------------------------------
void RunMakeRazorPlots ( string signalfile, string signalLabel,  vector<string> bkgfiles,vector<string> bkgLabels, int boxOption = 0, int option = -1, string label = "", string latexlabel = "") {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  double intLumi = 2000; //in units of pb^-1
  string Label = "";
  if (label != "") Label = "_" + label;

  vector<string> inputfiles;
  vector<string> processLabels;

  bool hasSignal = false;
  if (signalfile != "") {
    hasSignal = true;
    inputfiles.push_back(signalfile);
    processLabels.push_back(signalLabel);
  }
  assert(bkgfiles.size() == bkgLabels.size());
  for (int i=0; i < bkgfiles.size(); ++i) {
     inputfiles.push_back(bkgfiles[i]);
     processLabels.push_back(bkgLabels[i]);
  }

  //*******************************************************************************************
  //Define Histograms
  //*******************************************************************************************
  TH1F* histMRAllBkg =  new TH1F( "MRAllBkg",";M_{R} [GeV/c^{2}];Number of Events", 100, 400, 2400);
  TH1F* histRsqAllBkg =  new TH1F( "RsqAllBkg", ";R^{2};Number of Events", 24, 0.25, 1.45);
  histMRAllBkg->SetStats(false);
  histRsqAllBkg->SetStats(false);
  
  vector<TH1F*> histMR;
  vector<TH1F*> histRsq; 

  vector<TH2F*> histMRRsq;
  vector<TH1F*> histUnrolled; 
  vector<TH1F*> histUnrolled2bins; 
  vector<TH1F*> histUnrolledPercentage; 
  vector<TH1F*> histUnrolledPercentage2bins; 

  //  float MRBinLowEdges[] = {500, 600, 700, 900, 1200, 1600, 2500, 4000};
  //  float RsqBinLowEdges[] = {0.25, 0.30, 0.41, 0.52, 0.64, 1.5};

  // float MRBinLowEdges[] = {500, 600, 700, 900, 1200, 1600, 2500, 4000}; // Multijet Bins
  // float RsqBinLowEdges[] = {0.25, 0.30, 0.41, 0.52, 0.64, 1.5}; // Multijet Bins

  float MRBinLowEdges[] = {400, 500, 600, 700, 900, 1200, 1600, 2500, 4000}; // Lepton boxes
  float RsqBinLowEdges[] = {0.15, 0.20, 0.25, 0.30, 0.41, 0.52, 0.64, 1.5};  // Lepton boxes


  const int nMRBins = sizeof(MRBinLowEdges)/sizeof(float)-1;
  const int nRsqBins = sizeof(RsqBinLowEdges)/sizeof(float)-1;

  std::cout<<"AAAAAAA "<<nMRBins<<" "<<nRsqBins<<std::endl;

  assert (inputfiles.size() == processLabels.size());

  for (int i=0; i < inputfiles.size(); ++i) {    
    // histMR.push_back( new TH1F( Form("MR_%s",processLabels[i].c_str()), ";M_{R} [GeV/c^{2}];Number of Events", 100, 400, 2400));
    histMR.push_back( new TH1F( Form("MR_%s",processLabels[i].c_str()), ";M_{R} [GeV/c^{2}];Number of Events", nMRBins, MRBinLowEdges));
    if (!hasSignal || i != 0) histMR[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histMR[i]->SetLineWidth(3);
    histMR[i]->SetLineColor(color[i]);    
    histMR[i]->SetStats(false);    
    histMR[i]->Sumw2();

    // histRsq.push_back( new TH1F( Form("Rsq_%s",processLabels[i].c_str()), ";R^{2} ;Number of Events", 24, 0.25, 1.45));
    histRsq.push_back( new TH1F( Form("Rsq_%s",processLabels[i].c_str()), ";R^{2} ;Number of Events", nRsqBins, RsqBinLowEdges));
    if (!hasSignal || i != 0) histRsq[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histRsq[i]->SetLineWidth(3);
    histRsq[i]->SetLineColor(color[i]);
    histRsq[i]->SetStats(false);

    histMRRsq.push_back( new TH2F( Form("MRRsq_%s",processLabels[i].c_str()), ";M_{R} [GeV/c^{2}]; R^{2}", nMRBins, MRBinLowEdges, nRsqBins, RsqBinLowEdges));
    if (!hasSignal || i != 0) histMRRsq[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histMRRsq[i]->SetLineWidth(3);
    histMRRsq[i]->SetLineColor(color[i]);
    histMRRsq[i]->SetStats(false);
    histMRRsq[i]->Sumw2();

    histUnrolled.push_back( new TH1F( Form("Unrolled_%s",processLabels[i].c_str()), ";Bin Number ;Number of Events", nMRBins*nRsqBins, 0, nMRBins*nRsqBins));
    if (!hasSignal || i != 0) histUnrolled[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histUnrolled[i]->SetLineWidth(3);
    histUnrolled[i]->SetLineColor(color[i]);
    histUnrolled[i]->SetStats(false);     

    histUnrolled2bins.push_back( new TH1F( Form("Unrolled2bins_%s",processLabels[i].c_str()), ";Bin Number ;Event Density", 3, 0, 3));
    if (!hasSignal || i != 0) histUnrolled2bins[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histUnrolled2bins[i]->SetLineWidth(3);
    histUnrolled2bins[i]->SetLineColor(color[i]);
    histUnrolled2bins[i]->SetStats(false);     

    histUnrolledPercentage2bins.push_back( new TH1F( Form("UnrolledPercentage2bins_%s",processLabels[i].c_str()), ";;Event Density", 3, 0, 3));
    if (!hasSignal || i != 0) histUnrolledPercentage2bins[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histUnrolledPercentage2bins[i]->SetLineWidth(3);
    histUnrolledPercentage2bins[i]->SetLineColor(color[i]);
    histUnrolled2bins[i]->SetStats(false);     

    histUnrolledPercentage.push_back( new TH1F( Form("UnrolledPercentage_%s",processLabels[i].c_str()), ";Bin Number ; Fraction of total", nMRBins*nRsqBins, 0, nMRBins*nRsqBins));
    if (!hasSignal || i != 0) histUnrolledPercentage[i]->SetFillColor(color[i]);
    if (hasSignal && i==0) histUnrolledPercentage[i]->SetLineWidth(3);
    histUnrolledPercentage[i]->SetLineColor(color[i]);
    histUnrolledPercentage[i]->SetStats(false);     
}

  //*******************************************************************************************
  //Define Counts
  //*******************************************************************************************


  //*******************************************************************************************
  //Read files
  //*******************************************************************************************
  for (uint i=0; i < inputfiles.size(); ++i) {

    TFile* inputFile = new TFile(inputfiles[i].c_str(),"READ");
    assert(inputFile);
    TTree* tree = 0;
    tree = (TTree*)inputFile->Get("RazorInclusive");
 
    float weight = 0;
    int box = -1;
    int nBTaggedJets = 0;
    float dPhiRazor = 0;
    float MR = 0;
    float Rsq = 0;
    float mT = 0;
    int nGenMuons = 0;
    int nGenElectrons = 0;
    int nGenTaus = 0;

    // bool Flag_HBHENoiseFilter = false;
    // bool Flag_goodVertices    = false;
    // bool Flag_eeBadScFilter   = false;
    // bool Flag_EcalDeadCellTriggerPrimitiveFilter = false;


    tree->SetBranchAddress("weight",&weight);
    tree->SetBranchAddress("box",&box);
    tree->SetBranchAddress("nBTaggedJets",&nBTaggedJets);
    tree->SetBranchAddress("dPhiRazor",&dPhiRazor);
    tree->SetBranchAddress("MR",&MR);
    tree->SetBranchAddress("Rsq",&Rsq);
    tree->SetBranchAddress("mT",&mT);
    tree->SetBranchAddress("nGenMuons",&nGenMuons);
    tree->SetBranchAddress("nGenElectrons",&nGenElectrons);
    tree->SetBranchAddress("nGenTaus",&nGenTaus);
    // tree->SetBranchAddress("Flag_HBHENoiseFilter",&Flag_HBHENoiseFilter);
    // tree->SetBranchAddress("Flag_goodVertices",&Flag_goodVertices);
    // tree->SetBranchAddress("Flag_eeBadScFilter",&Flag_eeBadScFilter);
    // tree->SetBranchAddress("Flag_EcalDeadCellTriggerPrimitiveFilter",&Flag_EcalDeadCellTriggerPrimitiveFilter);
 

    cout << "Process : " << processLabels[i] << " : Total Events: " << tree->GetEntries() << "\n";
    for (int n=0;n<tree->GetEntries();n++) { 
    // for (int n=0;n<10000;n++) { 
    
      tree->GetEntry(n);
      if (n % 1000000 == 0) cout << "Processing Event " << n << "\n";       

      // if (intLumi*weight > 100) continue;

      //Box Options
      if (option == 0 ) {
	if (nBTaggedJets != 0) continue; 
      }
      if (option == 1 ) {
	if (nBTaggedJets != 1) continue;
      }
      if (option == 2 ) {
	if (nBTaggedJets != 2) continue;
      }
      if (option == 3 ) {
	if (nBTaggedJets < 3) continue;
      }
      if (option == 4 ) {
	if (nBTaggedJets < 0) continue; // all b-tag categories combined
      }

     //Box Options
      if (boxOption == 0) { // Multijet Box for Jamboree
	if( !(box == 11 || box == 12) ) continue;
      }
      if (boxOption == 1) { // MuonMultijet Box for Jamboree
	if( !(box == 3 || box == 4) ) continue;
      } 
      if (boxOption == 2) { // EleMultijet Box for Jamboree
	if( !(box == 6 || box == 7) ) continue;
      }

      // LeptonMultijet Box for Jamboree
      if(boxOption == 1 || boxOption == 2)
	if(mT<120) continue;

      // Multijet Box for Jamboree
      if (boxOption == 0)
	if(fabs(dPhiRazor) > 2.8) continue;

      //apply baseline cuts
      if(boxOption == 1 || boxOption == 2) 
	if (!(MR > 400 && Rsq > 0.15)) continue;
      
      if(boxOption == 0) 
	if (!(MR > 500 && Rsq > 0.25)) continue;

      // if(!Flag_HBHENoiseFilter) continue;
      // if(!Flag_goodVertices) continue;
      // if(!Flag_EcalDeadCellTriggerPrimitiveFilter) continue;
      // if(!Flag_eeBadScFilter) continue;
      
      // fill the histos
      if (!hasSignal || i>0) {
	histMRAllBkg->Fill(MR, intLumi*weight);
	histRsqAllBkg->Fill(Rsq, intLumi*weight);
      }
            
      if(strstr(processLabels[i].c_str(), "TTJets")==NULL && strstr(processLabels[i].c_str(), "T1bbbb")==NULL)
      	histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
      
      // if(strstr(processLabels[i].c_str(), "T1bbbb")!=NULL)
      // 	histMRRsq[i]->Fill(MR, Rsq, intLumi*weight*2.69506e-07);
      
      histMR[i]->Fill(MR, intLumi*weight);
      histRsq[i]->Fill(Rsq, intLumi*weight);
      
      // separate by number of gen leptons for lepton boxes
      if(boxOption==1 || boxOption==2)
	{
	  if(strstr(processLabels[i].c_str(), "TTJets")!=NULL && strstr(bkgLabels[i].c_str(), "2L")!=NULL) {
	    if(nGenMuons+nGenElectrons>=2)
	      histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
	  }
	  else if(strstr(processLabels[i].c_str(), "TTJets")!=NULL && strstr(bkgLabels[i].c_str(), "Tau")!=NULL) {
	    if((nGenMuons+nGenElectrons+nGenTaus>=2) && !(nGenMuons+nGenElectrons>=2))
	      histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
	  }
	  else if(strstr(processLabels[i].c_str(), "TTJets")!=NULL && strstr(bkgLabels[i].c_str(), "1L")!=NULL) {
	    if(!(nGenMuons+nGenElectrons>=2) && !(nGenMuons+nGenElectrons+nGenTaus>=2))
	      histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
	  }
	}
      
	// Multijet box top
      	if(boxOption==0)
	  if(strstr(processLabels[i].c_str(), "TTJets")!=NULL) {
	    histMRRsq[i]->Fill(MR, Rsq, intLumi*weight);
	  }
      }

    inputFile->Close();
    delete inputFile;
  }
  
  //*******************************************************************************************
  //Draw Plots
  //*******************************************************************************************
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.7,0.53,0.90,0.88);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);

  for (Int_t i = histMRRsq.size()-1 ; i >= 0; --i) {
    if (hasSignal && i==0) {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "L");
    } else {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "F");
    }
  }

  THStack *stackUnrolled = new THStack();
  THStack *stackUnrolled2bins = new THStack();
  THStack *stackUnrolledPercentage = new THStack();
  THStack *stackUnrolledPercentage2bins = new THStack();

  float bintotal[nMRBins*nRsqBins] = {0.};

  // fill out the unrolled histograms 
  for (uint i=0; i < histMRRsq.size(); ++i) {
    
    int binN = 0;
    float total_SB = 0.;
    float total_SR = 0.;

    for(int ii = 0; ii<nMRBins; ii++)
      for (int jj = 0; jj<nRsqBins; jj++)      
  	{      
  	  float value = (histMRRsq[i]->GetBinContent(ii+1, jj+1) > 0) ? histMRRsq[i]->GetBinContent(ii+1, jj+1) : 0. ;
	  
	  float Xrange = histMRRsq[i]->GetXaxis()->GetBinLowEdge(ii+2) - histMRRsq[i]->GetXaxis()->GetBinLowEdge(ii+1);
	  float Yrange = histMRRsq[i]->GetYaxis()->GetBinLowEdge(jj+2) - histMRRsq[i]->GetYaxis()->GetBinLowEdge(jj+1);

	  float area =1.;
	  
	  if(density) area = Xrange*Yrange; //normalize each bin by its area

	  histUnrolled[i]->SetBinContent(binN+1, value/area);

	  if(!hasSignal || i>0)
	    bintotal[binN+1] += value/area;	 
	  
	  if(ii<1 || jj<1)
	    total_SB += value/area;
	  else
	    total_SR += value/area;
	  	  
  	  binN++;
  	}

    histUnrolled2bins[i]->SetBinContent(1, total_SB);
    histUnrolled2bins[i]->SetBinContent(2, total_SR);

    histUnrolled[i]->SetMinimum(0.00001);

    if ( histUnrolled[i]->Integral() > 0) {
      if( !hasSignal || i > 0 )
	stackUnrolled->Add(histUnrolled[i]);
    }

    if ( histUnrolled[i]->Integral() > 0) {
      if( !hasSignal || i > 0 )
	stackUnrolled2bins->Add(histUnrolled2bins[i]);
    }

    cout << "Process : " << processLabels[i] << "\n";	  
  }


  // Unroll into two bins for fractions
  float AllBkg_SB = 0;
  float AllBkg_SR = 0;

  for (uint i=0; i < histMRRsq.size(); ++i) {
    if( !hasSignal || i > 0 ){
      AllBkg_SB += histUnrolled2bins[i]->GetBinContent(1);
      AllBkg_SR += histUnrolled2bins[i]->GetBinContent(2);
    }
  }

  for (uint i=0; i < histMRRsq.size(); ++i) {
    if( !hasSignal || i > 0 ){
      histUnrolledPercentage2bins[i]->SetBinContent(1, histUnrolled2bins[i]->GetBinContent(1)/AllBkg_SB);
      histUnrolledPercentage2bins[i]->SetBinContent(2, histUnrolled2bins[i]->GetBinContent(2)/AllBkg_SR);
    }
    
    if ( histUnrolled2bins[i]->Integral() > 0) {
      if( !hasSignal || i > 0 )
	stackUnrolledPercentage2bins->Add(histUnrolledPercentage2bins[i]);
    }
  }
  
  ///
  // fill out the unrolled percentage histograms 
  for (uint i=0; i < histMRRsq.size(); ++i) {
    if( hasSignal && i == 0 ) continue;
      
    int binN = 0;

    for(int ii = 0; ii<nMRBins; ii++)
      for (int jj = 0; jj<nRsqBins; jj++)      
  	{      
  	  float value = (histMRRsq[i]->GetBinContent(ii+1, jj+1) > 0) ? histMRRsq[i]->GetBinContent(ii+1, jj+1) : 0. ;
	  
	  float Xrange = histMRRsq[i]->GetXaxis()->GetBinLowEdge(ii+2) - histMRRsq[i]->GetXaxis()->GetBinLowEdge(ii+1);
	  float Yrange = histMRRsq[i]->GetYaxis()->GetBinLowEdge(jj+2) - histMRRsq[i]->GetYaxis()->GetBinLowEdge(jj+1);

	  float area =1.;
	  
	  if(density) area = Xrange*Yrange; //normalize each bin by its area

	  if(bintotal[binN+1]>0)
	    histUnrolledPercentage[i]->SetBinContent(binN+1, (value/area)/bintotal[binN+1]);

	  binN++;
	}
		
    if ( histUnrolled[i]->Integral() > 0) {
	stackUnrolledPercentage->Add(histUnrolledPercentage[i]);
    }

    cout << "Unrolling Percentage for Process : " << processLabels[i] << "\n";	  
  }

  /// Unrolled plots in bins of R&MR
  TLatex t1(0.1,0.92, "CMS Preliminary");
  TLatex t2(0.6,0.92, "#sqrt{s}=13 TeV, L = 2 fb^{-1}");
  TLatex t3(0.4,0.92, Form("%s",latexlabel.c_str()) );
  t1.SetNDC();
  t2.SetNDC();
  t3.SetNDC();
  t1.SetTextSize(0.05);
  t2.SetTextSize(0.05);
  t3.SetTextSize(0.02);
  t1.SetTextFont(42);
  t2.SetTextFont(42);
  t3.SetTextFont(42);

  stackUnrolled->Draw();
  stackUnrolled->SetMinimum(0.0001);
  // stackUnrolled->SetMaximum(1000);
  cv->SetLogy();
  stackUnrolled->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackUnrolled->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackUnrolled->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackUnrolled->GetHists()->At(0)))->GetYaxis()->GetTitle());
  stackUnrolled->Draw();
  if(hasSignal) histUnrolled[0]->Draw("same hist");
  legend->Draw();
  t1.Draw();
  t2.Draw();
  t3.Draw();
  cv->SaveAs(Form("Unrolled%s.pdf",Label.c_str()));

  // Unrolled plots in percentages
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.85,0.20,0.95,0.80);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);

  for (Int_t i = histMRRsq.size()-1 ; i >= 0; --i) {
    if (hasSignal && i==0) {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "L");
    } else {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "F");
    }
  }
  stackUnrolledPercentage->Draw();
  stackUnrolledPercentage->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackUnrolledPercentage->GetHists()->At(0)))->GetXaxis()->GetTitle());
  // stackUnrolledPercentage->GetHistogram()->GetXaxis()->SetRangeUser(0, 35);
  stackUnrolledPercentage->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackUnrolledPercentage->GetHists()->At(0)))->GetYaxis()->GetTitle());
  if(hasSignal) histUnrolledPercentage[0]->Draw("same hist"); 
  legend->Draw();
  t1.Draw();
  t2.Draw();
  t3.Draw();
  cv->SaveAs(Form("UnrolledPercentage%s.pdf",Label.c_str()));

  // Unrolled plots in sideband vs signal box
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.85,0.20,0.95,0.80);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);

  for (Int_t i = histMRRsq.size()-1 ; i >= 0; --i) {
    if (hasSignal && i==0) {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "L");
    } else {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "F");
    }
  }
  stackUnrolled2bins->Draw();
  stackUnrolled2bins->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackUnrolled2bins->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackUnrolled2bins->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackUnrolled2bins->GetHists()->At(0)))->GetYaxis()->GetTitle());
  if(hasSignal) histUnrolled2bins[0]->Draw("same hist");
  legend->Draw();
  t1.Draw();
  t2.Draw();
  t3.Draw();
  cv->SaveAs(Form("Unrolled2bins%s.pdf",Label.c_str()));

  // Unrolled plots in sideband vs signal box in fractions
  cv = new TCanvas("cv","cv", 800,600);
  legend = new TLegend(0.7,0.23,0.90,0.88);
  legend->SetTextSize(0.03);
  legend->SetBorderSize(0);

  for (Int_t i = histMRRsq.size()-1 ; i >= 0; --i) {
    if (hasSignal && i==0) {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "L");
    } else {
      legend->AddEntry(histMRRsq[i],processLabels[i].c_str(), "F");
    }
  }

  stackUnrolledPercentage2bins->Draw();
  stackUnrolledPercentage2bins->GetHistogram()->GetXaxis()->SetTitle(((TH1F*)(stackUnrolledPercentage2bins->GetHists()->At(0)))->GetXaxis()->GetTitle());
  stackUnrolledPercentage2bins->GetHistogram()->GetYaxis()->SetTitle(((TH1F*)(stackUnrolledPercentage2bins->GetHists()->At(0)))->GetYaxis()->GetTitle());
  stackUnrolledPercentage2bins->GetHistogram()->GetXaxis()->SetBinLabel(1, "Sideband");
  stackUnrolledPercentage2bins->GetHistogram()->GetXaxis()->SetBinLabel(2, "Signal Sensitive Region");
  if(hasSignal) histUnrolledPercentage2bins[0]->Draw("same hist");
  legend->Draw();
  t1.Draw();
  t2.Draw();
  t3.Draw();
  cv->SaveAs(Form("UnrolledPercentage2bins%s.pdf",Label.c_str()));


   //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  TFile *file = TFile::Open(("RazorPlots"+Label+".root").c_str(), "RECREATE");
  file->cd();

  for(int i=0; i<int(inputfiles.size()); i++) {
    file->WriteTObject(histMR[i], Form("histMR_%s",processLabels[i].c_str()), "WriteDelete");
    file->WriteTObject(histRsq[i], Form("histRsq_%s",processLabels[i].c_str()), "WriteDelete");
    file->WriteTObject(histMRRsq[i], Form("histMRRsq_%s",processLabels[i].c_str()), "WriteDelete");
    histUnrolled[i]->Write();  
    histUnrolled2bins[i]->Write();  
    histUnrolledPercentage[i]->Write();  
    histUnrolledPercentage2bins[i]->Write();  
  }
  
  stackUnrolled->Write();
  stackUnrolled2bins->Write();
  stackUnrolledPercentage->Write();
  stackUnrolledPercentage2bins->Write();
 }
Example #16
0
void ElectronTagAndProbeMC(const string dataInputFilename, const string Label, 
                           Int_t ChargeSelection = 0) {   

  gBenchmark->Start("ElectronTagAndProbe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  string label = Label;
  if (Label != "") label = "_" + label;

  Double_t lumi;              // luminosity (pb^-1)
    

  //********************************************************
  // Define Bins
  //********************************************************
  vector<string> ptbinLabel;
  vector<Double_t> ptbinLowEdge;
  vector<Double_t> ptbinUpEdge;
   ptbinLabel.push_back("Pt20ToInf"); ptbinLowEdge.push_back(20.0); ptbinUpEdge.push_back(14000.0);
//   ptbinLabel.push_back("Pt10To15"); ptbinLowEdge.push_back(10.0); ptbinUpEdge.push_back(15.0);
//   ptbinLabel.push_back("Pt15To20"); ptbinLowEdge.push_back(15.0); ptbinUpEdge.push_back(20.0);
//   ptbinLabel.push_back("Pt20To30"); ptbinLowEdge.push_back(20.0); ptbinUpEdge.push_back(30.0);
//   ptbinLabel.push_back("Pt30To40"); ptbinLowEdge.push_back(30.0); ptbinUpEdge.push_back(40.0);
//   ptbinLabel.push_back("Pt40To50"); ptbinLowEdge.push_back(40.0); ptbinUpEdge.push_back(50.0);
//   ptbinLabel.push_back("Pt50ToInf"); ptbinLowEdge.push_back(50.0); ptbinUpEdge.push_back(14000.0);
  vector<string> etabinLabel;
  vector<Double_t> etabinLowEdge;
  vector<Double_t> etabinUpEdge;
  etabinLabel.push_back("EE"); etabinLowEdge.push_back(1.5); etabinUpEdge.push_back(2.5);
  etabinLabel.push_back("EB"); etabinLowEdge.push_back(0); etabinUpEdge.push_back(1.5);
  vector<string> chargebinLabel;
  vector<Double_t> chargeSelection;
  chargebinLabel.push_back("All");  chargeSelection.push_back(0);
  chargebinLabel.push_back("Plus"); chargeSelection.push_back(1);
  chargebinLabel.push_back("Minus"); chargeSelection.push_back(-1);
  vector<vector<vector<Double_t> > > EventCount_TagPlusRecoFailWWTightIdIso_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusRecoPassWWTightIdIso_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusWWTightIdIsoPassHLT_binned;
  vector<vector<vector<Double_t> > > EventCount_TagPlusWWTightIdIsoFailHLT_binned;
  for (int k=0; k < chargebinLabel.size(); ++k) {
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned;
    vector<vector<Double_t> > tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned;    
    
    for (int i=0; i < etabinLabel.size(); ++i) {
      vector<Double_t> tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned;
      vector<Double_t> tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned;
      vector<Double_t> tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned;
      vector<Double_t> tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned;    
      
      for (int j=0; j < ptbinLabel.size(); ++j) {
        Double_t tmp_EventCount_TagPlusRecoFailWWTightIdIso = 0;
        tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoFailWWTightIdIso);
        
        Double_t tmp_EventCount_TagPlusRecoPassWWTightIdIso = 0;
        tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoPassWWTightIdIso);
        
        Double_t tmp_EventCount_TagPlusWWTightIdIsoFailHLT = 0;
        tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoFailHLT);
        
        Double_t tmp_EventCount_TagPlusWWTightIdIsoPassHLT = 0;
        tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoPassHLT);
        
        cout << "make bins : " << k << " " << i << " " << j << " " << endl;
        
      }
      
      tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned);
      tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned);
      tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned);
      tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned);
      
    }

    EventCount_TagPlusRecoFailWWTightIdIso_binned.push_back(tmp_tmp_EventCount_TagPlusRecoFailWWTightIdIso_binned);
    EventCount_TagPlusRecoPassWWTightIdIso_binned.push_back(tmp_tmp_EventCount_TagPlusRecoPassWWTightIdIso_binned);
    EventCount_TagPlusWWTightIdIsoPassHLT_binned.push_back(tmp_tmp_EventCount_TagPlusWWTightIdIsoPassHLT_binned);
    EventCount_TagPlusWWTightIdIsoFailHLT_binned.push_back(tmp_tmp_EventCount_TagPlusWWTightIdIsoFailHLT_binned);
    
  }

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  Double_t EventCount_TagPlusRecoFailWWTightIdIso = 0;
  Double_t EventCount_TagPlusRecoPassWWTightIdIso = 0;
  Double_t EventCount_TagPlusWWTightIdIsoFailHLT = 0;
  Double_t EventCount_TagPlusWWTightIdIsoPassHLT = 0;

  Int_t nbins = 20;
  TH1F *histogram = new TH1F ("histogram", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *ProbePt = new TH1F ("ProbePt", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *TagPt = new TH1F ("TagPt", "; xaxis; yaxis; ", 100, 0 , 200);
  TH1F *TagPlusRecoFailWWTightIdIso = new TH1F ("TagPlusRecoFailWWTightIdIso", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusRecoPassWWTightIdIso = new TH1F ("TagPlusRecoPassWWTightIdIso", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusWWTightIdIsoFailHLT = new TH1F ("TagPlusWWTightIdIsoFailHLT", "; xaxis; yaxis; ", nbins, 60 , 120);
  TH1F *TagPlusWWTightIdIsoPassHLT = new TH1F ("TagPlusWWTightIdIsoPassHLT", "; xaxis; yaxis; ", nbins, 60 , 120);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("mithep::TElectron");
  

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(dataInputFilename.c_str(),"Events");
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
  

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
	
    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

    //********************************************************
    // Load the branches
    //********************************************************
    electronArr->Clear();    
    electronBr->GetEntry(ientry);
 

    //********************************************************
    // TcMet
    //********************************************************
    TVector3 met;        
    if(info->tcMEx!=0 || info->tcMEy!=0) {       
      met.SetXYZ(info->tcMEx, info->tcMEy, 0);
    }

    //******************************************************************************
    //dilepton preselection
    //******************************************************************************
    if (electronArr->GetEntries() < 2) continue;


    //******************************************************************************
    //loop over electron pairs
    //******************************************************************************
    for(Int_t i=0; i<electronArr->GetEntries(); i++) {
      const mithep::TElectron *tag = (mithep::TElectron*)((*electronArr)[i]);
      if ( !(
             fabs(tag->eta) < 2.5
             && 
             tag->pt > 20.0
             &&
             passElectronTagCuts(tag)
             )
        ) continue;
      

      for(Int_t j=0; j<electronArr->GetEntries(); j++) {
        if (i==j) continue;

        const mithep::TElectron *probe = (mithep::TElectron*)((*electronArr)[j]);
        if ( !(
               fabs(probe->eta) < 2.5
               && probe->pt > 10.0
               && probe->isEcalDriven
               )
          ) continue;
        
        mithep::FourVectorM tagVector;
        mithep::FourVectorM probeVector;
        tagVector.SetCoordinates(tag->pt, tag->eta, tag->phi, 0.51099892e-3 );
        probeVector.SetCoordinates(probe->pt, probe->eta, probe->phi, 0.51099892e-3 );
        mithep::FourVectorM dilepton = tagVector+probeVector;
 
        if (dilepton.M() > 60 && dilepton.M() < 120
            
          ) {
          
          //For binned efficiencies
          for (int q=0; q < chargebinLabel.size(); ++q) {
            for (int e=0; e < etabinLabel.size(); ++e) {
              for (int p=0; p < ptbinLabel.size(); ++p) {
                
                //Require the probe is in the right pt and eta bin
                if ( 		  
                (probe->pt >= ptbinLowEdge[p] && probe->pt < ptbinUpEdge[p])
                &&
                (fabs(probe->eta) >= etabinLowEdge[e] && fabs(probe->eta) < etabinUpEdge[e]) 
                && 
                (probe->q == chargeSelection[q] || chargeSelection[q] == 0)
//                 &&
//                 met.Pt() < 20.0
                  ) {
                  
                  //*****************************************************************************************************
                  //Reco -> WWTight
                  //*****************************************************************************************************	    
                
                  if (passElectronCuts(probe)) {	 
                    EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p]++;                  
                  } else {
                  EventCount_TagPlusRecoFailWWTightIdIso_binned[q][e][p]++;
                  }
                  
                  //*****************************************************************************************************
                  //WWTight -> HLT
                  //*****************************************************************************************************	    
                  if (passElectronCuts(probe)) {
                    if (passHLT(probe, info->runNum)) {	 		     
                      EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p]++;
                    } else {
                      EventCount_TagPlusWWTightIdIsoFailHLT_binned[q][e][p]++;
                    }
                  }	    	    	
                }
              }
            }
          }            

          //*****************************************************************************************************
          //Reco -> WWTight
          //*****************************************************************************************************	    
          if (passElectronCuts(probe)) {	 
            EventCount_TagPlusRecoPassWWTightIdIso++;
            TagPlusRecoPassWWTightIdIso->Fill(dilepton.M());	      		  	      
          } else {
            EventCount_TagPlusRecoFailWWTightIdIso++;
            TagPlusRecoFailWWTightIdIso->Fill(dilepton.M());	   
          }
	    
          //*****************************************************************************************************
          //WWTight -> HLT
          //*****************************************************************************************************	    
          if (passElectronCuts(probe)) {
            if (passHLT(probe, info->runNum)) {	 
              EventCount_TagPlusWWTightIdIsoPassHLT++;
              TagPlusWWTightIdIsoPassHLT->Fill(dilepton.M());	
              ProbePt->Fill(probe->pt);
            } else {
              EventCount_TagPlusWWTightIdIsoFailHLT++;
              TagPlusWWTightIdIsoPassHLT->Fill(dilepton.M());			
            }
          }

        } //passes T&P selection

              
      } //loop over probes
    } //loop over tags


  } //end loop over data     

  delete info;
  delete electronArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  TagPlusRecoPassWWTightIdIso->Draw();
  cv->SaveAs("TagPlusRecoPassWWTightIdIso.gif");
  TagPlusRecoFailWWTightIdIso->Draw();
  cv->SaveAs("TagPlusRecoFailWWTightIdIso.gif");
  TagPlusWWTightIdIsoPassHLT->Draw();
  cv->SaveAs("TagPlusWWTightIdIsoPassHLT.gif");
  TagPlusWWTightIdIsoFailHLT->Draw();
  cv->SaveAs("TagPlusWWTightIdIsoFailHLT.gif");

  ProbePt->Draw();
  cv->SaveAs("ProbePt.gif");
  TagPt->Draw();
  cv->SaveAs("TagPt.gif");

  //*****************************************************************************************
  //Summarize Efficiencies
  //*****************************************************************************************
  cout << "**********************************************************************\n";
  cout << "Summarize MC Efficiencies\n";
  TFile *file = new TFile("Efficiencies.root", "UPDATE");

  for (int q=0; q < chargebinLabel.size(); ++q) {    
    for (int e=0; e < etabinLabel.size(); ++e) {
      vector<Double_t> efficiency_RecoToWWTight;
      vector<Double_t> efficiency_RecoToWWTight_lowErr;
      vector<Double_t> efficiency_RecoToWWTight_highErr;
      vector<Double_t> efficiency_WWTightToHLT;
      vector<Double_t> efficiency_WWTightToHLT_lowErr;
      vector<Double_t> efficiency_WWTightToHLT_highErr;
      
      for (int p=0; p < ptbinLabel.size(); ++p) {
    
        cout << etabinLabel[e] << "  " << ptbinLabel[p] << "  Charge = " << chargeSelection[q] << endl;
        cout << endl;

        Int_t errorType = 2; //Clopper Pearson intervals
        Double_t ratio;
        Double_t errLow;
        Double_t errHigh;     
        Double_t n1;
        Double_t n2;

        n1 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p]);
        n2 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso_binned[q][e][p] + EventCount_TagPlusRecoFailWWTightIdIso_binned[q][e][p]);
        if (n1 > n2) n1 = n2;
        mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
        cout << "Reco -> WWTight  Efficiency (MC) : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
        cout << "\n";
        efficiency_RecoToWWTight.push_back(ratio);
        efficiency_RecoToWWTight_lowErr.push_back(errLow);
        efficiency_RecoToWWTight_highErr.push_back(errHigh);


        n1 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p]);
        n2 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT_binned[q][e][p] + EventCount_TagPlusWWTightIdIsoFailHLT_binned[q][e][p]);
        if (n1 > n2) n1 = n2;
        mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
        cout << "WWTight  -> HLT : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
        cout << "\n";

        efficiency_WWTightToHLT.push_back(ratio);
        efficiency_WWTightToHLT_lowErr.push_back(errLow);
        efficiency_WWTightToHLT_highErr.push_back(errHigh);

  
        cout << "\n\n\n";
      }

    //Make Efficiency Graphs
    const Int_t nbins = efficiency_RecoToWWTight.size();
    Double_t x[nbins];
    Double_t y[nbins];
    Double_t xErr[nbins];
    Double_t yErrLow[nbins];
    Double_t yErrHigh[nbins];

    //***********************************************************
    //Reco -> WW Tight    
    //***********************************************************
    for (int b=0; b< efficiency_RecoToWWTight.size(); ++b) {
      x[b] = (ptbinUpEdge[b] + ptbinLowEdge[b]) / 2;
      xErr[b] = fabs(ptbinUpEdge[b] - ptbinLowEdge[b]) / 2;
      if (b==efficiency_RecoToWWTight.size() - 1) {
        x[b] = (100 + ptbinLowEdge[b]) / 2;
        xErr[b] = fabs(100 - ptbinLowEdge[b]) / 2;
      }
      y[b] = efficiency_RecoToWWTight[b];
      yErrLow[b] = fabs(efficiency_RecoToWWTight_lowErr[b]);
      yErrHigh[b] = efficiency_RecoToWWTight_highErr[b];
    }
   
    TGraphAsymmErrors *efficiencyGraph_RecoToWWTight = new TGraphAsymmErrors(nbins, x, y, xErr, xErr, yErrLow,yErrHigh );
    efficiencyGraph_RecoToWWTight->SetName(("MCEfficiency_RecoToWWTight_" + chargebinLabel[q] + "_" + etabinLabel[e]).c_str());
    efficiencyGraph_RecoToWWTight->SetTitle("");
    efficiencyGraph_RecoToWWTight->GetXaxis()->SetTitle("p_{T} [GeV/c]");
    efficiencyGraph_RecoToWWTight->GetYaxis()->SetTitle("Efficiency");
    efficiencyGraph_RecoToWWTight->SetMaximum(1.0);
    efficiencyGraph_RecoToWWTight->SetMinimum(0.0);
    efficiencyGraph_RecoToWWTight->SetMarkerSize(1);
    efficiencyGraph_RecoToWWTight->SetLineWidth(2);
    efficiencyGraph_RecoToWWTight->GetXaxis()->SetRangeUser(0,100);

    file->WriteTObject(efficiencyGraph_RecoToWWTight, efficiencyGraph_RecoToWWTight->GetName(), "WriteDelete");


    //***********************************************************
    //WW Tight -> HLT
    //***********************************************************
    for (int b=0; b< efficiency_WWTightToHLT.size(); ++b) {
      x[b] = (ptbinUpEdge[b] + ptbinLowEdge[b]) / 2;
      xErr[b] = fabs(ptbinUpEdge[b] - ptbinLowEdge[b]) / 2;
      if (b==efficiency_RecoToWWTight.size() - 1) {
        x[b] = (100 + ptbinLowEdge[b]) / 2;
        xErr[b] = fabs(100 - ptbinLowEdge[b]) / 2;
      }
      y[b] = efficiency_WWTightToHLT[b];
      yErrLow[b] = fabs(efficiency_WWTightToHLT_lowErr[b]);
      yErrHigh[b] = efficiency_WWTightToHLT_highErr[b];
    }      
    TGraphAsymmErrors *efficiencyGraph_WWTightToHLT = new TGraphAsymmErrors(nbins, x, y, xErr, xErr, yErrLow,yErrHigh );
    efficiencyGraph_WWTightToHLT->SetName(("MCEfficiency_WWTightToHLT_" + chargebinLabel[q] + "_" + etabinLabel[e]).c_str());
    efficiencyGraph_WWTightToHLT->SetTitle("");
    efficiencyGraph_WWTightToHLT->GetXaxis()->SetTitle("p_{T} [GeV/c]");
    efficiencyGraph_WWTightToHLT->GetYaxis()->SetTitle("Efficiency");
    efficiencyGraph_WWTightToHLT->SetMaximum(1.0);
    efficiencyGraph_WWTightToHLT->SetMinimum(0.0);
    efficiencyGraph_WWTightToHLT->SetMarkerSize(1);
    efficiencyGraph_WWTightToHLT->SetLineWidth(2);
    efficiencyGraph_WWTightToHLT->GetXaxis()->SetRangeUser(0,100);

    file->WriteTObject(efficiencyGraph_WWTightToHLT, efficiencyGraph_WWTightToHLT->GetName(), "WriteDelete");

    } //end for loop over eta bins
  } //end for loop over charge bins

  file->Close();

  Int_t errorType = 2; //Clopper Pearson intervals
  Double_t ratio;
  Double_t errLow;
  Double_t errHigh;     
  Double_t n1;
  Double_t n2;


  n1 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso);
  n2 = TMath::Nint(EventCount_TagPlusRecoPassWWTightIdIso + EventCount_TagPlusRecoFailWWTightIdIso);
  if (n1 > n2) n1 = n2;
  mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
  cout << "Reco -> WWTight  Efficiency (MC) : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
  cout << "\n";



  n1 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT);
  n2 = TMath::Nint(EventCount_TagPlusWWTightIdIsoPassHLT + EventCount_TagPlusWWTightIdIsoFailHLT);
  if (n1 > n2) n1 = n2;
  mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, errorType);      
  cout << "WWTight  -> HLT : " << n1 << " / " << n2 << " = " << ratio << " + " << errHigh << " - " << errLow << endl;
  cout << "\n";

  

  cout << "**********************************************************************\n";

      
  gBenchmark->Show("ElectronTagAndProbe");       


} 
Example #17
0
void HwwDYBkgEstimate(const string inputFilename, Double_t mHiggs,
                 const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi = 35.5;              // luminosity (pb^-1)
  Int_t ChargeSelection = 0;
//   ChargeSelection = 1;
    
  Double_t fPtMaxLowerCut;
  Double_t fPtMinLowerCut;
  Double_t fDileptonMassUpperCut;
  Double_t fDeltaPhiCut;

  Double_t fHiggsMass = mHiggs;

  //Configure Higgs Mass Dependant Cuts
  if (fHiggsMass == 120) { fPtMaxLowerCut = 20.0;        fPtMinLowerCut = 20.0; 
                           fDileptonMassUpperCut = 40.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 130) { fPtMaxLowerCut = 25.0;        fPtMinLowerCut = 20.0;
                           fDileptonMassUpperCut = 45.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 140) { fPtMaxLowerCut = 25.0;        fPtMinLowerCut = 20.0;
                           fDileptonMassUpperCut = 45.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 150) { fPtMaxLowerCut = 27.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 160) { fPtMaxLowerCut = 30.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 170) { fPtMaxLowerCut = 34.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 50.0; fDeltaPhiCut = 60.0;
  }
  if (fHiggsMass == 180) { fPtMaxLowerCut = 36.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 60.0; fDeltaPhiCut = 70.0;
  }
  if (fHiggsMass == 190) { fPtMaxLowerCut = 38.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 80.0; fDeltaPhiCut = 90.0;
  }
  if (fHiggsMass == 200) { fPtMaxLowerCut = 40.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 90.0; fDeltaPhiCut = 100.0;
  }
  if (fHiggsMass == 210) { fPtMaxLowerCut = 44.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 110.0; fDeltaPhiCut = 110.0;
  }
  if (fHiggsMass == 220) { fPtMaxLowerCut = 48.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 120.0; fDeltaPhiCut = 120.0;
  }
  if (fHiggsMass == 230) { fPtMaxLowerCut = 52.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 130.0; fDeltaPhiCut = 130.0;
  }
  if (fHiggsMass == 250) { fPtMaxLowerCut = 55.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 150.0; fDeltaPhiCut = 140.0;
  }
  if (fHiggsMass == 300) { fPtMaxLowerCut = 70.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 200.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 350) { fPtMaxLowerCut = 80.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 250.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 400) { fPtMaxLowerCut = 90.0;         fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 300.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 450) { fPtMaxLowerCut = 110.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 350.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 500) { fPtMaxLowerCut = 120.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 400.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 550) { fPtMaxLowerCut = 130.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 450.0; fDeltaPhiCut = 175.0;
  }
  if (fHiggsMass == 600) { fPtMaxLowerCut = 140.0;        fPtMinLowerCut = 25.0;
                           fDileptonMassUpperCut = 500.0; fDeltaPhiCut = 175.0;
  }


  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *DileptonMass_allOtherCuts_ee = new TH1D("DileptonMass_allOtherCuts_ee", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCuts_emu = new TH1D("DileptonMass_allOtherCuts_emu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCuts_mumu = new TH1D("DileptonMass_allOtherCuts_mumu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_ee = new TH1D("DileptonMass_allOtherCutsExceptMetCut_ee", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_emu = new TH1D("DileptonMass_allOtherCutsExceptMetCut_emu", ";Mass_{ll};Number of Events",150,0.,300.);
  TH1D *DileptonMass_allOtherCutsExceptMetCut_mumu = new TH1D("DileptonMass_allOtherCutsExceptMetCut_mumu", ";Mass_{ll};Number of Events",150,0.,300.);

  Double_t NEventsIn_BeforeMetCut_ee = 0;
  Double_t NEventsIn_BeforeMetCut_em = 0;
  Double_t NEventsIn_BeforeMetCut_mm = 0;
  Double_t NEventsOut_BeforeMetCut_ee = 0;
  Double_t NEventsOut_BeforeMetCut_em = 0;
  Double_t NEventsOut_BeforeMetCut_mm = 0;
  Double_t NEventsIn_AfterMetCut_ee = 0;
  Double_t NEventsIn_AfterMetCut_em = 0;
  Double_t NEventsIn_AfterMetCut_mm = 0;
  Double_t NEventsOut_AfterMetCut_ee = 0;
  Double_t NEventsOut_AfterMetCut_em = 0;
  Double_t NEventsOut_AfterMetCut_mm = 0;


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TFile *inputFile=0;
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("mithep::TElectron");
  TClonesArray *muonArr = new TClonesArray("mithep::TMuon");
  TClonesArray *jetArr = new TClonesArray("mithep::TJet");
  
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
//   rlrm.AddJSONFile("Cert_TopOct22_Merged_135821-148058_allPVT.txt"); 
   rlrm.AddJSONFile("Cert_136033-149442_7TeV_Dec22ReReco_Collisions10_JSON_v3.txt"); 
   hasJSON = kFALSE;

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); 
  TBranch *infoBr;
  TBranch *electronBr;
  TBranch *muonBr;
  TBranch *jetBr;


  //*****************************************************************************************
  //Loop over muon Data Tree
  //*****************************************************************************************
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);      infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Electron", &electronArr); electronBr = eventTree->GetBranch("Electron");
  eventTree->SetBranchAddress("Muon", &muonArr);         muonBr = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("PFJet", &jetArr);         jetBr = eventTree->GetBranch("PFJet");
  
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;
		
    mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
    if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...
     
    //for the skimmed input, I already required the HLT bits.
    //    if (!passHLT(info->triggerBits, info->runNum, kTRUE)) continue;

    //********************************************************
    // Load the branches
    //********************************************************
    electronArr->Clear(); 
    muonArr->Clear(); 
    jetArr->Clear(); 
    electronBr->GetEntry(ientry);
    muonBr->GetEntry(ientry);
    jetBr->GetEntry(ientry);

    //event weight
    Double_t eventweight = info->eventweight * lumi;

    //********************************************************
    // TcMet
    //********************************************************
    TVector3 met;        
    if(info->tcMEx!=0 || info->tcMEy!=0) {       
      met.SetXYZ(info->tcMEx, info->tcMEy, 0);
    }

    //********************************************************
    // TcMet
    //********************************************************

    Int_t NSoftMuons = 0;
    Int_t NLeptons = 0;
    vector<Int_t> leptonType;
    vector<Int_t> leptonIndex;
    vector<Double_t> leptonPt;
    vector<Double_t> leptonEta;
    vector<Double_t> leptonPhi;
    vector<Int_t> leptonCharge;

    Int_t NJets = 0;
    const mithep::TJet *leadingJet = 0;
    
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);      
      if ( (0==0)
           &&
           passMuonCuts(mu)
           &&
           fabs(mu->eta) < 2.4
           && 
           mu->pt > 10.0
        ) {
        leptonPt.push_back(mu->pt);
        leptonEta.push_back(mu->eta);
        leptonPhi.push_back(mu->phi);
        leptonType.push_back(13);
        leptonIndex.push_back(i);  
        leptonCharge.push_back(mu->q);
      }
    }
    //soft muons
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);
      Bool_t isCleanMuon = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if ( leptonType[k] == 13 
             && mithep::MathUtils::DeltaR(mu->phi, mu->eta, leptonPhi[k],leptonEta[k]) < 0.1
          ) {
          isCleanMuon = kTRUE; 
          break;
        }
      }
      if ( mu->pt > 3.0
           && (mu->qualityBits & kTMLastStationAngTight)
           && mu->nTkHits > 10
           && fabs(mu->d0) < 0.2
           && (mu->typeBits & kTracker)
           && !isCleanMuon
        ) {
        NSoftMuons++;
      }
    }
    for(Int_t i=0; i<electronArr->GetEntries(); i++) {
      const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
      Bool_t isMuonOverlap = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if ( leptonType[k] == 13 
             && mithep::MathUtils::DeltaR(ele->phi, ele->eta, leptonPhi[k],leptonEta[k]) < 0.1
          ) {
          isMuonOverlap = kTRUE; 
          break;
        }        
      }

      if ( (0==0)
           && 
           passElectronCuts(ele)
           &&
           fabs(ele->eta) < 2.5
           && 
           ele->pt > 10.0
           &&
           !isMuonOverlap
        ) {
        leptonPt.push_back(ele->pt);
        leptonEta.push_back(ele->eta);
        leptonPhi.push_back(ele->phi);
        leptonType.push_back(11);
        leptonIndex.push_back(i);
        leptonCharge.push_back(ele->q);
      }
    }


    //sort leptons
    Int_t tempType;
    Int_t tempIndex;
    Double_t tempPt;
    Double_t tempEta;
    Double_t tempPhi;
    Int_t tempCharge;
    for (int l=0; l<leptonIndex.size(); l++) {
      for (int k=0; k < leptonIndex.size() - 1; k++) {
        if (leptonPt[k+1] > leptonPt[k]) {
          tempType = leptonType[k];
          tempIndex = leptonIndex[k];
          tempPt = leptonPt[k];
          tempEta = leptonEta[k];
          tempPhi = leptonPhi[k];
          tempCharge = leptonCharge[k];
          
          leptonType[k] = leptonType[k+1];
          leptonIndex[k] = leptonIndex[k+1];
          leptonPt[k] = leptonPt[k+1];
          leptonEta[k] = leptonEta[k+1];
          leptonPhi[k] = leptonPhi[k+1];
          leptonCharge[k] = leptonCharge[k+1];

          leptonType[k+1] = tempType;
          leptonIndex[k+1] = tempIndex;
          leptonPt[k+1] = tempPt;
          leptonEta[k+1] = tempEta;
          leptonPhi[k+1] = tempPhi;
          leptonCharge[k+1] = tempCharge;
          
        }
      }
    }

    double maxBtag = -99999;
    for(Int_t i=0; i<jetArr->GetEntries(); i++) {
      const mithep::TJet *jet = (mithep::TJet*)((*jetArr)[i]);

      Bool_t leptonOverlap = kFALSE;
      for (int k=0; k<leptonPt.size(); ++k) {
        if (mithep::MathUtils::DeltaR(jet->phi, jet->eta, leptonPhi[k],leptonEta[k]) < 0.3) {
          leptonOverlap = kTRUE;
        }
      }

      if (!leptonOverlap) {
        if (jet->pt > 25 && fabs(jet->eta) < 5.0 ) {
          if (!leadingJet || jet->pt > leadingJet->pt) {
            leadingJet = jet;
          }
          NJets++;
        } else {
          if (jet->TrackCountingHighEffBJetTagsDisc > maxBtag ) maxBtag = jet->TrackCountingHighEffBJetTagsDisc;
        }
      }
    }


    //******************************************************************************
    //dilepton preselection
    //******************************************************************************
    if (leptonPt.size() < 2) continue;
    if (!(leptonPt[0] > 20.0 && leptonPt[1] > 10.0)) continue;

    for(int i = 0; i < leptonPt.size(); ++i) {
      for(int j = i+1; j < leptonPt.size(); ++j) {

        //require opposite sign
        if ((ChargeSelection == 0 && leptonCharge[i] == leptonCharge[j]) || (ChargeSelection == 1 && leptonCharge[0] != leptonCharge[j])) continue;


        Int_t finalState = -1;
        if (leptonType[i] == 11 && leptonType[j] == 11) {
          finalState = 0;
        } else if (leptonType[i] == 13 && leptonType[j] == 13) {
          finalState = 1;
        } else if (leptonType[i] == 11 && leptonType[j] == 13) {
          finalState = 2;
        } else if (leptonType[i] == 13 && leptonType[j] == 11) {
          finalState = 3;
        }


        //***********************************************************************************************
        //|Z_vert-Z_l| maximum
        //***********************************************************************************************
        double zDiffMax = 0.0;
       
        double dz_i = 0;
        if (leptonType[0] == 11) {
          dz_i = ((mithep::TElectron*)((*electronArr)[leptonIndex[i]]))->dz;
        } else {
          dz_i = ((mithep::TMuon*)((*muonArr)[leptonIndex[i]]))->dz;
        }
        if (dz_i > zDiffMax) zDiffMax = dz_i;
    
        double dz_j;
        if (leptonType[j] == 11) {
          dz_j = ((mithep::TElectron*)((*electronArr)[leptonIndex[j]]))->dz;
        } else {
          dz_j = ((mithep::TMuon*)((*muonArr)[leptonIndex[j]]))->dz;
        }
        if (dz_j > zDiffMax) zDiffMax = dz_j;
        //szDiffMax = fabs(dz_i - dz_j);

        //******************************************************************************
        //construct event variables
        //******************************************************************************
        mithep::FourVectorM lepton1;
        mithep::FourVectorM lepton2;
        if (leptonType[i] == 11) {
          lepton1.SetCoordinates(leptonPt[i], leptonEta[i], leptonPhi[i], 0.51099892e-3 );
        } else {
          lepton1.SetCoordinates(leptonPt[i], leptonEta[i], leptonPhi[i], 105.658369e-3 );
        }
        if (leptonType[j] == 11) {
          lepton2.SetCoordinates(leptonPt[j], leptonEta[j], leptonPhi[j], 0.51099892e-3 );
        } else {
          lepton2.SetCoordinates(leptonPt[j], leptonEta[j], leptonPhi[j], 105.658369e-3 );
        }
        mithep::FourVectorM dilepton = lepton1+lepton2;

        double deltaPhiLeptons = mithep::MathUtils::DeltaPhi(lepton1.Phi(), 
                                                             lepton2.Phi())* 180.0 / TMath::Pi();    
        double deltaPhiDileptonMet = mithep::MathUtils::DeltaPhi(met.Phi(), 
                                                                 dilepton.Phi())*180.0 / TMath::Pi();    
        double mtHiggs = TMath::Sqrt(2.0*dilepton.Pt() * met.Phi()*
                                     (1.0 - cos(deltaPhiDileptonMet * TMath::Pi() / 180.0)));

        //angle between MET and closest lepton
        double deltaPhiMetLepton[2] = {mithep::MathUtils::DeltaPhi(met.Phi(), lepton1.Phi()),
                                       mithep::MathUtils::DeltaPhi(met.Phi(), lepton2.Phi())};
  
        double mTW[2] = {TMath::Sqrt(2.0*lepton1.Pt()*met.Pt()*
                                     (1.0 - cos(deltaPhiMetLepton[0]))),
                         TMath::Sqrt(2.0*lepton2.Pt()*met.Pt()*
                                     (1.0 - cos(deltaPhiMetLepton[1])))};

        double minDeltaPhiMetLepton = (deltaPhiMetLepton[0] < deltaPhiMetLepton[1])?
          deltaPhiMetLepton[0]:deltaPhiMetLepton[1];

        double METdeltaPhilEt = met.Pt();
        if(minDeltaPhiMetLepton < TMath::Pi()/2.)
          METdeltaPhilEt = METdeltaPhilEt * sin(minDeltaPhiMetLepton);

    
        //*********************************************************************************************
        //Define Cuts
        //*********************************************************************************************
        const int nCuts = 14;
        bool passCut[nCuts] = {false, false, false, false, false, false, false, false, false, false,
                               false, false, false, false};
  
        if(lepton1.Pt() >  20.0 &&
           lepton2.Pt() >= 10.0) passCut[0] = true;

        if(zDiffMax < 1.0)                    passCut[1] = true;
  
        if(met.Pt()    > 20.0)               passCut[2] = true;
  
        if(dilepton.M() > 12.0)            passCut[3] = true;
   
        if (finalState == 0 || finalState == 1){ // mumu/ee
          if(fabs(dilepton.M()-91.1876)   > 15.0)   passCut[4] = true;
          if(METdeltaPhilEt > 35) passCut[5] = true;
        }
        else if(finalState == 2 ||finalState == 3 ) { // emu
          passCut[4] = true;
          if(METdeltaPhilEt > 35) passCut[5] = true;
        }

        if(NJets     < 1)              passCut[6] = true;
        
        if (NSoftMuons == 0 )      passCut[7] = true;

        if (!(leptonPt.size() >= 3 && leptonPt[2] > 10.0)) passCut[8] = true;

        if(maxBtag < 2.1)                     passCut[9] = true;

        if (lepton1.Pt() > fPtMaxLowerCut) passCut[10] = true;
        if (lepton2.Pt() > fPtMinLowerCut) passCut[11] = true;
        if (dilepton.M() < fDileptonMassUpperCut)   passCut[12] = true;
        if (deltaPhiLeptons < fDeltaPhiCut) passCut[13] = true;

        //*********************************************************************************************
        //Make Selection Histograms. Number of events passing each level of cut
        //*********************************************************************************************  
        bool passAllCuts = true;
        for(int c=0; c<nCuts; c++) passAllCuts = passAllCuts & passCut[c];
    
  
        //*****************************************************************************************
        //Make Histograms Before Met Cut
        //*****************************************************************************************
        if (passCut[0] && passCut[1] && passCut[3] && passCut[6] &&passCut[7] && passCut[8] && passCut[9] 
//             && passCut[10] && passCut[11] && passCut[13] 
          ) {

          if (finalState == 0) {
            DileptonMass_allOtherCutsExceptMetCut_ee->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_ee++;
            } else {
              NEventsIn_BeforeMetCut_ee++;
            }

          } else if (finalState == 1) {
            DileptonMass_allOtherCutsExceptMetCut_mumu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_mm++;
            } else {
              NEventsIn_BeforeMetCut_mm++;
            }

          } else {
            DileptonMass_allOtherCutsExceptMetCut_emu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_BeforeMetCut_em++;
            } else {
              NEventsIn_BeforeMetCut_em++;
            }
          }        
        }

        //*****************************************************************************************
        //Make Histograms  
        //*****************************************************************************************
        if (passCut[0] && passCut[1] && passCut[2] && passCut[3] && passCut[5] &&passCut[6] &&passCut[7] && passCut[8] && passCut[9] 
//             && passCut[10] && passCut[11] && passCut[13] 
          ) {

          if (finalState == 0) {
            DileptonMass_allOtherCuts_ee->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_ee++;
            } else {
              NEventsIn_AfterMetCut_ee++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          } else if (finalState == 1) {
            DileptonMass_allOtherCuts_mumu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_mm++;
            } else {
              NEventsIn_AfterMetCut_mm++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          } else {
            DileptonMass_allOtherCuts_emu->Fill(dilepton.M());
            if(fabs(dilepton.M()-91.1876)   > 15.0) {
              NEventsOut_AfterMetCut_em++;
            } else {
              NEventsIn_AfterMetCut_em++;
              cout << info->runNum << " " << info->lumiSec << " " << info->evtNum << " : " << dilepton.M() << " " 
                   << finalState << " : " << lepton1.Pt() << " " << lepton1.Eta() << " " << lepton1.Phi() << " : " 
                   << " : " << lepton2.Pt() << " " << lepton2.Eta() << " " << lepton2.Phi() << " \n" ;
            }
          }        
        }



      }
    }
  

  } //end loop over data     



  delete info;
  delete electronArr;
  delete muonArr;
  delete jetArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 



  cout << "Before Met Cut\n";
  cout << "Number of Events in Z window : (ee) " << NEventsIn_BeforeMetCut_ee << " (mm) " << NEventsIn_BeforeMetCut_mm << endl;
  cout << "Number of Events out of Z window : (ee) " << NEventsOut_BeforeMetCut_ee << " (mm) " << NEventsOut_BeforeMetCut_mm << endl;
  cout << "Ratio Out/In : (ee) " << NEventsOut_BeforeMetCut_ee / NEventsIn_BeforeMetCut_ee << " (mm) "
       << NEventsOut_BeforeMetCut_mm / NEventsIn_BeforeMetCut_mm << endl; 


  cout << "After Met Cut\n";
  cout << "Number of Events in Z window : (ee) " << NEventsIn_AfterMetCut_ee << " (mm) " 
       << NEventsIn_AfterMetCut_mm << " (em) " << NEventsIn_AfterMetCut_em << endl;
  cout << "Number of Events out of Z window : (ee) " << NEventsOut_AfterMetCut_ee << " (mm) " 
       << NEventsOut_AfterMetCut_mm << " (em) " << NEventsOut_AfterMetCut_em << endl;








  //--------------------------------------------------------------------------------------------------------------
  // Save Histograms;
  //============================================================================================================== 
  TFile *file = new TFile("HwwSelectionPlots.root", "RECREATE");
  
  
  file->WriteTObject(DileptonMass_allOtherCuts_ee ,DileptonMass_allOtherCuts_ee->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCuts_mumu ,DileptonMass_allOtherCuts_mumu->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCuts_emu ,DileptonMass_allOtherCuts_emu->GetName(), "WriteDelete");

  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_ee ,DileptonMass_allOtherCutsExceptMetCut_ee->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_mumu ,DileptonMass_allOtherCutsExceptMetCut_mumu->GetName(), "WriteDelete");
  file->WriteTObject(DileptonMass_allOtherCutsExceptMetCut_emu ,DileptonMass_allOtherCutsExceptMetCut_emu->GetName(), "WriteDelete");
  file->Close();
  delete file;

        
  gBenchmark->Show("WWTemplate");       
} 
void combineOSWeights(int erg_tev, double m4l_low, double m4l_high){
  TString erg_dir;
  erg_dir.Form("LHC_%iTeV", erg_tev);
  TString comstring;
  comstring.Form("%iTeV", erg_tev);

  TString cinput_common = user_dir_hep + "Analysis/Auxiliary/";
  TString coutput_common = user_dir_hep + "Analysis/Auxiliary/";

  TFile* finput[2];
  for (int iCR=0; iCR<2; iCR++){
    TString fname = "OSfakeweights_";
    if (iCR==0) fname.Append("ZLL_");
    else fname.Append("QQBZZ_");
    fname += comstring;
    fname.Append(Form("_m4l_%.1f_%.1f%s", m4l_low, m4l_high, ".root"));
    fname.Prepend(cinput_common);
    finput[iCR] = new TFile(fname, "read");
  }

  TString coutput = "OSfakeweights_AfterCorrection_";
  coutput += comstring;
  coutput.Prepend(coutput_common);
  coutput.Append(".root");
  TFile* foutput = new TFile(coutput, "recreate");

  TH3F* hOSweight_ZLL_unweighted[nSIPCuts][3*2];
  TH3F* hOSweight_ZLL_2p2fin3p1f[nSIPCuts][3*2];
  TH3F* hOSweight_ZLL_weighted[nSIPCuts][3*2];
  TH3F* hOSweight_qqZZ[nSIPCuts][3*2];
  TH3F* hOSweight_3p1fFinal[nSIPCuts][3*2];

  int iM1cut=0;
  int isocut=3;
  for (int icut=0; icut<nSIPCuts; icut++){
    for (int catZ1=0; catZ1<2; catZ1++){
      for (int catZ2=0; catZ2<3; catZ2++){
        int index_catZ = 3*catZ1+catZ2;
        TString strOSweight_ZLL_unweighted = produceCRname(0, 0, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");
        TString strOSweight_ZLL_2p2fin3p1f = produceCRname(0, 1, 2, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS_2p2fin3p1f");
        TString strOSweight_ZLL_weighted = produceCRname(0, 1, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");
        TString strOSweight_qqZZ = produceCRname(2, 0, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS");

        cout << strOSweight_ZLL_unweighted << endl;
        hOSweight_ZLL_unweighted[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_unweighted);
        cout << strOSweight_ZLL_2p2fin3p1f << endl;
        hOSweight_ZLL_2p2fin3p1f[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_2p2fin3p1f);
        cout << strOSweight_ZLL_weighted << endl;
        hOSweight_ZLL_weighted[icut][index_catZ] = (TH3F*)finput[0]->Get(strOSweight_ZLL_weighted);
        cout << strOSweight_qqZZ << endl;
        hOSweight_qqZZ[icut][index_catZ] = (TH3F*)finput[1]->Get(strOSweight_qqZZ);
/*
        cout << "Nbins hOSweight_ZLL_unweighted: " << hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_unweighted[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_ZLL_2p2fin3p1f: " << hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_ZLL_weighted: " << hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsX()*hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsY()*hOSweight_ZLL_weighted[icut][index_catZ]->GetNbinsZ() << endl;
        cout << "Nbins hOSweight_qqZZ: " << hOSweight_qqZZ[icut][index_catZ]->GetNbinsX()*hOSweight_qqZZ[icut][index_catZ]->GetNbinsY()*hOSweight_qqZZ[icut][index_catZ]->GetNbinsZ() << endl;
*/
        TString strOSweight_3p1fFinal = "OSfakeweight_";
        if (catZ1==0) strOSweight_3p1fFinal.Append("_Zmumu");
        else strOSweight_3p1fFinal.Append("_Zee");
        if (catZ2==0) strOSweight_3p1fFinal.Append("_mumuOS");
        else if (catZ2==1) strOSweight_3p1fFinal.Append("_emuOS");
        else if (catZ2==2) strOSweight_3p1fFinal.Append("_eeOS");
        strOSweight_3p1fFinal.Append("_");
        strOSweight_3p1fFinal += cutNames[icut];
        strOSweight_3p1fFinal.Append("_");
        strOSweight_3p1fFinal += strLepIsoCut_label[isocut-1];

        hOSweight_3p1fFinal[icut][index_catZ] = (TH3F*)hOSweight_ZLL_weighted[icut][index_catZ]->Clone(strOSweight_3p1fFinal);
        hOSweight_3p1fFinal[icut][index_catZ]->Sumw2();
        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              hOSweight_3p1fFinal[icut][index_catZ]->SetBinContent(binx, biny, binz, 1);
              hOSweight_3p1fFinal[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
            }
          }
        }

        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              hOSweight_ZLL_unweighted[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
              hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->SetBinError(binx, biny, binz, 0);
            }
          }
        }

        hOSweight_qqZZ[icut][index_catZ]->Divide(hOSweight_ZLL_unweighted[icut][index_catZ]);
        hOSweight_ZLL_2p2fin3p1f[icut][index_catZ]->Divide(hOSweight_ZLL_unweighted[icut][index_catZ]);
        hOSweight_3p1fFinal[icut][index_catZ]->Add(hOSweight_qqZZ[icut][index_catZ], -1);
        hOSweight_3p1fFinal[icut][index_catZ]->Add(hOSweight_ZLL_2p2fin3p1f[icut][index_catZ], -1);
        int nzeros=0;
        for (int binz=0; binz<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ()+1; binz++){
          for (int biny=0; biny<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()+1; biny++){
            for (int binx=0; binx<=hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()+1; binx++){
              double bincontent = hOSweight_3p1fFinal[icut][index_catZ]->GetBinContent(binx, biny, binz);
              double binerror = hOSweight_3p1fFinal[icut][index_catZ]->GetBinError(binx, biny, binz);

              if (binerror>=fabs(bincontent)){
                cout << "Bin error larger than content: " << strOSweight_3p1fFinal << '\t' << bincontent << '\t' << binerror
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetXaxis()->GetBinCenter(binx)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetYaxis()->GetBinCenter(biny)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetZaxis()->GetBinCenter(binz)
                  << endl;
              }

              if (bincontent<0){
                cout << "Bin content <0: " << strOSweight_3p1fFinal << '\t' << bincontent
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetXaxis()->GetBinCenter(binx)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetYaxis()->GetBinCenter(biny)
                  << '\t' << hOSweight_3p1fFinal[icut][index_catZ]->GetZaxis()->GetBinCenter(binz)
                  << endl;
                hOSweight_3p1fFinal[icut][index_catZ]->SetBinContent(binx, biny, binz,0);
                hOSweight_3p1fFinal[icut][index_catZ]->SetBinError(binx, biny, binz, (fabs(bincontent)>binerror?bincontent:binerror));
              }
              if (bincontent<1 && bincontent>0)nzeros++;
            }
          }
        }

        cout << "Nvalid: " << nzeros << '/' << hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsX()*hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsY()*hOSweight_3p1fFinal[icut][index_catZ]->GetNbinsZ() << endl;

        hOSweight_ZLL_weighted[icut][index_catZ]->Multiply(hOSweight_3p1fFinal[icut][index_catZ]);
        hOSweight_ZLL_weighted[icut][index_catZ]->SetName(Form("%s_corrected", hOSweight_ZLL_weighted[icut][index_catZ]->GetName()));
        foutput->WriteTObject(hOSweight_3p1fFinal[icut][index_catZ]);
        foutput->WriteTObject(hOSweight_ZLL_weighted[icut][index_catZ]);
      }
    }
  }

  TH1F* hOS[4];
  TFile* fweight[2] ={
    new TFile(Form("./data/Zmu_OS_%iTeV.root", erg_tev)),
    new TFile(Form("./data/Ze_OS_%iTeV.root", erg_tev))
  };
  hOS[0] = (TH1F*)fweight[0]->Get("h1D_FRmu_EB");
  hOS[1] = (TH1F*)fweight[0]->Get("h1D_FRmu_EE");
  hOS[2] = (TH1F*)fweight[1]->Get("h1D_FRel_EB");
  hOS[3] = (TH1F*)fweight[1]->Get("h1D_FRel_EE");
  hOS[0]->SetName("Zmu_Barrel_FakeRate");
  hOS[1]->SetName("Zmu_Endcap_FakeRate");
  hOS[2]->SetName("Ze_Barrel_FakeRate");
  hOS[3]->SetName("Ze_Endcap_FakeRate");

  for (int hh=0; hh<4; hh++) foutput->WriteTObject(hOS[hh]);
  for (int hh=0; hh<2; hh++) fweight[hh]->Close();



  foutput->Close();
  for (int iCR=0; iCR<2; iCR++) finput[iCR]->Close();
}
void MakePileupReweight(int option = 0) {


  TFile *pileupTargetFile = 0;
  if (option == 0) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogram.root", "READ");
  else if (option == 1) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogramUp.root", "READ");
  else if (option == 2) pileupTargetFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/MyDataPileupHistogramDown.root", "READ");
  else {
    return;
  }
  TH1F *pileupTargetHist = (TH1F*)pileupTargetFile->Get("pileup");
  assert(pileupTargetHist);
  std::cout << "pileupTargetHist " << pileupTargetHist->Integral() << std::endl;

  TFile *pileupSourceFile = new TFile("/afs/cern.ch/work/c/cpena/public/CMSSW_7_6_3/src/RazorAnalyzer/data/DoubleEG_Run2015_CMSSW_7_6_March15.root", "READ");
  //TH1F *pileupSourceHist = (TH1F*)pileupSourceFile->Get("PileupSourceHist");
  TH1F *pileupSourceHist = (TH1F*)pileupSourceFile->Get("pileup"); 
  assert(pileupSourceHist);
  std::cout << "pileupSourceFile " << pileupSourceHist->Integral() << std::endl;
  std::cout << "FILES RETRIEVED" << std::endl;
  //*******************************************************************************************
  //Make NVtx Reweighting Function
  //*******************************************************************************************
  TH1F *PileupTargetNormalized = NormalizeHist( pileupTargetHist );
  TH1F *PileupSourceNormalized = NormalizeHist( pileupSourceHist );
  std::cout << "HISTOS NORMALIZED" << std::endl;
  TH1F *PileupReweight = new TH1F ("PileupReweight",";NPU;Weight",50,0,50);

  for (int i=0; i<PileupReweight->GetXaxis()->GetNbins()+2; i++) {

    double data = 0;
    double bkg = 0;
    if (PileupSourceNormalized->GetBinContent(i) > 0) {
      PileupReweight->SetBinContent(i,PileupTargetNormalized->GetBinContent(i)/PileupSourceNormalized->GetBinContent(i));
    } else if (PileupTargetNormalized->GetBinContent(i) == 0){
      PileupReweight->SetBinContent(i,0.0);
    } else {
      if (i == 1) {
	PileupReweight->SetBinContent(i,1);
      } else {
	PileupReweight->SetBinContent(i,PileupReweight->GetBinContent(i-1));
      }
    }

    cout << "Bin " << i << " : " << PileupReweight->GetXaxis()->GetBinCenter(i) << " : " << PileupReweight->GetBinCenter(i) << " : " << PileupTargetNormalized->GetBinContent(i) << " / " << PileupSourceNormalized->GetBinContent(i) << " = " << PileupReweight->GetBinContent(i) << "\n";
  }

  
  double k = 0;
  for (int i=0; i<PileupSourceNormalized->GetXaxis()->GetNbins()+2; i++) {
    double weight = PileupReweight->GetBinContent(PileupReweight->GetXaxis()->FindFixBin(i-1));
    cout << i << " : " << i-1 << " : " << weight << " : " << PileupSourceNormalized->GetBinContent(i) << " -> " << PileupSourceNormalized->GetBinContent(i)*weight << "\n";
    k += PileupSourceNormalized->GetBinContent(i)*weight;    
  }
  cout << "int = " << k << "\n";

  TFile *file = TFile::Open("PileupReweight2015.root", "UPDATE");
  file->cd();
  if (option == 0) file->WriteTObject(PileupReweight, "PileupReweight", "WriteDelete");
  else if (option == 1) file->WriteTObject(PileupReweight, "PileupReweightSysUp", "WriteDelete");
  else if (option == 2) file->WriteTObject(PileupReweight, "PileupReweightSysDown", "WriteDelete");
  file->Close();
  delete file;

}
Example #20
0
Int_t integrateRatePlots()
{
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
  TGaxis::SetMaxDigits(3);

  const Int_t nFiles = 3;
  //  const Int_t nElectrons = 3;

  TFile * histoFile = new TFile("integratedRates-eta2p1-26Jan12.root","RECREATE");
  TFile * inputFile[nFiles]; 

  inputFile[0] = TFile::Open("RctEmTree-Rates-scaleV1-thr2p0-01Dec11.root"); // v1, 2.0, BOTH ISO AND NON-ISO
  inputFile[1] = TFile::Open("RctEmTree-Rates-scaleV3-thr1p0-12Jan12.root"); // v3, 1.0, iso
  inputFile[2] = TFile::Open("RctEmTree-Rates-HighPU-scaleV3-thr1p0-18Jan12.root"); // v3, 1.0, highPU, iso

  TH1F * h_rank[nFiles], * h_rankIntegrated[nFiles];
  TH1F * h_rankBarrel[nFiles], * h_rankBarrelIntegrated[nFiles];

  // scale factor here is 1./(total n LS * 23 s/LS) * (total lumi / effective lumi) to get from total event counts to rate (event count per second)
  Float_t scaleFactor[3];
  scaleFactor[0] = 14.2 * 1./(15379.*23.) * (713729./68.794); 
  scaleFactor[1] = 1./(15379.*23.) * (713729./68.794); 
  scaleFactor[2] = 1./(299. * 23.) * (299.556 / 49.926) * (201.78 / 4.3559); // scaled up to 2e33 inst lumi from 4e31 -- those last two numbers are times 10^31 

  // tree stuff
  TTree * tree;
  vector<int>     *emRank;
  vector<int>     *emIso;
  vector<int>     *emIeta;
  TBranch        *b_emRank;
  TBranch        *b_emIso;
  TBranch        *b_emIeta;

  // end tree stuff

//   Int_t nBins = 64;
//   Float_t xMin = 0., xMax = 64.;
  Int_t nBins = 52;
  Float_t xMin = 12., xMax = 64.;

  // |eta| < 1.5, barrel-only
//   Int_t barrelIEtaBoundaryLower = 7; // this is REGION ieta -- goes from 4 to 17, not including HF.  
//   Int_t barrelIEtaBoundaryUpper = 14; // this takes first four regions (last 3 are endcap)

// |eta| < 2.1  
  Int_t barrelIEtaBoundaryLower = 8; // this is REGION ieta -- goes from 4 to 17, not including HF.  
  Int_t barrelIEtaBoundaryUpper = 13; // this takes first three regions (first 24 towers), going to eta 2.1720
  
  TCanvas * rankCanvas = new TCanvas("rankCanvas","EM rank distribution");
  TCanvas * rankBarrelCanvas = new TCanvas("rankBarrelCanvas","EM rank distribution (|#eta| < 2.1)");

  TCanvas * integratedCanvas = new TCanvas("integratedCanvas","Rate by trigger threshold");
  integratedCanvas->cd();
  TPad * pad1 = new TPad("pad1","pad1",0.,0.35,1.0,1.0);
  pad1->SetBottomMargin(0);
  pad1->Draw();
  TPad * pad2 = new TPad("pad2","pad2",0.,0.,1.0,0.35);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(0.3);
  pad2->Draw();

  TCanvas * integratedBarrelCanvas = new TCanvas("integratedBarrelCanvas","Rate by trigger threshold (|#eta| < 2.1)");
  integratedBarrelCanvas->cd();
  TPad * pad1B = new TPad("pad1B","pad1B",0.,0.35,1.0,1.0);
  pad1B->SetBottomMargin(0);
  pad1B->Draw();
  TPad * pad2B = new TPad("pad2B","pad2B",0.,0.,1.0,0.35);
  pad2B->SetTopMargin(0);
  pad2B->SetBottomMargin(0.3);
  pad2B->Draw();


  for (Int_t file = 0; file < nFiles; file++)
    {
      std::cout << "File " << file << std::endl;
      
      inputFile[file]->cd();

      TString treeName = TString("rctAnalyzer/emTree;1");

      std::cout << "getting tree" << std::endl;
      gDirectory->GetObject(treeName,tree);

      //   std::cout << "X min = " << h_rank->GetXaxis()->GetXmin() << std::endl;
      //   std::cout << "X max = " << h_rank->GetXaxis()->GetXmax() << std::endl;
      
      //   Int_t nBins = h_rank->GetNbinsX();
      
      //   h_rank = new TH1F("h_rank","EM Rank",nBins,h_rank->GetXaxis()->GetXmin(),h_rank->GetXaxis()->GetXmax());
      //   h_rankIntegrated = new TH1F("h_rankIntegrated","Rates by trigger threshold",nBins,h_rank->GetXaxis()->GetXmin(),h_rank->GetXaxis()->GetXmax());
      std::cout << "making histograms" << std::endl;
      
      h_rank[file] = new TH1F(makeName("h_rank",file),"EM Rank",nBins,xMin,xMax);
      h_rankIntegrated[file] = new TH1F(makeName("h_rankIntegrated",file),"Rates by trigger threshold",nBins,xMin,xMax);
      h_rankBarrel[file] = new TH1F(makeName("h_rankBarrel",file),"EM Rank (|#eta| < 2.1)",nBins,xMin,xMax);
      h_rankBarrelIntegrated[file] = new TH1F(makeName("h_rankBarrelIntegrated",file),"Rates by trigger threshold (|#eta| < 2.1)",nBins,xMin,xMax);
      
      rankCanvas->cd();

      // tree stuff
      emRank = 0;
      emIso = 0;
      emIeta = 0;
      
      tree->SetBranchAddress("emRank", &emRank, &b_emRank);
      tree->SetBranchAddress("emIso", &emIso, &b_emIso);
      tree->SetBranchAddress("emIeta", &emIeta, &b_emIeta);
      b_emRank->SetAutoDelete(kTRUE);
      b_emIso->SetAutoDelete(kTRUE);
      b_emIeta->SetAutoDelete(kTRUE);

      tree->SetBranchStatus("*",0);
      tree->SetBranchStatus("emRank",1);
      tree->SetBranchStatus("emIso",1);
      tree->SetBranchStatus("emIeta",1);

      // loop over tree
      std::cout << "Looping over tree" << std::endl;
      Long64_t nentries = tree->GetEntriesFast();
      for (Long64_t jentry = 0; jentry < nentries; jentry++) 
	{
	  //std::cout << "entry " << jentry << std::endl;
	  //Long64_t ientry = tree->LoadTree(jentry);
	  //tree->LoadTree(jentry); // Set current entry.
	  tree->GetEntry(jentry); // Read all branches of entry and return total number of bytes read.
	  
	  Int_t elecSize = emRank->size();
	  for (Int_t elec = 0; elec < elecSize; elec++)
	    {
	      if (file == 0) // isolated and non-isolated
		{
		  h_rank[file]->Fill(emRank->at(elec));
		  if (emIeta->at(elec) >= barrelIEtaBoundaryLower &&
		      emIeta->at(elec) <= barrelIEtaBoundaryUpper)
		    {
		      h_rankBarrel[file]->Fill(emRank->at(elec));
		    }
		  break;
		}
	      else // isolated only
		{
		  if (emIso->at(elec) == 1)
		    {
		      h_rank[file]->Fill(emRank->at(elec));
		      if (emIeta->at(elec) >= barrelIEtaBoundaryLower &&
			emIeta->at(elec) <= barrelIEtaBoundaryUpper)
			{
			  h_rankBarrel[file]->Fill(emRank->at(elec));
			}
		      break;
		    }
		}
	    }
	}
      
      // end tree stuff
      
      // making pretty colors for the lines in the rank plots
      h_rank[file]->SetLineColor(file+1);
      if (file+1 == 3)
	{
	  h_rank[file]->SetLineColor(8);
	}
      if (file+1 == 5)
	{
	  h_rank[file]->SetLineColor(41);
	}
      h_rank[file]->SetLineWidth(2);

      h_rankBarrel[file]->SetLineColor(file+40);
      h_rankBarrel[file]->SetLineWidth(2);

      if (file == 0)
	{
	  h_rank[file]->Draw();
	}
      else
	{
	  h_rank[file]->Draw("same");
	  h_rankBarrel[file]->Draw("same");
	}

      rankBarrelCanvas->cd();
      if (file == 0)
	{
	  h_rankBarrel[file]->Draw();
	}
      else
	{
	  h_rankBarrel[file]->Draw("same");
	}

      // doing the integration      
      Int_t eventsAboveThreshold = 0;
      for (int i = nBins-1; i >= 0; i--)
	{
	  eventsAboveThreshold = eventsAboveThreshold + h_rank[file]->GetBinContent(i);
	  std::cout << "bin is " << i << ", bin content is " << h_rank[file]->GetBinContent(i)
		    << ", eventsAboveThreshold is " << eventsAboveThreshold << std::endl;
	  h_rankIntegrated[file]->Fill(xMin+i,eventsAboveThreshold);
	}
      eventsAboveThreshold = 0;
      for (int i = nBins-1; i >= 0; i--)
	{
	  eventsAboveThreshold = eventsAboveThreshold + h_rankBarrel[file]->GetBinContent(i);
	  std::cout << "bin is " << i << ", bin content is " << h_rankBarrel[file]->GetBinContent(i)
		    << ", eventsAboveThreshold is " << eventsAboveThreshold << std::endl;
	  h_rankBarrelIntegrated[file]->Fill(xMin+i,eventsAboveThreshold);
	}
      std::cout << "sumw2" << std::endl;
      h_rankIntegrated[file]->Sumw2();
      h_rankIntegrated[file]->Scale(scaleFactor[file]);
      h_rankBarrelIntegrated[file]->Sumw2();
      h_rankBarrelIntegrated[file]->Scale(scaleFactor[file]);
      
      // more pretty colors, this time for integrated plots
      h_rankIntegrated[file]->SetLineColor(file+1);
      if (file+1 == 3)
	{
	  h_rankIntegrated[file]->SetLineColor(8);
	}
      if (file+1 == 5)
	{
	  h_rankIntegrated[file]->SetLineColor(41);
	}
      h_rankIntegrated[file]->SetLineWidth(2);

      if (file == 1)
	{
	  h_rankBarrelIntegrated[file]->SetLineColor(kRed+2);
	}
      if (file == 2)
	{
	  h_rankBarrelIntegrated[file]->SetLineColor(kYellow+2);
	}
      h_rankBarrelIntegrated[file]->SetLineWidth(2);

      integratedCanvas->cd();
      pad1->cd();
      std::cout << "Draw" << std::endl;
      if(file == 0)
	{
	  h_rankIntegrated[file]->Draw();
	}
      else
	{
	  h_rankIntegrated[file]->Draw("same");
	  h_rankBarrelIntegrated[file]->Draw("same");
	}

      integratedBarrelCanvas->cd();
      pad1B->cd();
      std::cout << "Draw" << std::endl;
      if(file == 0)
	{
	  h_rankBarrelIntegrated[file]->Draw();
	}
      else
	{
	  h_rankBarrelIntegrated[file]->Draw("same");
	}
      std::cout << "Done drawing" << std::endl;
      
    }

  std::cout << "Making legend" << std::endl;

  TLegend legend(0.3,0.6,0.89,0.89);
  legend.AddEntry(h_rankIntegrated[0],"v1 scales, thr = 2.0, Relaxed");
  legend.AddEntry(h_rankIntegrated[1],"v3 scales, thr = 1.0, Isolated");
  legend.AddEntry(h_rankBarrelIntegrated[1],"v3 scales, thr = 1.0, Isolated, |#eta| < 2.1");
  legend.AddEntry(h_rankIntegrated[2],"High-PU, v3 scales, thr = 1.0, Isolated");
  legend.AddEntry(h_rankBarrelIntegrated[2],"High-PU, v3 scales, thr = 1.0, Isolated, |#eta| < 2.1");
  legend.SetFillColor(0);

  integratedCanvas->cd();
  pad1->cd();
  legend.Draw("same");

  integratedBarrelCanvas->cd();
  pad1B->cd();
  legend.Draw("same");


  std::cout << "Making ratio plots" << std::endl;

  integratedCanvas->cd();
  pad2->cd();
  TH1F * r_eff1;
  TH1F * r_eff2;
  r_eff1 = (TH1F*) h_rankIntegrated[1]->Clone("r_eff1");
  r_eff2 = (TH1F*) h_rankIntegrated[2]->Clone("r_eff2");
  r_eff1->Divide(h_rankIntegrated[0]);
  r_eff2->Divide(h_rankIntegrated[0]);
  r_eff1->SetTitle("");
  r_eff2->SetTitle("");
  r_eff1->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff2->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff1->SetMinimum(0.3);
  r_eff1->SetMaximum(1.0);
  r_eff2->SetMinimum(0.3);
  r_eff2->SetMaximum(1.0);
  r_eff1->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff1->GetXaxis()->SetLabelSize(0.07);
  r_eff1->GetXaxis()->SetTitleSize(0.07);
  r_eff1->GetYaxis()->SetLabelSize(0.07);
  r_eff2->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff2->GetXaxis()->SetLabelSize(0.07);
  r_eff2->GetXaxis()->SetTitleSize(0.07);
  r_eff2->GetYaxis()->SetLabelSize(0.07);
  r_eff1->Draw();
  r_eff2->Draw("same");

  integratedBarrelCanvas->cd();
  pad2B->cd();
  TH1F * r_eff1B;
  TH1F * r_eff2B;
  r_eff1B = (TH1F*) h_rankBarrelIntegrated[1]->Clone("r_eff1B");
  r_eff2B = (TH1F*) h_rankBarrelIntegrated[2]->Clone("r_eff2B");
  r_eff1B->Divide(h_rankIntegrated[0]);
  r_eff2B->Divide(h_rankIntegrated[0]);
  r_eff1B->SetTitle("");
  r_eff2B->SetTitle("");
  r_eff1B->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff2B->GetXaxis()->SetRangeUser(xMin,xMax);
  r_eff1B->SetMinimum(0.3);
  r_eff1B->SetMaximum(1.0);
  r_eff2B->SetMinimum(0.3);
  r_eff2B->SetMaximum(1.0);
  r_eff1B->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff1B->GetXaxis()->SetLabelSize(0.07);
  r_eff1B->GetXaxis()->SetTitleSize(0.07);
  r_eff1B->GetYaxis()->SetLabelSize(0.07);
  r_eff2B->GetXaxis()->SetTitle("Trigger threshold (GeV)");
  r_eff2B->GetXaxis()->SetLabelSize(0.07);
  r_eff2B->GetXaxis()->SetTitleSize(0.07);
  r_eff2B->GetYaxis()->SetLabelSize(0.07);
  r_eff1B->Draw();
  r_eff2B->Draw("same");

  integratedCanvas->cd();
  r_eff1B->Draw("same");
  r_eff2B->Draw("same");

  TLine * unity;
  unity = new TLine(0.,1.0,64.,1.0);
  unity->SetX1(gPad->PadtoX(xMin));
  unity->SetX2(gPad->PadtoX(xMax));
  unity->SetLineColor(kBlue);

  integratedCanvas->cd();
  pad2->cd();
  r_eff1B->Draw("same");
  r_eff2B->Draw("same");
  unity->Draw("same");

  integratedBarrelCanvas->cd();
  pad2B->cd();
  unity->Draw("same");

  std::cout << "Writing canvases to file" << std::endl;
  histoFile->WriteTObject(rankCanvas);
  histoFile->WriteTObject(rankBarrelCanvas);
  histoFile->WriteTObject(integratedCanvas);
  histoFile->WriteTObject(integratedBarrelCanvas);

  std::cout << "Closing input files" << std::endl;
  for (Int_t i = 0; i < nFiles; i++)
    {
      inputFile[i]->Close();
    }

  std::cout << "Deleting canvases" << std::endl;

  delete rankCanvas;
  delete rankBarrelCanvas;
  delete pad1;
  delete pad2;
  delete integratedCanvas;
  delete pad1B;
  delete pad2B;
  delete integratedBarrelCanvas;

  return 0;

}
void ProduceMuonEfficiencyPlots(const string inputfile, int wp = 0,  int option = -1, string label = "") {

  string Label = "";
  if (label != "") Label = "_" + label;

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  bool printdebug = false;


  //*****************************************************************************************
  //Make some histograms
  //*****************************************************************************************
  TH1F *histDenominatorPt = new TH1F ("histDenominatorPt",";Muon p_{T} [GeV/c^{2}]; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorPt = new TH1F ("histNumeratorPt",";Muon p_{T} [GeV/c^{2}]; Number of Events", 50, 0 , 100);
  TH1F *histDenominatorEta = new TH1F ("histDenominatorEta",";Muon Eta; Number of Events", 50, -2.5 , 2.5);
  TH1F *histNumeratorEta = new TH1F ("histNumeratorEta",";Muon Eta; Number of Events", 50, -2.5 , 2.5);
  TH1F *histDenominatorPhi = new TH1F ("histDenominatorPhi",";Muon Phi; Number of Events", 50, 0 , 3.2);
  TH1F *histNumeratorPhi = new TH1F ("histNumeratorPhi",";Muon Phi; Number of Events", 50, 0 , 3.2);
  TH1F *histDenominatorRho = new TH1F ("histDenominatorRho",";Muon Rho; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorRho = new TH1F ("histNumeratorRho",";Muon Rho; Number of Events", 50, 0 , 100);
  TH1F *histDenominatorNpv = new TH1F ("histDenominatorNpv",";Muon Npv; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorNpv = new TH1F ("histNumeratorNpv",";Muon Npv; Number of Events", 50, 0 , 100);
  TH1F *histDenominatorNpu = new TH1F ("histDenominatorNpu",";Muon Npu; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorNpu = new TH1F ("histNumeratorNpu",";Muon Npu; Number of Events", 50, 0 , 100);

  TH2F *histDenominatorPtEta = new TH2F ("histDenominatorPtEta",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, -3.0, 3.0);
  TH2F *histNumeratorPtEta = new TH2F ("histNumeratorPtEta",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, -3.0, 3.0);

  //*******************************************************************************************
  //Read file
  //*******************************************************************************************                
  MuonTree *MuTree = new MuonTree;
  MuTree->LoadTree(inputfile.c_str());
  MuTree->InitTree(MuonTree::kMuTreeLight);

  cout << "Total Entries: " << MuTree->tree_->GetEntries() << "\n";
  int nentries = MuTree->tree_->GetEntries();
  for(UInt_t ientry=0; ientry < MuTree->tree_->GetEntries(); ientry++) {       	
    MuTree->tree_->GetEntry(ientry);

    if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

    //Cuts
    if (MuTree->fMuGenPt < 5) continue;
    if (abs(MuTree->fMuGenEta) > 2.4) continue;

    if (!(MuTree->fMuPt > 5)) continue;

    //For Iso only efficiency require ID cuts   
    if (wp == 10 || wp == 11) {
      if (!(MuTree->fMuPt > 0 && MuTree->fMuIsLoose  && fabs(MuTree->fMuIP3dSig)<4)) continue;
    } 

    //For Trigger efficiency require tight selection
    if (wp >= 100 ){
      if (!(MuTree->fPassTightSelection)) continue;
    }

    if (option==0) {
      //**** PT - ETA ****
      histDenominatorPtEta->Fill(MuTree->fMuGenPt,MuTree->fMuGenEta);
      if(PassSelection(MuTree,wp)) {
	histNumeratorPtEta->Fill(MuTree->fMuGenPt,MuTree->fMuGenEta);
      }


      //**** PT ****
      histDenominatorPt->Fill(MuTree->fMuGenPt);

      //Numerator
      if(PassSelection(MuTree,wp)) {
        histNumeratorPt->Fill(MuTree->fMuGenPt);        
      }


      //**** Eta ****
      if (fabs(MuTree->fMuGenPt) > 30) {
	histDenominatorEta->Fill(MuTree->fMuGenEta);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorEta->Fill(MuTree->fMuGenEta);        
	}

      }

      //**** Phi ****
      if (fabs(MuTree->fMuGenEta) < 2.4) {
	histDenominatorPhi->Fill(MuTree->fMuGenPhi);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorPhi->Fill(MuTree->fMuGenPhi);        
	}

      }

      //**** Rho ****
      if (fabs(MuTree->fMuGenEta) < 2.4) {
	histDenominatorRho->Fill(MuTree->fRho);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorRho->Fill(MuTree->fRho);        
	}

      }
      //**** Npv ****
      if (fabs(MuTree->fMuGenEta) < 2.4) {
	histDenominatorNpv->Fill(MuTree->fNVertices);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorNpv->Fill(MuTree->fNVertices);        
	}

      }

      // //**** Npu ****
      // if (fabs(MuTree->fMuGenEta) < 2.4) {
      //   histDenominatorNpu->Fill(MuTree->);

      //   //Numerator
      //   if(PassSelection(MuTree,wp)) {
      //     histNumeratorNpu->Fill(MuTree->);        
      //   }

      // }
    }
    if (option==1) {
      //**** PT - ETA ****
      histDenominatorPtEta->Fill(MuTree->fMuPt,MuTree->fMuEta);
      if(PassSelection(MuTree,wp)) {
	histNumeratorPtEta->Fill(MuTree->fMuPt,MuTree->fMuEta);
      }


      //**** PT ****
      histDenominatorPt->Fill(MuTree->fMuPt);

      //Numerator
      if(PassSelection(MuTree,wp)) {
        histNumeratorPt->Fill(MuTree->fMuPt);        
      }


      //**** Eta ****
      if (fabs(MuTree->fMuPt) > 55) {
	histDenominatorEta->Fill(MuTree->fMuEta);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorEta->Fill(MuTree->fMuEta);        
	}

      }

      //**** Phi ****
      if (fabs(MuTree->fMuEta) < 2.4) {
	histDenominatorPhi->Fill(MuTree->fMuPhi);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorPhi->Fill(MuTree->fMuPhi);        
	}

      }

      //**** Rho ****
      if (fabs(MuTree->fMuEta) < 2.4) {
	histDenominatorRho->Fill(MuTree->fRho);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorRho->Fill(MuTree->fRho);        
	}

      }
      //**** Npv ****
      if (fabs(MuTree->fMuEta) < 2.4) {
	histDenominatorNpv->Fill(MuTree->fNVertices);

	//Numerator
	if(PassSelection(MuTree,wp)) {
	  histNumeratorNpv->Fill(MuTree->fNVertices);        
	}

      }

    
    }



  }


  //--------------------------------------------------------------------------------------------------------------
  // Make Efficiency Plots
  //==============================================================================================================

  TGraphAsymmErrors *efficiency_pt = createEfficiencyGraph(histNumeratorPt, histDenominatorPt, "Efficiency_Pt" , vector<double>() ,  -99, -99, 0, 1);
  TGraphAsymmErrors *efficiency_eta = createEfficiencyGraph(histNumeratorEta, histDenominatorEta, "Efficiency_Eta" , vector<double>() ,  -99, -99, 0, 1);
  TGraphAsymmErrors *efficiency_phi = createEfficiencyGraph(histNumeratorPhi, histDenominatorPhi, "Efficiency_Phi" , vector<double>() ,  -99, -99, 0, 1);
  TGraphAsymmErrors *efficiency_rho = createEfficiencyGraph(histNumeratorRho, histDenominatorRho, "Efficiency_Rho" , vector<double>() ,  -99, -99, 0, 1);
  TGraphAsymmErrors *efficiency_npv = createEfficiencyGraph(histNumeratorNpv, histDenominatorNpv, "Efficiency_Npv" , vector<double>() ,  -99, -99, 0, 1);
  TGraphAsymmErrors *efficiency_npu = createEfficiencyGraph(histNumeratorNpu, histDenominatorNpu, "Efficiency_Npu" , vector<double>() ,  -99, -99, 0, 1);  
  TH2F *efficiency_pteta = createEfficiencyHist2D(histNumeratorPtEta, histDenominatorPtEta, "Efficiency_PtEta" , vector<double>() ,vector<double>());  


  //--------------------------------------------------------------------------------------------------------------
  // Draw
  //==============================================================================================================
  TCanvas *cv =0;

  cv = new TCanvas("cv","cv",800,600);
  efficiency_pt->Draw("AP");
  efficiency_pt->SetTitle("");
  efficiency_pt->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Pt.gif").c_str());

  cv = new TCanvas("cv","cv",800,600);
  efficiency_eta->Draw("AP");
  efficiency_eta->SetTitle("");
  efficiency_eta->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Eta.gif").c_str());

  cv = new TCanvas("cv","cv",800,600);
  efficiency_phi->Draw("AP");
  efficiency_phi->SetTitle("");
  efficiency_phi->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Phi.gif").c_str());

  cv = new TCanvas("cv","cv",800,600);
  efficiency_rho->Draw("AP");
  efficiency_rho->SetTitle("");
  efficiency_rho->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Rho.gif").c_str());

  cv = new TCanvas("cv","cv",800,600);
  efficiency_npv->Draw("AP");
  efficiency_npv->SetTitle("");
  efficiency_npv->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Npv.gif").c_str());

  cv = new TCanvas("cv","cv",800,600);
  efficiency_npu->Draw("AP");
  efficiency_npu->SetTitle("");
  efficiency_npu->GetYaxis()->SetRangeUser(0.0,1.0);
  cv->SaveAs(("Efficiency"+Label+"_Npu.gif").c_str());


  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  TFile *file = TFile::Open(("Efficiency"+Label+".root").c_str(), "UPDATE");
  file->cd();
  file->WriteTObject(efficiency_pt, "Efficiency_Pt", "WriteDelete");
  file->WriteTObject(efficiency_eta, "Efficiency_Eta", "WriteDelete");
  file->WriteTObject(efficiency_phi, "Efficiency_Phi", "WriteDelete");
  file->WriteTObject(efficiency_rho, "Efficiency_Rho", "WriteDelete");
  file->WriteTObject(efficiency_npv, "Efficiency_NPV", "WriteDelete");
  file->WriteTObject(efficiency_npu, "Efficiency_NPU", "WriteDelete");
  file->WriteTObject(efficiency_pteta, "Efficiency_PtEta", "WriteDelete");

  file->Close();
  delete file;       

}
void makeGenLevel_pTRatios(int erg_tev){
  char TREE_NAME[]="candTree";
  TString OUTPUT_NAME = Form("compareProductionModes_pT_%iTeV.root", erg_tev);
  char csuffix[] = "_pToverMZZ";
  char cxtitle[] = "p_{T} / m_{4l}";

  TFile* foutput = new TFile(OUTPUT_NAME, "recreate");
  TH1F* h_pt[nProdModes];
  TH1F* hratio_pt[nProdModes-1];
  TProfile* hpr_pt[nProdModes-1];
  TGraphAsymmErrors* tgratio_pt[nProdModes-1];
  TF1* fratio_pt[nProdModes];
  double xmin = 0;
  double xmax = 6;
  const int nbins = 23;
  double xbins[nbins+1];
  for (int bin=0; bin<=nbins; bin++){
    if (bin==0) xbins[bin] = xmin;
    else if (xbins[bin-1]<1.2) xbins[bin] = xbins[bin-1] + 0.1; // 12
    else if (xbins[bin-1]<2.4) xbins[bin] = xbins[bin-1] + 0.2; // 6
    else if (xbins[bin-1]<4) xbins[bin] = xbins[bin-1] + 0.4; // 4
    else if (xbins[bin-1]<xmax) xbins[bin] = xbins[bin-1] + 2.0; // 1
  }
  TString cytitle = "Rate / bin";
  for (int p = 0; p < nProdModes; p++){
    TString hname = Form("%s%s", prodName[p], csuffix);
//    TString htitle = Form("%s %i TeV", prodName[p], erg_tev);
    h_pt[p] = new TH1F(hname, "", nbins, xbins);
    h_pt[p]->Sumw2();
    h_pt[p]->GetXaxis()->SetTitle(cxtitle);
    h_pt[p]->GetYaxis()->SetTitle(cytitle);

    if (p>0){
      hname = Form("%s%s_profile", prodName[p], csuffix);
      hpr_pt[p-1] = new TProfile(hname, "", nbins, xbins);
      hpr_pt[p-1]->Sumw2();
    }
  }
  int genFinalState = -1;
  float GenHMass = 0;
  float GenHPt = 0;
  TString cinput_common = location_primaryTrees;
  if (erg_tev==7) cinput_common.Append("141217/");
  else if (erg_tev==8) cinput_common.Append("141021/");
  for (int p = 0; p < nProdModes; p++){
    TString cinput = cinput_common;
//    cinput.Append(Form("%s/ZZ4lAnalysis_%s%s", sampleName[p], sampleName[p], ".root"));
    cinput.Append(Form("ZZ4lAnalysis_%s%s", sampleName[p], ".root"));
    TFile* finput = new TFile(cinput, "read");
    cout << "Production " << prodName[p] << endl;
    TTree* tin[3] ={
      (TTree*)finput->Get(Form("ZZ4muTree/%s", TREE_NAME)),
      (TTree*)finput->Get(Form("ZZ4eTree/%s", TREE_NAME)),
      (TTree*)finput->Get(Form("ZZ2e2muTree/%s", TREE_NAME))
    };
    for (int f = 0; f < 3; f++){
      cout << "Channel " << f << endl;
      cout << "Nentries: " << tin[f]->GetEntries() << endl;
      tin[f]->SetBranchAddress("genFinalState", &genFinalState);
      tin[f]->SetBranchAddress("GenHMass", &GenHMass);
      tin[f]->SetBranchAddress("GenHPt", &GenHPt);
      for (int ev = 0; ev < tin[f]->GetEntries(); ev++){
        //			for (int ev = 0; ev < 1000; ev++){
        genFinalState = -1;
        GenHMass = 0;
        GenHPt = 0;
        tin[f]->GetEntry(ev);
        if (f != genFinalState) continue;
        double kd = GenHPt / GenHMass;
        h_pt[p]->Fill(kd);
        if (p==0){
          for (int pp=0; pp<nProdModes-1; pp++) hpr_pt[pp]->Fill(kd, kd);
        }
        else hpr_pt[p-1]->Fill(kd, kd);
      }
    }
    finput->Close();
    cout << "File closed" << endl;
  }
  foutput->cd();
/*  double zhxsec, whxsec;
  if (erg_tev == 7){ whxsec = 0.5688; zhxsec = 0.3299; }
  else if (erg_tev == 8){ whxsec = 0.6931; zhxsec = 0.4091; }
  h_pt[nProdModes]->Add(h_pt[nProdModes-1], whxsec);
  h_pt[nProdModes]->Add(h_pt[nProdModes-2], zhxsec);
*/  

  double max_plot = 0;
  for (int p = 0; p < nProdModes; p++){
    h_pt[p]->Scale(1. / h_pt[p]->Integral(0, h_pt[p]->GetNbinsX() + 1));

    h_pt[p]->GetYaxis()->SetRangeUser(0, 1);
    h_pt[p]->SetLineWidth(2);
    h_pt[p]->SetLineStyle(1);
    if (p==0) h_pt[p]->SetLineColor(kBlack);
    else if (p==3) h_pt[p]->SetLineColor(kRed);
    else if (p==4) h_pt[p]->SetLineColor(kGreen+2);
    else if (p==2) h_pt[p]->SetLineColor(kBlue);
    else if (p==1) h_pt[p]->SetLineColor(kViolet);
    if (p==0) h_pt[p]->SetMarkerColor(kBlack);
    else if (p==3) h_pt[p]->SetMarkerColor(kRed);
    else if (p==4) h_pt[p]->SetMarkerColor(kGreen+2);
    else if (p==2) h_pt[p]->SetMarkerColor(kBlue);
    else if (p==1) h_pt[p]->SetMarkerColor(kViolet);
    cout << "Writing hpt at " << p << endl;
    foutput->WriteTObject(h_pt[p]);
    if (p > 0){
      cout << "Creating ratio at " << p << endl;
      hratio_pt[p - 1] = (TH1F*)h_pt[p]->Clone(Form("%s_ratio", h_pt[p]->GetName()));
      hratio_pt[p - 1]->Divide(h_pt[0]);
      hratio_pt[p - 1]->GetYaxis()->SetTitle("Ratio to ggH");
      hratio_pt[p - 1]->SetTitle(Form("%s / %s", prodName[p], h_pt[0]->GetTitle()));

      double xx[nbins];
      double yy[nbins];
      double xx_up[nbins];
      double yy_up[nbins];
      double xx_dn[nbins];
      double yy_dn[nbins];
      int nAcc=0;
      for (int bin=1; bin<=nbins; bin++){
        double bincontent = hratio_pt[p - 1]->GetBinContent(bin);
        double binerror = hratio_pt[p - 1]->GetBinError(bin);
        if (bincontent == 0) continue;
        else{
          xx[nAcc] = hpr_pt[p-1]->GetBinContent(bin);
          xx_up[nAcc] = hpr_pt[p-1]->GetBinError(bin);
          xx_dn[nAcc] = hpr_pt[p-1]->GetBinError(bin);
          yy[nAcc] = bincontent;
          yy_up[nAcc] = binerror;
          yy_dn[nAcc] = binerror;
          nAcc++;
          max_plot = max(max_plot, (bincontent+binerror));
        }
      }
      tgratio_pt[p-1] = new TGraphAsymmErrors(nAcc, xx, yy, xx_dn, xx_up, yy_dn, yy_up);
      tgratio_pt[p-1]->SetName(Form("tg_%s_ratio", h_pt[p]->GetName()));
      tgratio_pt[p-1]->GetYaxis()->SetTitle("Ratio to ggH");
      tgratio_pt[p-1]->GetXaxis()->SetTitle(cxtitle);
      tgratio_pt[p-1]->GetYaxis()->SetRangeUser(0, 30);
      tgratio_pt[p-1]->SetLineWidth(2);
      tgratio_pt[p-1]->SetLineStyle(1);
      if (p==3) tgratio_pt[p-1]->SetMarkerColor(kRed);
      else if (p==4) tgratio_pt[p-1]->SetMarkerColor(kGreen+2);
      else if (p==2) tgratio_pt[p-1]->SetMarkerColor(kBlue);
      else if (p==1) tgratio_pt[p-1]->SetMarkerColor(kViolet);
      if (p==3) tgratio_pt[p-1]->SetLineColor(kRed);
      else if (p==4) tgratio_pt[p-1]->SetLineColor(kGreen+2);
      else if (p==2) tgratio_pt[p-1]->SetLineColor(kBlue);
      else if (p==1) tgratio_pt[p-1]->SetLineColor(kViolet);

      TF1* fitratio;
      if (p != 4){
        fitratio = new TF1(Form("%s_fit", hratio_pt[p - 1]->GetName()), "([0]-[1]*exp(-pow(x/[2],2)))*exp(-x/[3])", hratio_pt[p - 1]->GetXaxis()->GetXmin(), hratio_pt[p - 1]->GetXaxis()->GetXmax());
        if (p==1) fitratio->SetParameters(8.76, 8.69, 0.98, 4.3);
        else fitratio->SetParameters(8.76, 8.69, 0.98, -24);
      }
      else{
        fitratio = new TF1(Form("%s_fit", hratio_pt[p - 1]->GetName()), "([0]-[1]*exp(-pow(x/[2],2)))", hratio_pt[p - 1]->GetXaxis()->GetXmin(), hratio_pt[p - 1]->GetXaxis()->GetXmax());
        fitratio->SetParameters(4.2, 4.0, 0.7);
      }
      fitratio->SetParameters(6, 5.77, 1, 5);
      fitratio->SetTitle("");
      fitratio->SetLineColor(hratio_pt[p - 1]->GetLineColor());
      fitratio->SetLineStyle(7);
      fitratio->SetLineWidth(3);
      hratio_pt[p - 1]->GetYaxis()->SetRangeUser(1e-3, 1000);
      tgratio_pt[p - 1]->Fit(fitratio, "N");
      cout << "Writing ratio fit at " << p << endl;
      foutput->WriteTObject(fitratio);
      cout << "Writing ratio at " << p << endl;
      foutput->WriteTObject(hratio_pt[p - 1]);
      foutput->WriteTObject(tgratio_pt[p - 1]);
      fratio_pt[p - 1] = fitratio;
    }
  }
  foutput->cd();
  gStyle->SetTitleFont(62, "t");
  gROOT->SetStyle(gStyle->GetName());
  gROOT->ForceStyle();

  TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
  pt->SetBorderSize(0);
  pt->SetFillStyle(0);
  pt->SetTextAlign(12);
  pt->SetTextFont(42);
  pt->SetTextSize(0.045);
  TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
  text->SetTextSize(0.044);
  text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
  text->SetTextSize(0.0315);
  if (erg_tev==8) text = pt->AddText(0.837, 0.45, "#font[42]{               8 TeV}");
  else if (erg_tev==7) text = pt->AddText(0.837, 0.45, "#font[42]{               7 TeV}");
//  if (erg_tev==7) text = pt->AddText(0.837, 0.45, "#font[42]{5.1 fb^{-1} (7 TeV)}");
  text->SetTextSize(0.0315);


  TString canvasname_2D = Form("cCompare_SignalProductionMC_AllChannels_%iTeV", erg_tev);
  canvasname_2D.Append(Form("_%s_ratio", csuffix));
  TCanvas* c2D = new TCanvas(canvasname_2D, "", 8, 30, 800, 800);
  c2D->cd();
  gStyle->SetOptStat(0);
  c2D->SetFillColor(0);
  c2D->SetBorderMode(0);
  c2D->SetBorderSize(2);
  c2D->SetTickx(1);
  c2D->SetTicky(1);
  //		c2D->SetLogy();
  c2D->SetLeftMargin(0.17);
  c2D->SetRightMargin(0.05);
  c2D->SetTopMargin(0.07);
  c2D->SetBottomMargin(0.13);
  c2D->SetFrameFillStyle(0);
  c2D->SetFrameBorderMode(0);
  c2D->SetFrameFillStyle(0);
  c2D->SetFrameBorderMode(0);

  TLegend *l2D = new TLegend(0.20, 0.67, 0.58, 0.90);
  l2D->SetBorderSize(0);
  l2D->SetTextFont(42);
  l2D->SetTextSize(0.03);
  l2D->SetLineColor(1);
  l2D->SetLineStyle(1);
  l2D->SetLineWidth(1);
  l2D->SetFillColor(0);
  l2D->SetFillStyle(0);
/*
  for (int p = 0; p < nProdModes-1; p++){
    hratio_pt[p]->SetTitle("");
    hratio_pt[p]->GetXaxis()->SetNdivisions(505);
    hratio_pt[p]->GetXaxis()->SetLabelFont(42);
    hratio_pt[p]->GetXaxis()->SetLabelOffset(0.007);
    hratio_pt[p]->GetXaxis()->SetLabelSize(0.04);
    hratio_pt[p]->GetXaxis()->SetTitleSize(0.06);
    hratio_pt[p]->GetXaxis()->SetTitleOffset(0.9);
    hratio_pt[p]->GetXaxis()->SetTitleFont(42);
    hratio_pt[p]->GetYaxis()->SetNdivisions(505);
    hratio_pt[p]->GetYaxis()->SetLabelFont(42);
    hratio_pt[p]->GetYaxis()->SetLabelOffset(0.007);
    hratio_pt[p]->GetYaxis()->SetLabelSize(0.04);
    hratio_pt[p]->GetYaxis()->SetTitleSize(0.06);
    hratio_pt[p]->GetYaxis()->SetTitleOffset(1.1);
    hratio_pt[p]->GetYaxis()->SetTitleFont(42);
    hratio_pt[p]->GetYaxis()->SetRangeUser(0, 30);
    hratio_pt[p]->GetXaxis()->SetRangeUser(0, 5);
    l2D->AddEntry(hratio_pt[p], prodTitle[p], "l");
    if (p == 0) hratio_pt[p]->Draw("e1p");
    else hratio_pt[p]->Draw("e1psame");
    fratio_pt[p]->Draw("csame");
  }
*/
  for (int p = 0; p < nProdModes-1; p++){
    tgratio_pt[p]->SetTitle("");
    tgratio_pt[p]->GetXaxis()->SetNdivisions(505);
    tgratio_pt[p]->GetXaxis()->SetLabelFont(42);
    tgratio_pt[p]->GetXaxis()->SetLabelOffset(0.007);
    tgratio_pt[p]->GetXaxis()->SetLabelSize(0.04);
    tgratio_pt[p]->GetXaxis()->SetTitleSize(0.06);
    tgratio_pt[p]->GetXaxis()->SetTitleOffset(0.9);
    tgratio_pt[p]->GetXaxis()->SetTitleFont(42);
    tgratio_pt[p]->GetYaxis()->SetNdivisions(505);
    tgratio_pt[p]->GetYaxis()->SetLabelFont(42);
    tgratio_pt[p]->GetYaxis()->SetLabelOffset(0.007);
    tgratio_pt[p]->GetYaxis()->SetLabelSize(0.04);
    tgratio_pt[p]->GetYaxis()->SetTitleSize(0.06);
    tgratio_pt[p]->GetYaxis()->SetTitleOffset(1.1);
    tgratio_pt[p]->GetYaxis()->SetTitleFont(42);
    tgratio_pt[p]->GetYaxis()->SetRangeUser(0, max_plot*1.25);
    tgratio_pt[p]->GetXaxis()->SetRangeUser(0, 6);
    l2D->AddEntry(tgratio_pt[p], prodTitle[p+1], "l");
    if (p == 0) tgratio_pt[p]->Draw("ae1p");
    else tgratio_pt[p]->Draw("e1psame");
    fratio_pt[p]->Draw("csame");
  }


  l2D->Draw("same");
  pt->Draw();

  c2D->RedrawAxis();
  c2D->Modified();
  c2D->Update();
  foutput->WriteTObject(c2D);

  c2D->Close();
  foutput->cd();

  for (int p = 0; p < nProdModes; p++){
    delete h_pt[p];
    if (p>0){
      delete tgratio_pt[p-1];
      delete hpr_pt[p-1];
      delete hratio_pt[p-1];
    }
  }
  foutput->Close();
}
Example #23
0
Double_t CalibTree::Loop(int loop) {
  char name[500];
  bool debug=false;
  if (fChain == 0) return 0;
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;
  std::map<unsigned int, std::pair<double,double> >SumW;
  std::map<unsigned int, unsigned int >nTrks;
  unsigned int mask(0xFF80), ntrkMax(0);
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
  //  for (Long64_t jentry=0; jentry<1000;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(debug) std::cout << "***Entry (Track) Number : " << ientry 
			<< " p/eHCal/eMipDR/nDets : " << t_p << "/" << t_eHcal 
			<< "/" << t_eMipDR << "/" << (*t_DetIds).size() 
			<< std::endl;
    if (goodTrack()) {
      if (loop == 0) hprof_ndets->Fill(t_ieta, (*t_DetIds).size());
      double Etot=0.0;
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) { 
	double hitEn=0.0;
        unsigned int detid = (*t_DetIds)[idet] & mask;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	Etot += hitEn;
      }
      for (unsigned int idet=0; idet<(*t_DetIds).size(); idet++) {
	unsigned int detid = (*t_DetIds)[idet] & mask;
	double hitEn=0.0;
	if (debug) std::cout << "idet " << idet << " detid/hitenergy : " 
			     << std::hex << (*t_DetIds)[idet] << ":" << detid
			     << "/" << (*t_HitEnergies)[idet] << std::endl;
	if (Cprev.find(detid) != Cprev.end()) 
	  hitEn = Cprev[detid] * (*t_HitEnergies)[idet];
	else 
	  hitEn = (*t_HitEnergies)[idet];
	double Wi = hitEn/Etot;
	double Fac = (Wi* t_p) / Etot;
	if( SumW.find(detid) != SumW.end() ) {
	  Wi  += SumW[detid].first;
	  Fac += SumW[detid].second;
	  SumW[detid] = std::pair<double,double>(Wi,Fac); 
	  nTrks[detid]++;
	} else {
	  SumW.insert( std::pair<unsigned int, std::pair<double,double> >(detid,std::pair<double,double>(Wi,Fac)));
	  nTrks.insert(std::pair<unsigned int,unsigned int>(detid, 1));
	}
	if (nTrks[detid] > ntrkMax) ntrkMax = nTrks[detid];
      }
    }
  }
  
  std::map<unsigned int, std::pair<double,double> >::iterator SumWItr = SumW.begin();
  unsigned int kount(0), mkount(0);
  double       sumfactor(0);
  double       dets[150], cfacs[150], wfacs[150], nTrk[150];
  unsigned int ntrkCut = ntrkMax/10;
  for (; SumWItr != SumW.end(); SumWItr++) {
    if (debug) 
      std::cout<< "Detid/SumWi/SumFac : " << SumWItr->first << " / "
	       << (SumWItr->second).first << " / " << (SumWItr->second).second
	       << std::endl;
    unsigned int detid = SumWItr->first;
    double factor = (SumWItr->second).second / (SumWItr->second).first;

    if(nTrks[detid]>ntrkCut) {
      if (factor > 1) sumfactor += (1-1/factor);
      else            sumfactor += (1-factor);
      mkount++;
    }
    if (Cprev.find(detid) != Cprev.end()) {
      Cprev[detid] *= factor;
      cfacs[kount] = Cprev[detid];
    } else {
      Cprev.insert( std::pair<unsigned int, double>(detid, factor) );
      cfacs[kount] = factor;
    }
    int ieta = (detid>>7) & 0x3f;
    int zside= (detid&0x2000) ? 1 : -1;
    int depth= (detid>>14)&0x1F;
    wfacs[kount]= factor;
    dets[kount] = zside*(ieta+0.1*(depth-1));
    nTrk[kount] = nTrks[detid];
    kount++;
  }
  TGraph *g_fac, *g_fac2, *g_nTrk;
  g_fac = new TGraph(kount, dets, cfacs); 
  sprintf(name, "Cfacs_detid_it%d", loop);
  fout->WriteTObject(g_fac, name);

  g_fac2 = new TGraph(kount, dets, wfacs); 
  sprintf(name, "Wfacs_detid_it%d", loop);
  fout->WriteTObject(g_fac2, name);

  g_nTrk = new TGraph(kount, dets, nTrk); 
  if (loop==0) fout->WriteTObject(g_nTrk, "nTrk_detid");

  std::cout << "The new factors are :" << std::endl;
  std::map<unsigned int, double>::iterator CprevItr = Cprev.begin();
  unsigned int indx(0);
  for (CprevItr=Cprev.begin(); CprevItr != Cprev.end(); CprevItr++, indx++){
    unsigned int detid = CprevItr->first;
    int ieta = (detid>>7) & 0x3f;
    int zside= (detid&0x2000) ? 1 : -1;
    int depth= (detid>>14)&0x1F;
    std::cout << "DetId[" << indx << "] " << std::hex << detid << std::dec
	      << "(" << ieta*zside << "," << depth << ") ( nTrks:" 
	      << nTrks[detid] << ") : " << CprevItr->second << std::endl;
  }
  double mean = (mkount > 0) ? (sumfactor/mkount) : 0;
  std::cout << "Mean deviation " << mean << " from 1 for " << mkount << ":"
	    << kount << " DetIds" << std::endl;
  return mean;
}
Example #24
0
void ZmmGenJetVetoEfficiency(const string inputFilename,  const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  string label = "";
  if (Label != "") label = "_" + Label;

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *genMet = new TH1D("genMet", ";  Met [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonPtMin = new TH1D("leptonPtMin", ";  Lepton p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonEta = new TH1D("leptonEta", "; Lepton #eta; Number of Events", 50, -5, 5);
  TH1D *bosonSystemPt = new TH1D((string("bosonSystemPt")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str(), "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *nGenJets = new TH1D("nGenJets", "; Mass [GeV/c^{2}]; Number of Events", 10, -0.5, 9.5);
  TH1D *leptonDeltaPhi = new TH1D("leptonDeltaPhi", "; #Delta #phi (l,l); Number of Events", 50, 0, 180);



  Double_t NEventsGenerated = 0;
  Double_t NEventsAccepted = 0;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  mithep::TGenInfo *genInfo    = new mithep::TGenInfo();


  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); assert(eventTree);
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Gen", &genInfo); TBranch *genInfoBr = eventTree->GetBranch("Gen");
   

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    genInfoBr->GetEntry(ientry);
		
    NEventsGenerated++;

    if (genInfo->pt_1 > 20.0 && genInfo->pt_2 > 20.0
        && fabs(genInfo->eta_1) < 2.5 && fabs(genInfo->eta_2) < 2.5
        && genInfo->vmass_1 > 76 && genInfo->vmass_1 < 106
      ) {
      leadingGenJetPt->Fill(genInfo->jetpt_1);
      bosonSystemPt->Fill(genInfo->ptBosonSystem);
    }
  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Compute Jet Veto Efficiency
  //==============================================================================================================
  TH1D *jetVetoEfficiency = (TH1D*)leadingGenJetPt->Clone((string("jetVetoEfficiency")+label).c_str()); 
  jetVetoEfficiency->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt->Integral(1,i);
    Int_t d = leadingGenJetPt->Integral(1,leadingGenJetPt->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency->SetBinContent(i,ratio);
    jetVetoEfficiency->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }

  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");

  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  leadingGenJetPt->Draw();
  cv->SaveAs("leadingGenJetPt.gif");

  jetVetoEfficiency->Draw();
  cv->SaveAs("jetVetoEfficiency.gif");
 
  bosonSystemPt->Draw();
  cv->SaveAs("bosonSystemPt.gif");

  file->WriteTObject(leadingGenJetPt, leadingGenJetPt->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency, jetVetoEfficiency->GetName(), "WriteDelete");
  file->WriteTObject(bosonSystemPt, bosonSystemPt->GetName(), "WriteDelete");
  file->Close();

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
 


        
  gBenchmark->Show("plotZ");       
} 
void test_JVBF(int erg_tev=8, float mSample=0, bool isggH=false){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "SelectedTree";

  //	TVar::VerbosityLevel verbosity = TVar::INFO;

  Mela mela(erg_tev, mPOLE);

  TFile* foutput;
  if (!isggH){
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_H%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_HAll_%iTeV.root", erg_tev), "recreate");
  }
  else{
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggH%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggHAll_%iTeV.root", erg_tev), "recreate");
  }
  TLorentzVector nullFourVector(0, 0, 0, 0);

  float MC_weight_noxsec;

  float pjvbf_VAJHU;
  float pjvbf_VAJHU_first;
  float pjvbf_VAJHU_second;
  float phj_VAJHU_first;
  float phj_VAJHU_second;
  float pAux_vbf;
  float pAux_vbf_first;
  float pAux_vbf_second;

  float jet1Pt, jet2Pt;
  float jet1Eta, jet2Eta;
  float jet1Phi, jet2Phi;
  float jet1E, jet2E;
  float jet1Pt_Fake, jet2Pt_Fake;
  float jet1Eta_Fake, jet2Eta_Fake;
  float jet1Phi_Fake, jet2Phi_Fake;
  float jet1E_Fake, jet2E_Fake;
  float jet1px, jet1py, jet1pz;
  float jet2px, jet2py, jet2pz;
  float ZZPx, ZZPy, ZZPz, ZZE, dR;
  short NJets30;
  std::vector<double> * JetPt=0;
  std::vector<double> * JetEta=0;
  std::vector<double> * JetPhi=0;
  std::vector<double> * JetMass=0;
  std::vector<double> myJetPt;
  std::vector<double> myJetCosTheta;
  std::vector<double> myJetEta;
  std::vector<double> myJetPhi;
  std::vector<double> myJetMass;
  TBranch* bJetPt=0;
  TBranch* bJetEta=0;
  TBranch* bJetPhi=0;
  TBranch* bJetMass=0;

  float ZZMass, ZZPt, ZZPhi, ZZEta;

  int GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;

  TChain* tree = new TChain(TREE_NAME);
  char* user_folder[3]={ "4mu", "4e", "2mu2e" };
  TString cinput_main = "/scratch0/hep/ianderso/CJLST/140519/PRODFSR";
  if (erg_tev==8) cinput_main.Append("_8TeV");

//  TString cinput_main = "/afs/cern.ch/work/u/usarica/HZZ4l-125p6-FullAnalysis/LHC_";
//  cinput_main.Append(Form("%iTeV", erg_tev));

  for (int ff=0; ff<3; ff++){
    if (!isggH){
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_VBFH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_VBFH*.root", cinput_main.Data(), user_folder[ff]));
    }
    else{
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_minloH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_minloH*.root", cinput_main.Data(), user_folder[ff]));
    }
  }
  tree->SetBranchAddress("MC_weight_noxsec", &MC_weight_noxsec);
  tree->SetBranchAddress("NJets30", &NJets30);
  tree->SetBranchAddress("JetPt", &JetPt, &bJetPt);
  tree->SetBranchAddress("JetEta", &JetEta, &bJetEta);
  tree->SetBranchAddress("JetPhi", &JetPhi, &bJetPhi);
  tree->SetBranchAddress("JetMass", &JetMass, &bJetMass);
  tree->SetBranchAddress("ZZMass", &ZZMass);
  tree->SetBranchAddress("ZZPt", &ZZPt);
  tree->SetBranchAddress("ZZEta", &ZZEta);
  tree->SetBranchAddress("ZZPhi", &ZZPhi);

  TTree* newtree = new TTree("TestTree", "");
  newtree->Branch("MC_weight_noxsec", &MC_weight_noxsec);
  newtree->Branch("ZZMass", &ZZMass);
  newtree->Branch("pAux_vbf", &pAux_vbf);
  newtree->Branch("pAux_vbf_first", &pAux_vbf_first);
  newtree->Branch("pAux_vbf_second", &pAux_vbf_second);
  newtree->Branch("pjvbf_VAJHU", &pjvbf_VAJHU);
  newtree->Branch("pjvbf_VAJHU_first", &pjvbf_VAJHU_first);
  newtree->Branch("pjvbf_VAJHU_second", &pjvbf_VAJHU_second);
  newtree->Branch("phj_VAJHU_first", &phj_VAJHU_first);
  newtree->Branch("phj_VAJHU_second", &phj_VAJHU_second);
  newtree->Branch("NJets30", &NJets30);
  newtree->Branch("jet1Pt", &jet1Pt);
  newtree->Branch("jet1Eta", &jet1Eta);
  newtree->Branch("jet1Phi", &jet1Phi);
  newtree->Branch("jet1E", &jet1E);
  newtree->Branch("jet2Pt", &jet2Pt);
  newtree->Branch("jet2Eta", &jet2Eta);
  newtree->Branch("jet2Phi", &jet2Phi);
  newtree->Branch("jet2E", &jet2E);
  newtree->Branch("jet1_Fake_Pt", &jet1Pt_Fake);
  newtree->Branch("jet1_Fake_Eta", &jet1Eta_Fake);
  newtree->Branch("jet1_Fake_Phi", &jet1Phi_Fake);
  newtree->Branch("jet1_Fake_E", &jet1E_Fake);
  newtree->Branch("jet2_Fake_Pt", &jet2Pt_Fake);
  newtree->Branch("jet2_Fake_Eta", &jet2Eta_Fake);
  newtree->Branch("jet2_Fake_Phi", &jet2Phi_Fake);
  newtree->Branch("jet2_Fake_E", &jet2E_Fake);
  newtree->Branch("JetPt", &myJetPt);
//  newtree->Branch("JetCosTheta", &myJetCosTheta);
  newtree->Branch("JetPhi", &myJetPhi);
  newtree->Branch("JetMass", &myJetMass);


  int nEntries = tree->GetEntries();
  double selfDHggcoupl[SIZE_HGG][2] ={ { 0 } };
  double selfDHvvcoupl[SIZE_HVV_VBF][2] ={ { 0 } };
  double selfDHwwcoupl[SIZE_HWW_VBF][2] ={ { 0 } };
  double ggvvcoupl[2]={ 0, 0 };
  mela.setProcess(TVar::SelfDefine_spin0, TVar::JHUGen, TVar::ZZGG);
  int recorded=0;
  for (int ev = 0; ev < nEntries; ev++){
    pjvbf_VAJHU=-1;
    pjvbf_VAJHU_first=-1;
    pjvbf_VAJHU_second=-1;
    jet1Pt=-1;
    jet2Pt=-1;
    jet1Eta=0;
    jet2Eta=0;

    tree->GetEntry(ev);
    GenLep1Id=11;
    GenLep2Id=-11;
    GenLep3Id=11;
    GenLep4Id=-11;

    myJetPt.clear();
    myJetEta.clear();
    myJetPhi.clear();
    myJetMass.clear();
    myJetCosTheta.clear();

    TLorentzVector jet1(0, 0, 1e-3, 1e-3), jet2(0, 0, 1e-3, 1e-3), higgs(0, 0, 0, 0);
    TLorentzVector p4[3], jets[2];
    higgs.SetPtEtaPhiM(ZZPt, ZZEta, ZZPhi, ZZMass);
    for (int i = 0; i < NJets30; i++){
      myJetPt.push_back(JetPt->at(i));
      myJetEta.push_back(JetEta->at(i));
      myJetPhi.push_back(JetPhi->at(i));
      myJetMass.push_back(JetMass->at(i));
      myJetCosTheta.push_back(eta_to_costheta(JetEta->at(i)));
    }

    int filled = 0;
    if (myJetPt.size()>=1){

      jets[0].SetPxPyPzE(0, 0, 0, 1);
      jets[1].SetPxPyPzE(0, 0, 0, 1);
      for (int i = 0; i < myJetPt.size(); i++){
        jets[filled].SetPtEtaPhiM(myJetPt[i], myJetEta[i], myJetPhi[i], myJetMass[i]);

        if (filled==0){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet1.SetPxPyPzE(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet1Pt = jet1.Pt();
          jet1Eta = jet1.Eta();
          jet1Phi = jet1.Phi();
          jet1E = jet1.E();
          jet2.SetXYZT(0, 0, 0, 0);
        }
        else if(filled==1){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet2.SetXYZT(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet2Pt = jet2.Pt();
          jet2Eta = jet2.Eta();
          jet2Phi = jet2.Phi();
          jet2E = jet2.E();
        }
        else continue;

/*
        if (filled == 0){
          if (jets[filled].Pt()>jet1.Pt()){
            jet1.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet1Pt = jet1.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
            i = 0;
          }
        }
        else{
          if (jets[filled].Pt()<jet1.Pt() && jets[filled].Pt()>jet2.Pt()){
            jet2.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet2Pt = jet2.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
          }
        }
        if (filled == 2) break;
*/
      }
//cos(atan(exp(-jet2Eta))*2)

      if (filled == 2){
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);

        TLorentzVector pTotal;
        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_first);
        mela.get_PAux(pAux_vbf_first);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, pTotal);
        jet2Pt_Fake = pTotal.Pt();
        jet2Eta_Fake = pTotal.Eta();
        jet2Phi_Fake = pTotal.Phi();
        jet2E_Fake = pTotal.E();

        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_second);
        mela.get_PAux(pAux_vbf_second);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_second);
        mela::computeFakeJet(jet2, higgs, pTotal);
        jet1Pt_Fake = pTotal.Pt();
        jet1Eta_Fake = pTotal.Eta();
        jet1Phi_Fake = pTotal.Phi();
        jet1E_Fake = pTotal.E();

        newtree->Fill();
      }
      else if (filled == 1){
/*
        TLorentzVector pTotal = higgs+jet1;
        pTotal.SetVect(-pTotal.Vect());
        pTotal.SetE(pTotal.P());
        jet2 = pTotal;

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();


        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();

        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
*/
//
        jet2.SetXYZT(0,0,0,0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, jet2);
/*
        cout << "TEST:"
          << " Higgs Pz: " <<  higgs.Pz()
          << " Higgs P: " <<  higgs.P()
          << " Higgs E: " <<  higgs.T()
          << " Jet 1 Pz: " <<  jet1.Pz()
          << " Jet 1 P: " <<  jet1.P()
          << " Jet 1 E: " <<  jet1.T()
          << " Jet 2 Pz: " <<  jet2.Pz()
          << " Jet 2 P: " <<  jet2.P()
          << " Jet 2 E: " <<  jet2.T() << '\n' << endl;
*/

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();

        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();
//
        pjvbf_VAJHU_first = pjvbf_VAJHU;
        pjvbf_VAJHU_second = pjvbf_VAJHU;
        pAux_vbf_first = pAux_vbf;
        pAux_vbf_second = pAux_vbf;
        phj_VAJHU_second = phj_VAJHU_first;

        newtree->Fill();
      }
    }
  }


  foutput->WriteTObject(newtree);
  delete newtree;
  foutput->Close();
  delete tree;
}
void FitScenariosTwoD_RequiredPerformance_card(const string inputfilePho = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_diphotonMass.root", const string inputfileBjet = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_dibjetMass.root", const string inputfileTwoD = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_twoDMass.root", const string scanOption = "lum", Int_t NToys = 500, Int_t s = 5) {
	
  

  TRandom3 *randomNumber = new TRandom3(1200);
  TFile *file = new TFile(Form("HHToBBGGWorkspace_%s_%d.root",scanOption.c_str(),s),"RECREATE");
  RooWorkspace* ws = new RooWorkspace("CMSAna/HHToBBGG/fits/Workspace");
  AddModels(ws, inputfilePho, inputfileBjet, inputfileTwoD, scanOption, s);

  //Import variables from workspace
  RooAbsPdf *model2Dpdf = ws->pdf("model2Dpdf");
  RooAbsPdf *model2Dpdf_cat0 = ws->pdf("model2Dpdf_cat0");
  RooAbsPdf *model2Dpdf_cat1 = ws->pdf("model2Dpdf_cat1");
  RooRealVar *massBjet = ws->var("massBjet");
  RooRealVar *massPho = ws->var("massPho");
  RooCategory *sampleCategory = ws->cat("sampleCategory");

  RooRealVar *nsig = ws->var("nsig"); RooRealVar constNsig(*nsig);
  RooRealVar *nres_cat0 = ws->var("nres_cat0"); RooRealVar constNres_cat0(*nres_cat0);
  RooRealVar *nnonres_cat0 = ws->var("nnonres_cat0"); RooRealVar constNnonres_cat0(*nnonres_cat0);
  RooRealVar *nres_cat1 = ws->var("nres_cat1"); RooRealVar constNres_cat1(*nres_cat1);
  RooRealVar *nnonres_cat1 = ws->var("nnonres_cat1"); RooRealVar constNnonres_cat1(*nnonres_cat1);
  
  //Create TTree to store the resulting yield data
  TFile *f = new TFile(Form(("CMSAna/HHToBBGG/data/MassFitResults/ResolutionAnalysis/OptionB_Categories/tmp/"+scanOption+"FitScenario%d.root").c_str(), s), "RECREATE");
  TTree *resultTree = new TTree("resultTree", "Parameter results from fitting");
  Float_t nsigOut, nresOut, nnonresOut;
  Float_t nsigStd, nresStd, nnonresStd;
  
  resultTree->Branch("nsigOut",&nsigOut, "nsigOut/F");
  resultTree->Branch("nresOut",&nresOut, "nresOut/F");
  resultTree->Branch("nnonresOut",&nnonresOut, "nnonresOut/F");
  resultTree->Branch("nsigStd",&nsigStd, "nsigStd/F");
  resultTree->Branch("nresStd",&nresStd, "nresStd/F");
  resultTree->Branch("nnonresStd",&nnonresStd, "nnonresStd/F");
  
  //-------------------------------------------------------------
  //Yield Information
  //=============================================================     
  double myPhoEffRatio = 1.00;
  double myBtagEffRatio = 1.00;
  double myEndcapPhotonFakerateRatio = 1.0;
  if (scanOption == "phoEff") {
    myPhoEffRatio = phoEffRatio[s];
    myBtagEffRatio = 1.25;
  }
  if (scanOption == "btagEff") {
    myBtagEffRatio = btagEffRatio[s];
    myPhoEffRatio = 1.25;
  }
  if (scanOption == "endcapPhotonFakerate") myEndcapPhotonFakerateRatio = endcapPhotonFakerate[s];
  
  double totalYield = 
    6.11*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    7.88*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +      
    31.1*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 26.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 48.7*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio
    + 1.8*myBtagEffRatio*myBtagEffRatio
    +
    2.41*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    17.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 17.2*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 206.0*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio*myEndcapPhotonFakerateRatio
    + 1.7*myBtagEffRatio*myBtagEffRatio
    ;
  double cat0Yield = 6.11*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    7.88*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +      
    31.1*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 26.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 48.7*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio
    + 1.8*myBtagEffRatio*myBtagEffRatio;
  double cat1Yield = 2.41*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    17.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 17.2*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 206.0*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio*myEndcapPhotonFakerateRatio
    + 1.7*myBtagEffRatio*myBtagEffRatio;
  double cat0Fraction = cat0Yield / totalYield;
  double cat1Fraction = cat1Yield / totalYield;

  //-------------------------------------------------------------
  //Generate Toy MC experiment data and fit
  //=============================================================     
  for(UInt_t t=0; t < NToys; ++t) {
    cout << t << "|" << s << endl;
    nsig->setVal(constNsig.getVal());
    nres_cat0->setVal(constNres_cat0.getVal());
    nnonres_cat0->setVal(constNnonres_cat0.getVal());
    nres_cat1->setVal(constNres_cat1.getVal());
    nnonres_cat1->setVal(constNnonres_cat1.getVal());
    Float_t ran;

    //if (scanOption == "lum") ran = randomNumber->Poisson(totalYield*luminosity[s]);
    //else ran = randomNumber->Poisson(totalYield);

    if (scanOption == "lum") ran = totalYield*luminosity[s];
    else ran = totalYield;


    RooDataSet *pseudoData2D = model2Dpdf->generate(RooArgList(*massBjet,*massPho, *sampleCategory), ran);
    RooFitResult *fitResult2D = model2Dpdf->fitTo(*pseudoData2D, RooFit::Save(), RooFit::Extended(kTRUE), RooFit::Strategy(2));
    ws->import(*pseudoData2D, kTRUE);
    ws->import(*pseudoData2D, Rename("pseudoData2D"));

    RooDataSet *pseudoData2D_cat0 = model2Dpdf_cat0->generate(RooArgList(*massBjet,*massPho), ran*cat0Fraction);
    RooDataSet *pseudoData2D_cat1 = model2Dpdf_cat1->generate(RooArgList(*massBjet,*massPho), ran*cat1Fraction);
    ws->import(*pseudoData2D_cat0, kTRUE);
    ws->import(*pseudoData2D_cat0, Rename("pseudoData2D_cat0"));
    ws->import(*pseudoData2D_cat1, kTRUE);
    ws->import(*pseudoData2D_cat1, Rename("pseudoData2D_cat1"));
    
    //Save variables into separate branches of root tree
    nsigOut = nsig->getVal();
    nresOut = nres_cat0->getVal();
    nnonresOut = nnonres_cat0->getVal();
    nsigStd = nsig->getPropagatedError(*fitResult2D);
    nresStd = nres_cat0->getPropagatedError(*fitResult2D);
    nnonresStd = nnonres_cat0->getPropagatedError(*fitResult2D);
    
    resultTree->Fill();      
  }
  
  //Write to the TTree and close it
  resultTree->Write();

  file->WriteTObject(ws, Form("HHToBBGGWorkspace",scanOption.c_str(),s), "WriteDelete");
  file->Close();
  delete file;




}
Example #27
0
void bToDRawYield()
{
	gStyle->SetTextSize(0.05);
	gStyle->SetTextFont(42);
	gStyle->SetPadRightMargin(0.04);
	gStyle->SetPadLeftMargin(0.14);
	gStyle->SetPadTopMargin(0.1);
	gStyle->SetPadBottomMargin(0.14);
	gStyle->SetTitleX(.0f);
	gStyle->SetOptFit(1111);
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);

	TCanvas* c4 = new TCanvas("c4","",800,600);
	c4->Divide(2,2);

	TCanvas* c2 = new TCanvas("c2","",400,600);
	c2->Divide(1,2);

	TCanvas* c1 = new TCanvas();

	TCanvas* c15 = new TCanvas("c15","",810,1000);
	c15->Divide(3,5);

	TFile* fPbPb = new TFile("bFeedDownPbPb.hist.root");
	TFile* fPbPbMB = new TFile("bFeedDownPbPbMB.hist.root");
	TFile* fPbPbMC = new TFile("bFeedDownPbPbMC.hist.root");
	TFile* fPbPbMBMC = new TFile("bFeedDownPbPbMBMC.hist.root");

	TH3D* hDataPbPb = (TH3D*)fPbPb->Get("hData");
	TH3D* hSidebandPbPb = (TH3D*)fPbPb->Get("hSideband");
	TH3D* hDataPbPbMB = (TH3D*)fPbPbMB->Get("hData");
	TH3D* hSidebandPbPbMB = (TH3D*)fPbPbMB->Get("hSideband");
	TH3D* hPtMD0DcaPbPb = (TH3D*)fPbPb->Get("hPtMD0Dca");
	TH3D* hPtMD0DcaPbPbMB = (TH3D*)fPbPbMB->Get("hPtMD0Dca");

	TH3D* hMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCNPSignal");
	TH3D* hMCPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCNPSignal");
	TH3D* hPtMD0DcaMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSwapped");
	TH3D* hPtMD0DcaMCPSignalPbPbMB =(TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPbMB = (TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSwapped");

	TH3D* hData = (TH3D*)hDataPbPb->Clone("hData");
	hData->Sumw2();
	hData->Add(hDataPbPbMB);

	TH3D* hSideband = (TH3D*)hSidebandPbPb->Clone("hSideband");
	hSideband->Sumw2();
	hSideband->Add(hSidebandPbPbMB);

	TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPbPb->Clone("hPtMD0Dca");
	hPtMD0Dca->Sumw2();
	hPtMD0Dca->Add(hPtMD0DcaPbPbMB);

	TH3D* hMCPSignal = (TH3D*)hMCPSignalPbPb->Clone("hMCPSignal");
	hMCPSignal->Sumw2();
	hMCPSignal->Add(hMCPSignalPbPbMB);

	TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPbPb->Clone("hMCNPSignal");
	hMCNPSignal->Sumw2();
	hMCNPSignal->Add(hMCNPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPbPb->Clone("hPtMD0DcaMCPSignal");
	hPtMD0DcaMCPSignal->Sumw2();
	hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPbPb->Clone("hPtMD0DcaMCPSwapped");
	hPtMD0DcaMCPSwapped->Sumw2();
	hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPbPbMB);

	TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
	texCms->SetNDC();
	texCms->SetTextAlign(12);
	texCms->SetTextSize(0.06);
	texCms->SetTextFont(42);

	TLatex* texCol = new TLatex(0.96,0.93, "PbPb #sqrt{s_{NN}} = 5.02 TeV");
	texCol->SetNDC();
	texCol->SetTextAlign(32);
	texCol->SetTextSize(0.06);
	texCol->SetTextFont(42);

	const int nPtBins = 14;
	float ptBins[nPtBins+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100};

	float pts[nPtBins];
	float ptErrors[nPtBins];
	float promptFraction[nPtBins];
	float totalYield[nPtBins];
	float totalYieldInvMassFit[nPtBins];
	float totalYieldInvMassFitError[nPtBins];
	float bToDYield[nPtBins];
	float bToDYieldError[nPtBins];
	float bToDYieldErrorDataOnly[nPtBins];
	float promptDYield[nPtBins];
	float promptDYieldError[nPtBins];
	float promptDYieldErrorDataOnly[nPtBins];

	const int nBinY = 14;
	Float_t binsY[nBinY+1];
	float firstBinYWidth = 0.001;
	float binYWidthRatio = 1.27;
	binsY[0]=0;
	for(int i=1; i<=nBinY; i++)
		binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
	cout<<"last y bin: "<<binsY[nBinY]<<endl;

	//  for(int i=1; i<=nPtBins; i++)
	for(int i =7; i<=7; i++)
	{
		pts[i-1] = 0.5*(ptBins[i-1]+ptBins[i]);
		ptErrors[i-1] = 0.5*(ptBins[i]-ptBins[i-1]);
		float ptLow = ptBins[i-1];
		float ptHigh = ptBins[i];
		cout<<endl<<"======================================="<<endl;
		cout<<"pT range: "<<ptLow<<" "<<ptHigh<<endl;

		TLatex* texPtY = new TLatex(0.32,0.82,Form("%.1f < p_{T} < %.1f GeV/c      |y| < 1.0",ptLow,ptHigh));
		texPtY->SetNDC();
		texPtY->SetTextFont(42);
		texPtY->SetTextSize(0.06);
		texPtY->SetLineWidth(2);

		TLatex* texPt = new TLatex(0.18,0.82,Form("%.1f < p_{T} < %.1f GeV/c",ptLow,ptHigh));
		texPt->SetNDC();
		texPt->SetTextFont(42);
		texPt->SetTextSize(0.06);
		texPt->SetLineWidth(2);

		TLatex* texY = new TLatex(0.18,0.74,Form("|y| < 1.0"));
		texY->SetNDC();
		texY->SetTextFont(42);
		texY->SetTextSize(0.06);
		texY->SetLineWidth(2);

		c2->cd(1);

		hPtMD0Dca->GetZaxis()->SetRange(1,100);
		hPtMD0Dca->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSwapped->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		TH1D* hMData = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_%1.1f_%1.1f", ptLow, ptHigh));
		TH1D* hMMCSignal = (TH1D*)hPtMD0DcaMCPSignal->Project3D("y");
		TH1D* hMMCSwapped = (TH1D*)hPtMD0DcaMCPSwapped->Project3D("y");

		setColorTitleLabel(hMData);
		setColorTitleLabel(hMMCSignal);
		setColorTitleLabel(hMMCSwapped);

		TF1* fMass = fitMass(hMData, hMMCSignal, hMMCSwapped);

		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		TF1* fSignalAndSwapped = new TF1("fSignalAndSwapped","[0]*([3]*([5]*Gaus(x,[1],[2]*(1+[7]))/(sqrt(2*3.1415927)*[2]*(1+[7]))+(1-[5])*Gaus(x,[1],[6]*(1+[7]))/(sqrt(2*3.1415927)*[6]*(1+[7])))+(1-[3])*Gaus(x,[1],[4]*(1+[7]))/(sqrt(2*3.1415927)*[4]*(1+[7])))", 1.7, 2.0);      
		fSignalAndSwapped->SetParameter(0,fMass->GetParameter(0));
		fSignalAndSwapped->SetParameter(1,fMass->GetParameter(1));
		fSignalAndSwapped->SetParameter(2,fMass->GetParameter(2));
		fSignalAndSwapped->SetParameter(3,fMass->GetParameter(7));
		fSignalAndSwapped->SetParameter(4,fMass->GetParameter(8));
		fSignalAndSwapped->SetParameter(5,fMass->GetParameter(9));
		fSignalAndSwapped->SetParameter(6,fMass->GetParameter(10));
		fSignalAndSwapped->SetParameter(7,fMass->GetParameter(11));

		TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
		background->SetParameter(0,fMass->GetParameter(3));
		background->SetParameter(1,fMass->GetParameter(4));
		background->SetParameter(2,fMass->GetParameter(5));
		background->SetParameter(3,fMass->GetParameter(6));

		cout<<"MC signal width: "<<fMass->GetParameter(2)<<"   "<<fMass->GetParameter(10)<<endl;
		cout<<"MC swapped width: "<<fMass->GetParameter(8)<<endl;

		float massD = 1.8649;
		float massSignal1 = massD-0.025;
		float massSignal2 = massD+0.025;
		float massSideBand1 = massD-0.1;
		float massSideBand2 = massD-0.075;
		float massSideBand3 = massD+0.075;
		float massSideBand4 = massD+0.1;

		float scaleSideBandBackground = background->Integral(massSignal1, massSignal2)/(background->Integral(massSideBand1, massSideBand2)+background->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandBackground: "<<scaleSideBandBackground<<endl;
		totalYieldInvMassFit[i-1] = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		totalYieldInvMassFitError[i-1] = fMass->GetParError(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		cout<<"totalYieldInvMassFit: "<<totalYieldInvMassFit[i-1]<<" +- "<<totalYieldInvMassFitError[i-1]<<endl;
		float scaleSideBandMethodSignal = fSignalAndSwapped->GetParameter(0)*fSignalAndSwapped->GetParameter(3) / (fSignalAndSwapped->Integral(massSignal1, massSignal2)-fSignalAndSwapped->Integral(massSideBand1, massSideBand2)-fSignalAndSwapped->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandMethodSignal: "<<scaleSideBandMethodSignal<<endl;

		TLatex* texScale = new TLatex(0.18,0.66,Form("side band bg scale: %1.3f", scaleSideBandBackground));
		texScale->SetNDC();
		texScale->SetTextFont(42);
		texScale->SetTextSize(0.06);
		texScale->SetLineWidth(2);
		texScale->Draw();

		TLine* lineSignal1 = new TLine(massSignal1, 0, massSignal1, hMData->GetMaximum()*0.5);
		TLine* lineSignal2 = new TLine(massSignal2, 0, massSignal2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand1 = new TLine(massSideBand1, 0, massSideBand1, hMData->GetMaximum()*0.5);
		TLine* lineSideBand2 = new TLine(massSideBand2, 0, massSideBand2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand3 = new TLine(massSideBand3, 0, massSideBand3, hMData->GetMaximum()*0.5);
		TLine* lineSideBand4 = new TLine(massSideBand4, 0, massSideBand4, hMData->GetMaximum()*0.5);
		lineSignal1->Draw();
		lineSignal2->Draw();
		lineSideBand1->Draw();
		lineSideBand2->Draw();
		lineSideBand3->Draw();
		lineSideBand4->Draw();

		c2->cd(2);
		gPad->SetLogy();

		hData->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hSideband->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCNPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);

		TH1D* hD0DcaData0 = (TH1D*)hData->Project3D("y")->Clone("hD0DcaData0");
		TH1D* hD0DcaSideband = (TH1D*)hSideband->Project3D("y")->Clone("hD0DcaSideband");
		TH1D* hD0DcaMCPSignal0 = (TH1D*)hMCPSignal->Project3D("y")->Clone("hD0DcaMCPSignal0");
		TH1D* hD0DcaMCNPSignal0 = (TH1D*)hMCNPSignal->Project3D("y")->Clone("hD0DcaMCNPSignal0");

		float integralRawYieldMCP = hD0DcaMCPSignal0->Integral();
		float integralRawYieldMCNP = hD0DcaMCNPSignal0->Integral();
		cout<<"integralRawYieldMCP: "<<integralRawYieldMCP<<endl;
		cout<<"integralRawYieldMCNP: "<<integralRawYieldMCNP<<endl;

		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

		divideBinWidth(hD0DcaData0);
		divideBinWidth(hD0DcaSideband);
		setColorTitleLabel(hD0DcaData0, 1);
		hD0DcaData0->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData0->GetYaxis()->SetTitle("counts per cm");

		TH1D* hD0DcaSideband0 = (TH1D*)hD0DcaSideband->Clone("hD0DcaSideband0");
		hD0DcaSideband->Scale(scaleSideBandBackground);

		TH1D* hD0DcaDataSubSideBand = (TH1D*)hD0DcaData0->Clone("hD0DcaDataSubSideBand");
		hD0DcaDataSubSideBand->Add(hD0DcaSideband,-1);
		hD0DcaDataSubSideBand->Scale(scaleSideBandMethodSignal);

		hD0DcaData0->SetMarkerSize(0.6);
		hD0DcaData0->Draw();
		hD0DcaSideband->Draw("hsame");
		hD0DcaSideband0->SetLineStyle(2);
		hD0DcaSideband0->Draw("hsame");

		TLegend* leg1 = new TLegend(0.44,0.6,0.90,0.76,NULL,"brNDC");
		leg1->SetBorderSize(0);
		leg1->SetTextSize(0.06);
		leg1->SetTextFont(42);
		leg1->SetFillStyle(0);
		leg1->AddEntry(hD0DcaData0,"D^{0} candidate","pl");
		leg1->AddEntry(hD0DcaSideband,"side band","l");
		leg1->AddEntry(hD0DcaSideband0,"side band unscaled","l");
		leg1->Draw("same");

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_sideBand.pdf",ptLow,ptHigh));

		c2->cd(1);
		hMMCSignal->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->cd(2);
		gPad->SetLogy(0);
		hMMCSwapped->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_McInvMassFit.pdf",ptLow,ptHigh));

		c15->cd(1);

		fitMass(hMData, hMMCSignal, hMMCSwapped);

		texPt->Draw();
		texY->Draw();

		TH1D* hD0DcaDataFit = new TH1D("hD0DcaDataFit", ";D^{0} DCA (cm);dN / d(D^{0} DCA) (cm^{-1})", nBinY, binsY);

		for(int j=1; j<=14; j++)
		{
			c15->cd(j+1);
			hPtMD0Dca->GetZaxis()->SetRange(j,j);
			float D0DcaLow = hPtMD0Dca->GetZaxis()->GetBinLowEdge(j);
			float D0DcaHigh = hPtMD0Dca->GetZaxis()->GetBinUpEdge(j);
			TH1D* hMData_D0Dca = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_pt_%1.1f_%1.1f_D0Dca_%1.4f_%1.4f", ptLow, ptHigh, D0DcaLow, D0DcaHigh));
			setColorTitleLabel(hMData_D0Dca);
			fMass = fitMass(hMData_D0Dca, hMMCSignal, hMMCSwapped);

			float yield = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);
			float yieldError = fMass->GetParError(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);

			hD0DcaDataFit->SetBinContent(j, yield);
			hD0DcaDataFit->SetBinError(j, yieldError);

			TLatex* texD0Dca = new TLatex(0.18,0.82,Form("D^{0} DCA: %1.4f - %1.4f",D0DcaLow,D0DcaHigh));
			texD0Dca->SetNDC();
			texD0Dca->SetTextFont(42);
			texD0Dca->SetTextSize(0.06);
			texD0Dca->SetLineWidth(2);
			texD0Dca->Draw();

			TLatex* texYield = new TLatex(0.18,0.74,Form("D^{0} yield: %1.0f #pm %1.0f",yield,yieldError));
			texYield->SetNDC();
			texYield->SetTextFont(42);
			texYield->SetTextSize(0.06);
			texYield->SetLineWidth(2);
			texYield->Draw();
		}

		c15->SaveAs(Form("plots/PbPb_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

		divideBinWidth(hD0DcaDataFit);

		c4->cd(1);
		gPad->SetLogy();

		normalize(hD0DcaMCPSignal);
		setColorTitleLabel(hD0DcaMCPSignal, 2);
		hD0DcaMCPSignal->GetXaxis()->SetRangeUser(0,0.07);

		normalize(hD0DcaMCNPSignal);
		setColorTitleLabel(hD0DcaMCNPSignal, 4);
		hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaMCNPSignal->GetYaxis()->SetTitle("dN / d(D^{0} DCA) (cm^{-1})");
		hD0DcaMCNPSignal->GetXaxis()->SetTitle("D^{0} DCA (cm)");
		hD0DcaMCNPSignal->SetMaximum(hD0DcaMCPSignal->GetMaximum()*3.);

		hD0DcaMCNPSignal->Draw("");
		hD0DcaMCPSignal->Draw("same");

		TLegend* leg2 = new TLegend(0.54,0.72,0.90,0.88,NULL,"brNDC");
		leg2->SetBorderSize(0);
		leg2->SetTextSize(0.06);
		leg2->SetTextFont(42);
		leg2->SetFillStyle(0);
		leg2->AddEntry(hD0DcaMCPSignal,"MC Prompt D^{0}","pl");
		leg2->AddEntry(hD0DcaMCNPSignal,"MC Non-prompt D^{0}","pl");
		leg2->Draw("same");

		c4->cd(2);
		gPad->SetLogy();

		TH1D* hD0DcaData = hD0DcaDataFit;
		if(pts[i-1]>20) hD0DcaData = hD0DcaDataSubSideBand;

		setColorTitleLabel(hD0DcaData, 1);

		double integralTotalYield = hD0DcaData->Integral(1,hD0DcaData->GetXaxis()->GetNbins(),"width");
		cout<<"integralTotalYield: "<<integralTotalYield<<endl;

		TF1* fMix = new TF1("fMix",&funMix, 0., 0.5, 2);
		fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
		fMix->SetParLimits(0,0,2*integralTotalYield);
		fMix->SetParLimits(1,0,2*integralTotalYield);

		fMix->SetLineColor(2);
		fMix->SetFillColor(kRed-9);
		fMix->SetFillStyle(1001);

		float fitRangeL = 0;
		float fitRangeH = 0.08;

		hD0DcaData->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData->Draw();
		int fitStatus = 1;
		TFitResultPtr fitResult;
		double fitPrecision = 1.e-6;
		while(fitStatus)
		{
			TFitter::SetPrecision(fitPrecision);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);
			fitResult = hD0DcaData->Fit("fMix","E SNQ0", "", fitRangeL, fitRangeH);
			fitStatus = fitResult->Status();
			cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;
			if(fitStatus)
				fitPrecision *= 10;
		}
		cout<<"============== do main fit ============"<<endl;
		fMix->SetParameters(integralTotalYield,0.9);
		fMix->SetParError(0,0.1*integralTotalYield);
		fMix->SetParError(1,0.1);
		fMix->SetNpx(10000);
		fitResult = hD0DcaData->Fit("fMix","E S0", "", fitRangeL, fitRangeH);
		hD0DcaData->GetFunction("fMix")->Draw("flsame");
		fitStatus = fitResult->Status();
		cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;

		TF1* fNP = new TF1("fNP",&funNonPrompt, 0., 0.5, 2);
		fNP->SetParameters(fMix->GetParameter(0),fMix->GetParameter(1));
		fNP->SetRange(fitRangeL,fitRangeH);
		fNP->SetLineColor(4);
		fNP->SetFillStyle(1001);
		fNP->SetFillColor(kBlue-9);
		fNP->SetNpx(10000);
		fNP->Draw("same");  

		hD0DcaData->Draw("same");

		promptDYield[i-1] = fMix->GetParameter(0);
		promptDYieldErrorDataOnly[i-1] = fMix->GetParError(0);
		bToDYield[i-1] = fMix->GetParameter(1);
		bToDYieldErrorDataOnly[i-1] = fMix->GetParError(1);
		totalYield[i-1] = promptDYield[i-1]+bToDYield[i-1];
		promptFraction[i-1] = promptDYield[i-1]/totalYield[i-1];

		cout<<"chi2 / NDF: "<<fitResult->Chi2()<<" / "<<fitResult->Ndf()<<endl;

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		TLatex* texPrompt = new TLatex(0.4,0.73,Form("Prompt D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(0),fMix->GetParError(0)));
		texPrompt->SetNDC();
		texPrompt->SetTextFont(42);
		texPrompt->SetTextSize(0.06);
		texPrompt->SetLineWidth(2);
		texPrompt->Draw();

		TLatex* texNonPrompt = new TLatex(0.4,0.65,Form("B to D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(1),fMix->GetParError(1)));
		texNonPrompt->SetNDC();
		texNonPrompt->SetTextFont(42);
		texNonPrompt->SetTextSize(0.06);
		texNonPrompt->SetLineWidth(2);
		texNonPrompt->Draw();

		TLegend* leg4 = new TLegend(0.56,0.38,0.90,0.62);
		leg4->SetBorderSize(0);
		leg4->SetTextSize(0.06);
		leg4->SetTextFont(42);
		leg4->SetFillStyle(0);
		leg4->AddEntry(hD0DcaData,"Data","pl");
		leg4->AddEntry(fMix,"Prompt D^{0}","f");
		leg4->AddEntry(fNP,"B to D^{0}","f");
		leg4->Draw("same");

		//smear MC smaple with the error, to simulate the MC statistic error effect.
		c4->cd(3);

		hD0DcaMCPSignal = (TH1D*)hD0DcaMCPSignal0->Clone("hMCPSignal");
		hD0DcaMCNPSignal = (TH1D*)hD0DcaMCNPSignal0->Clone("hMCNPSignal");

		TH1D* hNPYield = new TH1D("hNPYield", ";hNPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		TH1D* hPYield = new TH1D("hPYield", ";hPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		setColorTitleLabel(hNPYield, 1);
		setColorTitleLabel(hPYield, 1);

		int nSmear = 1000;

		for(int j=0; j<nSmear; j++)
		{
			RandomSmear(hD0DcaMCPSignal0, hD0DcaMCPSignal);
			RandomSmear(hD0DcaMCNPSignal0, hD0DcaMCNPSignal);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);

			hD0DcaData->Fit("fMix","E QN0");

			hPYield->Fill(fMix->GetParameter(0));
			hNPYield->Fill(fMix->GetParameter(1));
		}

		hPYield->GetXaxis()->SetTitle("prompt D^{0} yield");
		hPYield->GetYaxis()->SetTitle("counts");
		hPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hPYield->GetMaximum());
		hPYield->SetMarkerStyle(20);
		hPYield->SetStats(0);
		hPYield->Draw("e");
		hPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hPYield->GetFunction("gaus")->GetParameter(1),hPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaP->SetNDC();
		texGaussMeanSigmaP->SetTextFont(42);
		texGaussMeanSigmaP->SetTextSize(0.06);
		texGaussMeanSigmaP->SetLineWidth(2);
		texGaussMeanSigmaP->Draw();

		float promptYieldErrorMc = hPYield->GetFunction("gaus")->GetParameter(2);
		promptDYieldError[i-1] = sqrt(pow(promptDYieldErrorDataOnly[i-1],2)+pow(promptYieldErrorMc,2));

		c4->cd(4);

		hNPYield->GetXaxis()->SetTitle("B to D^{0} yield");
		hNPYield->GetYaxis()->SetTitle("counts");
		hNPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hNPYield->GetMaximum());
		hNPYield->SetMarkerStyle(20);
		hNPYield->SetStats(0);
		hNPYield->Draw("e");
		hNPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaNP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hNPYield->GetFunction("gaus")->GetParameter(1),hNPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaNP->SetNDC();
		texGaussMeanSigmaNP->SetTextFont(42);
		texGaussMeanSigmaNP->SetTextSize(0.06);
		texGaussMeanSigmaNP->SetLineWidth(2);
		texGaussMeanSigmaNP->Draw();

		float bToDYieldErrorMc = hNPYield->GetFunction("gaus")->GetParameter(2);
		bToDYieldError[i-1] = sqrt(pow(bToDYieldErrorDataOnly[i-1],2)+pow(bToDYieldErrorMc,2));

		cout<<"prompt D yield: "<<promptDYield[i-1]<<" +- "<<promptDYieldError[i-1]<<" (+- "<<promptDYieldErrorDataOnly[i-1]<<" +- "<<promptYieldErrorMc<<" )"<<endl;
		cout<<"B to D yield: "<<bToDYield[i-1]<<" +- "<<bToDYieldError[i-1]<<" (+- "<<bToDYieldErrorDataOnly[i-1]<<" +- "<<bToDYieldErrorMc<<" )"<<endl;
		cout<<"total yield: "<<totalYield[i-1]<<endl;
		cout<<"prompt fraction: "<<promptFraction[i-1]<<endl;

		float promptMCScale = promptDYield[i-1]/integralRawYieldMCP;
		float nonPromptMCScale = bToDYield[i-1]/integralRawYieldMCNP;

		cout<<"promptMCScale: "<<promptMCScale<<endl;
		cout<<"nonPromptMCScale: "<<nonPromptMCScale<<endl;

		//restore original unsmeared histograms before saving plots
		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;
		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;
		hD0DcaData->Fit("fMix","E QN0");

		c4->SaveAs(Form("plots/PbPb_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		c1->cd();

		TH1D* hD0DcaDataOverFit = (TH1D*)hD0DcaData->Clone("hD0DcaDataOverFit");
		hD0DcaDataOverFit->Divide(fMix);
		hD0DcaDataOverFit->GetYaxis()->SetTitle("data / fit");
		hD0DcaDataOverFit->GetYaxis()->SetRangeUser(0,5);
		hD0DcaDataOverFit->GetXaxis()->SetRangeUser(0,0.07);
		setColorTitleLabel(hD0DcaDataOverFit, 1);
		hD0DcaDataOverFit->Draw("e");

		TF1* fLine1 = new TF1("fLine1", "1", 0,1);
		fLine1->Draw("same");
		hD0DcaDataOverFit->Draw("esame");

		c1->SaveAs(Form("plots/dataOverFit_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;

	} // end for i ptbins
	c1->cd();

	TH1D* hStupidJie = new TH1D("hStupidJie", "", 100, 0, 100);
	hStupidJie->GetYaxis()->SetRangeUser(0,1);
	hStupidJie->GetXaxis()->SetTitle("p_{T} (GeV/c)");
	hStupidJie->GetYaxis()->SetTitle("prompt fraction");
	hStupidJie->SetStats(0);
	hStupidJie->Draw();
	TGraph* grFraction = new TGraph(nPtBins, pts, promptFraction);
	grFraction->SetName("grPromptFraction");
	grFraction->SetMarkerStyle(20);
	grFraction->Draw("psame");

	c1->SaveAs("promptFraction.pdf");

	c1->SetLogy();

	TH1D* hBtoDRawYield = new TH1D("hBtoDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(bToDYield[i-1] <= 0) continue;
		hBtoDRawYield->SetBinContent(i, bToDYield[i-1]);
		hBtoDRawYield->SetBinError(i, bToDYieldError[i-1]);
	}
	divideBinWidth(hBtoDRawYield);
	setColorTitleLabel(hBtoDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hBtoDRawYield->Draw("p");
	c1->SaveAs("BtoD.pdf");

	TH1D* hPromptDRawYield = new TH1D("hPromptDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(promptDYield[i-1] <= 0) continue;
		hPromptDRawYield->SetBinContent(i, promptDYield[i-1]);
		hPromptDRawYield->SetBinError(i, promptDYieldError[i-1]);
	}
	divideBinWidth(hPromptDRawYield);
	setColorTitleLabel(hPromptDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hPromptDRawYield->Draw("p");
	c1->SaveAs("promptD.pdf");

	TH1D* hTotalDYieldInvMassFit = new TH1D("hTotalDYieldInvMassFit", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(totalYieldInvMassFit[i-1] <= 0) continue;
		hTotalDYieldInvMassFit->SetBinContent(i, totalYieldInvMassFit[i-1]);
		hTotalDYieldInvMassFit->SetBinError(i, totalYieldInvMassFitError[i-1]);
	}
	divideBinWidth(hTotalDYieldInvMassFit);
	setColorTitleLabel(hTotalDYieldInvMassFit, 1);
	hTotalDYieldInvMassFit->Draw("p");
	c1->SaveAs("totalDInvMassFit.pdf");

	TFile* fOut = new TFile("bFeedDownResult.root", "recreate");
	fOut->WriteTObject(grFraction);
	fOut->WriteTObject(hBtoDRawYield);
	fOut->WriteTObject(hPromptDRawYield);
	fOut->WriteTObject(hTotalDYieldInvMassFit);
	fOut->Write();
	fOut->Close();
}
Example #28
0
void doCreateMuonFakeRateMap(const string filename, const string Label = "ZZ") 
{  
  gBenchmark->Start("HZZTemplate");
  string label = Label;
  if (Label != "") label = "_" + Label;

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================

  //*****************************************************************************************
  //Make some histograms
  //*****************************************************************************************
  TH1F *histDenominatorPt = new TH1F ("histDenominatorPt",";Electron p_{T} [GeV/c^{2}]; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorPt = new TH1F ("histNumeratorPt",";Electron p_{T} [GeV/c^{2}]; Number of Events", 50, 0 , 100);
  TH1F *histDenominatorEta = new TH1F ("histDenominatorEta",";Electron Eta; Number of Events", 50, -2.5 , 2.5);
  TH1F *histNumeratorEta = new TH1F ("histNumeratorEta",";Electron Eta; Number of Events", 50, -2.5 , 2.5);
  TH1F *histDenominatorPhi = new TH1F ("histDenominatorPhi",";Electron Phi; Number of Events", 50, 0 , 3.2);
  TH1F *histNumeratorPhi = new TH1F ("histNumeratorPhi",";Electron Phi; Number of Events", 50, 0 , 3.2);
  TH1F *histDenominatorRho = new TH1F ("histDenominatorRho",";Electron Rho; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorRho = new TH1F ("histNumeratorRho",";Electron Rho; Number of Events", 50, 0 , 100);
  TH1F *histDenominatorNpv = new TH1F ("histDenominatorNpv",";Electron Npv; Number of Events", 50, 0 , 100);
  TH1F *histNumeratorNpv = new TH1F ("histNumeratorNpv",";Electron Npv; Number of Events", 50, 0 , 100);

  TH2F *histDenominatorPtEta = new TH2F ("histDenominatorPtEta",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histNumeratorPtEta = new TH2F ("histNumeratorPtEta",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);

  TH1F *histDenominatorPt_lq = new TH1F ("histDenominatorPt_lq",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH1F *histNumeratorPt_lq = new TH1F ("histNumeratorPt_lq",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH1F *histDenominatorPt_b = new TH1F ("histDenominatorPt_b",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH1F *histNumeratorPt_b = new TH1F ("histNumeratorPt_b",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH1F *histDenominatorPt_g = new TH1F ("histDenominatorPt_g",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH1F *histNumeratorPt_g = new TH1F ("histNumeratorPt_g",";Electron p_{T} [GeV/c^{2}]; Number of Events", 25, 0 , 100);
  TH2F *histDenominatorPtEta_lq = new TH2F ("histDenominatorPtEta_lq",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histNumeratorPtEta_lq = new TH2F ("histNumeratorPtEta_lq",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histDenominatorPtEta_b = new TH2F ("histDenominatorPtEta_b",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histNumeratorPtEta_b = new TH2F ("histNumeratorPtEta_b",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histDenominatorPtEta_g = new TH2F ("histDenominatorPtEta_g",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);
  TH2F *histNumeratorPtEta_g = new TH2F ("histNumeratorPtEta_g",";Photon p_{T} [GeV/c] ; Photon #eta; Number of Events", 50, 0 , 200, 50, 0, 3.0);


  //********************************************************
  // Create Arrays to store the map
  //********************************************************
   const UInt_t NPtBins_Response = 4; 
   const UInt_t NEtaBins_Response = 3;
   double ptBins_Response[NPtBins_Response+1] = { 5, 7, 10, 15, 25 };
   double etaBins_Response[NEtaBins_Response+1] = { 0.0, 1.2, 2.2, 2.4 };


   const UInt_t NPtBins = 7; 
   const UInt_t NEtaBins = 3;
   double ptBins[NPtBins+1] = { 5, 7, 10, 15, 20, 25, 30, 35 };
   double etaBins[NEtaBins+1] = { 0.0, 1.2, 2.2, 2.4 };

   vector<vector<double> > NDenominator_Muons_PtEta;
   vector<vector<double> > NNumerator_Muons_PtEta;
   vector<vector<double> > Efficiency_Muons_PtEta;
   vector<vector<TH1F*> > PtResolution_PtEta_Muons;


   initialize2DArray(NDenominator_Muons_PtEta, NPtBins, NEtaBins);
   initialize2DArray(NNumerator_Muons_PtEta, NPtBins, NEtaBins);
   initialize2DArray(Efficiency_Muons_PtEta, NPtBins, NEtaBins);
   initializeHistograms(PtResolution_PtEta_Muons, "LeptonPtResolution_Muons", NPtBins_Response, NEtaBins_Response, 100, -1.0, 0.25);  
   
   //--------------------------------------------------------------------------------------------------------------
   // Read efficiency map ntuple
   //==============================================================================================================  
   cmsana::MuonTree muTree;
   muTree.LoadTree(filename.c_str());
   muTree.InitTree(cmsana::ElectronTree::kEleTreeLight);

   cout << "Total : " << muTree.tree_->GetEntries() << "\n";
   for(UInt_t i=0; i<muTree.tree_->GetEntries(); i++) {       	
     muTree.tree_->GetEntry(i);
     if (i % 1000000 == 0) cout << "Mu " << i << endl;

    Int_t tmpPtBin = FindBin( muTree.fMuGenPt , ptBins, NPtBins);
    Int_t tmpEtaBin = FindBin( fabs(muTree.fMuGenEta) , etaBins, NEtaBins);
    Int_t tmpPtBin_Response = FindBin( muTree.fMuGenPt , ptBins_Response, NPtBins_Response);
    Int_t tmpEtaBin_Response = FindBin( fabs(muTree.fMuGenEta) , etaBins_Response, NEtaBins_Response);


    //selection cuts
    if (!(muTree.fMuGenPt > 3 && fabs(muTree.fMuGenEta) < 2.5)) continue;

    //**** PT - ETA ****
    NDenominator_Muons_PtEta[tmpPtBin][tmpEtaBin] += 1.0;
    histDenominatorPtEta->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
    histDenominatorPt->Fill(muTree.fMuGenPt);
    histDenominatorEta->Fill(muTree.fMuGenEta);
    histDenominatorRho->Fill(muTree.fRho);
    histDenominatorNpv->Fill(muTree.fNVertices);

    if (abs(muTree.fPdgId) == 5) {
      histDenominatorPtEta_b->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
      histDenominatorPt_b->Fill(muTree.fMuGenPt);
    } else if (abs(muTree.fPdgId) == 21) {
      histDenominatorPtEta_g->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
      histDenominatorPt_g->Fill(muTree.fMuGenPt);
    } else {
      histDenominatorPtEta_lq->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
      histDenominatorPt_lq->Fill(muTree.fMuGenPt);
    }

    if(muTree.fMuPt > 0) {
      NNumerator_Muons_PtEta[tmpPtBin][tmpEtaBin] += 1.0;      
      histNumeratorPtEta->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
      histNumeratorPt->Fill(muTree.fMuGenPt);
      histNumeratorEta->Fill(muTree.fMuGenEta);
      histNumeratorRho->Fill(muTree.fRho);
      histNumeratorNpv->Fill(muTree.fNVertices);

      if (abs(muTree.fPdgId) == 5) {
        histNumeratorPtEta_b->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
        histNumeratorPt_b->Fill(muTree.fMuGenPt);
      } else if (abs(muTree.fPdgId) == 21) {
        histNumeratorPtEta_g->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));        
        histNumeratorPt_g->Fill(muTree.fMuGenPt);
      } else {
        histNumeratorPtEta_lq->Fill(muTree.fMuGenPt,fabs(muTree.fMuGenEta));
        histNumeratorPt_lq->Fill(muTree.fMuGenPt);
      }

      //fill response function
      PtResolution_PtEta_Muons[tmpPtBin_Response][tmpEtaBin_Response]->Fill( (muTree.fMuPt - muTree.fMuGenPt)/muTree.fMuGenPt , 1.0);
      
    }
    
  }

  //--------------------------------------------------------------------------------------------------------------
  // Make Efficiency Plots
  //==============================================================================================================

  TGraphAsymmErrors *efficiency_pt = cmsana::createEfficiencyGraph(histNumeratorPt, histDenominatorPt, "Efficiency_Pt" , vector<double>() ,  -99, -99, 0, 1, false);
  TGraphAsymmErrors *efficiency_eta = cmsana::createEfficiencyGraph(histNumeratorEta, histDenominatorEta, "Efficiency_Eta" , vector<double>() ,  -99, -99, 0, 1, false);
  TGraphAsymmErrors *efficiency_rho = cmsana::createEfficiencyGraph(histNumeratorRho, histDenominatorRho, "Efficiency_Rho" , vector<double>() ,  -99, -99, 0, 1, false);
  TGraphAsymmErrors *efficiency_npv = cmsana::createEfficiencyGraph(histNumeratorNpv, histDenominatorNpv, "Efficiency_Npv" , vector<double>() ,  -99, -99, 0, 1, false);
  TH2F *efficiency_pteta = cmsana::createEfficiencyHist2D(histNumeratorPtEta, histDenominatorPtEta, "Efficiency_PtEta" , vector<double>() ,vector<double>());  


  TGraphAsymmErrors *efficiency_lq_pt = cmsana::createEfficiencyGraph(histNumeratorPt_lq, histDenominatorPt_lq, "Efficiency_lq_Pt" , vector<double>() ,  -99, -99, 0, 1, false);
  TGraphAsymmErrors *efficiency_b_pt = cmsana::createEfficiencyGraph(histNumeratorPt_b, histDenominatorPt_b, "Efficiency_b_Pt" , vector<double>() ,  -99, -99, 0, 1, false);
  TGraphAsymmErrors *efficiency_g_pt = cmsana::createEfficiencyGraph(histNumeratorPt_g, histDenominatorPt_g, "Efficiency_g_Pt" , vector<double>() ,  -99, -99, 0, 1, false);
  TH2F *efficiency_lq_pteta = cmsana::createEfficiencyHist2D(histNumeratorPtEta_lq, histDenominatorPtEta_lq, "Efficiency_lq_PtEta" , vector<double>() ,vector<double>());  
  TH2F *efficiency_b_pteta = cmsana::createEfficiencyHist2D(histNumeratorPtEta_b, histDenominatorPtEta_b, "Efficiency_b_PtEta" , vector<double>() ,vector<double>());  
  TH2F *efficiency_g_pteta = cmsana::createEfficiencyHist2D(histNumeratorPtEta_g, histDenominatorPtEta_g, "Efficiency_g_PtEta" , vector<double>() ,vector<double>());  

  //--------------------------------------------------------------------------------------------------------------
  // Draw
  //==============================================================================================================
  TCanvas *cv =0;

  cv = new TCanvas("cv","cv",800,600);
  efficiency_pt->Draw("AP");
  //efficiency_pt->SetTitle("");
  efficiency_pt->GetYaxis()->SetRangeUser(0.0,0.1);
  cv->SaveAs("Efficiency_Pt.gif");

  cv = new TCanvas("cv","cv",800,600);
  efficiency_eta->Draw("AP");
  //efficiency_eta->SetTitle("");
  efficiency_eta->GetYaxis()->SetRangeUser(0.0,0.1);
  cv->SaveAs("Efficiency_Eta.gif");

  cv = new TCanvas("cv","cv",800,600);
  efficiency_rho->Draw("AP");
  //efficiency_rho->SetTitle("");
  efficiency_rho->GetYaxis()->SetRangeUser(0.0,0.1);
  cv->SaveAs("Efficiency_Rho.gif");

  cv = new TCanvas("cv","cv",800,600);
  efficiency_npv->Draw("AP");
  //efficiency_npv->SetTitle("");
  efficiency_npv->GetYaxis()->SetRangeUser(0.0,0.1);
  cv->SaveAs("Efficiency_Npv.gif");


  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  TFile *file = TFile::Open(("FakeRate"+label+".root").c_str(), "UPDATE");
  file->cd();
  file->WriteTObject(efficiency_pt, "Efficiency_Pt", "WriteDelete");
  file->WriteTObject(efficiency_eta, "Efficiency_Eta", "WriteDelete");
  file->WriteTObject(efficiency_rho, "Efficiency_Rho", "WriteDelete");
  file->WriteTObject(efficiency_npv, "Efficiency_NPV", "WriteDelete");
  file->WriteTObject(efficiency_pteta, "Efficiency_PtEta", "WriteDelete");

  file->WriteTObject(efficiency_lq_pt, "Efficiency_lq_Pt", "WriteDelete");
  file->WriteTObject(efficiency_b_pt, "Efficiency_b_Pt", "WriteDelete");
  file->WriteTObject(efficiency_g_pt, "Efficiency_g_Pt", "WriteDelete");
  file->WriteTObject(efficiency_b_pteta, "Efficiency_b_PtEta", "WriteDelete");
  file->WriteTObject(efficiency_lq_pteta, "Efficiency_lq_PtEta", "WriteDelete");
  file->WriteTObject(efficiency_g_pteta, "Efficiency_g_PtEta", "WriteDelete");


  for (uint i=0; i < NPtBins_Response+2; ++i) {
    for (uint j=0; j < NEtaBins_Response+2; ++j) {
      file->WriteTObject(PtResolution_PtEta_Muons[i][j], PtResolution_PtEta_Muons[i][j]->GetName(), "WriteDelete");
    }
  }

   computeEfficiencyPtEta(NNumerator_Muons_PtEta, NDenominator_Muons_PtEta, Efficiency_Muons_PtEta);


  //********************************************************
  // Produce output lookup table
  //******************************************************** 
  ofstream outf_e("FakeMuonEfficiencyMap.h");

  outf_e << "UInt_t FindMuonEfficiencyBin( double value, double bins[], UInt_t nbins) {" << endl;
  outf_e << "  UInt_t nbinboundaries = nbins+1;" << endl;
  outf_e << "  UInt_t bin = 0;" << endl;
  outf_e << "  for (uint i=0; i < nbinboundaries; ++i) {" << endl;
  outf_e << "    if (i < nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i] && value < bins[i+1]) {" << endl;
  outf_e << "        bin = i+1;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    } else if (i == nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i]) {" << endl;
  outf_e << "        bin = nbinboundaries;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    }    " << endl;
  outf_e << "  }" << endl;
  outf_e << "  return bin;" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonEfficiencyPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t Efficiency[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << Efficiency_Muons_PtEta[i][j];
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindMuonEfficiencyBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindMuonEfficiencyBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return Efficiency[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;


  outf_e.close();



  file->Close();
  delete file;       



  gBenchmark->Show("WWTemplate");       
} 
void makeEfficiencyScaleFactors(string DataFilename = "data_eleWPEffTP/basic_76_106/eff.root", 
                   string MCFilename = "s11_zee_eleWPEffTP/basic_76_106/eff.root" , 
                   string outputDir = "data_eleWPEffTP/basic_76_106/", 
                   string histName = "h2_results_ele_selection",
                   string Label = "htt")
{
  gBenchmark->Start("printMuonWPEff");
    
  string label = Label;
  if (Label != "") label = "_" + Label;

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  
  TString outfname = (outputDir + "/eff_table.txt").c_str();
  TFile mcfile(MCFilename.c_str());
  TFile datafile(DataFilename.c_str());
  
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================   
  
  TH2F *hMCEff=0,    *hMCErrl=0,    *hMCErrh=0;
  TH2F *hDataEff1=0, *hDataErrl1=0, *hDataErrh1=0;
  TH2F *hDataEff2=0, *hDataErrl2=0, *hDataErrh2=0;
  
  hMCEff  = (TH2F*)mcfile.Get("hEffEtaPt");
  hMCErrl = (TH2F*)mcfile.Get("hErrlEtaPt");
  hMCErrh = (TH2F*)mcfile.Get("hErrhEtaPt");
  
  hDataEff  = (TH2F*)datafile.Get("hEffEtaPt");
  hDataErrl = (TH2F*)datafile.Get("hErrlEtaPt");
  hDataErrh = (TH2F*)datafile.Get("hErrhEtaPt");
  
  TGraphAsymmErrors* MCEffVsRho   = ( TGraphAsymmErrors*)mcfile.Get("grEffRho");
  TGraphAsymmErrors* DataEffVsRho = ( TGraphAsymmErrors*)datafile.Get("grEffRho");
 
  TGraphAsymmErrors* MCEffVsNVtx   = ( TGraphAsymmErrors*)mcfile.Get("grEffNPV");
  TGraphAsymmErrors* DataEffVsNVtx = ( TGraphAsymmErrors*)datafile.Get("grEffNPV");


  //--------------------------------------------------------------------------------------------------------------
  // Update root file histograms
  //==============================================================================================================   
  const Int_t nx = hMCEff->GetNbinsX();
  const Int_t ny = hMCEff->GetNbinsY();

  TFile *outputFile = new TFile(("efficiency_results"+label+".root").c_str(), "UPDATE");

  //Do Binning
  Double_t *ptbins = new Double_t[ny+1];
  Double_t *etabins = new Double_t[nx+1];
  for(Int_t iy=1; iy<=ny; iy++) {
      ptbins[iy-1] = hMCEff->GetYaxis()->GetBinLowEdge(iy);
  }
  for(Int_t ix=1; ix<=nx; ix++) {
    etabins[ix-1]= hMCEff->GetXaxis()->GetBinLowEdge(ix);
  }
  ptbins[ny] = 60;
  etabins[nx] = 2.5;
    
  TH2F *h2_results_selection = new TH2F(histName.c_str(),"",ny,ptbins,nx,etabins);
  for(Int_t iy=0; iy<=ny+2; iy++) {
    for(Int_t ix=0; ix<=nx+2; ix++) {
      h2_results_selection->SetCellContent(iy,ix, 1.0);
      h2_results_selection->SetCellError(iy,ix, 0.0);
    }
  }

  cout << "ptbins : ";
  for(Int_t i=0; i<ny+1;++i) {
    cout << ptbins[i] << " ";
  }
  cout << endl;
  cout << "etabins : ";
  for(Int_t i=0; i<nx+1;++i) {
    cout << etabins[i] << " ";
  }
  cout << endl;

  //--------------------------------------------------------------------------------------------------------------
  // Produce Text file table
  //==============================================================================================================   

  ofstream txtfile;
  txtfile.open(outfname.Data());
  assert(txtfile.is_open());
    
  
  txtfile << " pT        ";
  txtfile << " eta           ";
  txtfile << "    MC T&P           ";
  txtfile << "    Data T&P         ";  
  txtfile << "    Scale factor     ";
  txtfile << endl;
  txtfile << "----------------------------------------------------------------------------------------------------------------------------------------------------";
  txtfile << endl;
  for(Int_t iy=1; iy<=ny; iy++) {
    for(Int_t ix=1; ix<=nx; ix++) {
      txtfile << "[" << setw(4) << hMCEff->GetYaxis()->GetBinLowEdge(iy) << "," << setw(4) << hMCEff->GetYaxis()->GetBinLowEdge(iy+1) << "]";
      txtfile << "[" << setw(6) << hMCEff->GetXaxis()->GetBinLowEdge(ix) << "," << setw(6) << hMCEff->GetXaxis()->GetBinLowEdge(ix+1) << "]";      
      ios_base::fmtflags flags = txtfile.flags();
      txtfile.precision(4);
      
      Double_t mceff  = hMCEff->GetCellContent(ix,iy);
      Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
      Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
      txtfile << " " << setw(9) << fixed << mceff << " +/- " << TMath::Max(mcerrl,mcerrh);

      Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
      Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
      Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
      txtfile << " " << setw(9) << fixed << dataeff << " +/- " << TMath::Max(dataerrl,dataerrh);
      
      Double_t scale     = (hDataEff->GetCellContent(ix,iy))/(hMCEff->GetCellContent(ix,iy));
      Double_t scaleErrl = scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff);
      Double_t scaleErrh = scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff);
      txtfile << " " << setw(9) << fixed << scale << " +/- " << TMath::Max(scaleErrl,scaleErrh);

      txtfile << endl;
      txtfile.flags(flags);

      cout << "Set " << iy << " " << ix << " " << scale << endl;
      h2_results_selection->SetCellContent(iy,ix, scale);
      h2_results_selection->SetCellError(iy,ix, (scaleErrl + scaleErrh)/2);
      //fill overflow bins with the same values as last bin
      if (ix == nx) {
      cout << "Set " << iy << " " << ix+1 << " " << scale << endl;
        h2_results_selection->SetCellContent(iy,nx+1, scale);
        h2_results_selection->SetCellError(iy,nx+1, (scaleErrl + scaleErrh)/2);
      }
    }
    if (iy == ny) {
      for(Int_t ix=1; ix<=nx; ix++) {
        Double_t mceff  = hMCEff->GetCellContent(ix,iy);
        Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
        Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
        Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
        Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
        Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
        Double_t scale     = (hDataEff->GetCellContent(ix,iy))/(hMCEff->GetCellContent(ix,iy));
        Double_t scaleErrl = scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff);
        Double_t scaleErrh = scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff);
        
        cout << "Set " << iy+1 << " " << ix << " " << scale << endl;
        h2_results_selection->SetCellContent(iy+1,ix, scale);
        h2_results_selection->SetCellError(iy+1,ix, (scaleErrl + scaleErrh)/2);
        //fill overflow bins with the same values as last bin
        if (ix == nx) {
          cout << "Set " << iy+1 << " " << ix+1 << " " << scale << endl;
          h2_results_selection->SetCellContent(iy+1,nx+1, scale);
          h2_results_selection->SetCellError(iy+1,nx+1, (scaleErrl + scaleErrh)/2);
        }
      }
    }

    txtfile << endl;
  }
  txtfile.close();
  
  cout << outfname << " created!" << endl;
  



  //--------------------------------------------------------------------------------------------------------------
  // Create TEX table
  //==============================================================================================================   

  ofstream texfile;
  texfile.open((outputDir + "/eff_table.tex").c_str());
  assert(texfile.is_open());

  texfile << " \\begin{table}[!ht]" << endl;
  texfile << " \\begin{center} " << endl;
  texfile << " \\begin{tabular}{|c|c|c|c|}" << endl;
  texfile << " \\hline\n";


  texfile << " $p_{T}$ / $\\eta$ bin    &  Monte Carlo Efficiency    &  Data Efficiency   &  MC to Data Scale Factor \\\\  ";
  texfile << " \\hline           ";
  texfile << endl;
  for(Int_t iy=1; iy<=ny; iy++) {
    for(Int_t ix=1; ix<=nx; ix++) {

      string binLabel = Form("$%5.1f < p_{T} \\le %5.1f$ , $%5.1f  \\le |\\eta| < %5.1f$", 
                             hMCEff->GetYaxis()->GetBinLowEdge(iy), hMCEff->GetYaxis()->GetBinLowEdge(iy+1),
                             hMCEff->GetXaxis()->GetBinLowEdge(ix), hMCEff->GetXaxis()->GetBinLowEdge(ix+1));
      if (iy == ny) {
        binLabel = Form("$%5.1f < p_{T} $ , $%5.1f  \\le |\\eta| < %5.1f$", 
                        hMCEff->GetYaxis()->GetBinLowEdge(iy), 
                        hMCEff->GetXaxis()->GetBinLowEdge(ix), hMCEff->GetXaxis()->GetBinLowEdge(ix+1));
      }
      
      texfile << binLabel;
      texfile << "   &   ";

      ios_base::fmtflags flags = texfile.flags();
      texfile.precision(4);
      
      Double_t mceff  = hMCEff->GetCellContent(ix,iy);
      Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
      Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
      texfile << " " << setw(9) << fixed << mceff << " +/- " << TMath::Max(mcerrl,mcerrh);
      texfile << "   &   ";

      Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
      Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
      Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
      texfile << " " << setw(9) << fixed << dataeff << " +/- " << TMath::Max(dataerrl,dataerrh);
      texfile << "   &   ";
     
      Double_t scale     = (hDataEff->GetCellContent(ix,iy))/(hMCEff->GetCellContent(ix,iy));
      Double_t scaleErrl = scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff);
      Double_t scaleErrh = scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff);
      texfile << " " << setw(9) << fixed << scale << " +/- " << TMath::Max(scaleErrl,scaleErrh);
      texfile << "   \\\\   ";
      texfile << endl;
      texfile << "\\hline";
      texfile << endl;

    }
  }
  texfile << "\\end{tabular}" << endl;
  texfile << "\\caption{CAPTION.}" << endl;
  texfile << "\\label{tab:eff_ele_offline}" << endl;
  texfile << "\\end{center}" << endl;
  texfile << "\\end{table}" << endl;
  texfile.close();
  cout << outputDir + "/eff_table.tex" << " created!" << endl;




  //--------------------------------------------------------------------------------------------------------------
  // Create TWIKI table
  //==============================================================================================================   

  ofstream twikifile;
  twikifile.open((outputDir + "/eff_table.twiki").c_str());
  assert(twikifile.is_open());
  

  twikifile << "| *pT bin* | *eta bin* | *MC Efficiency* | *Data Efficiency* | *ScaleFactor* | \n";
  
  for(Int_t iy=1; iy<=ny; iy++) {
    for(Int_t ix=1; ix<=nx; ix++) {

      string binLabel = Form("| *%4.1f < pT \\le %4.1f* | *%3.1f  <= eta < %3.1f* | ", 
                             hMCEff->GetYaxis()->GetBinLowEdge(iy), hMCEff->GetYaxis()->GetBinLowEdge(iy+1),
                             hMCEff->GetXaxis()->GetBinLowEdge(ix), hMCEff->GetXaxis()->GetBinLowEdge(ix+1));
      if (iy == ny) {
        binLabel = Form("| *%4.1f < pT* | *%3.1f  <= eta < %3.1f* | ", 
                        hMCEff->GetYaxis()->GetBinLowEdge(iy), 
                        hMCEff->GetXaxis()->GetBinLowEdge(ix), hMCEff->GetXaxis()->GetBinLowEdge(ix+1));
      }
      
      twikifile << binLabel ;

      ios_base::fmtflags flags = twikifile.flags();
      twikifile.precision(4);
      
      Double_t mceff  = hMCEff->GetCellContent(ix,iy);
      Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
      Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
      twikifile << " " << setw(9) << fixed << mceff << " +/- " << TMath::Max(mcerrl,mcerrh);
      twikifile << " | ";

      Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
      Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
      Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
      twikifile << " " << setw(9) << fixed << dataeff << " +/- " << TMath::Max(dataerrl,dataerrh);
      twikifile << " | ";
     
      Double_t scale     = (hDataEff->GetCellContent(ix,iy))/(hMCEff->GetCellContent(ix,iy));
      Double_t scaleErrl = scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff);
      Double_t scaleErrh = scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff);
      twikifile << " " << setw(9) << fixed << scale << " +/- " << TMath::Max(scaleErrl,scaleErrh);
      twikifile << " |\n";

    }
  }
  twikifile.close();
  cout << outputDir + "/eff_table.twiki" << " created!" << endl;





  outputFile->WriteTObject(h2_results_selection, h2_results_selection->GetName(), "WriteDelete");
  outputFile->Close();

  gBenchmark->Show("printMuonWPEff"); 
}
void plotGJetsScaleFactorSystematics(string label) {

  TFile *inf = new TFile(Form("data/ScaleFactors/RazorMADD2015/RazorScaleFactors_%s.root",label.c_str()),"READ");

  TH2Poly *ttbarNominal = (TH2Poly*)inf->Get("TTJetsScaleFactors");
  TH2Poly *ttbarUp = (TH2Poly*)inf->Get("TTJetsScaleFactorsUp");
  TH2Poly *ttbarDown = (TH2Poly*)inf->Get("TTJetsScaleFactorsDown");
  TH2Poly *wNominal = (TH2Poly*)inf->Get("WJetsScaleFactors");
  TH2Poly *wUp = (TH2Poly*)inf->Get("WJetsScaleFactorsUp");
  TH2Poly *wDown = (TH2Poly*)inf->Get("WJetsScaleFactorsDown");
  TH2Poly *wInvNominal = (TH2Poly*)inf->Get("WJetsInvScaleFactors");
  TH2Poly *wInvUp = (TH2Poly*)inf->Get("WJetsInvScaleFactorsUp");
  TH2Poly *wInvDown = (TH2Poly*)inf->Get("WJetsInvScaleFactorsDown");
  TH2Poly *GJetInvNominal = (TH2Poly*)inf->Get("GJetsInvScaleFactors");

  TCanvas *cv = 0;
  gStyle->SetPaintTextFormat("4.2f");

  //****************************************************
  //Systematic Uncertainty and GJets Down SF Histogram
  //****************************************************
  TH2Poly *GJetsSystematicUnc = (TH2Poly*)GJetInvNominal->Clone("GJetsSystematicUnc");
  TH2Poly *GJetsScaleFactor_Down = (TH2Poly*)GJetInvNominal->Clone("GJetsInvScaleFactors_Down");

  //Get bins of each histogram
  TList *wInvBins = wInvNominal->GetBins();
  TList *gInvBins = GJetInvNominal->GetBins();

  //Loop over GJets bins
  TH2PolyBin *gBin, *wBin; //temp variables to hold bin info
  for (int i = 1; i < GJetsSystematicUnc->GetNumberOfBins()+1; ++i) {

      //Get GJets bin
      gBin = (TH2PolyBin*)gInvBins->At(i-1);

      cout << "In bin " << i << " of GJets histogram" << endl;
      //cout << gBin->GetXMin() << " " << gBin->GetXMax() << " " << gBin->GetYMin() << " " << gBin->GetYMax() << endl;

      //Find out which WJets bin we are in
      int wBinNum = -1;
      for (int j = 1; j < wInvNominal->GetNumberOfBins()+1; ++j) {

          //Get WJets bin
          wBin = (TH2PolyBin*)wInvBins->At(j-1);

          //cout << "In bin " << j << " of WJets histogram" << endl;
          //cout << wBin->GetXMin() << " " << wBin->GetXMax() << " " << wBin->GetYMin() << " " << wBin->GetYMax() << endl;

          //Check if this GJets bin is inside this WJets bin
          if ( gBin->GetXMin() >= wBin->GetXMin() &&
               gBin->GetXMax() <= wBin->GetXMax() &&
               gBin->GetYMin() >= wBin->GetYMin() &&
               gBin->GetYMax() <= wBin->GetYMax() ) {
              cout << "This GJets bin is inside bin " << j << " of WJets histogram" << endl;
              wBinNum = j;
              break;
          }
      }

      double gjet = GJetInvNominal->GetBinContent(i);
      double wjet = wInvNominal->GetBinContent(wBinNum);

      //Set bin content of each histogram
      GJetsSystematicUnc->SetBinContent(i, (gjet - wjet)/gjet );
      GJetsScaleFactor_Down->SetBinContent(i, gjet - (wjet - gjet) );

      cout << "Bin " << i << " : " << gjet << " , " << wjet << " , " <<  gjet - (wjet - gjet) << "\n";
  }

  cv = new TCanvas("cv","cv", 800,600);
  gStyle->SetPalette(1);
  GJetsSystematicUnc->Draw("colztext");
  cv->SetLogx();
  cv->SetLogy();
  cv->SetRightMargin(0.175);
  cv->SetBottomMargin(0.12);
  GJetsSystematicUnc->GetXaxis()->SetRangeUser(400,4000);
  GJetsSystematicUnc->GetYaxis()->SetRangeUser(0.25,1.5);
  GJetsSystematicUnc->GetZaxis()->SetTitle("Systematic Uncertainty");
  GJetsSystematicUnc->GetXaxis()->SetTitle("M_{R} [GeV/c^{2}]");
  GJetsSystematicUnc->GetYaxis()->SetTitle("R^{2}");
  GJetsSystematicUnc->SetTitle("");
  GJetsSystematicUnc->GetZaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetZaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetXaxis()->SetTitleOffset(0.8);
  GJetsSystematicUnc->GetYaxis()->SetLabelSize(0.05);
  GJetsSystematicUnc->GetYaxis()->SetTitleSize(0.05);
  GJetsSystematicUnc->GetYaxis()->SetTitleOffset(0.8);
  GJetsSystematicUnc->SetStats(false);
  GJetsSystematicUnc->SetMaximum(1.0);
  GJetsSystematicUnc->SetMinimum(-1.0);

  lumi_13TeV = "35.9 fb^{-1}";
  writeExtraText = true;
  relPosX = 0.13;
  lumiTextSize = 0.5;
  cmsTextSize = 0.6;
  extraOverCmsTextSize = 0.85;
  CMS_lumi(cv,4,0);
  cv->SaveAs(Form("GJetsVsWJetsSystematic_%s.png",label.c_str()));
  cv->SaveAs(Form("GJetsVsWJetsSystematic_%s.pdf",label.c_str()));

  TFile *outf = new TFile(Form("data/ScaleFactors/RazorMADD2015/RazorScaleFactors_%s.root",label.c_str()),"UPDATE");
  outf->WriteTObject(GJetsScaleFactor_Down, GJetsScaleFactor_Down->GetName(), "WRITEDELETE");
  outf->Close();

}