//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeHwwNtuple(const string InputFilename, const string datasetName,
                        const string OutputFilename, const int nsel) {

    TTree* HwwTree = getTreeFromFile(InputFilename.c_str(),nsel);
    assert(HwwTree);

    MitNtupleEvent event(HwwTree);

    Double_t normalizationWeight = getNormalizationWeight(InputFilename, datasetName);

    //*************************************************************************************************
    //Create new normalized tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    outputFile->cd();

    TTree *normalizedTree = HwwTree->CloneTree(0);

    cout << "Events in the ntuple: " << HwwTree->GetEntries() << endl;

    for (int n=0; n<HwwTree->GetEntries(); n++) {
        event.GetEntry(n);
        event.H_weight = event.H_weight * normalizationWeight;
        normalizedTree->Fill();
    }

    normalizedTree->Write();
    outputFile->Close();
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void SkimGoodLumiList(const string InputFilename, const string OutputFilename, Int_t type,
                      const string GoodLumiFile) {

  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile(GoodLumiFile.c_str()); 

  TTree* HwwTree = getTreeFromFile(InputFilename.c_str());
  assert(HwwTree);
  SmurfTree sigEvent;
  sigEvent.LoadTree(InputFilename.c_str(),type);
  sigEvent.InitTree(0);
  sigEvent.tree_->SetName("tree");

  //*************************************************************************************************
  //Create new normalized tree
  //*************************************************************************************************
  TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
  outputFile->cd();

  TTree *normalizedTree = sigEvent.tree_->CloneTree(0);
  
  cout << "Events in the ntuple: " << sigEvent.tree_->GetEntries() << endl;
  
  for (int n=0;n<sigEvent.tree_->GetEntries();n++) { 
    sigEvent.tree_->GetEntry(n);
    if (n%100000==0) cout << "Processed Event " << n << endl;    

    Bool_t passSkim = kFALSE;
    mithep::RunLumiRangeMap::RunLumiPairType rl(sigEvent.run_, sigEvent.lumi_);      
    if( sigEvent.dstype_ !=0 || rlrm.HasRunLumi(rl) ) passSkim = kTRUE;

    if (passSkim) {
      normalizedTree->Fill(); 
    }
  }
  cout << "Events in output ntuple: " << normalizedTree->GetEntries() << endl;
  normalizedTree->Write();
  outputFile->Close();
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void ModifySmurfNtupleDatasetType(const string InputFilename, const string OutputFilename, 
                                  Int_t type, string TargetDatasetType ) {

  TTree* HwwTree = getTreeFromFile(InputFilename.c_str());
  assert(HwwTree);
  SmurfTree sigEvent;
  sigEvent.LoadTree(InputFilename.c_str(),type);
  sigEvent.InitTree(0);
  sigEvent.tree_->SetName("tree");

  //*************************************************************************************************
  //Create new normalized tree
  //*************************************************************************************************
  cout << "Output File : " << OutputFilename << endl;
  TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
  outputFile->cd();
  TTree *normalizedTree = sigEvent.tree_->CloneTree(0);
  
  cout << "Events in the ntuple: " << sigEvent.tree_->GetEntries() << endl;
  
  for (int n=0;n<sigEvent.tree_->GetEntries();n++) { 
    sigEvent.tree_->GetEntry(n);
    if (n%100000==0) cout << "Processed Event " << n << endl;    

    if (TargetDatasetType == "qqww_MCAtNLO_ScaleUp") {
      sigEvent.dstype_ = SmurfTree::ggww;
    } 
    if (TargetDatasetType == "qqww_MCAtNLO_ScaleDown") {
      sigEvent.dstype_ = SmurfTree::ggzz;
    } 

    normalizedTree->Fill(); 
  }
  cout << "Events in output ntuple: " << normalizedTree->GetEntries() << endl;
  normalizedTree->Write();
  outputFile->Close();
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void AnalyzeYYPhotonEvent(const string InputFilename) {

  
  TTree* YYTree = getTreeFromFile(InputFilename.c_str());
  assert(YYTree);    
  YYPhotonEvent photon(YYTree);
      
  TH1D *plot = new TH1D("hPlot", ";XAxis; Number of Events ", 6, -3,3);

  for (int n=0;n<YYTree->GetEntries();n++) { 
    photon.GetEntry(n);

    Double_t weight = photon.photon_branch_weight;    
    //cout << weight << " " << photon.photon_branch_NPhotons << endl;
    if (photon.photon_branch_NPhotons > 0 ) {
      plot->Fill(photon.photon_branch_Photon1Eta);
    }

  }

  TCanvas *c = new TCanvas("canvas" , "canvas" , 800, 600);
  plot->DrawCopy();
  
}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void NormalizeElectronNtuple(const string InputFilename, const string datasetName, 
                             const string OutputFilename, Int_t sampleType, 
                             const string normalizationFile = "") {


  Double_t normalizationWeight = 0;
  Bool_t useReweightFactor = kFALSE;
  TH2F *PtEtaReweightFactor = 0;
  Double_t overallWJetsNormalizationFactor = 0;

  //For Normalizing each sample individually
  if (sampleType == 0 || sampleType >= 10) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str());
    assert(electronTree);    
    MitNtupleElectron ele(electronTree);
    
    normalizationWeight = getNormalizationWeight(InputFilename, datasetName);
    //*************************************************************************************************
    //Create new normalized tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    outputFile->cd();    
    TTree *normalizedTree = electronTree->CloneTree(0);
    
    for (int n=0;n<electronTree->GetEntries();n++) { 
      ele.GetEntry(n);

      if (sampleType == 10) {
        if (ele.electron_branch_passedSelectionCut == 1) {
          if (datasetName == "s09-wwll10-mc3" || datasetName == "s09-ttbar-mc3") {
            //for mu-e there should be only 1 electron candidate
            ele.electron_branch_weight = normalizationWeight; 
            normalizedTree->Fill(); 
          } else if (datasetName == "s09-we-mc3" || datasetName == "s09-wm-mc3" || datasetName == "s09-wt-mc3") {
            //For the W->enu sample, fill only the fake electron candidates.
            ele.electron_branch_weight = normalizationWeight; 
            if (ele.electron_branch_electronType < 100) {
              normalizedTree->Fill(); 
            }
          } else {
            cout << "Warning: The specified dataset " << datasetName 
                 << " is not recognized to be one of the selection cut samples.\n";
          }
        }        
      } else {
        //For regular samples just fill all electrons
        ele.electron_branch_weight = normalizationWeight; 
        normalizedTree->Fill(); 
      }      
    }
    normalizedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << normalizedTree->GetEntries() << endl;
    outputFile->Close();     
  }
  //For Normalization of Background sample
  else if (sampleType == 1) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in W+Jets/W+gamma bkg
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);

      TH2F *WJetsFakeElectronPtEta = (TH2F*)reweightInputFile->Get("hWJetsFakeElectronPtEta");
      assert(WJetsFakeElectronPtEta);      
      WJetsFakeElectronPtEta = (TH2F*)(WJetsFakeElectronPtEta->Clone());
      WJetsFakeElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WJetsFakeElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *BkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , WJetsFakeElectronPtEta->GetXaxis()->GetNbins(), WJetsFakeElectronPtEta->GetXaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetXaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetXaxis()->GetNbins()), WJetsFakeElectronPtEta->GetYaxis()->GetNbins(), WJetsFakeElectronPtEta->GetYaxis()->GetBinLowEdge(1), WJetsFakeElectronPtEta->GetYaxis()->GetBinUpEdge(WJetsFakeElectronPtEta->GetYaxis()->GetNbins()));
      BkgFakeElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        BkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WJetsFakeElectronPtEta, BkgFakeElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Background Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedBkgFakeElectronPtEta = new TH2F("BkgFakeElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedBkgFakeElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 

      ReweightedBkgFakeElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedBkgFakeElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronPt.gif");
    ReweightedBkgFakeElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("BkgReweightedFakeElectronEta.gif");
  } 
  
  //For Normalization of Signal sample
  else if (sampleType == 2) {
    TTree* electronTree = getTreeFromFile(InputFilename.c_str(), kFALSE);
    assert(electronTree);     
    MitNtupleElectron ele(electronTree);

    //*************************************************************************************************
    //Create new reweighted tree
    //*************************************************************************************************
    TFile *outputFile = new TFile(OutputFilename.c_str(), "RECREATE");
    TTree *reweightedTree = electronTree->CloneTree(0);    

    if (normalizationFile == "") {
      //normalize according to total number of electrons expected in WW -> ee nunu signal
      Double_t totalWeight = 0;
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        totalWeight += ele.electron_branch_weight;
      }

      cout << "Input Bkg Ntuple Total Weight = " << totalWeight << endl;
      normalizationWeight = 1126.5 / totalWeight;
    } else {
      //do pt/eta Reweighting

      TFile *reweightInputFile = new TFile(normalizationFile.c_str(), "READ");
      assert(reweightInputFile);
      TH2F *WWSigElectronPtEta = (TH2F*)reweightInputFile->Get("hWWRealElectronPtEta");
      assert(WWSigElectronPtEta);      
      WWSigElectronPtEta = (TH2F*)(WWSigElectronPtEta->Clone());
      WWSigElectronPtEta->SetDirectory(0);
      reweightInputFile->Close();

      //Create histogram for reweighting factor
      PtEtaReweightFactor = (TH2F*)WWSigElectronPtEta->Clone();
      PtEtaReweightFactor->SetName("PtEtaReweightFactor");
      PtEtaReweightFactor->SetDirectory(0);

      TH2F *SigSampleElectronPtEta = new TH2F("SigSampleElectronPtEta", ";Pt [GeV/c];#eta;" , WWSigElectronPtEta->GetXaxis()->GetNbins(), WWSigElectronPtEta->GetXaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetXaxis()->GetBinUpEdge(WWSigElectronPtEta->GetXaxis()->GetNbins()), WWSigElectronPtEta->GetYaxis()->GetNbins(), WWSigElectronPtEta->GetYaxis()->GetBinLowEdge(1), WWSigElectronPtEta->GetYaxis()->GetBinUpEdge(WWSigElectronPtEta->GetYaxis()->GetNbins()));
      SigSampleElectronPtEta->SetDirectory(0);
      for (int n=0;n<electronTree->GetEntries();n++) { 
        ele.GetEntry(n);
        SigSampleElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);        
      }
      PtEtaReweightFactor->Divide(WWSigElectronPtEta, SigSampleElectronPtEta, 1.0,1.0,"B");

      useReweightFactor = kTRUE;    
    }

    cout << "Reweighting Signal Ntuple\n";
    outputFile->cd();    

    //check Reweighting
    TH2F *ReweightedSigRealElectronPtEta = new TH2F("ReweightedSigRealElectronPtEta", ";Pt [GeV/c];#eta;" , 200, 0, 200, 200, -3.0, 3.0);    
    ReweightedSigRealElectronPtEta->SetDirectory(0);
    for (int n=0;n<electronTree->GetEntries();n++) { 
      if (n%250000 == 0) cout << "Entry " << n << endl;
      ele.GetEntry(n);
      if (useReweightFactor) {
        Double_t reweightFactor = PtEtaReweightFactor->GetBinContent(PtEtaReweightFactor->GetXaxis()->FindFixBin(ele.electron_branch_pt),PtEtaReweightFactor->GetYaxis()->FindFixBin(ele.electron_branch_eta));
        ele.electron_branch_weight = ele.electron_branch_weight*reweightFactor;//*overallWJetsNormalizationFactor;
      } else {
        ele.electron_branch_weight = normalizationWeight;
      }
      reweightedTree->Fill(); 
      ReweightedSigRealElectronPtEta->Fill(ele.electron_branch_pt, ele.electron_branch_eta, ele.electron_branch_weight);
    }
    reweightedTree->Write();
    cout << "Original Tree Entries: " << electronTree->GetEntries() << "  Normalized Tree Entries: " << reweightedTree->GetEntries() << endl;
    outputFile->Close();
  
    TCanvas *cv = new TCanvas("BkgReweightedFakeElectronPtEta", "BkgReweightedFakeElectronPtEta", 0,0,800,600);
    ReweightedSigRealElectronPtEta->ProjectionX()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronPt.gif");
    ReweightedSigRealElectronPtEta->ProjectionY()->DrawCopy("E1");
    cv->SaveAs("SigReweightedRealElectronEta.gif");
  } 
  else {
    cout << "Warning: Specified sampleType " << sampleType << " is not recognized.\n";
  }



}
예제 #6
0
// Main macro function
//--------------------------------------------------------------------------------------------------
void NormalizeNtuple(string inputFilename, string datasetName, string outputFilename) 
{
  gBenchmark->Start("NormalizeNtuple");
    
  TTree::SetMaxTreeSize(kMaxLong64);
  
  // Don't write TObject part of the objects
  mithep::TEventInfo::Class()->IgnoreTObjectStreamer();
  mithep::TMuon::Class()->IgnoreTObjectStreamer();
  mithep::TElectron::Class()->IgnoreTObjectStreamer();
  mithep::TJet::Class()->IgnoreTObjectStreamer();
  mithep::TPhoton::Class()->IgnoreTObjectStreamer();

  // Data structures to store info from TTrees
  mithep::TEventInfo *info  = new mithep::TEventInfo();
  TClonesArray *muonArr     = new TClonesArray("mithep::TMuon");
  TClonesArray *electronArr     = new TClonesArray("mithep::TElectron");
  TClonesArray *jetArr    = new TClonesArray("mithep::TJet");
  TClonesArray *photonArr     = new TClonesArray("mithep::TPhoton");

  UInt_t nInputEvts = 0;
  UInt_t nPassEvts  = 0;
  
  TFile* outfile = new TFile(outputFilename.c_str(), "RECREATE");

  //
  // Initialize data trees and structs
  // 
  TTree *outEventTree = new TTree("Events","Events"); 
  outEventTree->Branch("Info",     &info);
  outEventTree->Branch("Muon",     &muonArr);
  outEventTree->Branch("Electron", &electronArr);
  outEventTree->Branch("PFJet",    &jetArr);
  outEventTree->Branch("Photon",   &photonArr);

  TTree *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("Muon",     &muonArr);     TBranch *muonBr     = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
  eventTree->SetBranchAddress("PFJet",    &jetArr);      TBranch *jetBr    = eventTree->GetBranch("PFJet");
  eventTree->SetBranchAddress("Photon",    &photonArr);  TBranch *photonBr   = eventTree->GetBranch("Photon");

  Double_t normalizationWeight = getNormalizationWeight(inputFilename, datasetName);

  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { 
    infoBr->GetEntry(ientry);
    muonArr->Clear();     muonBr->GetEntry(ientry);
    electronArr->Clear(); electronBr->GetEntry(ientry);
    photonArr->Clear(); photonBr->GetEntry(ientry);
    jetArr->Clear();      jetBr->GetEntry(ientry);
      
    if (ientry % 100000 == 0) cout << "Events: " << ientry << endl;

    nInputEvts++;
     
    info->eventweight = info->eventweight * normalizationWeight;
   outEventTree->Fill();
    nPassEvts++;
  }
  
  outfile->Write();
  outfile->Close();
  
  delete info;
  delete muonArr;
  delete electronArr;
  delete jetArr;
    
  std::cout << outputFilename << " created!" << std::endl;
  std::cout << " >>> Events processed: " << nInputEvts << std::endl;
  std::cout << " >>>   Events passing: " << nPassEvts << std::endl;
  
  gBenchmark->Show("NormalizeNtuple");
}  
예제 #7
0
// Main macro function
//--------------------------------------------------------------------------------------------------
void SkimTightPlusRecoPerFile(string inputFilename, string outputFilename) 
{
  gBenchmark->Start("SkimNtuples");
    
  TTree::SetMaxTreeSize(kMaxLong64);
  

  mithep::MuonIDMVA *muonIDMVA = new mithep::MuonIDMVA();
  muonIDMVA->Initialize("BDTG method",
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin0_IDIsoCombined_BDTG.weights.xml", 
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin0_IDIsoCombined_BDTG.weights.xml", 
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin1_IDIsoCombined_BDTG.weights.xml", 
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin1_IDIsoCombined_BDTG.weights.xml", 
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/BarrelPtBin2_IDIsoCombined_BDTG.weights.xml", 
                        "/home/sixie/CMSSW_analysis/src/MitPhysics/data/MuonMVAWeights/EndcapPtBin2_IDIsoCombined_BDTG.weights.xml",
                        mithep::MuonIDMVA::kIDIsoCombinedDetIso);
  
  mithep::ElectronIDMVA *electronIDMVA = new mithep::ElectronIDMVA();
  electronIDMVA->Initialize("BDTG method",
                            "MitPhysics/data/ElectronMVAWeights/Subdet0LowPt_IDIsoCombined_BDTG.weights.xml", 
                            "MitPhysics/data/ElectronMVAWeights/Subdet1LowPt_IDIsoCombined_BDTG.weights.xml", 
                            "MitPhysics/data/ElectronMVAWeights/Subdet2LowPt_IDIsoCombined_BDTG.weights.xml", 
                            "MitPhysics/data/ElectronMVAWeights/Subdet0HighPt_IDIsoCombined_BDTG.weights.xml", 
                            "MitPhysics/data/ElectronMVAWeights/Subdet1HighPt_IDIsoCombined_BDTG.weights.xml", 
                            "MitPhysics/data/ElectronMVAWeights/Subdet2HighPt_IDIsoCombined_BDTG.weights.xml",
                            mithep::ElectronIDMVA::kIDIsoCombined);



  // Don't write TObject part of the objects
  mithep::TEventInfo::Class()->IgnoreTObjectStreamer();
  mithep::TMuon::Class()->IgnoreTObjectStreamer();
  mithep::TElectron::Class()->IgnoreTObjectStreamer();
  mithep::TJet::Class()->IgnoreTObjectStreamer();
  mithep::TPhoton::Class()->IgnoreTObjectStreamer();

  // Data structures to store info from TTrees
  mithep::TEventInfo *info  = new mithep::TEventInfo();
  TClonesArray *muonArr     = new TClonesArray("mithep::TMuon");
  TClonesArray *electronArr     = new TClonesArray("mithep::TElectron");
  TClonesArray *jetArr    = new TClonesArray("mithep::TJet");
  TClonesArray *photonArr     = new TClonesArray("mithep::TPhoton");
    
  UInt_t nInputEvts = 0;
  UInt_t nPassEvts  = 0;
  UInt_t nEventsTotal = 0;

  TFile* outfile = new TFile(outputFilename.c_str(), "RECREATE");
  
  //
  // Initialize data trees and structs
  // 
  TTree *outEventTree = new TTree("Events","Events"); 
  outEventTree->Branch("Info",     &info);
  outEventTree->Branch("Muon",     &muonArr);
  outEventTree->Branch("Electron", &electronArr);
  outEventTree->Branch("PFJet",    &jetArr);
  outEventTree->Branch("Photon",   &photonArr);

  cout << "Skimming " << inputFilename << "..." << endl;
  TTree *eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); 
  nEventsTotal += getNEvents(inputFilename.c_str()); 
  assert(eventTree);
    
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Muon",     &muonArr);     TBranch *muonBr     = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
  eventTree->SetBranchAddress("PFJet",    &jetArr);      TBranch *jetBr      = eventTree->GetBranch("PFJet");
  eventTree->SetBranchAddress("Photon",    &photonArr);  TBranch *photonBr   = eventTree->GetBranch("Photon");
     
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { 
    infoBr->GetEntry(ientry);
    muonArr->Clear();     muonBr->GetEntry(ientry);
    electronArr->Clear(); electronBr->GetEntry(ientry);      
    jetArr->Clear(); jetBr->GetEntry(ientry);
    photonArr->Clear(); photonBr->GetEntry(ientry);
     
    if (ientry % 100000 == 0) cout << "Events: " << ientry << endl;

    nInputEvts++;
      
    Bool_t keep = kTRUE;
    
    Double_t rho = 0;
    if (!(TMath::IsNaN(info->PileupEnergyDensity) || isinf(info->PileupEnergyDensity))) rho = info->PileupEnergyDensity;

    Int_t NTightMuons = 0;
    Int_t NRecoMuons = 0;
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);      
      if ( fabs(mu->eta) < 2.4
           && 
           mu->pt > 10.0
        ) {
        NRecoMuons++;

//         if ( passMuonCuts(mu)) NTightMuons++;
        if ( passMuonMVAIDIsoCombined(mu, muonIDMVA->MVAValue(
                                          mu->pt, mu->eta,
                                          mu->tkNchi2,
                                          mu->muNchi2,
                                          mu->nValidHits,
                                          mu->nTkHits,
                                          mu->nPixHits,
                                          mu->nMatch,
                                          mu->d0,
                                          mu->ip3d,
                                          mu->ip3dSig,
                                          mu->TrkKink,
                                          mu->SegmentCompatibility,
                                          mu->CaloCompatilibity,
                                          (mu->HadEnergy - rho*MuonEffectiveArea(kMuHadEnergy,mu->eta))/mu->pt,
                                          (mu->HoEnergy - rho*MuonEffectiveArea(kMuHoEnergy,mu->eta))/mu->pt,
                                          (mu->EmEnergy - rho*MuonEffectiveArea(kMuEmEnergy,mu->eta))/mu->pt,
                                          (mu->HadS9Energy - rho*MuonEffectiveArea(kMuHadS9Energy,mu->eta))/mu->pt,
                                          (mu->HoS9Energy - rho*MuonEffectiveArea(kMuHoS9Energy,mu->eta))/mu->pt,
                                          (mu->EmS9Energy - rho*MuonEffectiveArea(kMuEmS9Energy,mu->eta))/mu->pt,
                                          (mu->trkIso03 - rho*MuonEffectiveArea(kMuTrkIso03,mu->eta))/mu->pt,
                                          (mu->emIso03 - rho*MuonEffectiveArea(kMuEMIso03,mu->eta))/mu->pt,
                                          (mu->hadIso03 - rho*MuonEffectiveArea(kMuHadIso03,mu->eta))/mu->pt,
                                          (mu->trkIso05 - rho*MuonEffectiveArea(kMuTrkIso05,mu->eta))/mu->pt,
                                          (mu->emIso05 - rho*MuonEffectiveArea(kMuEMIso05,mu->eta))/mu->pt,
                                          (mu->hadIso05 - rho*MuonEffectiveArea(kMuHadIso05,mu->eta))/mu->pt
                                        ), rho)) NTightMuons++;
      }
    }
    Int_t NTightElectrons = 0;
    Int_t NRecoElectrons = 0;
    for(Int_t i=0; i<electronArr->GetEntries(); i++) {
      const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
      if ( fabs(ele->eta) < 2.5
           && 
           ele->pt > 10.0
        ) {
        NRecoElectrons++;

//         if (passElectronCuts(ele)) NTightElectrons++;
        if (passElectronMVAIDIsoCombined(ele, 
                                         electronIDMVA->MVAValue(
                                           ele->pt,ele->scEta,rho,
                                           ele->sigiEtaiEta, 
                                           ele->deltaEtaIn,
                                           ele->deltaPhiIn, 
                                           ele->HoverE,
                                           ele->d0,
                                           ele->dz, 
                                           ele->fBrem,
                                           ele->EOverP,
                                           ele->ESeedClusterOverPout,
                                           TMath::Sqrt(ele->sigiPhiiPhi),
                                           ele->nBrem,
                                           (1.0/(ele->scEt * TMath::CosH(ele->scEta)) - 1/ele->p), 
                                           ele->ESeedClusterOverPIn,
                                           ele->ip3d,
                                           ele->ip3dSig,
                                           ele->GsfTrackChi2OverNdof,
                                           ele->dEtaCalo,
                                           ele->dPhiCalo,
                                           ele->R9,
                                           ele->SCEtaWidth,
                                           ele->SCPhiWidth,
                                           ele->CovIEtaIPhi,
                                           ele->PreShowerOverRaw,
                                           ele->ChargedIso03,
                                           (ele->NeutralHadronIso03_05Threshold - ele->NeutralHadronIso007_05Threshold),
                                           (ele->GammaIso03_05Threshold - ele->GammaIsoVetoEtaStrip03_05Threshold),
                                           ele->ChargedIso04 ,
                                           (ele->NeutralHadronIso04_05Threshold - ele->NeutralHadronIso007_05Threshold),
                                           (ele->GammaIso04_05Threshold - ele->GammaIsoVetoEtaStrip04_05Threshold) 
                                           ), 
                                         0)) NTightElectrons++;



      }
    }

    //One Tight AND Two Loose
    if (!( NTightElectrons + NTightMuons >= 1  
           && NRecoElectrons + NRecoMuons >= 2
          ) ) {
      keep = kFALSE;
    }
      
    if(keep) {
      outEventTree->Fill();
      nPassEvts++;
    }
  }
  outfile->Write();
  outfile->Close();
  
  delete info;
  delete muonArr;
  delete electronArr;
  delete jetArr;
    
  std::cout << outputFilename << " created!" << std::endl;
  std::cout << " >>> Total Number of Events: " << nEventsTotal << std::endl;
  std::cout << " >>> Events processed: " << nInputEvts << std::endl;
  std::cout << " >>>   Events passing: " << nPassEvts << std::endl;

  gBenchmark->Show("SkimNtuples");
}  
예제 #8
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");       
} 
예제 #9
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");       


} 
void MakeNtuple(const string inputFilename, const string outputFilename, Int_t Option)
{  
  gBenchmark->Start("WWTemplate");

  //*****************************************************************************************
  //Setup
  //*****************************************************************************************
  TFile *outputFile = new TFile(outputFilename.c_str(), "RECREATE");
  ElectronTree *eleTree = new ElectronTree;
  eleTree->CreateTree();
  eleTree->tree_->SetAutoFlush(0);

  UInt_t NElectronsFilled = 0;
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  higgsana::TEventInfo *info    = new higgsana::TEventInfo();
  TClonesArray *electronArr = new TClonesArray("higgsana::TElectron");
  TClonesArray *muonArr = new TClonesArray("higgsana::TMuon");
  TClonesArray *jetArr = new TClonesArray("higgsana::TJet");
  TClonesArray *photonArr = new TClonesArray("higgsana::TPhoton");
  TClonesArray *pfcandidateArr = new TClonesArray("higgsana::TPFCandidate");
  
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile("/data/smurf/data/Winter11_4700ipb/auxiliar/hww.Full2011.json"); 
  rlrm.AddJSONFile("/data/blue/sixie/HZZ4l/auxiliar/2012/Cert_190456-196531_8TeV_PromptReco_Collisions12_JSON.txt");

  Int_t NEvents = 0;

  UInt_t DataEra = kDataEra_NONE;

  vector<string> inputfiles;
  if (inputFilename == "LIST") {
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-m10-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-pr-v4.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-a05-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11a-del-o03-v1.FakeTriggerSkim.root");
    inputfiles.push_back("/home/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r11b-del-pr-v1.FakeTriggerSkim.root");    
  } 
  else if (inputFilename == "2012Data") {
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12a-del-pr-v1_FakeRateTriggerSkimmed.root");
    inputfiles.push_back("/data/smurf/sixie/hist/HZZ4lNtuples/data/AllNtuple_HZZ4lNtuple_r12b-del-pr-v1_FakeRateTriggerSkimmed.root");
    DataEra = kDataEra_2012_MC;
  }
  else {
    inputfiles.push_back(inputFilename);
  }

  for (UInt_t f = 0; f < inputfiles.size(); ++f) {

    //********************************************************
    // Get Tree
    //********************************************************
    eventTree = getTreeFromFile(inputfiles[f].c_str(),"Events"); 
    TBranch *infoBr;
    TBranch *electronBr;
    TBranch *muonBr;
    TBranch *jetBr;
    TBranch *photonBr;
    TBranch *pfcandidateBr;


    //*****************************************************************************************
    //Loop over 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("Photon", &photonArr);     photonBr = eventTree->GetBranch("Photon");
    eventTree->SetBranchAddress("PFJet", &jetArr);         jetBr = eventTree->GetBranch("PFJet");
    eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr); pfcandidateBr = eventTree->GetBranch("PFCandidate");

    cout << "InputFile " << inputfiles[f] << " --- Total Events : " << eventTree->GetEntries() << endl;
    for(UInt_t ientry=0; ientry < eventTree->GetEntries(); ientry++) {       	
      infoBr->GetEntry(ientry);
		
      if (ientry % 100000 == 0) cout << "Event " << ientry << endl;

      Double_t eventweight = info->eventweight;

      mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
      if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  // not certified run? Skip to next event...

      NEvents++;

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


      //********************************************************
      // Pileup Energy Density
      //********************************************************
      Double_t rhoEleIso = 0;
      UInt_t EleEAEra = 0;

      if (DataEra == kDataEra_2011_MC) {     
        if (!(isnan(info->RhoKt6PFJetsForIso25) || 
              isinf(info->RhoKt6PFJetsForIso25))) {
          rhoEleIso = info->RhoKt6PFJetsForIso25;
        }
        EleEAEra = kDataEra_2011_Data;
      } else if (DataEra == kDataEra_2012_MC) {
        if (!(isnan(info->RhoKt6PFJets) || 
              isinf(info->RhoKt6PFJets))) {
          rhoEleIso = info->RhoKt6PFJets;
        }
        EleEAEra = kDataEra_2012_Data;
      }

      //********************************************************
      // TcMet
      //********************************************************
      TVector3 pfMet;        
      if(info->pfMEx!=0 || info->pfMEy!=0) {       
        pfMet.SetXYZ(info->pfMEx, info->pfMEy, 0);
      }
      Double_t met = pfMet.Pt();

      Int_t NElectrons = electronArr->GetEntries();
 

      //********************************************************
      // Event Selection Cuts
      //********************************************************
      //veto events with more than 1 reco electron
      if (NElectrons > 1) continue;
      //met cut removed W events
      if (met > 20) continue;


      //******************************************************************************
      //loop over electrons 
      //******************************************************************************
      for(Int_t i=0; i<electronArr->GetEntries(); i++) {
        const higgsana::TElectron *ele = (higgsana::TElectron*)((*electronArr)[i]);
 

        //make cut on dz
        if (fabs(ele->dz) > 0.1) continue;

        //protect against pathologies
        if (TMath::IsNaN(ele->sigiPhiiPhi)) {
          cout << "Pathological SigmaIPhiIPhi : " 
               << info->runNum << " " << info->lumiSec << " " << info->evtNum << endl;
          continue;
        }
        
        //********************************************************
        //find leading jet in the event
        //********************************************************
        Double_t leadingJetPt = -1;
        //pass event selection     
        for(Int_t j=0; j<jetArr->GetEntries(); j++) {
          const higgsana::TJet *jet = (higgsana::TJet*)((*jetArr)[j]);        
          if (jet->pt > leadingJetPt &&
              higgsana::deltaR(jet->eta, jet->phi, ele->eta, ele->phi) > 1.0) {
            leadingJetPt = jet->pt;          
          }
        }
      
        //Fill These Electrons
        NElectronsFilled++;
        
        if (Option == 0) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, EleEAEra, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        } else if (Option == 1) {
          FillElectronTree( eleTree, ele, pfcandidateArr, rhoEleIso, kDataEra_NONE, 
                            info->nPV0, info->runNum, info->lumiSec, info->evtNum);
        }

      } //loop over electrons

    } //end loop over data  

    cout << "Total Electrons: " << NElectronsFilled << endl;

  } //end loop over files

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


  cout << "Total Electrons: " << NElectronsFilled << endl;
  outputFile->Write();
  outputFile->Close();

  gBenchmark->Show("WWTemplate");       
} 
예제 #11
0
void HwwGenJetVetoEfficiency(const string inputFilename,  const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  cout << "here1\n";
  string label = "";
  cout << "here11\n";
  if (Label != "") label = "_" + Label;
  cout << "here12\n";

  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");
  cout << "here13\n";
  assert(file);
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPtFineBinning_ggHww160_PowhegToNNLL");
  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_PowhegToNNLL");
  cout << "here14\n";
//    TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_MCAtNLOToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww180_PowhegToNNLL");//  
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww200_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww220_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww250_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww300_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww400_PowhegToNNLL");
  assert(kFactorHiggsPt);
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    
  cout << "here2\n";

  //--------------------------------------------------------------------------------------------------------------
  // 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 *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *leadingGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *secondGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ 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);


  vector<Double_t> NEvents_0Jets;
  vector<Double_t> NEvents_1Jets;
  vector<Double_t> NEvents_2Jets;
  for(UInt_t k=0 ; k < 200; ++k) {
    NEvents_0Jets.push_back(0); 
    NEvents_1Jets.push_back(0); 
    NEvents_2Jets.push_back(0);
  }


  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();

  cout << "here3\n";

  //********************************************************
  // 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");
   
  cout << "here4\n";

  //*****************************************************************************************
  //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++;

   mithep::FourVectorM lepton1;
    mithep::FourVectorM lepton2;
    lepton1.SetCoordinates(genInfo->pt_1, genInfo->eta_1, genInfo->phi_1, 0.51099892e-3 );
    lepton2.SetCoordinates(genInfo->pt_2, genInfo->eta_2, genInfo->phi_2, 0.51099892e-3 );
    mithep::FourVectorM dilepton = lepton1+lepton2;

    if (genInfo->pt_1 > 20.0 && genInfo->pt_2 > 20.0
        && fabs(genInfo->eta_1) < 2.5 && fabs(genInfo->eta_2) < 2.5
        && genInfo->met > 30.0
        && fabs(dilepton.M() - 91.2) > 15.0
      ) {
      Double_t scale = kFactorHiggsPt->GetBinContent(kFactorHiggsPt->GetXaxis()->FindFixBin(genInfo->ptBosonSystem));
      scale = 1;

      if (info->eventweight >= 0) {
        
        //don't use a scale factor for Higgs pt < 1.0, because HQT does negative.
        if (genInfo->ptBosonSystem < 1.25 ) scale = 1.0;

        //powheg
        if (genInfo->ptBosonSystem > 200) scale = 0.6;
        //MC@NLO
//          if (genInfo->ptBosonSystem > 200) scale = 1.5;        

         leadingGenJetPt->Fill(genInfo->jetpt_1,1.0);
         leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,scale);

         for(UInt_t k=0 ; k < 200; ++k) {
           if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
             NEvents_2Jets[k] += scale;
           } else if (genInfo->jetpt_1 > k) {
             NEvents_1Jets[k] += scale; 
           } else {
             NEvents_0Jets[k] += scale;
           }                                
         }

      } else {       
        leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,-1*scale);
        leadingGenJetPt->Fill(genInfo->jetpt_1,-1*scale);
        
        for(UInt_t k=0 ; k < 200; ++k) {
          if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
            NEvents_2Jets[k] += -1*scale;
          } else if (genInfo->jetpt_1 > k) {
            NEvents_1Jets[k] += -1*scale; 
          } else {
             NEvents_0Jets[k] += -1*scale;
          }                                
        }

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

  TH1D *jetVetoEfficiency_reweighted = (TH1D*)leadingGenJetPt_reweighted->Clone((string("jetVetoEfficiency_reweighted")+label).c_str()); 
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency_reweighted->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt_reweighted->Integral(1,i);
    Int_t d = leadingGenJetPt_reweighted->Integral(1,leadingGenJetPt_reweighted->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_reweighted->SetBinContent(i,ratio);
    jetVetoEfficiency_reweighted->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency_reweighted->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }





  //*****************************************************************************************************
  //0,1,2 - Jet Fractions
  //*****************************************************************************************************
  const int nPoints = 100;
  double jetPtCut[nPoints];
  double jetPtCutError[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    jetPtCut[i] = i;
    jetPtCutError[i] = 0;     
  }

  double ZeroJetFraction[nPoints];
  double ZeroJetFractionErrLow[nPoints];
  double ZeroJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_0Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    ZeroJetFraction[i] = ratio;
    ZeroJetFractionErrLow[i] = errLow;
    ZeroJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *ZeroJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, ZeroJetFraction, jetPtCutError, jetPtCutError, ZeroJetFractionErrLow, ZeroJetFractionErrHigh);
  ZeroJetFractionVsJetPtCut->SetName(("ZeroJetFractionVsJetPtCut"+label).c_str());
  ZeroJetFractionVsJetPtCut->SetMarkerColor(kRed);
  ZeroJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double OneJetFraction[nPoints];
  double OneJetFractionErrLow[nPoints];
  double OneJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_1Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    OneJetFraction[i] = ratio;
    OneJetFractionErrLow[i] = errLow;
    OneJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *OneJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, OneJetFraction, jetPtCutError, jetPtCutError, OneJetFractionErrLow, OneJetFractionErrHigh);
  OneJetFractionVsJetPtCut->SetName(("OneJetFractionVsJetPtCut"+label).c_str());
  OneJetFractionVsJetPtCut->SetMarkerColor(kBlue);
  OneJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  OneJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double TwoJetFraction[nPoints];
  double TwoJetFractionErrLow[nPoints];
  double TwoJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_2Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    TwoJetFraction[i] = ratio;
    TwoJetFractionErrLow[i] = errLow;
    TwoJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *TwoJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, TwoJetFraction, jetPtCutError, jetPtCutError, TwoJetFractionErrLow, TwoJetFractionErrHigh);
  TwoJetFractionVsJetPtCut->SetName(("TwoJetFractionVsJetPtCut"+label).c_str());
  TwoJetFractionVsJetPtCut->SetMarkerColor(kMagenta);
  TwoJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  TwoJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);




  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================

  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  TLegend *tmpLegend = new TLegend(0.73,0.55,0.93,0.70); 
  

  tmpLegend->SetTextSize(0.03);
  tmpLegend->SetBorderSize(1);
  tmpLegend->AddEntry(leadingGenJetPt, "Powheg", "LP");   
  tmpLegend->AddEntry(leadingGenJetPt_reweighted, "MC@NLO(reweighted)", "LP");   
  cv->SetLogy();
  leadingGenJetPt->Draw();
  leadingGenJetPt->SetLineColor(kRed);
  leadingGenJetPt_reweighted->Draw("same");
  tmpLegend->Draw();
  cv->SaveAs("leadingGenJetPt.gif");

  jetVetoEfficiency->Draw();
  cv->SaveAs("jetVetoEfficiency.gif");
 
  cv->SetLogy(0);
  tmpLegend->Clear();
  tmpLegend->AddEntry(ZeroJetFractionVsJetPtCut, "0Jet Fraction", "LP");   
  tmpLegend->AddEntry(OneJetFractionVsJetPtCut, "1Jet Fraction", "LP");   
  tmpLegend->AddEntry(TwoJetFractionVsJetPtCut, ">2 Jet Fraction", "LP");   
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetRangeUser(0.0,1.0);
  ZeroJetFractionVsJetPtCut->Draw("AP");
  OneJetFractionVsJetPtCut->Draw("Psame");
  TwoJetFractionVsJetPtCut->Draw("Psame");
  cv->SaveAs("NJetFractions.gif");


  file->WriteTObject(leadingGenJetPt, leadingGenJetPt->GetName(), "WriteDelete");
  file->WriteTObject(leadingGenJetPt_reweighted, leadingGenJetPt_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency, jetVetoEfficiency->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency_reweighted, jetVetoEfficiency_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(ZeroJetFractionVsJetPtCut, ZeroJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(OneJetFractionVsJetPtCut, OneJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(TwoJetFractionVsJetPtCut, TwoJetFractionVsJetPtCut->GetName(), "WriteDelete");
//   file->Close();

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


        
  gBenchmark->Show("plotZ");       
} 
예제 #12
0
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void HWWDistributions(const string signalInputFilename, const string bkgInputFilename,                       
                      int OnlyThisFinalState = -1,
                      const string SignalName = "", const string cutValuesFile = "") {
  TTree* signalTree = getTreeFromFile(signalInputFilename.c_str(),"all");
  TTree* bkgTree = getTreeFromFile(bkgInputFilename.c_str(),"all");
  assert(signalTree);
  assert(bkgTree);

  CheckInitialCutValueConsistency();
  
  //Load cut values from a root file;
  if (cutValuesFile != "" && SignalName != "")
    LoadCutValues(cutValuesFile, SignalName);

  //Summarize Cuts
  cout << "*********************************************************************\n";
  cout << "**  Load Cut Values from file " << cutValuesFile << endl;
  cout << "*********************************************************************\n";
  cout << "Final Cuts" << endl;
  cout << "*************************************************************************" << endl;

  for (int f=0; f<=2;f++) {  
    cout << "Final State : " << finalstatestring[f] << endl;
    for (int v = 0; v < NVARIABLES;v++) {
      cout << fVariableNames[v] << " : ";
      if (fCutBelow[v])
        cout << fCutBelowInitialValue[f][v];
      else 
        cout << "-Infinity ";
      cout << " -> ";
      if (fCutAbove[v])
        cout << fCutAboveInitialValue[f][v];      
      else 
        cout << " Infinity ";
      cout << endl;
    }
    cout << "----------------------------------------------------------------------" << endl;
  }


  MitNtupleEvent signalEvent(signalTree);
  MitNtupleEvent bkgEvent(bkgTree);

  cout << "*************************************************************************" << endl;
  cout << "Make Distribution Plots" << endl;
  cout << "*************************************************************************" << endl;
  if (OnlyThisFinalState == -1) {
    for (int f=10; f<=12;f++) {
      MakeStackedDistributionPlots(&signalEvent , &bkgEvent , signalTree->GetEntries(), 
                                   bkgTree->GetEntries(), f);
    }
  } else {
    MakeStackedDistributionPlots(&signalEvent , &bkgEvent , signalTree->GetEntries(), 
                                 bkgTree->GetEntries(), OnlyThisFinalState);
  }
  

  cout << "*************************************************************************" << endl;
  cout << "Print Final Results" << endl;
  cout << "*************************************************************************" << endl;
  if (OnlyThisFinalState == -1) {
    for (int f=10; f<=12;f++) {
      PrintFinalResults(&signalEvent , &bkgEvent , signalTree->GetEntries(), 
                        bkgTree->GetEntries(), f);
    }
  } else {
    PrintFinalResults(&signalEvent , &bkgEvent , signalTree->GetEntries(), 
                      bkgTree->GetEntries(), OnlyThisFinalState);
  }
  
}
예제 #13
0
void MakeMCHiggsPtDistribution( string inputFilename ,  const string Label) {

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

  //--------------------------------------------------------------------------------------------------------------
  // 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", 80, 1.25, 201.25);
  TH1D *bosonSystemPtFineBinning = new TH1D((string("bosonSystemPtFineBinning")+ label).c_str(), ";  Higgs p_{T} [GeV/c]; Number of Events", 4000, 1.225, 201.225);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *leadingGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ 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++;

    mithep::FourVectorM lepton1;
    mithep::FourVectorM lepton2;
    lepton1.SetCoordinates(genInfo->pt_1, genInfo->eta_1, genInfo->phi_1, 0.51099892e-3 );
    lepton2.SetCoordinates(genInfo->pt_2, genInfo->eta_2, genInfo->phi_2, 0.51099892e-3 );
    mithep::FourVectorM dilepton = lepton1+lepton2;

    if (info->eventweight >= 0 && genInfo->ptBosonSystem <= 300) {
      bosonSystemPt->Fill(genInfo->ptBosonSystem);
      bosonSystemPtFineBinning->Fill(genInfo->ptBosonSystem);
    } else {
      bosonSystemPt->Fill(genInfo->ptBosonSystem, -1);
      bosonSystemPtFineBinning->Fill(genInfo->ptBosonSystem,-1);
    }


  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Normalize Higgs Pt spectrum
  //==============================================================================================================
  Double_t norm = 0 ;
  for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
    norm += bosonSystemPt->GetBinContent(i);
  }
  for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
    bosonSystemPt->SetBinContent(i, bosonSystemPt->GetBinContent(i) / norm);
  }
//   for(int i=0; i<bosonSystemPt->GetXaxis()->GetNbins()+2 ; ++i) {
//     cout << "BosonPt " << i << " " << bosonSystemPt->GetBinContent(i) << endl;
//   }

  //smoothing - smooth to 1GeV bins
  double total = 0;
  for(int i=0; i<25 ; ++i) {
    total = 0;
    for (int j=0; j<20;j++) {
      total += bosonSystemPtFineBinning->GetBinContent(i*20 + j);
    }
    for (int j=0; j<20;j++) {
      bosonSystemPtFineBinning->SetBinContent(i*20 + j, total / 20);
    }
  }
  //smoothing - first big bin
  total = 0;
  for(int i=477; i<502 ; ++i) {
    total += bosonSystemPtFineBinning->GetBinContent(i);
  }
  for(int i=477; i<502 ; ++i) {
    bosonSystemPtFineBinning->SetBinContent(i,total / 26);
  }
  //smoothing - remaining big bins
  for (int i=10; i<80; ++i) {
    total = 0;
    for (int j=0; j<50;j++) {
      if (i*50 + 2 + j < 4001) {
        total += bosonSystemPtFineBinning->GetBinContent(i*50 + 2 + j);
      }
    }
    for (int j=0; j<50;j++) {
      if (i < 79) {        
        bosonSystemPtFineBinning->SetBinContent(i*50 + 2 + j, total / 50);
      } else {
        bosonSystemPtFineBinning->SetBinContent(i*50 + 2 + j, total / 49);
      }
    }
  }
  //normalize;
  norm = 0 ;
  for(int i=0; i<bosonSystemPtFineBinning->GetXaxis()->GetNbins()+2 ; ++i) {
    norm += bosonSystemPtFineBinning->GetBinContent(i);
  }
  for(int i=0; i<bosonSystemPtFineBinning->GetXaxis()->GetNbins()+2 ; ++i) {
    bosonSystemPtFineBinning->SetBinContent(i, bosonSystemPtFineBinning->GetBinContent(i) / norm);
  }

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

}
//*************************************************************************************************
//Main part of the macro
//*************************************************************************************************
void CreateTrainingAndTestSamples(const string InputFilename, Double_t TestSampleFraction) {

  TTree* HwwTree = getTreeFromFile(InputFilename.c_str());
  assert(HwwTree);
  MitNtupleEvent event(HwwTree);
    
  //*************************************************************************************************
  //Create randomized list of indices
  //*************************************************************************************************
  vector<Int_t> indices;
  for (Int_t i=0; i<HwwTree->GetEntries(); ++i) {
    indices.push_back(i);
  }
  random_shuffle(indices.begin(),indices.end());


  if ( TestSampleFraction > 1.0 || TestSampleFraction < 0.0 ) {
    cerr << "TestSampleFraction = " << TestSampleFraction << " is not in the range [0,1]. " 
         << endl;
    assert( TestSampleFraction >= 1.0 && TestSampleFraction <= 0.0 );
  }
  cout << "Input Tree Size : " << HwwTree->GetEntries() << endl;

  //Remove the '.root' from end of filename
  size_t p;
  p = InputFilename.find(".root");  
  string tmpInputFilename = InputFilename.substr(0,p);
  
  //change 'unrandomized' to 'randomized' in the file name.
  p = tmpInputFilename.find("_unrandomized");
  if (p != string::npos) {
    tmpInputFilename = tmpInputFilename.substr(0,p) + "_randomized" ;
  }

  //*************************************************************************************************
  //Create Randomized Sample Tree
  //*************************************************************************************************
  TFile *allSampleFile = new TFile((tmpInputFilename+".all.root").c_str(), "RECREATE");
  allSampleFile->cd();
  TTree *allSampleTree = HwwTree->CloneTree(0);

  for (Int_t n=0;n<HwwTree->GetEntries();n++) { 
    event.GetEntry(indices[n]);
    allSampleTree->Fill(); 
  }  
  allSampleTree->Write();
  cout << "All Tree Size: " << allSampleTree->GetEntries() << endl;
  allSampleFile->Close();

 

  //*************************************************************************************************
  //Create Test Sample Tree
  //*************************************************************************************************
  //For some reason I need to make another TTree, otherwise when I try to clone it, root crashes.
  TTree* HwwTree2 = getTreeFromFile(InputFilename.c_str());
  assert(HwwTree2);
  assert(HwwTree2->GetEntries() == 
         HwwTree->GetEntries());
  MitNtupleEvent event2(HwwTree2);

  TFile *testSampleFile = new TFile((tmpInputFilename+".test.root").c_str(), "RECREATE");
  testSampleFile->cd();

  Int_t testSampleSize = Int_t(TestSampleFraction * double(HwwTree->GetEntries()));
  TTree *testSampleTree = HwwTree2->CloneTree(0);

  for (Int_t n=0;n<testSampleSize;n++) { 
    event2.GetEntry(indices[n]);
    event2.H_weight = event2.H_weight / (TestSampleFraction);
    testSampleTree->Fill(); 
  }  
  testSampleTree->Write();
  cout << "Test Tree Size: " << testSampleTree->GetEntries() << endl;
  testSampleFile->Close();



  //*************************************************************************************************
  //Create Training Sample Tree
  //*************************************************************************************************
  //For some reason I need to make another TTree, otherwise when I try to clone it, root crashes.
  TTree* HwwTree3 = getTreeFromFile(InputFilename.c_str());
  assert(HwwTree3);
  assert(HwwTree3->GetEntries() ==
         HwwTree->GetEntries());
  MitNtupleEvent event3(HwwTree3);

  TFile *trainingSampleFile = new TFile((tmpInputFilename+".training.root").c_str(), "RECREATE");
  trainingSampleFile->cd();
  TTree *trainingSampleTree = HwwTree3->CloneTree(0);

  for (Int_t n=testSampleSize;n<HwwTree->GetEntries();n++) { 
    event3.GetEntry(indices[n]);
    event3.H_weight = event3.H_weight / (1 - TestSampleFraction);
    trainingSampleTree->Fill(); 
  }
  trainingSampleTree->Write();
  cout << "Training Tree Size: " << trainingSampleTree->GetEntries() << endl;
  trainingSampleFile->Close();

}
예제 #15
0
// Main macro function
//--------------------------------------------------------------------------------------------------
void SkimMultipleFiles_fakes(string inputFilename, string outputFilename) 
{
  gBenchmark->Start("SkimNtuples");
    
  TTree::SetMaxTreeSize(kMaxLong64);
  
  // Don't write TObject part of the objects
  mithep::TEventInfo::Class()->IgnoreTObjectStreamer();
  mithep::TMuon::Class()->IgnoreTObjectStreamer();
  mithep::TElectron::Class()->IgnoreTObjectStreamer();
  mithep::TJet::Class()->IgnoreTObjectStreamer();
  mithep::TPhoton::Class()->IgnoreTObjectStreamer();

  // Data structures to store info from TTrees
  mithep::TEventInfo *info  = new mithep::TEventInfo();
  TClonesArray *muonArr     = new TClonesArray("mithep::TMuon");
  TClonesArray *electronArr     = new TClonesArray("mithep::TElectron");
  TClonesArray *jetArr    = new TClonesArray("mithep::TJet");
  TClonesArray *photonArr     = new TClonesArray("mithep::TPhoton");
    
  UInt_t nInputEvts = 0;
  UInt_t nPassEvts  = 0;
  UInt_t nEventsTotal = 0;

  TFile* outfile = new TFile(outputFilename.c_str(), "RECREATE");
  
  //
  // Initialize data trees and structs
  // 
  TTree *outEventTree = new TTree("Events","Events"); 
  outEventTree->Branch("Info",     &info);
  outEventTree->Branch("Muon",     &muonArr);
  outEventTree->Branch("Electron", &electronArr);
  outEventTree->Branch("PFJet",    &jetArr);
  outEventTree->Branch("Photon",   &photonArr);


  // list input ntuple files to be skimmed
  vector<string> infilenames;  
  ifstream ifs;
  ifs.open(inputFilename.c_str()); 
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) { infilenames.push_back(line); }
  ifs.close();

  for(UInt_t ifile=0; ifile<infilenames.size(); ifile++) {
    cout << "Skimming " << infilenames[ifile] << "..." << endl;
    TTree *eventTree = getTreeFromFile(infilenames[ifile].c_str(),"Events"); 
    nEventsTotal += getNEvents(infilenames[ifile].c_str()); 
    assert(eventTree);
    
    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Muon",     &muonArr);     TBranch *muonBr     = eventTree->GetBranch("Muon");
    eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("PFJet",    &jetArr);      TBranch *jetBr      = eventTree->GetBranch("PFJet");
    eventTree->SetBranchAddress("Photon",    &photonArr);  TBranch *photonBr   = eventTree->GetBranch("Photon");
     
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) { 
      infoBr->GetEntry(ientry);
      muonArr->Clear();     muonBr->GetEntry(ientry);
      electronArr->Clear(); electronBr->GetEntry(ientry);
      jetArr->Clear();      jetBr->GetEntry(ientry);
      
      if (ientry % 100000 == 0) cout << "Events: " << ientry << endl;

      nInputEvts++;
      
      //********************************************************
      // TcMet
      //********************************************************
      TVector3 met;        
      if(info->tcMEx!=0 || info->tcMEy!=0) {       
        met.SetXYZ(info->tcMEx, info->tcMEy, 0);
      }
      
      Double_t tempLeadingJetPt = 0;
      for(Int_t i=0; i<jetArr->GetEntries(); i++) {
        const mithep::TJet *jet = (mithep::TJet*)((*jetArr)[i]);
        if( jet->pt > tempLeadingJetPt) tempLeadingJetPt = jet->pt;
      }


      Bool_t keep = kTRUE;
    
      Int_t NRecoMuon = 0;
      Int_t NDenominatorMuon = 0;
      Int_t NMuons = 0;
      for(Int_t i=0; i<muonArr->GetEntries(); i++) {
        const mithep::TMuon *mu = (mithep::TMuon*)((*muonArr)[i]);      
        if (fabs(mu->eta) < 2.4 && mu->pt > 10.0) {
          NRecoMuon++;
          if (passMuonDenominatorCuts(mu)) {
            NDenominatorMuon++;
          }
        }
      }
      Int_t NRecoElectrons = 0;
      Int_t NDenominatorElectrons = 0;
      for(Int_t i=0; i<electronArr->GetEntries(); i++) {
        const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
        if ( fabs(ele->eta) < 2.5 && ele->pt > 10.0 ) {
          NRecoElectrons++;
          if (passElectronDenominatorCuts(ele) ) {
            NDenominatorElectrons++;
          }
        }
      }

      //Skim Lepton + Jet
      if (!(
            (NRecoMuon == 1 || NRecoElectrons == 1)
            &&
            tempLeadingJetPt > 15.0
            &&
            met.Pt() < 20
            )
        ) {
        keep = kFALSE;
      }

      if(keep) {
        outEventTree->Fill();
        nPassEvts++;
      }
    }
  }
  outfile->Write();
  outfile->Close();
  
  delete info;
  delete muonArr;
  delete electronArr;
  delete jetArr;
    
  std::cout << outputFilename << " created!" << std::endl;
  std::cout << " >>> Total Number of Events: " << nEventsTotal << std::endl;
  std::cout << " >>> Events processed: " << nInputEvts << std::endl;
  std::cout << " >>>   Events passing: " << nPassEvts << std::endl;

  gBenchmark->Show("SkimNtuples");
}  
예제 #16
0
void MakeBJetEfficiencyNtuple(const string inputFilename, const string outputFilename, int denominatorType = 0)
{  
  gBenchmark->Start("WWTemplate");

  //*****************************************************************************************
  //Define Data Era
  //*****************************************************************************************
  UInt_t DataEra = kDataEra_NONE;
  DataEra = kDataEra_2012_MC;

  cout << "using DataEra = " << DataEra << endl;


  //*****************************************************************************************
  //Setup Output Tree
  //*****************************************************************************************
  TFile *outputFile = new TFile(outputFilename.c_str(), "RECREATE");
  cmsana::EfficiencyTree *effTree = new cmsana::EfficiencyTree;
  effTree->CreateTree();
  effTree->tree_->SetAutoFlush(0);

  UInt_t NDenominatorsFilled = 0;
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  cmsana::TEventInfo *info    = new cmsana::TEventInfo();
  TClonesArray *jetArr = new TClonesArray("cmsana::TJet");
  TClonesArray *pfcandidateArr = new TClonesArray("cmsana::TPFCandidate");
  TClonesArray *genparticleArr = new TClonesArray("cmsana::TGenParticle");
  TClonesArray *genjetArr = new TClonesArray("cmsana::TGenJet");

  Int_t NEvents = 0;



  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); 
  TBranch *infoBr;
  TBranch *jetBr;
  TBranch *pfcandidateBr;
  TBranch *genparticleBr;
  TBranch *genjetBr;
  
  
  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);  infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("PFJet", &jetArr); jetBr  = eventTree->GetBranch("PFJet");
  eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr); pfcandidateBr = eventTree->GetBranch("PFCandidate");
  eventTree->SetBranchAddress("GenParticle", &genparticleArr); genparticleBr = eventTree->GetBranch("GenParticle");
  eventTree->SetBranchAddress("GenJet", &genjetArr); genjetBr = eventTree->GetBranch("GenJet");

  cout << "InputFile " << inputFilename << " --- Total Events : " << eventTree->GetEntries() << endl;
  for(UInt_t ientry=0; ientry < eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
		
    if (ientry % 100 == 0) cout << "Event " << ientry << endl;

    Double_t eventweight = info->eventweight;

    //********************************************************
    // Load the branches
    //********************************************************
    jetArr->Clear(); 
    pfcandidateArr->Clear(); 
    genparticleArr->Clear(); 
    genjetArr->Clear(); 
    jetBr->GetEntry(ientry);
    pfcandidateBr->GetEntry(ientry);
    genparticleBr->GetEntry(ientry);
    genjetBr->GetEntry(ientry);
 

    //********************************************************
    // Pileup Energy Density
    //********************************************************
    Double_t rho = info->RhoKt6PFJets;
    UInt_t EAEra = kDataEra_2012_Data;


    if (denominatorType == 0) {
    //********************************************************
    // genjets denominator
    //********************************************************
      for(Int_t k=0; k<genjetArr->GetEntries(); k++) {
        const cmsana::TGenJet *genjet = (cmsana::TGenJet*)((*genjetArr)[k]);

        //some kinematic cuts to save ntupling time
        if (!(genjet->pt > 30)) continue;
        if (!(fabs(genjet->eta) < 2.5)) continue;        

        bool pass = false;
        //Find matching jet
        for(Int_t i=0; i<jetArr->GetEntriesFast(); i++) {
          const cmsana::TJet *jet = (cmsana::TJet*)((*jetArr)[i]);
          if (!(jet->pt > 20)) continue;
          if (!(fabs(jet->eta) < 2.5)) continue;
          
          //match in dR?
          double DR = cmsana::deltaR(jet->eta,jet->phi,genjet->eta,genjet->phi);
          if (!(DR < 0.5)) continue;

          if (!(jet->CombinedSecondaryVertexBJetTagsDisc > 0.679)) continue;
          
          pass = true;
          break;
        }
        
        effTree->weight = eventweight;
        effTree->mass = 0;
        effTree->pt = genjet->pt;
        effTree->eta = genjet->eta;
        effTree->phi = genjet->phi;
        effTree->rho = info->RhoKt6PFJets;
        effTree->q = 0;
        effTree->npv = info->nGoodPV;
        effTree->npu = info->nPU;
        effTree->matchedPdgId = genjet->matchedPdgId;
        effTree->run = info->runNum;
        effTree->lumi = info->lumiSec;
        effTree->event = info->evtNum;
        effTree->pass = pass;

        //***********************
        //Fill Denominator
        //***********************
        NDenominatorsFilled++;
        effTree->tree_->Fill();

      }//loop over genjet denominators
    } //if denominatorType == 0

  } //loop over events
  
  cout << "Total Denominators: " << NDenominatorsFilled << endl;

  delete info;
  delete jetArr;
  delete pfcandidateArr;
  delete genparticleArr;
  delete genjetArr;

  outputFile->Write();
  outputFile->Close();
  
  delete outputFile;
  if (effTree) delete effTree;
} 
예제 #17
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");       
} 
예제 #18
0
파일: ZmmSelection.C 프로젝트: sixie/EWKAna
void ZmmSelection(const string dataInputFilename, const string Label) {   

  gBenchmark->Start("ZeeSelection");

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

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_ee = new TH1D("dileptonMass_ee", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_emu = new TH1D("dileptonMass_emu", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *dileptonMass_mumu = new TH1D("dileptonMass_mumu", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  Int_t Count_ee_BB = 0;
  Int_t Count_ee_BE = 0;
  Int_t Count_ee_EE = 0;
  Int_t Count_mm_BB = 0;
  Int_t Count_mm_BE = 0;
  Int_t Count_mm_EE = 0;
  Int_t Count_em_BB = 0;
  Int_t Count_em_BE = 0;
  Int_t Count_em_EE = 0;
  ofstream eventListFile("eventList.txt");

  //--------------------------------------------------------------------------------------------------------------
  // 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 *muonArr = new TClonesArray("mithep::TMuon");
  TClonesArray *jetArr = new TClonesArray("mithep::TJet");
  

  infile = new TFile(dataInputFilename.c_str());
  assert(infile);

    
  //********************************************************
  // Good RunLumi Selection
  //********************************************************
  Bool_t hasJSON = kTRUE;
  mithep::RunLumiRangeMap rlrm;
  rlrm.AddJSONFile("Cert_TopNov5_Merged_135821-149442_allPVT.txt"); 

  

  //********************************************************
  // 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("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");
  eventTree->SetBranchAddress("PFJet", &jetArr); TBranch *jetBr = eventTree->GetBranch("PFJet");
  
  cout << "Total: " << eventTree->GetEntries() << endl;
  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
	
//     Double_t eventweight = info->eventweight*3.1;
    double eventweight = 1;
//    cout << eventweight << endl;
    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...
     
    if (!passHLT(info->triggerBits, info->runNum, kTRUE)) continue;


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


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

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

      if (!(jet->pt > 25 && fabs(jet->pt) < 5.0)) continue;
      if (!leadingJet || jet->pt > leadingJet->pt) {
        leadingJet = jet;
      }
      NJets++;
    }


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


    //******************************************************************************
    //loop over muon pairs
    //******************************************************************************
    for(Int_t i=0; i<muonArr->GetEntries(); i++) {
      const mithep::TMuon *mu1 = (mithep::TMuon*)((*muonArr)[i]);
      if ( !(
//              fabs(mu1->eta) < 2.1
//              && 
             mu1->pt > 20.0
             &&
             passMuonCuts(mu1)
             )
        ) continue;
      

      for(Int_t j=i+1; j<muonArr->GetEntries(); j++) {
        const mithep::TMuon *mu2 = (mithep::TMuon*)((*muonArr)[j]);
        if ( !(
//                fabs(mu2->eta) < 2.1
//                && 
               mu2->pt > 20.0
               && passMuonCuts(mu2)
               )
          ) continue;
        
        mithep::FourVectorM lepton1;
        mithep::FourVectorM lepton2;
        lepton1.SetCoordinates(mu1->pt, mu1->eta, mu1->phi, 0.51099892e-3 );
        lepton2.SetCoordinates(mu2->pt, mu2->eta, mu2->phi, 0.51099892e-3 );
        mithep::FourVectorM dilepton = lepton1+lepton2;
 

        dileptonMass->Fill(dilepton.M());
        dileptonMass_mumu->Fill(dilepton.M());
        if (dilepton.M() > 60 
            //  && dilepton.M() < 120
          ) {
          if (fabs(lepton1.Eta()) < 1.5 && fabs(lepton2.Eta()) < 1.5) {
            Count_mm_BB += eventweight;
          } else if (fabs(lepton1.Eta()) > 1.5 && fabs(lepton2.Eta()) > 1.5) {
            Count_mm_EE += eventweight;
          } else {
            Count_mm_BE += eventweight;
          }
        }
        
      }
    }


  } //end loop over data     

  delete info;
  delete muonArr;
  delete jetArr;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  dileptonMass->Draw("E");
  cv->SaveAs("dileptonMass_mm.gif");

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
  cout << "**************************************************************\n";
  cout << "Event Count : mm final state\n";
  cout << "BB :" << Count_mm_BB << endl;
  cout << "BE :" << Count_mm_BE << endl;
  cout << "EE :" << Count_mm_EE << endl;
  cout << "Total :" << Count_mm_BB + Count_mm_BE + Count_mm_EE << endl;



        
  gBenchmark->Show("ZeeSelection");       
}