示例#1
0
void ComputeWeights(){
  
  //*** mc pileup file
  //  TFile *fmc = TFile::Open("./PU_DYJetsToLL_Summer12_DR53X-PU_S10.root"); // 2012
  TFile *fmc = TFile::Open("./PU_DYJetsToLL_Summer12_DR53X-PU_RD1.root"); // 2012 RD ReReco
  //TFile *fmc = TFile::Open("./PU_DYJetsToLL_Summer11dr53X-PU_S13.root"); // 2011 53X ReReco
  TH1F *hmc  = (TH1F*)fmc->Get("hmc");
  TH1F *hmctrue  = (TH1F*)fmc->Get("hmctrue");
  cout << "Number of bins in MC histogram: " << hmc->GetNbinsX()<< endl;
  int nbinsmc = hmc->GetNbinsX();

  //*** data file -- observed PU
  //  TFile *fda   = TFile::Open("../pileup/pileup_2012D_minBiasXsec69400_corr_observed.root");
  //TFile *fda   = TFile::Open("../pileup/pileup_2012ABCD_22Jan2013ReReco_corr_observed.root");
  //TFile *fda   = TFile::Open("../pileup/pileup_2012ABCD_22Jan2013ReReco_pixelcorr_observed.root");
  //TFile *fda   = TFile::Open("../pileup/pileup_2011_minBiasXsec68000_pixelcorr_observed.root");

  // globe pileup files
  //  TFile *fda   = TFile::Open("/afs/cern.ch/work/m/malberti/HGG/LegacyPaper/CMSSW_6_1_1/src/h2gglobe/AnalysisScripts/aux/AB.json.69400.observed.pileup.root");
  //  TFile *fda   = TFile::Open("/afs/cern.ch/work/m/malberti/HGG/LegacyPaper/CMSSW_6_1_1/src/h2gglobe/AnalysisScripts/aux/C.json.69400.observed.pileup.root");
  TFile *fda   = TFile::Open("/afs/cern.ch/work/m/malberti/HGG/LegacyPaper/CMSSW_6_1_1/src/h2gglobe/AnalysisScripts/aux/D.json.69400.observed.pileup.root");

  TH1F  *hdata = (TH1F*)fda->Get("pileup");
  cout << "Number of bins in DATA histogram: " << hdata->GetNbinsX()<< endl;
  int nbinsdata = hdata->GetNbinsX();

  if (nbinsdata!=nbinsmc){
    TH1D  *htemp = (TH1D*)fda->Get("pileup");
    hdata = new TH1F("hdata","hdata",60,0,60);
    for (int ibin = 1; ibin < 61; ibin++){
      cout << hdata->GetBinContent(ibin) <<endl;
      hdata->SetBinContent(ibin,htemp->GetBinContent(ibin));
      cout << htemp->GetBinContent(ibin) <<endl;
    }
  }

  //*** compute weights
  TH1F *hweights = (TH1F*)hdata->Clone("hweights");
  hweights->Divide(hdata,hmc,1./hdata->GetSumOfWeights(),1./hmc->GetSumOfWeights());

  //  TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer12_DR53X-PU_RD1_minBiasXsec69400_corr_observed_2012ABCD.root","create");
  //  TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer12_DR53X-PU_RD1_minBiasXsec69400_pixelcorr_observed_2012ABCD.root","create");
  //  TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer11dr53X-PU_S13_minBiasXsec68000_pixelcorr_observed_2011.root","create");
  //  TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer11dr53X-PU_RD1_minBiasXsec69400_AB.root","create");
  //TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer11dr53X-PU_RD1_minBiasXsec69400_C.root","create");
  TFile *fout = new TFile("./PUweights_DYJetsToLL_Summer11dr53X-PU_RD1_minBiasXsec69400_D.root","create");
  hweights->Write("hweights");
  hdata->Write("hdata");
  hmc->Write("hmc");
  fout->Close();


//   //*** data file -- true PU
//   TFile *fdatrue = TFile::Open("../pileup/pileup_190456-208686_minBiasXsec69400_corr_observed.root");
//   TH1F *hdatatrue = (TH1F*)fdatrue->Get("pileup");
//   cout << hdatatrue->GetNbinsX()<< endl;

//   //*** compute weights
//   TH1F *hweightstrue = (TH1F*)hdatatrue->Clone("hweightstrue");
//   hweightstrue->Divide(hdatatrue,hmctrue,1./hdatatrue->GetSumOfWeights(),1./hmctrue->GetSumOfWeights());
 
//   TFile *fout2 = new TFile("./PUweights_DYJetsToLL_Summer12_DR53X-PU_S10_minBiasXsec69400_corr_true_Run2012ABCD.root","create");
//   hweightstrue->Write("hweights");
//   hdatatrue->Write("hdata");
//   hmctrue->Write("hmc");
//   fout2->Close();
}
TCanvas *drawOneVariable(TTree *signalTree, TTree *backgroundTree1, TTree *backgroundTree2,TTree *backgroundTree3,
			 TCut signalCuts, TCut backgroundCuts,
			 TString var,
			 int nbins, double xlow, double xhigh,
			 TString sigLegend, TString bg1Legend, TString bg2Legend,TString bg3Legend,
			 TString comment)
{

  TString cname = "c_";
  cname += var;
  TCanvas *c1 = new TCanvas(cname,cname,10,10,600,600);
  c1->cd();

  TH1F *hsig = new TH1F(TString("hsig_")+var,"",nbins, xlow, xhigh);
  TH1F *hbg1 = new TH1F(TString("hbg1_")+var,"",nbins, xlow, xhigh);
  TH1F *hbg2 = new TH1F(TString("hbg2_")+var,"",nbins, xlow, xhigh);
  TH1F *hbg3 = new TH1F(TString("hbg3_")+var,"",nbins, xlow, xhigh);

  TString projectCommandSig = var+TString(">>hsig_")+var;
  TString projectCommandBg1 = var+TString(">>hbg1_")+var;
  TString projectCommandBg2 = var+TString(">>hbg2_")+var;
  TString projectCommandBg3 = var+TString(">>hbg3_")+var;
  
  if( !useSmallEventCount ){
    signalTree->Draw(projectCommandSig, "genWeight"*signalCuts);
  }else{
    printf("DEBUG MODE: using small event count\n");
    signalTree->Draw(projectCommandSig, "genWeight"*signalCuts, "", 100000);
  }
  TGaxis::SetMaxDigits(3);
  hsig->GetXaxis()->SetTitle(var);
  hsig->SetDirectory(0);

  if(backgroundTree1 != 0){
    if( !useSmallEventCount ){
      backgroundTree1->Draw(projectCommandBg1, "genWeight"*backgroundCuts);
    }else{
      printf("DEBUG MODE: using small event count\n");
      backgroundTree1->Draw(projectCommandBg1, "genWeight"*backgroundCuts, "", 100000);
    }
    hbg1->Scale(hsig->GetSumOfWeights() / hbg1->GetSumOfWeights());
    hbg1->SetDirectory(0);
  } else {
    delete hbg1;
    hbg1 = 0;
  }

  if(backgroundTree2 != 0){
    if( !useSmallEventCount ){
      backgroundTree2->Draw(projectCommandBg2, "genWeight"*backgroundCuts);
    }else{
      printf("DEBUG MODE: using small event count\n");
      backgroundTree2->Draw(projectCommandBg2, "genWeight"*backgroundCuts, "", 100000);
    }
    hbg2->Scale(hsig->GetSumOfWeights() / hbg2->GetSumOfWeights());
    hbg2->SetDirectory(0);
  } else {
    delete hbg2;
    hbg2 = 0;
  }


  if(backgroundTree3 != 0){
    if( !useSmallEventCount ){
      backgroundTree3->Draw(projectCommandBg3, "genWeight"*backgroundCuts);
    }else{
      printf("DEBUG MODE: using small event count\n");
      backgroundTree3->Draw(projectCommandBg3, "genWeight"*backgroundCuts, "", 100000);
    }
    hbg3->Scale(hsig->GetSumOfWeights() / hbg3->GetSumOfWeights());
    hbg3->SetDirectory(0);
  } else {
    delete hbg3;
    hbg3 = 0;
  }


  setHistogramAttributes(hsig, hbg1, hbg2, hbg3);

  c1->Clear();

  hsig->Draw("hist");
  if( hbg1 ){

    hbg1->Draw("same");
  }
  if( hbg2 ){

    hbg2->Draw("same");
  }
  if( hbg3 ){

    //hbg3->Draw("same");
  }
  TLegend *leg = new TLegend(0.55, 0.65, 0.95, 0.80); // 0.6 0.9
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->AddEntry(hsig, sigLegend, "lf");
  leg->AddEntry(hbg1, bg1Legend, "lf");
  leg->AddEntry(hbg2, bg2Legend, "lf");
  //  leg->AddEntry(hbg3, bg3Legend, "lf");
  leg->Draw("same");

  TLatex *lat = new TLatex(0.5, 0.95, comment); // 0.85
  lat->SetNDC(kTRUE);
  lat->Draw("same");

  c1->Update();

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

  // first argument - config file 
  // second argument - filelist

  using namespace std;

  // **** configuration
  Config cfg(argv[1]);

  const bool isData = cfg.get<bool>("IsData");
  const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");

  const bool applyGoodRunSelection = cfg.get<bool>("ApplyGoodRunSelection");

  // pile up reweighting
  const bool applyPUreweighting_vertices = cfg.get<bool>("ApplyPUreweighting_vertices");
  const bool applyPUreweighting_official = cfg.get<bool>("ApplyPUreweighting_official");


  // kinematic cuts on muons
  const float ptMuonLowCut   = cfg.get<float>("ptMuonLowCut");
  const float ptMuonHighCut  = cfg.get<float>("ptMuonHighCut");
  const float etaMuonHighCut = cfg.get<float>("etaMuonHighCut");
  const float etaMuonLowCut = cfg.get<float>("etaMuonLowCut");
  const float dxyMuonCut     = cfg.get<float>("dxyMuonCut");
  const float dzMuonCut      = cfg.get<float>("dzMuonCut");
  const float isoMuonCut     = cfg.get<float>("isoMuonCut");
  const bool  applyTauTauSelection = cfg.get<bool>("ApplyTauTauSelection");
  const bool  selectZToTauTauMuMu = cfg.get<bool>("SelectZToTauTauMuMu");

  // topological cuts
  const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
  const float DRTrigMatch    = cfg.get<float>("DRTrigMatch"); 
  const bool oppositeSign    = cfg.get<bool>("OppositeSign");


  // vertex cuts
  const float ndofVertexCut  = cfg.get<float>("NdofVertexCut");   
  const float zVertexCut     = cfg.get<float>("ZVertexCut");
  const float dVertexCut     = cfg.get<float>("DVertexCut");

  // jet related cuts
  const float jetEtaCut      = cfg.get<float>("JetEtaCut");
  const float jetEtaTrkCut   = cfg.get<float>("JetEtaTrkCut");
  const float jetPtHighCut   = cfg.get<float>("JetPtHighCut");
  const float jetPtLowCut    = cfg.get<float>("JetPtLowCut");
  const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");

  // Run range
  const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
  const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");

  const string dataBaseDir = cfg.get<string>("DataBaseDir");
  // vertex distributions filenames and histname
  const string vertDataFileName = cfg.get<string>("VertexDataFileName");
  const string vertMcFileName   = cfg.get<string>("VertexMcFileName");
  const string vertHistName     = cfg.get<string>("VertexHistName");

  const string jsonFile = cfg.get<string>("jsonFile");
  string cmsswBase = (getenv ("CMSSW_BASE"));
  string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;

  // Run-lumi selector
  std::vector<Period> periods;  
  if (isData) { // read the good runs 
	  std::fstream inputFileStream(fullPathToJsonFile.c_str(), std::ios::in);
  	  if (inputFileStream.fail() ) {
            std::cout << "Error: cannot find json file " << fullPathToJsonFile << std::endl;
            std::cout << "please check" << std::endl;
            std::cout << "quitting program" << std::endl;
	    exit(-1);
	  }
  
          for(std::string s; std::getline(inputFileStream, s); ) {
           periods.push_back(Period());
           std::stringstream ss(s);
           ss >> periods.back();
          }
  }

  // **** end of configuration
/*
  // Run-lumi selector
  std::vector<Period> periods;
    
  std::fstream inputFileStream("temp", std::ios::in);
  for(std::string s; std::getline(inputFileStream, s); )
    {
      periods.push_back(Period());
      std::stringstream ss(s);
      ss >> periods.back();
    }
*/
  char ff[100];

  sprintf(ff,"%s/%s",argv[3],argv[2]);
  // file name and tree name
  std::string rootFileName(argv[2]);
  std::ifstream fileList(ff);
  std::ifstream fileList0(ff);
  std::string ntupleName("makeroottree/AC1B");
  
  TString era=argv[3];
  TString TStrName(rootFileName);
  std::cout <<TStrName <<std::endl;  

  TFile * file = new TFile(era+"/"+TStrName+TString(".root"),"update");
  file->cd("");

  TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
  TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);


  TH1D * metAll  = new TH1D("metAll","",400,0,4000);

  TH1D * hDiJetmet = new TH1D("hDiJetmet","",400,0,4000);
  TH1D * hDiJetmass = new TH1D("hDiJetmass","",400,0,4000);
  TH1D * hDiJet1mass = new TH1D("hDiJet1mass","",400,0,4000);
  TH1D * hDiJet2mass = new TH1D("hDiJet2mass","",400,0,4000);
  TH1D * hHT_ = new TH1D("hHT_","",400,0,4000);
  TH1D * PUweightsOfficialH = new TH1D("PUweightsOfficialH","PU weights w/ official reweighting",1000, 0, -1);

 // PILE UP REWEIGHTING - OPTIONS

  if (applyPUreweighting_vertices and applyPUreweighting_official) 
	{std::cout<<"ERROR: Choose only ONE PU reweighting method (vertices or official, not both!) " <<std::endl; exit(-1);}

  // reweighting with vertices

  // reading vertex weights
  TFile * fileDataNVert = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertDataFileName);
  TFile * fileMcNVert   = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertMcFileName);

  TH1F * vertexDataH = (TH1F*)fileDataNVert->Get(TString(vertHistName));
  TH1F * vertexMcH   = (TH1F*)fileMcNVert->Get(TString(vertHistName));

  float normVertexData = vertexDataH->GetSumOfWeights();
  float normVertexMc   = vertexMcH->GetSumOfWeights();

  vertexDataH->Scale(1/normVertexData);
  vertexMcH->Scale(1/normVertexMc);


 // reweighting official recipe 
  	// initialize pile up object
  PileUp * PUofficial = new PileUp();
  

  
  if (applyPUreweighting_official) {
    TFile * filePUdistribution_data = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/Data_Pileup_2015D_Nov17.root","read"); 
    TFile * filePUdistribution_MC = new TFile (TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/MC_Spring15_PU25_Startup.root", "read"); 
    TH1D * PU_data = (TH1D *)filePUdistribution_data->Get("pileup");
    TH1D * PU_mc = (TH1D *)filePUdistribution_MC->Get("pileup");
    PUofficial->set_h_data(PU_data); 
    PUofficial->set_h_MC(PU_mc);
  }

  

  int nFiles = 0;
  int nEvents = 0;
  int selEventsAllMuons = 0;
  int selEventsIdMuons = 0;
  int selEventsIsoMuons = 0;



  int nTotalFiles = 0;
  std::string dummy;
  // count number of files --->
  while (fileList0 >> dummy) nTotalFiles++;

  unsigned int RunMin = 9999999;
  unsigned int RunMax = 0;

  std::vector<unsigned int> allRuns; allRuns.clear();
 vector <unsigned int> run_;
 vector <unsigned int> lumi_;
 vector <unsigned int> event_;
 run_.clear();
 lumi_.clear();
 event_.clear();
 

    std::vector<Event> EventList;
    std::string line;
    std::ifstream EventsFile;
    TString file_events=argv[4]; //eventlist_csc2015.txt
    //EventsFile.open("MET_filters/eventlist_"+file_events+".txt");
    EventsFile.open(era+"/"+file_events+".txt");
    //cout<<"  limits  int -> "<<std::numeric_limits<int>::max()<<"  long int -> "<<std::numeric_limits<long int>::max()<<"  unsigned int -> "<<std::numeric_limits<unsigned int>::max()<<endl;
    cout<<" The file that will be used will be "<<era<<"/"<<file_events<<".txt"<<endl;


    while (getline(EventsFile, line))
    {
        std::vector<std::string> columns = split(line,':');
        run_.push_back(std::stoi(columns[0]));
        lumi_.push_back(std::stoi(columns[1]));
        event_.push_back(std::stoul(columns[2]));
   	/*   Event events_;

        events_.name     = "Test";
        events_.run     = std::stoi(columns[0]);
        events_.lumi   = std::stoi(columns[1]);
        events_.eventrn = std::stof(columns[2]);

        EventList.push_back(events_);
  */
      	}

  cout<<" In total there are "<<run_.size()<< " entries for "<<file_events<<" filter "<<endl;
    EventsFile.close();

//    for (unsigned int sz=0;sz<run_.size();sz++)
//	    cout<<" run "<<run_[sz]<<"  "<<lumi_[sz]<<"  "<<event_[sz]<<endl;
    /*
         for (const Event & m: EventList) 
	{
	if (m.run == 20286)
	cout<<"  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/

  //----Attention----//
  //if(XSec!=1) nTotalFiles=20;
  //nTotalFiles=5;
  //
  //
 

  std::string initNtupleName("initroottree/AC1B");

  for (int iF=0; iF<nTotalFiles; ++iF) {

    std::string filen;
    fileList >> filen;

    std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
    TFile * file_ = TFile::Open(TString(filen));
    
    TH1D * histoInputEvents = NULL;
    histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
    if (histoInputEvents==NULL) continue;
    int NE = int(histoInputEvents->GetEntries());
    for (int iE=0;iE<NE;++iE)
      inputEventsH->Fill(0.);
    std::cout << "      number of input events         = " << NE << std::endl;

    TTree * _inittree = NULL;
    _inittree = (TTree*)file_->Get(TString(initNtupleName));
    if (_inittree==NULL) continue;
    Float_t genweight;
    if (!isData)
      _inittree->SetBranchAddress("genweight",&genweight);
    Long64_t numberOfEntriesInitTree = _inittree->GetEntries();
    std::cout << "      number of entries in Init Tree = " << numberOfEntriesInitTree << std::endl;
    for (Long64_t iEntry=0; iEntry<numberOfEntriesInitTree; iEntry++) {
      _inittree->GetEntry(iEntry);
      if (isData)
	histWeightsH->Fill(0.,1.);
      else
	histWeightsH->Fill(0.,genweight);
    }

    TTree * _tree = NULL;
    _tree = (TTree*)file_->Get(TString(ntupleName));
    if (_tree==NULL) continue;
    Long64_t numberOfEntries = _tree->GetEntries();
    std::cout << "      number of entries in Tree      = " << numberOfEntries << std::endl;
    AC1B analysisTree(_tree);


    // EVENT LOOP //
    
    
    std::cout << "      number of entries in Tree = " << numberOfEntries << std::endl;
    
    for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) { 
    
      analysisTree.GetEntry(iEntry);
      nEvents++;
      
      if (nEvents%10000==0) 
	cout << "      processed " << nEvents << " events" << endl; 

      float weight = 1;



      //------------------------------------------------
      // vertex cuts
      
      if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
      if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
      float dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
		       analysisTree.primvertex_y*analysisTree.primvertex_y);
      if (dVertex>dVertexCut) continue;

      if (!isData) 
	weight *=analysisTree.genweight;

      histWeightsH->Fill(float(0),weight);


      //cout<< " We have zero counts ? "<<analysisTree.primvertex_count<<endl;

      if (!isData) {
	if (applyPUreweighting_vertices) {
	  int binNvert = vertexDataH->FindBin(analysisTree.primvertex_count);
	  float_t dataNvert = vertexDataH->GetBinContent(binNvert);
	  float_t mcNvert = vertexMcH->GetBinContent(binNvert);
	  if (mcNvert < 1e-10){mcNvert=1e-10;}
	  float_t vertWeight = dataNvert/mcNvert;
	  weight *= vertWeight;
	  //	  cout << "NVert = " << analysisTree.primvertex_count << "   weight = " << vertWeight << endl;
	}

        if (applyPUreweighting_official) {

	double Ninteractions = analysisTree.numtruepileupinteractions;
	double PUweight = PUofficial->get_PUweight(Ninteractions);
	weight *= PUweight;
	PUweightsOfficialH->Fill(PUweight);

        }
      }
      if (isData){
	
	
	bool lumi = false;
	int n=analysisTree.event_run;
	int lum = analysisTree.event_luminosityblock;
	int nr = analysisTree.event_nr;

	std::string num = std::to_string(n);
	std::string lnum = std::to_string(lum);
	for(const auto& a : periods)
	  {
	    
	    if ( num.c_str() ==  a.name ) {
	      //std::cout<< " Eureka "<<num<<"  "<<a.name<<" ";
	      //     std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      
	      for(auto b = a.ranges.begin(); b != std::prev(a.ranges.end()); ++b) {
		
		//	cout<<b->lower<<"  "<<b->bigger<<endl;
		if (lum  >= b->lower && lum <= b->bigger ) lumi = true;
	      }
	      auto last = std::prev(a.ranges.end());
	      //    std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
	      if (  (lum >=last->lower && lum <= last->bigger )) lumi=true;
	      
	      
	    }
	    
	  }
    
	//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
	//std::remove("myinputfile");
	if (!lumi) continue;
        bool runbool=false;
	bool lumibool=false;
	bool eventbool=false;
	runbool= std::find(run_.begin(), run_.end(), n) != run_.end();
	lumibool= std::find(lumi_.begin(), lumi_.end(), lum) != lumi_.end();
	eventbool= std::find(event_.begin(), event_.end(), nr) != event_.end();

       if (runbool && lumibool && eventbool) continue;
//	cout<<"=========================================== >>>>>>>>>>>> "<<n<<"  "<<lum<<"  "<<nr<<endl;
/*	//cout<<" Will cross-check against the list now "<<endl;
        for (const Event & m: EventList) 
	{
	if (m.run == n && m.lumi==lnum && m.eventrn == nr)
	cout<<"=========================================== >>>>>>>>>>>>  "<<m.name<<"  "<<m.run<<"  "<<m.lumi<<"  "<<m.eventrn<<endl;
	}
*/
	}


      float metall = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
                
             metAll->Fill(metall,weight);

      if (analysisTree.event_run<RunMin)
	RunMin = analysisTree.event_run;
      
      if (analysisTree.event_run>RunMax)
	RunMax = analysisTree.event_run;
      
      //std::cout << " Run : " << analysisTree.event_run << std::endl;
      
      bool isNewRun = true;
      if (allRuns.size()>0) {
	for (unsigned int iR=0; iR<allRuns.size(); ++iR) {
	  if (analysisTree.event_run==allRuns.at(iR)) {
	    isNewRun = false;
	    break;
	  }
	}
      }
	
      if (isNewRun) 
	allRuns.push_back(analysisTree.event_run);
      

	// selecting good jets --->
	if (analysisTree.pfjet_count>1) { 
			
	  for (unsigned int jet=0; jet<2; ++jet) {
	  float energy = analysisTree.pfjet_e[jet];
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;

	  if ( analysisTree.pfjet_pt[0] > 200. && analysisTree.pfjet_pt[1] > 200.) 
	  { 
          float metSel = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
	  hDiJetmet->Fill(metSel, weight);
	  
	  TLorentzVector jmass1; jmass1.SetPxPyPzE(analysisTree.pfjet_px[0],
					analysisTree.pfjet_py[0],
					analysisTree.pfjet_pz[0],
					analysisTree.pfjet_e[0]);

	  TLorentzVector jmass2; jmass2.SetPxPyPzE(analysisTree.pfjet_px[1],
					analysisTree.pfjet_py[1],
					analysisTree.pfjet_pz[1],
					analysisTree.pfjet_e[1]);

	  TLorentzVector dijet = jmass1 + jmass2;
	  hDiJetmass->Fill(dijet.M(),weight);
	  hDiJet1mass->Fill(jmass1.M(),weight);
	  hDiJet2mass->Fill(jmass2.M(),weight);

	  }
         }
	 }	 
     // HT variables
	float HT_=0;
	for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
	  float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	  if (absJetEta>jetEtaCut) continue;
          
	  

	  float energy = analysisTree.pfjet_e[jet];
	  float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
	  float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
	  float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
	  float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	  float chm = analysisTree.pfjet_chargedmulti[jet];
	  float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	  bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0));
	  if (!isPFJetId) continue;
	  
	  HT_=HT_+analysisTree.pfjet_pt[jet];

	  }	  
        
	  hHT_->Fill(HT_,weight);



      
    } // end of file processing (loop over events in one file)
    nFiles++;
    delete _tree;
    file_->Close();
    delete file_;
  }
  std::cout << std::endl;
  int allEvents = int(inputEventsH->GetEntries());
  std::cout << "Total number of input events                     = " << allEvents << std::endl;
  std::cout << "Total number of events in Tree                   = " << nEvents << std::endl;
  std::cout << "Total number of selected events (iso muon pairs) = " << selEventsIsoMuons << std::endl;
  std::cout << std::endl;
  std::cout << "RunMin = " << RunMin << std::endl;
  std::cout << "RunMax = " << RunMax << std::endl;

  //cout << "weight used:" << weight << std::endl;

  // using object as comp
  std::sort (allRuns.begin(), allRuns.end(), myobject);
  std::cout << "Runs : ";
  for (unsigned int iR=0; iR<allRuns.size(); ++iR)
    std::cout << " " << allRuns.at(iR);
  std::cout << std::endl;
  
  file->Write();
  file->Close();
  delete file;
  
  }
示例#4
0
  TLegend *leg = new TLegend(0.5,0.7,0.85, 0.90);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);


  //leg->AddEntry(&h1, "E near 1st peak", "l");
  //leg->AddEntry(&h2, "E near 2nd peak", "l");

  noise->Draw("ereco>>h1","wgt*((eshower==0)&&(ncore==0))");
  noise->Draw("ereco>>h2","wgt*((eshower==0)&&(ncore==1))");
  noise->Draw("ereco>>h3","wgt*((eshower==0)&&(ncore==2))");
  noise->Draw("ereco>>h4","wgt*((eshower==0)&&(ncore==3))");
  noise->Draw("ereco>>h5","wgt*((eshower==0)&&(ncore==4))");
  noise->Draw("ereco>>h6","wgt*((eshower==0)&&(ncore==5))");
  
  double s1 = h1->GetSumOfWeights();
  double s2 = h2->GetSumOfWeights();
  double s3 = h3->GetSumOfWeights();
  double s4 = h4->GetSumOfWeights();
  double s5 = h5->GetSumOfWeights();
  double s6 = h6->GetSumOfWeights();

  
  h1->Scale(100.0/s1);
  h2->Scale(100.0/s2);
  h3->Scale(100.0/s3);
  h4->Scale(100.0/s4);
  h5->Scale(100.0/s5);
  h6->Scale(100.0/s6);

  h1->SetMaximum(60.0);
示例#5
0
void eff_IdHlt(const TString configFile, TString triggerSetString) 
{

  //  ---------------------------------
  //       Preliminary checks
  //  ---------------------------------

  // verify whether it was a compilation check
  if (configFile.Contains("_DebugRun_") || triggerSetString.Contains("_DebugRun_")) {
    std::cout << "eff_IdHlt: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  // fast check
  TriggerConstantSet triggerSet=DetermineTriggerSet(triggerSetString);  
  assert ( triggerSet != TrigSet_UNDEFINED );

  //  ---------------------------------
  //         Normal execution
  //  ---------------------------------

  gBenchmark->Start("eff_IdHlt");
  

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t massLow  = 60;
  Double_t massHigh = 120;

  // Read in the configuratoin file
  TString sampleTypeString = "";
  TString effTypeString    = "";
  TString calcMethodString = "";
  TString etBinningString  = "";
  TString etaBinningString = "";
  TString dirTag;
  vector<TString> ntupleFileNames;
  ifstream ifs;
  ifs.open(configFile.Data());
  if (!ifs.is_open()) {
    std::cout << "tried to open the configuration file <" << configFile << ">\n";
    assert(ifs.is_open());
  }
  string line;
  Int_t state=0;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(line[0]=='%') break;
    if(state==0){
      // Read 1st line of content: data or MC?
      sampleTypeString = TString(line);
      state++;
    }else if(state==1) {
      // Read 2d content line: efficiency type string
      effTypeString = TString(line);
      state++;
    }else if(state==2) {
      // Read 3d content line: fitting mode
      calcMethodString = TString(line);
      state++;
    }else if(state==3) {
      // Read 4th content line: SC ET binning
      etBinningString = TString(line);
      state++;
    }else if(state==4) {
      // Read 5th content line: SC eta binning
      etaBinningString = TString(line);
      state++;
    }else if(state==5) {
      // Read 5th content line: SC eta binning
      dirTag = TString(line);
      state++;
    }else if(state==6) {
      ntupleFileNames.push_back(TString(line));
    }
  }
  
  int calcMethod = 0;
  if(calcMethodString == "COUNTnCOUNT")
    calcMethod = COUNTnCOUNT;
  else if(calcMethodString == "COUNTnFIT")
    calcMethod = COUNTnFIT;
  else if(calcMethodString == "FITnFIT")
    calcMethod = FITnFIT;
  else
    assert(0);
  printf("Efficiency calculation method: %s\n", calcMethodString.Data());

  int effType = 0;
  if(effTypeString == "ID")
    effType = ID;
  else if(effTypeString == "HLT")
    effType = HLT;
  else
    assert(0);
  printf("Efficiency type to measure: %s\n", effTypeString.Data());

  int etBinning = 0;
  if(etBinningString == "ETBINS1")
    etBinning = ETBINS1;
  else if(etBinningString == "ETBINS5")
    etBinning = ETBINS5;
  else
    assert(0);
  printf("SC ET binning: %s\n", etBinningString.Data());

  int etaBinning = 0;
  if(etaBinningString == "ETABINS1")
    etaBinning = ETABINS1;
  else if(etaBinningString == "ETABINS2")
    etaBinning = ETABINS2;
  else
    assert(0);
  printf("SC eta binning: %s\n", etaBinningString.Data());

  int sample;
  if(sampleTypeString == "DATA")
    sample = DATA;
  else if(sampleTypeString == "MC")
    sample = MC;
  else
    assert(0);
  printf("Sample: %s\n", sampleTypeString.Data());

  // Construct the trigger object
  TriggerSelection triggers(triggerSetString, (sample==DATA)?true:false, 0);
  if (effType==HLT) std::cout << "\tHLT efficiency calculation method " << triggers.hltEffCalcName() << ", triggerSet=" << triggers.triggerSetName() << "\n";
  else triggers.hltEffCalcMethod(HLTEffCalc_2011Old);

  TRandom *rnd= new TRandom();
  rnd->SetSeed(0); 

 // The label is a string that contains the fields that are passed to
  // the function below, to be used to name files with the output later.
  TString label = getLabel(sample, effType, calcMethod, etBinning, etaBinning, triggers);

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================
  
  //  
  // Set up histograms
  //
  TH1F* hMass           = new TH1F("hMass"     ,"",30,massLow,massHigh);
  TH1F* hMassTotal      = new TH1F("hMassTotal","",30,massLow,massHigh);
  TH1F* hMassPass       = new TH1F("hMassPass" ,"",30,massLow,massHigh);
  TH1F* hMassFail       = new TH1F("hMassFail" ,"",30,massLow,massHigh);

  // Save MC templates if sample is MC
  TString tagAndProbeDir(TString("../root_files/tag_and_probe/")+dirTag);
  gSystem->mkdir(tagAndProbeDir,kTRUE);

  TFile *templatesFile = 0;
  vector<TH1F*> hPassTemplateV;
  vector<TH1F*> hFailTemplateV;
  if( sample != DATA) {
    // For simulation, we will be saving templates
    TString labelMC = getLabel(-1111, effType, calcMethod, etBinning, etaBinning, triggers);
    TString templatesLabel = tagAndProbeDir + TString("/mass_templates_")+labelMC+TString(".root");
    templatesFile = new TFile(templatesLabel,"recreate");
    for(int i=0; i<getNEtBins(etBinning); i++){
      for(int j=0; j<getNEtaBins(etaBinning); j++){
	TString hname = "hMassTemplate_Et";
	hname += i;
	hname += "_eta";
	hname += j;
	hPassTemplateV.push_back(new TH1F(hname+TString("_pass"),"",60,massLow,massHigh));
	hFailTemplateV.push_back(new TH1F(hname+TString("_fail"),"",60,massLow,massHigh));
      }
    }
  } else {
    // For data, we will be using templates,
    // however, if the request is COUNTnCOUNT, do nothing
    if( calcMethod != COUNTnCOUNT ){
      TString labelMC = getLabel(-1111, effType, calcMethod, etBinning, etaBinning, triggers);
      TString templatesLabel = tagAndProbeDir+TString("/mass_templates_")+labelMC+TString(".root");
      templatesFile = new TFile(templatesLabel);
      if( ! templatesFile->IsOpen() )
	assert(0);
    }
  }

  // This file can be utilized in the future, but for now
  // opening it just removes complaints about memory resident
  // trees. No events are actually written.
  TFile *selectedEventsFile = new TFile("selectedEventsFile.root","recreate");
  if (!selectedEventsFile) {
    assert(0);
  }

  TTree *passTree = new TTree("passTree","passTree");
  Double_t storeMass, storeEt, storeEta;
  passTree->Branch("mass",&storeMass,"mass/D");
  passTree->Branch("et",&storeEt  ,"et/D");
  passTree->Branch("eta",&storeEta ,"eta/D");

  TTree *failTree = new TTree("failTree","failTree");
  failTree->Branch("mass",&storeMass,"mass/D");
  failTree->Branch("et",&storeEt  ,"et/D");
  failTree->Branch("eta",&storeEta ,"eta/D");

  int nDivisions = getNEtBins(etBinning)*getNEtaBins(etaBinning);
  double ymax = 800;
  if(nDivisions <4 )
    ymax = nDivisions * 200;
  TCanvas *c1 = MakeCanvas("c1","c1", 600, int(ymax));
  c1->Divide(2,nDivisions);

  int eventsInNtuple = 0;
  int eventsAfterTrigger = 0;
  int totalCand = 0;
  int totalCandInMassWindow = 0;
  int totalCandInEtaAcceptance = 0;
  int totalCandEtAbove10GeV = 0;
  int totalCandMatchedToGen = 0;

  // Loop over files
  for(UInt_t ifile=0; ifile<ntupleFileNames.size(); ifile++){

    //
    // 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   *gen  = new mithep::TGenInfo();
    TClonesArray *dielectronArr = new TClonesArray("mithep::TDielectron");
    
    // Read input file
    cout << "Processing " << ntupleFileNames[ifile] << "..." << endl;
    infile = new TFile(ntupleFileNames[ifile]); 
    assert(infile);
    
    // Get the TTrees
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);

    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",&info);                TBranch *infoBr       = eventTree->GetBranch("Info");

    // check whether the file is suitable for the requested run range
    UInt_t runNumMin = UInt_t(eventTree->GetMinimum("runNum"));
    UInt_t runNumMax = UInt_t(eventTree->GetMaximum("runNum"));
    std::cout << "runNumMin=" << runNumMin << ", runNumMax=" << runNumMax << "\n";
    if (!triggers.validRunRange(runNumMin,runNumMax)) {
      std::cout << "... file contains uninteresting run range\n";
      continue;
    }

    // Define other branches
    eventTree->SetBranchAddress("Dielectron",&dielectronArr); TBranch *dielectronBr = eventTree->GetBranch("Dielectron");
    TBranch *genBr = 0;
    if(sample != DATA){
      eventTree->SetBranchAddress("Gen",&gen);
      genBr = eventTree->GetBranch("Gen");
    }

    // loop over events    
    eventsInNtuple += eventTree->GetEntries();
     for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
       //  for(UInt_t ientry=0; ientry<200000; ientry++) { // This is for faster turn-around in testing
       
      if(sample != DATA)
	genBr->GetEntry(ientry);
      
      // Check that the whole event has fired the appropriate trigger
      infoBr->GetEntry(ientry);
      
      /* Old code
      // For EPS2011 for both data and MC (starting from Summer11 production)
      // we use a special trigger for tag and probe that has second leg
      // unbiased with cuts at HLT
      ULong_t eventTriggerBit = kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30
	| kHLT_Ele32_CaloIdL_CaloIsoVL_SC17;
      // The tag trigger bit matches the "electron" of the trigger we
      // use for this tag and probe study: electron+sc
      ULong_t tagTriggerObjectBit = kHLT_Ele17_CaloIdVT_CaloIsoVT_TrkIdT_TrkIsoVT_SC8_Mass30_EleObj
	| kHLT_Ele32_CaloIdL_CaloIsoVL_SC17_EleObj;
      // The probe trigger, however, is any of possibilities used in
      // the trigger that is used in the main analysis
      ULong_t probeTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele1Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele1Obj
	| kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele2Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele2Obj;
      */

      ULong_t eventTriggerBit= triggers.getEventTriggerBit_TagProbe(info->runNum);

      if(!(info->triggerBits & eventTriggerBit)) continue;  // no trigger accept? Skip to next event... 
      eventsAfterTrigger++;

      ULong_t tagTriggerObjectBit= triggers.getTagTriggerObjBit(info->runNum);
      ULong_t probeTriggerObjectBit_Tight= triggers.getProbeTriggerObjBit_Tight(info->runNum);
      ULong_t probeTriggerObjectBit_Loose= triggers.getProbeTriggerObjBit_Loose(info->runNum);
      ULong_t probeTriggerObjectBit= probeTriggerObjectBit_Tight | probeTriggerObjectBit_Loose;

      // loop through dielectrons
      dielectronArr->Clear();
      dielectronBr->GetEntry(ientry);
      for(Int_t i=0; i<dielectronArr->GetEntriesFast(); i++) {
	
	totalCand++;
	const mithep::TDielectron *dielectron = (mithep::TDielectron*)((*dielectronArr)[i]);
	
	// Tag and probe is done around the Z peak
	if((dielectron->mass < massLow) || (dielectron->mass > massHigh)) continue;
	totalCandInMassWindow++;
	//
	// Exclude ECAL gap region (should already be done for ntuple, but just to make sure...)
	if((fabs(dielectron->scEta_1)>kGAP_LOW) && (fabs(dielectron->scEta_1)<kGAP_HIGH)) continue;
	if((fabs(dielectron->scEta_2)>kGAP_LOW) && (fabs(dielectron->scEta_2)<kGAP_HIGH)) continue;
	// ECAL acceptance cut on supercluster Et
	if((fabs(dielectron->scEta_1) > 2.5)       || (fabs(dielectron->scEta_2) > 2.5)) continue;  // outside eta range? Skip to next event...
	totalCandInEtaAcceptance++;
	// None of the electrons should be below 10 GeV
	if((dielectron->scEt_1 < 10)               || (dielectron->scEt_2 < 10))	      continue;  // below supercluster ET cut? Skip to next event...
	totalCandEtAbove10GeV++;
	
	// Next, we will do a loose kinematic matching to generator level
	// info. 
	// For the data, this is not needed and not done. We take all
	// candidates, and take care of background by fitting.
	// For MC, however, we do not fit, but count pass/fail events.
	// So we need to make sure there is no background. However, even
	// in the signal Z->ee MC sample there jets and therefore fake
	// electrons. So we drop all candidates that do not have both leptons
	// matched.
	// 
	if( sample != DATA )
	  if( ! dielectronMatchedToGeneratorLevel(gen, dielectron) ) continue;
	totalCandMatchedToGen++;

	// ECAL driven: this condition is NOT applied	

	// Preliminary selection is complete. Now work on tags and probes.
	
	TElectron *ele1 = extractElectron(dielectron, 1);
	TElectron *ele2 = extractElectron(dielectron, 2);
	bool isTag1 = isTag(ele1, tagTriggerObjectBit);
	bool isTag2 = isTag(ele2, tagTriggerObjectBit);
	
	// Any electron that made it here is eligible to be a probe
	// for ID cuts.
	bool isIDProbe1     = true;
	bool isIDProbe2     = true;
	bool isIDProbePass1 = passID(ele1);
	bool isIDProbePass2 = passID(ele2);
	
	// Probes for HLT cuts:

	bool isHLTProbe1     = passID(ele1);
	bool isHLTProbe2     = passID(ele2);
	bool isHLTProbePass1 = ( isHLTProbe1 && (ele1 ->hltMatchBits & probeTriggerObjectBit) );
	bool isHLTProbePass2 = ( isHLTProbe2 && (ele2 ->hltMatchBits & probeTriggerObjectBit) );

	// 
	//  Apply tag and probe, and accumulate counters or histograms
	//       
	
	bool isProbe1     = false;
	bool isProbe2     = false;
	bool isProbePass1 = false;
	bool isProbePass2 = false;
	if( effType == ID ){
	  isProbe1     = isIDProbe1;
	  isProbe2     = isIDProbe2;
	  isProbePass1 = isIDProbePass1;
	  isProbePass2 = isIDProbePass2;
	}else if( effType == HLT ){
	  isProbe1     = isHLTProbe1;
	  isProbe2     = isHLTProbe2;
	  isProbePass1 = isHLTProbePass1;
	  isProbePass2 = isHLTProbePass2;
	  if (triggers.useRandomTagTnPMethod(info->runNum)) {
	    if (rnd->Uniform() <= 0.5) {
	      // tag is 1st electron
	      if (!isTag1) continue;
	      isTag2=0; // ignore whether ele2 can be a tag
	    }
	    else {
	      if (!isTag2) continue;
	      isTag1=0; // ignore whether ele1 can be a tag
	    }
	  }
	}else {
	  printf("ERROR: unknown efficiency type requested\n");
	}

	storeMass = dielectron->mass;
	// First electron is the tag, second is the probe
	if( isTag1 && isProbe2){
	  // total probes
	  hMassTotal->Fill(dielectron->mass);
	  storeEt   = dielectron->scEt_2;
	  storeEta  = dielectron->scEta_2;
	  int templateBin = getTemplateBin( findEtBin(storeEt,etBinning),
					    findEtaBin(storeEta,etaBinning),
					    etaBinning);
	  if( isProbePass2 ){
	    // passed
	    hMassPass->Fill(dielectron->mass);
	    passTree->Fill();
	    if(sample != DATA && templateBin != -1)
	      hPassTemplateV[templateBin]->Fill(dielectron->mass);
	  }else{
	    // fail
	    hMassFail->Fill(dielectron->mass);
	    failTree->Fill();
	    if(sample != DATA && templateBin != -1)
	      hFailTemplateV[templateBin]->Fill(dielectron->mass);
	  }
	}
	// Second electron is the tag, first is the probe
	if( isTag2 && isProbe1 ){
	  // total probes
	  hMassTotal->Fill(dielectron->mass);
	  storeEt   = dielectron->scEt_1;
	  storeEta  = dielectron->scEta_1;
	  int templateBin = getTemplateBin( findEtBin(storeEt,etBinning),
					    findEtaBin(storeEta,etaBinning),
					    etaBinning);
	  if( isProbePass1 ){
	    // passed
	    hMassPass->Fill(dielectron->mass);
	    passTree->Fill();
	    if(sample != DATA && templateBin != -1)
	      hPassTemplateV[templateBin]->Fill(dielectron->mass);
	  }else{
	    // fail
	    hMassFail->Fill(dielectron->mass);
	    failTree->Fill();
	    if(sample != DATA && templateBin != -1)
	      hFailTemplateV[templateBin]->Fill(dielectron->mass);
	  }
	}
	
	// In case the full selection is applied:
	//       if( !(isTag1 && ele2_passID) && !(isTag2 && ele1_passID) ) continue;
	if( !(isTag1 && isIDProbePass2) && !(isTag2 && isIDProbePass1) ) continue;
	//       if( !(isTag1) && !(isTag2) ) continue;
	// Fill histogram
	hMass->Fill(dielectron->mass);
	
      } // end loop over dielectron candidates
    } // end loop over events
  
    delete infile;
    infile=0;
    eventTree=0;
    
    delete gen;
    delete info;
    delete dielectronArr;
  } // end loop over files

  //
  // Efficiency analysis
  //
  
//   printf("Number of regular candidates:      %15.0f\n", hMass->GetSumOfWeights());
  printf("Total events in ntuple                                       %15d\n",eventsInNtuple);
  printf("    events after event level trigger cut                     %15d\n",eventsAfterTrigger);
  printf("\nTotal candidates (no cuts)                                   %15d\n",totalCand);
  printf("        candidates in 60-120 mass window                     %15d\n",totalCandInMassWindow);
  printf("        candidates witheta 0-1.4442, 1.566-2.5               %15d\n",totalCandInEtaAcceptance);
  printf("        candidates, both electrons above 10 GeV              %15d\n",totalCandEtAbove10GeV);
  printf("        candidates matched to GEN level (if MC)              %15d\n",totalCandMatchedToGen);
  printf("\nNumber of probes, total                                      %15.0f\n", hMassTotal->GetSumOfWeights());
  printf("Number of probes, passed                                     %15.0f\n", hMassPass->GetSumOfWeights());
  printf("Number of probes, failed                                     %15.0f\n", hMassFail->GetSumOfWeights());


  // Human-readbale text file to store measured efficiencies
  TString reslog = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString(".txt");
  ofstream effOutput;
  effOutput.open(reslog);
  // Print into the results file the header.
  effOutput << "Efficiency calculation method: " << calcMethodString.Data() << endl;
  effOutput << "Efficiency type to measure: " << effTypeString.Data() << endl;
  effOutput << "SC ET binning: " << etBinningString.Data() << endl;
  effOutput << "SC eta binning: " << etaBinningString.Data() << endl;
  effOutput << "Sample: " << sampleTypeString.Data() << endl;
  effOutput << "Files processed: " << endl;
  for(UInt_t i=0; i<ntupleFileNames.size(); i++)
    effOutput << "   " << ntupleFileNames[i].Data() << endl;
  
  // ROOT file to store measured efficiencies in ROOT format
  TString resroot = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString(".root");
  TFile *resultsRootFile = new TFile(resroot,"recreate");

  // Fit log 
  TString fitlogname = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString("_fitlog.dat");
  ofstream fitLog;
  fitLog.open(fitlogname);

  //
  //  Find efficiency
  //
  bool useTemplates = false;
  if(sample == DATA && effType == ID && (calcMethod == COUNTnFIT || FITnFIT) )
    useTemplates = true;

  int NsetBins=120;
  bool isRECO=0;
  const char* setBinsType="cache";

  measureEfficiency(passTree, failTree,
		    calcMethod, etBinning, etaBinning, c1, effOutput, fitLog,
		    useTemplates, templatesFile, resultsRootFile,
		    NsetBins, isRECO, setBinsType, 
		    dirTag, triggers.triggerSetName());

  effOutput.close();
  fitLog.close();
  TString command = "cat ";
  command += reslog;
  system(command.Data());

  TString fitpicname = tagAndProbeDir+TString("/efficiency_TnP_")+label+TString("_fit.png");
  c1->SaveAs(fitpicname);

  // Save MC templates
  if(sample != DATA){
    templatesFile->cd();
    for(int i=0; i<getNEtBins(etBinning); i++){
      for(int j=0; j<getNEtaBins(etaBinning); j++){
	int templateBin = getTemplateBin( i, j, etaBinning);
	hPassTemplateV[templateBin]->Write();
	hFailTemplateV[templateBin]->Write();
      }
    }
    templatesFile->Close();
  }

  gBenchmark->Show("eff_IdHlt");
  
  
}
void HwwNoteFigs(TString filename = "../histo_tmva_new-ntuples-1_160_0.root",
                 int mass = 170, int ReBin = 4, int ysel = 0)
{
	TFile* infile = new TFile(filename.Data(),"READ");
	setTDRStyle(0);
	
	//BDTD dists
	TCanvas* c1 = new TCanvas("c1","c1",0,-200,500,500);
	
        TH1F* histoBg =  histo4->Clone();
        histoBg->Add(histo3);
        histoBg->Add(histo2);
        histoBg->Add(histo1);

    	TH1F* histo_4 =  histo4->Clone();
    	histo3->Add(histo_4);
    	TH1F* histo_3 =  histo3->Clone();
    	histo2->Add(histo_3);
    	TH1F* histo_2 =  histo2->Clone();
    	histo1->Add(histo_2);

        histo1->Rebin(ReBin);
        histo1->SetFillColor(kBlue);
        histo1->SetFillStyle(1001);
        histo1->SetLineStyle(0);
        histo1->SetLineWidth(0);

        histo2->Rebin(ReBin);
        histo2->SetFillColor(kMagenta);
        histo2->SetFillStyle(1001);
        histo2->SetLineStyle(0);
        histo2->SetLineWidth(0);

        histo3->Rebin(ReBin);
        histo3->SetFillColor(kGreen);
        histo3->SetFillStyle(1001);
        histo3->SetLineStyle(0);
        histo3->SetLineWidth(0);
        
        histo4->Rebin(ReBin);
        histo4->SetFillColor(kCyan);
        histo4->SetFillStyle(1001);
        histo4->SetLineStyle(0);
        histo4->SetLineWidth(0);

        char YTitle[300];
        sprintf(YTitle,"events / bin");
        char XTitle[300];
        sprintf(XTitle,"BDT Output");
    	histo0->SetYTitle(YTitle);
    	histo1->SetYTitle(YTitle);
    	histo2->SetYTitle(YTitle);
    	histo3->SetYTitle(YTitle);
    	histo4->SetYTitle(YTitle);

    	histo0->SetXTitle(XTitle);
    	histo1->SetXTitle(XTitle);
    	histo2->SetXTitle(XTitle);
    	histo3->SetXTitle(XTitle);
    	histo4->SetXTitle(XTitle);
    	histo1->SetTitleSize(0.05, "X");
    	histo1->GetXaxis()->SetTitleFont(62);
    	histo1->GetXaxis()->SetLabelFont(61);
    	histo1->GetYaxis()->SetLabelFont(61); 
    	histo1->GetYaxis()->SetTitleOffset(1.3);
    	histo1->SetLabelSize(0.04, "Y");
    	histo1->SetLabelSize(0.04, "X");

	int min = histoBg->FindBin(-1.5);
	int max = histoBg->FindBin(1.5);

	histoBg->GetXaxis()->SetRange(min,max);
	
	histoBg->SetMarkerStyle(20);
	histoBg->SetMarkerSize(1.0);
	histoBg->GetYaxis()->SetTitleOffset(1.40);
	
	histo0->SetMarkerStyle(21);
	histo0->SetMarkerSize(1.0);
	
	histoBg->Rebin(ReBin);
	histo0->Rebin(ReBin);

	histoBg->SetLineColor(4);
	histo0->SetLineColor(1);

	scaleHist(histoBg);
	scaleHist(histo0);
	cout << "bg events: " << histoBg->GetSumOfWeights() << endl;
	cout << "si events: " << histo0->GetSumOfWeights() << endl;

	histoBg->SetYTitle("Events");
    	histo1->SetMinimum(0.01);
	if(ysel == 0)  {
	  histo1->Draw("hist");
	}
	else          {
	  histo0->Draw("E");
	  histo1->Draw("hist,same");
    	}
	histo2->Draw("hist,same");
    	histo3->Draw("hist,same");
    	histo4->Draw("hist,same");
    	histo0->Draw("E, same");
	//histoBg->DrawCopy("hist");
	//histo0->DrawCopy("hist,same");

	TLegend* leg = new TLegend(0.63, 0.75, 0.92, 0.92);
	leg->SetFillColor(0);
	char theSLine[100];
	if(mass != 999)	sprintf(theSLine,"Signal, m_{H}=%d GeV",mass);
	else    	sprintf(theSLine,"WW");
        cout << theSLine << endl;
	leg ->AddEntry(histo0,theSLine);
    	leg ->AddEntry(histo4,"W+Jets, W#gamma","F"); 
    	leg ->AddEntry(histo3,"di-boson","F");  
    	leg ->AddEntry(histo2,"t#bar{t}, tW","F"); 
    	leg ->AddEntry(histo1,"Drell-Yan","F"); 
	leg->Draw("same");
	
        TString fileOutput1(filename.Data());
	TString theLine = "_";
	theLine = theLine + "plot.eps";
        fileOutput1.ReplaceAll(".root",theLine.Data());
        fileOutput1.ReplaceAll("../","");
        fileOutput1.ReplaceAll("rootfiles_fastsim/","");
        fileOutput1.ReplaceAll("rootfiles_fullsim/","");
	c1->SaveAs(fileOutput1.Data());
        //return;
	//--------------------------------
	TCanvas* c3 = new TCanvas("c3","c3",550,-200,500,500);
	c3->SetLogx();
	c3->SetLogy();
	gPad->SetGrid(1,1);
	TGraphErrors* gBDTD = makeGraphFromHists(histo0, histoBg);
	gBDTD->Draw("APXl");
	TH1* zBDTD = gBDTD->GetHistogram();
	zBDTD->SetXTitle("Signal Events");
	zBDTD->SetYTitle("Signal/Background");
	//zBDTD->SetYTitle("Background Events");
	//zBDTD->DrawCopy();

	TLegend* leg3 = new TLegend(0.7, 0.7, 0.9, 0.9);
	leg3->SetFillColor(0);
	leg3->AddEntry(gBDTD,theSLine,"lp");
	leg3->Draw("same");
        TString fileOutput2(filename.Data());
	theLine = "_";
	theLine = theLine + "counts.eps";
        fileOutput2.ReplaceAll(".root",theLine.Data());
        fileOutput2.ReplaceAll("../","");
        fileOutput2.ReplaceAll("rootfiles_fastsim/","");
        fileOutput2.ReplaceAll("rootfiles_fullsim/","");
	c3->SaveAs(fileOutput2.Data());
	
}
示例#7
0
//------------------------------------------------------------------------------
// LatinosTreeScriptLL
//------------------------------------------------------------------------------
void LatinosTreeScriptLL(Float_t luminosity,
			 Int_t   jetChannel,
		         TString flavorChannel,
		         TString theSample,
		         Bool_t  verbose)
{

  TH1::SetDefaultSumw2();

  TString path = Form("rootfiles/%djet/%s/", jetChannel, flavorChannel.Data());

  gSystem->mkdir(path, kTRUE);

  TFile* output = new TFile(path + theSample + ".root", "recreate");


  // Counting histograms
  //----------------------------------------------------------------------------
  TH1F* hWTrigger     = new TH1F("hWTrigger",     "", 3, 0, 3);
  TH1F* hWTriggerLL     = new TH1F("hWTriggerLL",     "", 3, 0, 3);
  TH1F* hWTriggerA     = new TH1F("hWTriggerA",     "", 3, 0, 3);  
  TH1F* hWTriggerB     = new TH1F("hWTriggerB",     "", 3, 0, 3);  
  TH1F* hWTriggerC     = new TH1F("hWTriggerC",     "", 3, 0, 3);    
  TH1F* hWMetCut      = new TH1F("hWMetCut",      "", 3, 0, 3);
  TH1F* hWLowMinv     = new TH1F("hWLowMinv",     "", 3, 0, 3);
  TH1F* hWZVeto       = new TH1F("hWZVeto",       "", 3, 0, 3);
  TH1F* hWpMetCut     = new TH1F("hWpMetCut",     "", 3, 0, 3);
  TH1F* hWJetVeto     = new TH1F("hWJetVeto",     "", 3, 0, 3);
  TH1F* hWDeltaPhiJet = new TH1F("hWDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWSoftMuVeto  = new TH1F("hWSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWExtraLepton = new TH1F("hWExtraLepton", "", 3, 0, 3);
  TH1F* hWPtll        = new TH1F("hWPtll",        "", 3, 0, 3);
  TH1F* hWTopTagging  = new TH1F("hWTopTagging",  "", 3, 0, 3);

  TH1F* hWeffTrigger     = new TH1F("hWeffTrigger",     "", 3, 0, 3);
  TH1F* hWeffMetCut      = new TH1F("hWeffMetCut",      "", 3, 0, 3);
  TH1F* hWeffLowMinv     = new TH1F("hWeffLowMinv",     "", 3, 0, 3);
  TH1F* hWeffZVeto       = new TH1F("hWeffZVeto",       "", 3, 0, 3);
  TH1F* hWeffpMetCut     = new TH1F("hWeffpMetCut",     "", 3, 0, 3);
  TH1F* hWeffJetVeto     = new TH1F("hWeffJetVeto",     "", 3, 0, 3);
  TH1F* hWeffDeltaPhiJet = new TH1F("hWeffDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWeffSoftMuVeto  = new TH1F("hWeffSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWeffExtraLepton = new TH1F("hWeffExtraLepton", "", 3, 0, 3);
  TH1F* hWeffPtll        = new TH1F("hWeffPtll",        "", 3, 0, 3);
  TH1F* hWeffTopTagging  = new TH1F("hWeffTopTagging",  "", 3, 0, 3);


  // WW level histograms: Region A, from tight -to- loose method
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevelLL       = new TH1F("hPtLepton1WWLevelLL",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevelLL       = new TH1F("hPtLepton2WWLevelLL",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevelLL      = new TH1F("hPtDiLeptonWWLevelLL",      "", 200, 0, 200);
  TH1F* hMinvWWLevelLL            = new TH1F("hMinvWWLevelLL",            "", 200, 0, 200);
  TH1F* hMtWWLevelLL              = new TH1F("hMtWWLevelLL",              "", 250, 0, 250);
  TH1F* hNJets30WWLevelLL         = new TH1F("hNJetsPF30WWLevelLL",       "",  10, 0,  10);
  TH1F* hpfMetWWLevelLL           = new TH1F("hpfMetWWLevelLL",           "", 150, 0, 150);
  TH1F* hppfMetWWLevelLL          = new TH1F("hppfMetWWLevelLL",          "", 150, 0, 150);
  TH1F* hchMetWWLevelLL           = new TH1F("hchMetWWLevelLL",           "", 150, 0, 150);
  TH1F* hpchMetWWLevelLL          = new TH1F("hpchMetWWLevelLL",          "", 150, 0, 150);
  TH1F* hpminMetWWLevelLL         = new TH1F("hpminMetWWLevelLL",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevelLL   = new TH1F("hDeltaRLeptonsWWLevelLL",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevelLL = new TH1F("hDeltaPhiLeptonsWWLevelLL", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevelLL     = new TH1F("hDPhiPtllJetWWLevelLL",     "",  32, 0, 3.2);

  TH1F* hFakeLeptonIsoWWLevelLL = new TH1F("hFakeLeptonIsoWWLevelLL", "", 100, 0, 1);


  // WW level histograms: Region A, Tight+Tight
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevelA       = new TH1F("hPtLepton1WWLevelA",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevelA       = new TH1F("hPtLepton2WWLevelA",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevelA      = new TH1F("hPtDiLeptonWWLevelA",      "", 200, 0, 200);
  TH1F* hMinvWWLevelA            = new TH1F("hMinvWWLevelA",            "", 200, 0, 200);
  TH1F* hMtWWLevelA              = new TH1F("hMtWWLevelA",              "", 250, 0, 250);
  TH1F* hNJets30WWLevelA         = new TH1F("hNJetsPF30WWLevelA",       "",  10, 0,  10);
  TH1F* hpfMetWWLevelA           = new TH1F("hpfMetWWLevelA",           "", 150, 0, 150);
  TH1F* hppfMetWWLevelA          = new TH1F("hppfMetWWLevelA",          "", 150, 0, 150);
  TH1F* hchMetWWLevelA           = new TH1F("hchMetWWLevelA",           "", 150, 0, 150);
  TH1F* hpchMetWWLevelA          = new TH1F("hpchMetWWLevelA",          "", 150, 0, 150);
  TH1F* hpminMetWWLevelA         = new TH1F("hpminMetWWLevelA",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevelA   = new TH1F("hDeltaRLeptonsWWLevelA",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevelA = new TH1F("hDeltaPhiLeptonsWWLevelA", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevelA     = new TH1F("hDPhiPtllJetWWLevelA",     "",  32, 0, 3.2);

  TH1F* hFakeLeptonIsoWWLevelA = new TH1F("hFakeLeptonIsoWWLevelA", "", 100, 0, 1);


  // WW level histograms: Region B, Tight+NoTight
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevelB       = new TH1F("hPtLepton1WWLevelB",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevelB       = new TH1F("hPtLepton2WWLevelB",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevelB      = new TH1F("hPtDiLeptonWWLevelB",      "", 200, 0, 200);
  TH1F* hMinvWWLevelB            = new TH1F("hMinvWWLevelB",            "", 200, 0, 200);
  TH1F* hMtWWLevelB              = new TH1F("hMtWWLevelB",              "", 250, 0, 250);
  TH1F* hNJets30WWLevelB         = new TH1F("hNJetsPF30WWLevelB",       "",  10, 0,  10);
  TH1F* hpfMetWWLevelB           = new TH1F("hpfMetWWLevelB",           "", 150, 0, 150);
  TH1F* hppfMetWWLevelB          = new TH1F("hppfMetWWLevelB",          "", 150, 0, 150);
  TH1F* hchMetWWLevelB           = new TH1F("hchMetWWLevelB",           "", 150, 0, 150);
  TH1F* hpchMetWWLevelB          = new TH1F("hpchMetWWLevelB",          "", 150, 0, 150);
  TH1F* hpminMetWWLevelB         = new TH1F("hpminMetWWLevelB",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevelB   = new TH1F("hDeltaRLeptonsWWLevelB",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevelB = new TH1F("hDeltaPhiLeptonsWWLevelB", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevelB     = new TH1F("hDPhiPtllJetWWLevelB",     "",  32, 0, 3.2);

  TH1F* hFakeLeptonIsoWWLevelB = new TH1F("hFakeLeptonIsoWWLevelB", "", 100, 0, 1);
  TH1F* hpfMetWWLevelBNoMET = new TH1F("hppfMetWWLevelBNoMET",          "", 150, 0, 150);

  // WW level histograms: Region C, NoTight+NoTight
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevelC       = new TH1F("hPtLepton1WWLevelC",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevelC       = new TH1F("hPtLepton2WWLevelC",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevelC      = new TH1F("hPtDiLeptonWWLevelC",      "", 200, 0, 200);
  TH1F* hMinvWWLevelC            = new TH1F("hMinvWWLevelC",            "", 200, 0, 200);
  TH1F* hMtWWLevelC              = new TH1F("hMtWWLevelC",              "", 250, 0, 250);
  TH1F* hNJets30WWLevelC         = new TH1F("hNJetsPF30WWLevelC",       "",  10, 0,  10);
  TH1F* hpfMetWWLevelC           = new TH1F("hpfMetWWLevelC",           "", 150, 0, 150);
  TH1F* hppfMetWWLevelC          = new TH1F("hppfMetWWLevelC",          "", 150, 0, 150);
  TH1F* hchMetWWLevelC           = new TH1F("hchMetWWLevelC",           "", 150, 0, 150);
  TH1F* hpchMetWWLevelC          = new TH1F("hpchMetWWLevelC",          "", 150, 0, 150);
  TH1F* hpminMetWWLevelC         = new TH1F("hpminMetWWLevelC",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevelC   = new TH1F("hDeltaRLeptonsWWLevelC",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevelC = new TH1F("hDeltaPhiLeptonsWWLevelC", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevelC     = new TH1F("hDPhiPtllJetWWLevelC",     "",  32, 0, 3.2);

  TH1F* hFakeLeptonIsoWWLevelC = new TH1F("hFakeLeptonIsoWWLevelC", "", 100, 0, 1);


  //----------------------------------------------------------------------------
  // Input files
  //----------------------------------------------------------------------------
  TString filesPath;

  filesPath = "/gpfs/csic_projects/cms/piedra/latino/RunII/MC_Spring15/25ns/";
		 

  TChain* tree = new TChain("latino", "latino");

  double mybaseW = 1.0;

  if (theSample == "WJetsFakes_Total") {
    tree->Add("addWJet/output/latino_WJetsToLNu.root");
  }
  else if (theSample == "WJets") {
    tree->Add(filesPath + "latino_WJetsToLNu.root");
  }
  else if (theSample == "WWTo2L2Nu_pow") {
    tree->Add(filesPath + "latino_WWTo2L2Nu.root");
  }
  else if (theSample == "ZZ") {
    tree->Add(filesPath + "latino_ZZ.root");
  }
  else {
    return;
  }

  // Declaration of leaf types
  //----------------------------------------------------------------------------
  tree->SetBranchAddress("baseW"       , &baseW);
  tree->SetBranchAddress("channel"     , &channel);
  tree->SetBranchAddress("dataset"     , &dataset);
  tree->SetBranchAddress("effW"        , &effW);
  tree->SetBranchAddress("triggW"      , &triggW);
  tree->SetBranchAddress("dphilljetjet", &dphilljetjet);
  tree->SetBranchAddress("pfType1Met"  , &pfType1Met);
  tree->SetBranchAddress("dphill"      , &dphill);
  tree->SetBranchAddress("dphilljet"   , &dphilljet);
  tree->SetBranchAddress("jetRho"      , &jetRho);
  tree->SetBranchAddress("channel"     , &channel);
  tree->SetBranchAddress("baseW"       , &baseW);
  tree->SetBranchAddress("ptll"        , &ptll);
  tree->SetBranchAddress("mll"         , &mll);
  tree->SetBranchAddress("mth"         , &mth);
  tree->SetBranchAddress("dphilmet1"   , &dphilmet1);
  tree->SetBranchAddress("dphilmet2"   , &dphilmet2);
  tree->SetBranchAddress("trkMet"      , &trkMet);
  tree->SetBranchAddress("njet"      , &njet);
 

  tree->SetBranchAddress("std_vector_lepton_pt", &std_vector_lepton_pt);
  tree->SetBranchAddress("std_vector_lepton_eta", &std_vector_lepton_eta);
  tree->SetBranchAddress("std_vector_lepton_phi", &std_vector_lepton_phi);
  tree->SetBranchAddress("std_vector_lepton_id", &std_vector_lepton_id);
  tree->SetBranchAddress("std_vector_lepton_isTightMuon", &std_vector_lepton_isTightMuon);
  tree->SetBranchAddress("std_vector_lepton_eleIdMedium", &std_vector_lepton_eleIdMedium);
  tree->SetBranchAddress("std_vector_lepton_eleIdVeto", &std_vector_lepton_eleIdVeto);
  tree->SetBranchAddress("std_vector_lepton_chargedHadronIso", &std_vector_lepton_chargedHadronIso);
  tree->SetBranchAddress("std_vector_lepton_photonIso", &std_vector_lepton_photonIso);
  tree->SetBranchAddress("std_vector_lepton_neutralHadronIso", &std_vector_lepton_neutralHadronIso);
  tree->SetBranchAddress("std_vector_lepton_sumPUPt", &std_vector_lepton_sumPUPt);
  tree->SetBranchAddress("std_vector_electron_effectiveArea", &std_vector_electron_effectiveArea);
  tree->SetBranchAddress("std_vector_lepton_BestTrackdz", &std_vector_lepton_BestTrackdz);
  tree->SetBranchAddress("std_vector_lepton_BestTrackdxy", &std_vector_lepton_BestTrackdxy);

  tree->SetBranchAddress("fakeWJet", &fakeW);
  tree->SetBranchAddress("puW", &puW);
  

  // Set the channel
  //----------------------------------------------------------------------------
  Float_t SelectedChannel = -999;

  if      (flavorChannel == "MuMu") SelectedChannel =  0;
  else if (flavorChannel == "EE"  ) SelectedChannel =  1;
  else if (flavorChannel == "EMu" ) SelectedChannel =  2;
  else if (flavorChannel == "MuE" ) SelectedChannel =  3;
  else if (flavorChannel == "OF" )  SelectedChannel =  4;
  else if (flavorChannel == "SF" )  SelectedChannel =  5;
  
 
  
  //----------------------------------------------------------------------------
  // Loop
  //----------------------------------------------------------------------------
  //  for (int ievent=0; ievent<tree->GetEntries(); ievent++) {
    for (int ievent=0; ievent<1000000; ievent++) {

    tree->GetEntry(ievent);
    
    Double_t efficiencyW = effW * triggW;
    Double_t totalW      = -999;

    totalW = baseW*luminosity;


    bool isSemi = 0; 
  
    /*
    
    if (theSample.Contains("TopFakes")) {
      
      if ( leptonGenpid1 > 0 &&
	   leptonGenpid2 < 0  ) isSemi = 1; 
      
	   }*/	   
	    
   


   
    // Help variables
    //--------------------------------------------------------------------------
  
    float pt1  = std_vector_lepton_pt ->at(0); float pt2  = std_vector_lepton_pt ->at(1);
    float eta1 = std_vector_lepton_eta->at(0); float eta2 = std_vector_lepton_eta->at(1);
    float ch1  = std_vector_lepton_id->at(0);  float ch2  = std_vector_lepton_id->at(1);
    bool passLooseIDISO1 = IsLooseLepton(0) && IsLooseIsolatedLepton(0); 
    bool passLooseIDISO2 = IsLooseLepton(1) && IsLooseIsolatedLepton(1); 
    bool passIDISO1 = IsTightLepton(0) && IsIsolatedLepton(0); 
    bool passIDISO2 = IsTightLepton(1) && IsIsolatedLepton(1); 

    Float_t dphimin = (min(dphilmet1,dphilmet2));
    Float_t fullpmet = 0;
    Float_t trkpmet = 0;

    if (dphimin < TMath::Pi() / 2)
      fullpmet = pfType1Met * sin(dphimin);
    else 
      fullpmet = pfType1Met;

    if (dphimin < TMath::Pi() / 2)
      trkpmet = trkMet * sin(dphimin);
    else
      trkpmet = trkMet;
    
    Float_t mpmet = min(trkpmet,fullpmet);

 

    // The selection begins here
    //--------------------------------------------------------------------------
    
    if (pt2 <= 15) continue; // increase the pt of the leptons to further reduce Wjets 
    if (pt1 <= 15) continue; // increase the pt of the leptons to further reduce Wjets 
    //if (ch1*ch2 > 0) continue;
    if (!passLooseIDISO1) continue;
    if (!passLooseIDISO2) continue;

    if ( (SelectedChannel == -1)                                   || 
	 (channel == SelectedChannel)                              || 
	 (SelectedChannel == 4 && (channel == 2 || channel == 3) ) || 
	 (SelectedChannel == 5 && (channel == 0 || channel == 1) ) 
	 ) {
     

      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      //
      // Main analisis
      //
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        
 
      //int preSel = (nextra == 0) && mll > 12 && (zveto==1 || !sameflav) && (mpmet > 20  && dyMVA ) && (dphiv || !sameflav) && bveto_mu &&  ( ptll>30 && (!sameflav || ptll>45)) && (jetbin == jetChannel) && (bveto_ip==1 &&  nbjettche==0) ;


     
      if ( true ) { 

     	//if ( pfmet > 20 )  {	  
	hWTriggerLL ->Fill(1,      totalW*fakeW);
	hPtLepton1WWLevelLL      ->Fill(pt1,          totalW*fakeW);
	  hPtLepton2WWLevelLL      ->Fill(pt2,          totalW*fakeW);
	  hPtDiLeptonWWLevelLL     ->Fill(ptll,         totalW*fakeW);
	  hMinvWWLevelLL           ->Fill(mll,          totalW*fakeW);
	  hMtWWLevelLL             ->Fill(mth,          totalW*fakeW);
	  hNJets30WWLevelLL        ->Fill(njet,         totalW*fakeW);
	  hpfMetWWLevelLL          ->Fill(pfType1Met,   totalW*fakeW);
	  //hppfMetWWLevelLL         ->Fill(ppfmet,       totalW*fakeW);
	  //hchMetWWLevelLL          ->Fill(chmet,        totalW*fakeW);
	  //hpchMetWWLevelLL         ->Fill(pchmet,       totalW*fakeW);
	  hpminMetWWLevelLL        ->Fill(mpmet,        totalW*fakeW);
	  hDeltaRLeptonsWWLevelLL  ->Fill(drll,         totalW*fakeW);
	  hDeltaPhiLeptonsWWLevelLL->Fill(dphill,       totalW*fakeW);
	  hDPhiPtllJetWWLevelLL    ->Fill(dphilljet,    totalW*fakeW);
	  //}

	  if ( passIDISO1 && passIDISO2 ) { //&&  isSemi == 1) { //&& pfmet > 20 )  {
	    
	    hWTriggerA ->Fill(1,      totalW);
	    hPtLepton1WWLevelA      ->Fill(pt1,       totalW);
	    hPtLepton2WWLevelA      ->Fill(pt2,       totalW);
	    hPtDiLeptonWWLevelA     ->Fill(ptll,      totalW);
	    hMinvWWLevelA           ->Fill(mll,       totalW);
	    hMtWWLevelA             ->Fill(mth,       totalW);
	    hNJets30WWLevelA        ->Fill(njet,      totalW);
	    hpfMetWWLevelA          ->Fill(pfType1Met,     totalW);
	    //hppfMetWWLevelA         ->Fill(ppfmet,    totalW);
	    //hchMetWWLevelA          ->Fill(chmet,     totalW);
	    //hpchMetWWLevelA         ->Fill(pchmet,    totalW);
	    hpminMetWWLevelA        ->Fill(mpmet,     totalW);
	    hDeltaRLeptonsWWLevelA  ->Fill(drll,      totalW);
	    hDeltaPhiLeptonsWWLevelA->Fill(dphill,    totalW);
	    hDPhiPtllJetWWLevelA    ->Fill(dphilljet, totalW);
	    
	  }
	
	  if ( (passIDISO1 && !passIDISO2) || (!passIDISO1 && passIDISO2) ) {
	    
	    hWTriggerB ->Fill(1,      totalW);
	    hpfMetWWLevelBNoMET          ->Fill(pfType1Met,     totalW); 
	    
	    hPtLepton1WWLevelB      ->Fill(pt1,       totalW);
	    hPtLepton2WWLevelB      ->Fill(pt2,       totalW);
	    hPtDiLeptonWWLevelB     ->Fill(ptll,      totalW);
	    hMinvWWLevelB           ->Fill(mll,       totalW);
	    hMtWWLevelB             ->Fill(mth,       totalW);
	    hNJets30WWLevelB        ->Fill(njet,      totalW);
	    hpfMetWWLevelB          ->Fill(pfType1Met,     totalW);
	    //hppfMetWWLevelB         ->Fill(ppfmet,    totalW);
	    //hchMetWWLevelB          ->Fill(chmet,     totalW);
	    //hpchMetWWLevelB         ->Fill(pchmet,    totalW);
	    hpminMetWWLevelB        ->Fill(mpmet,     totalW);
	    hDeltaRLeptonsWWLevelB  ->Fill(drll,      totalW);
	    hDeltaPhiLeptonsWWLevelB->Fill(dphill,    totalW);
	    hDPhiPtllJetWWLevelB    ->Fill(dphilljet, totalW);
	  }	
	
	  if ( !passIDISO1 && !passIDISO2)  { // && pfmet > 20 ) { 
	    
	    hWTriggerC ->Fill(1,      totalW);
	    hPtLepton1WWLevelC      ->Fill(pt1,       totalW);
	    hPtLepton2WWLevelC      ->Fill(pt2,       totalW);
	    hPtDiLeptonWWLevelC     ->Fill(ptll,      totalW);
	    hMinvWWLevelC           ->Fill(mll,       totalW);
	    hMtWWLevelC             ->Fill(mth,       totalW);
	    hNJets30WWLevelC        ->Fill(njet,      totalW);
	    hpfMetWWLevelC          ->Fill(pfType1Met,     totalW);
	    //hppfMetWWLevelC         ->Fill(ppfmet,    totalW);
	    //hchMetWWLevelC          ->Fill(chmet,     totalW);
	    //hpchMetWWLevelC         ->Fill(pchmet,    totalW);
	    hpminMetWWLevelC        ->Fill(mpmet,     totalW);
	    hDeltaRLeptonsWWLevelC  ->Fill(drll,      totalW);
	    hDeltaPhiLeptonsWWLevelC->Fill(dphill,    totalW);
	    hDPhiPtllJetWWLevelC    ->Fill(dphilljet, totalW);	    
	  
	  }
		
      }
      
    }
    
  }


	  
  verbose = true;

  // Print
  //----------------------------------------------------------------------------
  if (verbose) {

    float norm = 1933235;
  

  //// OUTPUT 

  cout << "LL:  "  << hWTriggerLL->GetSumOfWeights() << endl;
  cout << "TT:  "  << hWTriggerA->GetSumOfWeights() << endl;
  cout << "TnoT:  "  << hWTriggerB->GetSumOfWeights() << endl;
  cout << "noTnoT:  "  << hWTriggerC->GetSumOfWeights() << endl;
  }
 
   

  // Save the histograms
  //----------------------------------------------------------------------------
  output->cd();
  output->Write("", TObject::kOverwrite);
  output->Close();
  
  

}
/*************************************************************************************
 * getYields: Goes through each Counts histogram for every process and subprocess
 *            (i.e., EE & Drell-Yan, E & WJets, etc.) and properly adds the yields
 *            for data and MC. Reports ratios of Data:MC as well.
 *  input:  the main() arguments array
 *  output: writes to stdout the LaTeX-formatted table of yields (pipe the output to 
 *          save)
 ***********************************/
void getYields(const char* argv[]) { 
  //open mlbwidth output file
  TFile *f = new TFile(argv[2]);
  f->cd();

  //very inefficient, but for now it works
  //loop over all procs, leps and figure out the event counts
  for(int i=0; i<lepsSize; i++) {
    char a[128];
    sprintf(a, "mlbwa_%s_Count", leps[i]);
    TDirectory *tDir = (TDirectory*) f->Get(a);
    TList *alok = tDir->GetListOfKeys();

    for(int j=0; j<procsSize; j++) {
      for(int k=0; alok->At(k)->GetName() != alok->Last()->GetName(); k++) {
        if(TString(alok->At(k)->GetName()).Contains(TRegexp(procs[j]))) {
          char b[128];
          sprintf(b, "mlbwa_%s_Count/%s", leps[i], alok->At(k)->GetName());

          TH1F *h = (TH1F*) f->Get(b);
          eCounts[i][j] += h->GetSumOfWeights();
          eErrors[i][j] =  sqrt(pow(eErrors[i][j],2) + pow(h->GetBinError(2),2));

          delete h;
        }
      }
    }

    char d[128];
    sprintf(d, "mlbwa_%s_Count/%s", leps[i], alok->Last()->GetName());
    if(d == "") { exit(EXIT_FAILURE); }

    TH1F *tth = (TH1F*) f->Get(d);
    eCounts[i][procsSize] = tth->GetEntries();
    double integral = tth->GetSumOfWeights();
    eErrors[i][procsSize] = tth->GetBinError(2)*eCounts[i][procsSize]/integral;
    delete tth;
  }

  //Get a string to tell us how many columns we want (size leps + 1)
  char cols[] = "c";
  for(int i=0; i<lepsSize; i++) {
    strcat(cols, "c");
  }

  //print out LaTeX:
  //formatting
  cout<<"\\documentclass[12pt,a4paper,titlepage]{article}"<<endl;
  cout<<"\\usepackage[utf8]{inputenc}"<<endl;
  cout<<"\\usepackage{amsmath}"<<endl;
  cout<<"\\usepackage{amsfonts}"<<endl;
  cout<<"\\usepackage{amssymb}"<<endl;
  cout<<"\\usepackage{hyperref}\n\n"<<endl;
  cout<<"\\usepackage[margin=0.0025in]{geometry}"<<endl;
  cout<<"\\begin{document}"<<endl;
  cout<<"\\begin{tabular}{l|"<<cols<<"} \\\\"<<endl;

  //Print out the table header
  cout<<"Sample & ";
  for(int i=0; i<lepsLaTeXSize; i++) {
    cout<<lepsLaTeX[i]<<" & ";
  }
  cout<<"Sum \\\\ \\hline\\hline"<<endl;

  //Printing out the yields for each process
  for(int i=0; i<procsSize; i++) {
      cout<<yieldLaTeX[i]<<" & ";
    for(int j=0; j<lepsSize; j++) {
      cout<<GetLatex(j,i)<<" & ";
    }
    cout<<GetLatexSum(true,i)<<"\\\\"<<(i==procsSize-1 ? "\\hline" : "")<<endl;
  }
 
  //Print out the total MC yield
  cout<<"Total MC & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatexSum(false,i)<<" & ";
  }
  cout<<GetLatexSum(false,-1)<<"\\\\"<<endl;

  //Print out the data yield
  cout<<"Data & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatex(i,lepsSize+1)<<" & ";
  }
  cout<<GetLatexSum(true,lepsSize+1)<<"\\\\\\hline\\hline"<<endl;
  
  //Print out the data:MC ratio
  cout<<"Data/MC & ";
  for(int i=1; i<=procsSize;i++) {
    cout<<GetLatexRatio(i)<<(i==procsSize ? "" : " & ");
  }
  cout<<"\\\\"<<endl;

  //We did it! End the document
  cout<<"\\end{tabular}"<<endl;
  cout<<"\\end{document}"<<endl;
}
示例#9
0
void plotDYUnfoldingMatrix(const TString input, int systematicsMode = DYTools::NORMAL, int randomSeed = 1, double reweightFsr = 1.0, double massLimit = -1.0)
//systematicsMode 0 (NORMAL) - no systematic calc
//1 (RESOLUTION_STUDY) - systematic due to smearing, 2 (FSR_STUDY) - systematics due to FSR, reweighting
//check mass spectra with reweightFsr = 0.95; 1.00; 1.05  
//mass value until which do reweighting
{

  // check whether it is a calculation
  if (input.Contains("_DebugRun_")) {
    std::cout << "plotDYUnfoldingMatrix: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  // normal calculation

  gBenchmark->Start("plotDYUnfoldingMatrix");

  if (systematicsMode==DYTools::NORMAL)
    std::cout<<"Running script in the NORMAL mode"<<std::endl;
  else if (systematicsMode==DYTools::RESOLUTION_STUDY)
    std::cout<<"Running script in the RESOLUTION_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::FSR_STUDY)
    std::cout<<"Running script in the FSR_STUDY mode"<<std::endl;
  else if (systematicsMode==DYTools::ESCALE_RESIDUAL) 
    std::cout << "Running script in the ESCALE_RESIDUAL mode\n";
  else { 
    std::cout<<"requested mode not recognized"<<std::endl;
    assert(0);
  }

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Bool_t doSave  = false;    // save plots?
  TString format = "png";   // output file format
  int saveMadePlots = 1;  // whether save produced canvases
  
  vector<TString> fnamev;   // file names   
  vector<TString> labelv;   // legend label
  vector<Int_t>   colorv;   // color in plots
  vector<Int_t>   linev;    // line style
  vector<Double_t> xsecv;
  vector<Double_t> lumiv;
  TString          dirTag;

  ifstream ifs;
  ifs.open(input.Data());
  if (!ifs.is_open()) std::cout << "failed to open a file <" << input.Data() << ">\n";
  assert(ifs.is_open());
  string line;
  Int_t state=0;
  const int inputFileMayContainEScaleDefinition = 1;
  int expectEscaleLine=1;
  ElectronEnergyScale escale((inputFileMayContainEScaleDefinition) ? 
	  ElectronEnergyScale::UNDEFINED : // read electron energy scale from the file
	  ElectronEnergyScale::Date20120101_default);
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    if(state == 0){
      dirTag = TString(line);
      state++;
      continue;
    }else{
      if (inputFileMayContainEScaleDefinition && expectEscaleLine) {
	expectEscaleLine=0;
	// try to determine whether the input file was updated
	if (ElectronEnergyScale::DetermineCalibrationSet(line.c_str()) !=
	    ElectronEnergyScale::UNDEFINED) {
	  //std::cout << "got it ok: <" << line << ">" << std::endl;
	  escale.init(TString(line.c_str()));
	  if (!escale.isInitialized()) {
	    std::cout << "code error\n";
	    return;
	  }
	  // continue reading the file
	  getline(ifs,line);
	}
	else {
	  std::cout << "\n";
	  std::cout << "\n\tInput file does not contain electron energy scale. The expected file format:\n";
	  std::cout << "\tLine1: directory\n";
	  std::cout << "\tLine2: electron energy scale correction name (NEW from 2012 Jan 21)\n";
	  std::cout << "\tLine3: file_name.root xsect color linesty label\n";
	  std::cout << "using the default set\n\n";
	  escale.init("Date20120101_default");
	  if (!escale.isInitialized()) {
	    std::cout << "failed to correct the behavior\n";
	    return;
	  }
	}
	std::cout << "energy scale corrections: " << escale.calibrationSetName() << "\n";
      }
      string fname;
      Int_t color, linesty;
      stringstream ss(line);
      Double_t xsec;
      ss >> fname >> xsec >> color >> linesty;
      string label = line.substr(line.find('@')+1);
      fnamev.push_back(fname);
      labelv.push_back(label);
      colorv.push_back(color);
      linev.push_back(linesty);
      xsecv.push_back(xsec);
      lumiv.push_back(0);
    }
  }
  ifs.close();
  
  const Double_t kGAP_LOW  = 1.4442;
  const Double_t kGAP_HIGH = 1.566;


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================


  TRandom random;
  // The random seeds are needed only if we are running this script in systematics mode
  int seed = randomSeed;
  random.SetSeed(seed);
  gRandom->SetSeed(seed);
  // In the case of systematic studies, generate an array of random offsets
  TVectorD shift(escale._nEtaBins); // this vector is outdated by the new features in the escale obj.class
  shift = 0;
  if(systematicsMode==DYTools::RESOLUTION_STUDY) {
    escale.randomizeSmearingWidth(seed);
    for(int i=0; i<escale._nEtaBins; i++)
      shift[i] = gRandom->Gaus(0,1);
  }

  // prepare tools for ESCALE_RESIDUAL
  TH1F *shapeWeights=NULL;
  if (systematicsMode==DYTools::ESCALE_RESIDUAL) {
    TString shapeFName=TString("../root_files/yields/") + dirTag + TString("/shape_weights.root");
    std::cout << "Obtaining shape_weights.root from <" << shapeFName << ">\n";
    TFile fshape(shapeFName);
    if (!fshape.IsOpen()) {
      std::cout << "failed to open a file <" << shapeFName << ">\n";
      throw 2;
    }
    shapeWeights = (TH1F*)fshape.Get("weights");
    shapeWeights->SetDirectory(0);
    dirTag += TString("_escale_residual");
    std::cout << "changing dirTag to <" << dirTag << ">\n";
  }

  //  
  // Set up histograms
  //
  vector<TH1F*> hZMassv;//, hZMass2v, hZPtv, hZPt2v, hZyv, hZPhiv;  
  
  char hname[100];
  for(UInt_t ifile = 0; ifile<fnamev.size(); ifile++) {
    sprintf(hname,"hZMass_%i",ifile); hZMassv.push_back(new TH1F(hname,"",500,0,1500)); hZMassv[ifile]->Sumw2();
  }

  TH1F *hMassDiff   = new TH1F("hMassDiff","", 100, -30, 30);
  TH1F *hMassDiffBB = new TH1F("hMassDiffBB","", 100, -30, 30);
  TH1F *hMassDiffEB = new TH1F("hMassDiffEB","", 100, -30, 30);
  TH1F *hMassDiffEE = new TH1F("hMassDiffEE","", 100, -30, 30);

  TH1F *hMassDiffV[DYTools::nMassBins];
  for(int i=0; i<DYTools::nMassBins; i++){
    sprintf(hname,"hMassDiffV_%d",i);
    hMassDiffV[i] = new TH1F(hname,"",100,-50,50);
  }

  // MC spectra for storage in ROOT file
  // The FSR of RECO means that this is the spectrum of generator-level
  // post-FSR mass for events that were actually reconstructed (i.e. includes
  // efficiency and acceptances losses)
  TVectorD yieldsMcFsrOfRec    (DYTools::nMassBins);
  TVectorD yieldsMcFsrOfRecErr (DYTools::nMassBins);
  TVectorD yieldsMcRec         (DYTools::nMassBins);
  TVectorD yieldsMcRecErr      (DYTools::nMassBins);
  yieldsMcFsrOfRec     = 0;
  yieldsMcFsrOfRecErr  = 0;
  yieldsMcRec          = 0;
  yieldsMcRecErr       = 0;
  // The yields at generator level with mass bins defined by post-FSR di-leptons
  TVectorD yieldsMcFsr    (DYTools::nMassBins);
  yieldsMcFsr          = 0;

  // Vectors for bin to bin corrections
  TVectorD DetCorrFactorNumerator  (DYTools::nMassBins);
  TVectorD DetCorrFactorDenominator(DYTools::nMassBins);
  TVectorD DetCorrFactor           (DYTools::nMassBins);
  TVectorD DetCorrFactorErrPos     (DYTools::nMassBins);
  TVectorD DetCorrFactorErrNeg     (DYTools::nMassBins);
  DetCorrFactorNumerator   = 0;
  DetCorrFactorDenominator = 0;
  DetCorrFactor            = 0;
  DetCorrFactorErrPos      = 0;
  DetCorrFactorErrNeg      = 0;
  
  // Matrices for unfolding
  TMatrixD DetMigration(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponse(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponseErrPos(DYTools::nMassBins, DYTools::nMassBins);
  TMatrixD DetResponseErrNeg(DYTools::nMassBins, DYTools::nMassBins);
  for(int i=0; i<DYTools::nMassBins; i++){
    for(int j=0; j<DYTools::nMassBins; j++){
      DetMigration(i,j) = 0;
      DetResponse(i,j) = 0;
      DetResponseErrPos(i,j) = 0;
      DetResponseErrNeg(i,j) = 0;
    }
  }

  //
  // 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 *gen  = new mithep::TGenInfo();
  TClonesArray *dielectronArr = new TClonesArray("mithep::TDielectron");
  
  // loop over samples  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
  
    // Read input file
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]); 
    assert(infile);

    // Get the TTrees
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);

    // Find weight for events for this file
    // The first file in the list comes with weight 1,
    // all subsequent ones are normalized to xsection and luminosity
    double xsec=xsecv[ifile];
    AdjustXSectionForSkim(infile,xsec,eventTree->GetEntries(),1);
    lumiv[ifile] = eventTree->GetEntries()/xsec;
    double scale = lumiv[0]/lumiv[ifile];
    cout << "       -> sample weight is " << scale << endl;

    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Info",&info);                TBranch *infoBr       = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("Gen",&gen);                  TBranch *genBr = eventTree->GetBranch("Gen");
    eventTree->SetBranchAddress("Dielectron",&dielectronArr); TBranch *dielectronBr = eventTree->GetBranch("Dielectron");
  
    // loop over events    
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      //if (ientry>100000) break;

      genBr->GetEntry(ientry);
      infoBr->GetEntry(ientry);

      double reweight;
      if (systematicsMode!=DYTools::FSR_STUDY) reweight=1.0;
      else if (((gen->mass)-(gen->vmass))>massLimit) reweight=1.0;
      else reweight=reweightFsr;

      if (ientry<20) std::cout<<"reweight="<<reweight<<std::endl;


      // Use post-FSR generator level mass in unfolding
      int ibinFsr = DYTools::findMassBin(gen->mass);
      if(ibinFsr != -1 && ibinFsr < yieldsMcFsr.GetNoElements()){
         yieldsMcFsr[ibinFsr] += reweight * scale * gen->weight;
      }


      /*
      // For EPS2011 for both data and MC (starting from Summer11 production)
      // we use an OR of the twi triggers below. Both are unpresecaled.
      ULong_t eventTriggerBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL 
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL;
      ULong_t leadingTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele1Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele1Obj;
      ULong_t trailingTriggerObjectBit = kHLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_Ele2Obj
	| kHLT_Ele17_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele8_CaloIdT_TrkIdVL_CaloIsoVL_TrkIsoVL_Ele2Obj;
      */

      const bool isData=kFALSE;
      TriggerConstantSet constantsSet = Full2011DatasetTriggers; // Enum from TriggerSelection.hh
      TriggerSelection requiredTriggers(constantsSet, isData, info->runNum);
      ULong_t eventTriggerBit = requiredTriggers.getEventTriggerBit(info->runNum);
      ULong_t leadingTriggerObjectBit = requiredTriggers.getLeadingTriggerObjectBit(info->runNum);
      ULong_t trailingTriggerObjectBit = requiredTriggers.getTrailingTriggerObjectBit(info->runNum);

      
      if(!(info->triggerBits & eventTriggerBit)) continue;  // no trigger accept? Skip to next event...                                   

      // loop through dielectrons
      dielectronArr->Clear();
      dielectronBr->GetEntry(ientry);    
      for(Int_t i=0; i<dielectronArr->GetEntriesFast(); i++) {

        const mithep::TDielectron *dielectron = (mithep::TDielectron*)((*dielectronArr)[i]);
	
	// Apply selection
	// Eta cuts
        if((fabs(dielectron->scEta_1)>kGAP_LOW) && (fabs(dielectron->scEta_1)<kGAP_HIGH)) continue;
        if((fabs(dielectron->scEta_2)>kGAP_LOW) && (fabs(dielectron->scEta_2)<kGAP_HIGH)) continue;
	if((fabs(dielectron->scEta_1) > 2.5)       || (fabs(dielectron->scEta_2) > 2.5))       continue;  // outside eta range? Skip to next event...
	
	// Asymmetric SC Et cuts
	if( ! ( ( dielectron->scEt_1 > DYTools::etMinLead  && dielectron->scEt_2 > DYTools::etMinTrail)
		|| ( dielectron->scEt_1 > DYTools::etMinTrail  && dielectron->scEt_2 > DYTools::etMinLead) )) continue;
    	
	// Both electrons must match trigger objects. At least one ordering
	// must match
	if( ! ( 
	       (dielectron->hltMatchBits_1 & leadingTriggerObjectBit && 
		dielectron->hltMatchBits_2 & trailingTriggerObjectBit )
	       ||
	       (dielectron->hltMatchBits_1 & trailingTriggerObjectBit && 
		dielectron->hltMatchBits_2 & leadingTriggerObjectBit ) ) ) continue;
	
	// The Smurf electron ID package is the same as used in HWW analysis
	// and contains cuts like VBTF WP80 for pt>20, VBTF WP70 for pt<10
	// with some customization, plus impact parameter cuts dz and dxy
	if(!passSmurf(dielectron)) continue;  

        // We have a Z candidate! HURRAY! 

	// Apply extra smearing to MC reconstructed dielectron mass
	// to better resemble the data
	/*
	  outdated lines. kept for reference
	double smear1 = escale.extraSmearingSigma(dielectron->scEta_1);
        double smear2 = escale::extraSmearingSigma(dielectron->scEta_2);
	// In systematics mode, overwrite the smear values with
	// shifted ones.
	if(systematicsMode==DYTools::RESOLUTION_STUDY){
	  smear1 = escale::extraSmearingSigmaShifted(dielectron->scEta_1,shift);
	  smear2 = escale::extraSmearingSigmaShifted(dielectron->scEta_2,shift);
	}
        double smearTotal = sqrt(smear1*smear1 + smear2*smear2);
        double massResmeared = dielectron->mass + random.Gaus(0.0,smearTotal);
	*/
	/* lines based on new features -- begin */
	double massSmear = (systematicsMode == DYTools::RESOLUTION_STUDY) ?
	  escale.generateMCSmearRandomized(dielectron->scEta_1,dielectron->scEta_2) :
	  escale.generateMCSmear(dielectron->scEta_1,dielectron->scEta_2);
        double massResmeared = dielectron->mass + massSmear;
	/* lines based on new features -- end */

	hZMassv[ifile]->Fill(massResmeared,scale * gen->weight);

	// Fill structures for response matrix and bin by bin corrections

	if(ibinFsr != -1 && ibinFsr < yieldsMcFsrOfRec.GetNoElements()){
	    yieldsMcFsrOfRec[ibinFsr] += reweight * scale * gen->weight;
	    DetCorrFactorDenominator(ibinFsr) += reweight * scale * gen->weight;
          }

	else if(ibinFsr >= yieldsMcFsrOfRec.GetNoElements())
	  cout << "ERROR: binning problem" << endl;

	int ibinRec = DYTools::findMassBin(massResmeared);
	double shape_weight = (shapeWeights && (ibinRec!=-1)) ? 
	  shapeWeights->GetBinContent(ibinRec+1) : 1.0;
	if(ibinRec != -1 && ibinRec < yieldsMcRec.GetNoElements()){
	    yieldsMcRec[ibinRec] += reweight * scale * gen->weight;
	    DetCorrFactorNumerator(ibinRec) += reweight * scale * gen->weight * shape_weight;
          }

	else if(ibinRec >= yieldsMcRec.GetNoElements())
	  cout << "ERROR: binning problem" << endl;
	
	if( ibinRec != -1 && ibinRec < yieldsMcRec.GetNoElements() 
	    && ibinFsr != -1 && ibinFsr < yieldsMcRec.GetNoElements() ){
          DetMigration(ibinFsr,ibinRec) += reweight * scale * gen->weight * shape_weight;
	}
	
        Bool_t isB1 = (fabs(dielectron->scEta_1)<kGAP_LOW);
        Bool_t isB2 = (fabs(dielectron->scEta_2)<kGAP_LOW);         
	hMassDiff->Fill(massResmeared - gen->mass);
	if( isB1 && isB2 )
	  hMassDiffBB->Fill(massResmeared - gen->mass);
	if( (isB1 && !isB2) || (!isB1 && isB2) )
	  hMassDiffEB->Fill(massResmeared - gen->mass);
	if( !isB1 && !isB2 )
	  hMassDiffEE->Fill(massResmeared - gen->mass);
	
	if(ibinFsr != -1){
	  hMassDiffV[ibinFsr]->Fill(massResmeared - gen->mass);
	}
// 	if(ibinRec == -1)
// 	  printf("Missed bin:  M_fsr=%f   M_reco=%f\n", gen->mass, massResmeared);
	
      } // end loop over dielectrons

    } // end loop over events 
    delete infile;
    infile=0, eventTree=0;
  } // end loop over files
  delete gen;


  //finish reweighting of mass spectra

  
  // Find bin by bin corrections and the errors
  double tCentral, tErrNeg, tErrPos;
  for(int i=0; i<DYTools::nMassBins; i++){
    if ( DetCorrFactorDenominator(i) != 0 ){
      // This method does not take into account correlation between numerator
      // and denominator in calculation of errors. This is a flaw to be corrected
      // in the future.
      SimpleDivide( DetCorrFactorNumerator(i), DetCorrFactorDenominator(i), tCentral, tErrNeg, tErrPos);
      DetCorrFactor(i) = tCentral;
      DetCorrFactorErrPos(i) = tErrPos;
      DetCorrFactorErrNeg(i) = tErrNeg;
    } else {
      DetCorrFactor(i) = 0;
      DetCorrFactorErrPos(i) = 0;
      DetCorrFactorErrNeg(i) = 0;
    }
  }
  
  // Find response matrix, which is simply the normalized migration matrix
  for(int ifsr = 0; ifsr < DetMigration.GetNrows(); ifsr++){
    double nEventsInFsrMassBin = 0;
    for(int ireco = 0; ireco < DetMigration.GetNcols(); ireco++)
      nEventsInFsrMassBin += DetMigration(ifsr,ireco);
    // Now normalize each element and find errors
    for(int ireco = 0; ireco < DetMigration.GetNcols(); ireco++){
      tCentral = 0;
      tErrPos  = 0;
      tErrNeg  = 0;
      // Note: the event counts supposedly are dominated with events with weight "1"
      // coming from the primary MC sample, so the error is assumed Poissonian in
      // the call for efficiency-calculating function below.
      if( nEventsInFsrMassBin != 0 ){
	EfficiencyDivide(DetMigration(ifsr,ireco), nEventsInFsrMassBin, tCentral, tErrNeg, tErrPos);
      // BayesEfficiency does not seem to be working in newer ROOT versions, 
      // so it is replaced by simler method
//         BayesEfficiency( DetMigration(ifsr,ireco), nEventsInFsrMassBin, tCentral, tErrNeg, tErrPos);
      }
      DetResponse      (ifsr,ireco) = tCentral;
      DetResponseErrPos(ifsr,ireco) = tErrPos;
      DetResponseErrNeg(ifsr,ireco) = tErrNeg;
    }
  }

  // Find inverted response matrix
  TMatrixD DetInvertedResponse = DetResponse;
  Double_t det;
  DetInvertedResponse.Invert(&det);
  TMatrixD DetInvertedResponseErr(DetInvertedResponse.GetNrows(), DetInvertedResponse.GetNcols());
  calculateInvertedMatrixErrors(DetResponse, DetResponseErrPos, DetResponseErrNeg, DetInvertedResponseErr);

  // Package bin limits into TVectorD for storing in a file
  TVectorD BinLimitsArray(DYTools::nMassBins+1);
  for(int i=0; i<DYTools::nMassBins+1; i++)
    BinLimitsArray(i) = DYTools::massBinLimits[i];

  // Store constants in the file
  TString outputDir(TString("../root_files/constants/")+dirTag);
  if((systematicsMode==DYTools::RESOLUTION_STUDY) || (systematicsMode==DYTools::FSR_STUDY))
    outputDir = TString("../root_files/systematics/")+dirTag;
  gSystem->mkdir(outputDir,kTRUE);
  TString unfoldingConstFileName(outputDir+TString("/unfolding_constants.root"));
  if(systematicsMode==DYTools::RESOLUTION_STUDY){
    unfoldingConstFileName = outputDir+TString("/unfolding_constants_seed_");
    unfoldingConstFileName += seed;
    unfoldingConstFileName += ".root";
  }
  if(systematicsMode==DYTools::FSR_STUDY){
    unfoldingConstFileName = outputDir+TString("/unfolding_constants_reweight_");
    unfoldingConstFileName += int(100*reweightFsr);
    unfoldingConstFileName += ".root";
  }

  TFile fConst(unfoldingConstFileName, "recreate" );
  DetResponse             .Write("DetResponse");
  DetInvertedResponse     .Write("DetInvertedResponse");
  DetInvertedResponseErr  .Write("DetInvertedResponseErr");
  BinLimitsArray          .Write("BinLimitsArray");
  DetCorrFactor           .Write("DetCorrFactor");
  DetCorrFactorErrPos     .Write("DetCorrFactorErrPos");
  DetCorrFactorErrNeg     .Write("DetCorrFactorErrNeg");
  fConst.Close();
  
  // Store reference MC arrays in a file
  TString refFileName(outputDir+TString("/yields_MC_unfolding_reference.root"));
  TFile fRef(refFileName, "recreate" );
  BinLimitsArray    .Write("BinLimitsArray");
  yieldsMcFsr       .Write("yieldsMcFsr");
  yieldsMcFsrOfRec  .Write("yieldsMcFsrOfRec");
  yieldsMcRec       .Write("yieldsMcRec");
  fRef.Close();


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

  std::vector<TCanvas*> canvasV; // holder for a quick saver
  canvasV.reserve(10);

  TCanvas *c = MakeCanvas("zMass1","zMass1",800,600);
  canvasV.push_back(c);

  // string buffers
  char ylabel[50];   // y-axis label

  // Z mass
  sprintf(ylabel,"a.u. / %.1f GeV/c^{2}",hZMassv[0]->GetBinWidth(1));
  CPlot plotZMass1("zmass1","","m(ee) [GeV/c^{2}]",ylabel);
  if (fnamev.size()) hZMassv[0]->GetXaxis()->SetLimits(10.,2000.);
  for(UInt_t i=0; i<fnamev.size(); i++) { 
    plotZMass1.AddHist1D(hZMassv[i],labelv[i],"hist",colorv[i],linev[i]); 
  }
  plotZMass1.SetLogy();
  plotZMass1.SetLogx(); 
  plotZMass1.TransLegend(0.02, 0.0);
  plotZMass1.Draw(c,doSave,format);

  // Create plots of how reco mass looks and how unfolded mass should look like
  TVectorD massBinCentral     (DYTools::nMassBins);
  TVectorD massBinHalfWidth   (DYTools::nMassBins);
  TVectorD yieldMcFsrOfRecErr (DYTools::nMassBins);
  TVectorD yieldMcRecErr      (DYTools::nMassBins);
  for(int i=0; i < DYTools::nMassBins; i++){
    massBinCentral  (i) = (DYTools::massBinLimits[i+1] + DYTools::massBinLimits[i])/2.0;
    massBinHalfWidth(i) = (DYTools::massBinLimits[i+1] - DYTools::massBinLimits[i])/2.0;
    yieldsMcFsrOfRecErr(i) = sqrt(yieldsMcFsrOfRec[i]);
    yieldsMcRecErr     (i) = sqrt(yieldsMcRec[i]);
  }
  TGraphErrors *grFsrOfRec = new TGraphErrors(massBinCentral, yieldsMcFsrOfRec, 
					      massBinHalfWidth, yieldsMcFsrOfRecErr);
  TGraphErrors *grRec      = new TGraphErrors(massBinCentral, yieldsMcRec, 
					      massBinHalfWidth, yieldsMcRecErr);
  TCanvas *d = MakeCanvas("zMass2","zMass2",800,600);
  canvasV.push_back(d);
  CPlot plotZMass2("zmass2","","m(ee) [GeV/c^{2}]","events");
  plotZMass2.SetLogx(1);
  plotZMass2.AddGraph(grFsrOfRec,"no detector effects","PE",kBlack);
  plotZMass2.AddGraph(grRec,"reconstructed","PE",kBlue);
  plotZMass2.Draw(d);

//   double xsize = 600;
//   double ysize = 600;
  int xsize = 600;
  int ysize = 400;

  // Create the plot of the response matrix
  TH2F *hResponse = new TH2F("hResponse","",DYTools::nMassBins, DYTools::massBinLimits,
			     DYTools::nMassBins, DYTools::massBinLimits);
  for(int i=1; i<=DYTools::nMassBins; i++)
    for(int j=1; j<=DYTools::nMassBins; j++)
      hResponse->SetBinContent(i,j,DetResponse(i-1,j-1));
  TCanvas *e = MakeCanvas("response","response",xsize,ysize);
  canvasV.push_back(e);
  CPlot plotResponse("response","",
		     "generator post-FSR m(ee) [GeV/c^{2}]",
		     "reconstructed  m(ee) [GeV/c^{2}]");
  plotResponse.AddHist2D(hResponse,"COLZ");
  e->cd();
  plotResponse.SetLogx();
  plotResponse.SetLogy();
  gPad->SetRightMargin(0.15);
  gStyle->SetPalette(1);
  hResponse->GetXaxis()->SetMoreLogLabels();
  hResponse->GetXaxis()->SetNoExponent();
  hResponse->GetYaxis()->SetNoExponent();
  plotResponse.Draw(e);

  // Create the plot of the inverted response matrix
  TH2F *hInvResponse = new TH2F("hInvResponse","",DYTools::nMassBins, DYTools::massBinLimits,
			     DYTools::nMassBins, DYTools::massBinLimits);
  for(int i=1; i<=DYTools::nMassBins; i++)
    for(int j=1; j<=DYTools::nMassBins; j++)
      hInvResponse->SetBinContent(i,j,DetInvertedResponse(i-1,j-1));
  TCanvas *f = MakeCanvas("invResponse","invResponse",xsize,ysize);
  canvasV.push_back(f);
  CPlot plotInvResponse("inverted response","",
			"reconstructed  m(ee) [GeV/c^{2}]",
			"generator post-FSR m(ee) [GeV/c^{2}]");
  plotInvResponse.AddHist2D(hInvResponse,"COLZ");
  f->cd();
  plotInvResponse.SetLogx();
  plotInvResponse.SetLogy();
  gPad->SetRightMargin(0.15);
  gStyle->SetPalette(1);
  hInvResponse->GetXaxis()->SetMoreLogLabels();
  hInvResponse->GetXaxis()->SetNoExponent();
  hInvResponse->GetYaxis()->SetNoExponent();
  plotInvResponse.Draw(f);

  // Create a plot of detector resolution without mass binning
  TCanvas *g = MakeCanvas("massDiff","massDiff",600,600);
  canvasV.push_back(g);
  CPlot plotMassDiff("massDiff","","reco mass - gen post-FSR mass [GeV/c^{2}]","a.u.");
  hMassDiffBB->Scale(1.0/hMassDiffBB->GetSumOfWeights());
  hMassDiffEB->Scale(1.0/hMassDiffEB->GetSumOfWeights());
  hMassDiffEE->Scale(1.0/hMassDiffEE->GetSumOfWeights());
  plotMassDiff.AddHist1D(hMassDiffBB,"EB-EB","hist",kBlack);
  plotMassDiff.AddHist1D(hMassDiffEB,"EE-EB","hist",kBlue);
  plotMassDiff.AddHist1D(hMassDiffEE,"EE-EE","hist",kRed);
  plotMassDiff.TransLegend(0.1, 0.0);
  plotMassDiff.Draw(g);



  // Create a plot of reco - gen post-FSR mass difference for several mass bins
  TCanvas *h = MakeCanvas("massDiffV","massDiffV",600,600);
  canvasV.push_back(h);
  CPlot plotMassDiffV("massDiffV","","reco mass - gen post-FSR mass [GeV/c^{2}]","a.u.");
  hMassDiffV[7]->Scale(1.0/hMassDiffV[7]->GetSumOfWeights());
  hMassDiffV[6]->Scale(1.0/hMassDiffV[6]->GetSumOfWeights());
  hMassDiffV[5]->Scale(1.0/hMassDiffV[5]->GetSumOfWeights());
  hMassDiffV[4]->Scale(1.0/hMassDiffV[4]->GetSumOfWeights());
  plotMassDiffV.AddHist1D(hMassDiffV[4],"50-60 GeV/c^{2}","hist",kBlack);
  plotMassDiffV.AddHist1D(hMassDiffV[5],"60-76 GeV/c^{2}","hist",kBlue);
  plotMassDiffV.AddHist1D(hMassDiffV[6],"76-86 GeV/c^{2}","hist",kRed);
  plotMassDiffV.AddHist1D(hMassDiffV[7],"86-96 GeV/c^{2}","hist",kMagenta);
  plotMassDiffV.SetXRange(-20,50);
  plotMassDiffV.Draw(h);

  // Create graph of bin-to-bin corrections
  TGraphAsymmErrors *grCorrFactor 
    = new TGraphAsymmErrors(massBinCentral, DetCorrFactor,
			    massBinHalfWidth, massBinHalfWidth,
			    DetCorrFactorErrNeg, DetCorrFactorErrPos);
  TCanvas *c11 = MakeCanvas("corrFactor","corrFactor",800,600);
  canvasV.push_back(c11);
  CPlot plotCorrFactor("corrFactor","","m(ee) [GeV/c^{2}]","correction factor");
  plotCorrFactor.AddGraph(grCorrFactor,"PE",kBlue);
  plotCorrFactor.SetLogx();
  plotCorrFactor.SetYRange(0,2.0);
  plotCorrFactor.Draw(c11);

  if (saveMadePlots) {
    TString plotPath=TString("../root_files/plots/") + dirTag; 
    TString name=plotPath + TString("/unfolding_plots.root");
    gSystem->mkdir(plotPath,true);
    TFile* fplots = TFile::Open(name,"RECREATE");
    for (unsigned int i=0; i<canvasV.size(); ++i) {
      canvasV[i]->Write();
    }
    fplots->Close();
  }

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //==============================================================================================================
  cout << endl;
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << endl; 
  
  // Printout of all constants, uncomment if needed

  //printf("DetMigration:\n"); DetMigration.Print();
  //printf("DetResponse:\n"); DetResponse.Print();
  //printf("DetInvertedResponse:\n"); DetInvertedResponse.Print();

//   DetCorrFactor.Print();
//   DetResponse.Print();
  
//   printf("Detector corr factor numerator:\n");
//   DetCorrFactorNumerator.Print();
//   printf("yieldsMcRec:\n");
//   yieldsMcRec.Print();

//   printf("Detector corr factor denominator:\n");
//   DetCorrFactorDenominator.Print();
//   printf("yieldsMcFsrOfRec:\n");
//   yieldsMcFsrOfRec.Print();

  gBenchmark->Show("plotDYUnfoldingMatrix");
}
示例#10
0
void fakeStudyMu( TCut Cuts_ = "ptL1>0",
		  TString variable_ = "MtLeg1",
		  TString XTitle_ = "M_{T}(#mu,MET)",
		  TString Unities_ = "GeV",
		  Int_t nBins_ = 12, Float_t xMin_=0, Float_t xMax_=120,
		  Float_t magnifySgn_ = 10,
		  Float_t hltEff_ = 1.0,
		  Int_t enableHLTmatching_ = 1,
		  Int_t logy_ = 0 ) 
{   
  
  float Lumi = 24.86+159.15;

  TCanvas *c1 = new TCanvas("c1","",5,30,650,600);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  c1->SetLogy(logy_);

  TLegend* leg = new TLegend(0.60,0.50,0.85,0.85,NULL,"brNDC");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetFillColor(10);
  leg->SetTextSize(0.04);
  leg->SetHeader("#mu+#tau_{had}");

  THStack* aStack = new THStack("aStack",Form("CMS Preliminary 2011    #sqrt{s}=7 TeV L=%.0f pb^{-1}", Lumi ));
  TH1F* hSiml = new TH1F();
  TH1F* hSgn   = new TH1F();
  TH1F* hSgn1  = new TH1F();
  TH1F* hSgn2  = new TH1F();
  TH1F* hData  = new TH1F();
 

  // OpenNTuples
  TString fDataName                = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleRun2011-Mu_Open_MuTauStream.root";
  TString fSignalNameVBF           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleVBFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fSignalNameGGH           = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleGGFH115-Mu-powheg-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYTauTau  = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDYJets-Mu-50-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameDYMuMu    = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDYJets-Mu-50-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameWJets     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleWJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameQCD       = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleQCDmu_Open_MuTauStream.root";
  TString fBackgroundNameTTbar     = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleTTJets-Mu-madgraph-PUS1_Open_MuTauStream.root";
  TString fBackgroundNameSingleTop = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleSingleTop-Mu_Open_MuTauStream.root";
  TString fBackgroundNameDiBoson   = "/data_CMS/cms/lbianchini/VbfJetsStudy/OpenNtuples/MuTauStream2011_iter2/Inclusive/nTupleDiBoson-Mu_Open_MuTauStream.root";

  TFile *fData(0); 
  TFile *fSignalVBF(0); 
  TFile *fSignalGGH(0); 
  TFile *fBackgroundDYTauTau(0);
  TFile *fBackgroundDYMuMu(0);
  TFile *fBackgroundWJets(0);
  TFile *fBackgroundQCD(0);
  TFile *fBackgroundTTbar(0);
  TFile *fBackgroundSingleTop(0);
  TFile *fBackgroundDiBoson(0);
 
  fData               = TFile::Open( fDataName ); 
  fSignalVBF          = TFile::Open( fSignalNameVBF ); 
  fSignalGGH          = TFile::Open( fSignalNameGGH ); 
  fBackgroundDYTauTau = TFile::Open( fBackgroundNameDYTauTau ); 
  fBackgroundDYMuMu   = TFile::Open( fBackgroundNameDYMuMu ); 
  fBackgroundWJets    = TFile::Open( fBackgroundNameWJets ); 
  fBackgroundQCD      = TFile::Open( fBackgroundNameQCD ); 
  fBackgroundTTbar    = TFile::Open( fBackgroundNameTTbar );
  fBackgroundSingleTop= TFile::Open( fBackgroundNameSingleTop ); 
  fBackgroundDiBoson  = TFile::Open( fBackgroundNameDiBoson ); 

  if(!fSignalVBF || !fBackgroundDYTauTau || !fBackgroundWJets || !fBackgroundQCD || !fBackgroundTTbar || !fBackgroundSingleTop ||
     !fSignalGGH || !fBackgroundDYMuMu || !fBackgroundDiBoson || !fData){
    std::cout << "ERROR: could not open files" << std::endl;
    exit(1);
  }

  TString tree = "outTreePtOrd";

  TTree *data                = (TTree*)fData->Get(tree);
  TTree *signalVBF           = (TTree*)fSignalVBF->Get(tree);
  TTree *signalGGH           = (TTree*)fSignalGGH->Get(tree);

  TFile* dummy1 = new TFile("dummy1.root","RECREATE");
  TTree *backgroundDYTauTau  = ((TTree*)fBackgroundDYTauTau->Get(tree))->CopyTree("isTauLegMatched>0.5");
  TTree *backgroundDYMuMu    = ((TTree*)fBackgroundDYMuMu->Get(tree))->CopyTree("isTauLegMatched<0.5");
  cout <<backgroundDYTauTau->GetEntries() << " -- " << backgroundDYMuMu->GetEntries() << endl;

  TTree *backgroundWJets     = (TTree*)fBackgroundWJets->Get(tree);
  TTree *backgroundQCD       = (TTree*)fBackgroundQCD->Get(tree);
  TTree *backgroundTTbar     = (TTree*)fBackgroundTTbar->Get(tree);
  TTree *backgroundSingleTop = (TTree*)fBackgroundSingleTop->Get(tree);
  TTree *backgroundDiBoson   = (TTree*)fBackgroundDiBoson->Get(tree);
 
  // here I choose the order in the stack
  std::vector<string> samples;
  samples.push_back("ggH115");
  samples.push_back("qqH115");
  samples.push_back("DiBoson");
  samples.push_back("SingleTop");
  samples.push_back("TTbar");
  samples.push_back("Wjets");
  samples.push_back("QCD");
  samples.push_back("ZfakeTau");
  samples.push_back("Ztautau");
  samples.push_back("Data");

  // here I define the map between a sample name and its tree
  std::map<std::string,TTree*> tMap;
  tMap["Data"]=data;
  tMap["ggH115"]=signalGGH;
  tMap["qqH115"]=signalVBF;
  tMap["Ztautau"]=backgroundDYTauTau;
  tMap["ZfakeTau"]=backgroundDYMuMu;
  tMap["Wjets"]=backgroundWJets;
  tMap["QCD"]=backgroundQCD;
  tMap["TTbar"]=backgroundTTbar;
  tMap["SingleTop"]=backgroundSingleTop;
  tMap["DiBoson"]=backgroundDiBoson;

  Float_t pt1, pt2, Deta, Mjj, eta1, eta2;
  Float_t diTauSVFitPt,diTauVisPt,diTauVisEta,diTauSVFitEta,diTauVisMass,diTauSVFitMass,ptL1,ptL2,etaL1,etaL2,diTauCharge,MtLeg1,numPV,combRelIsoLeg1DBeta,combRelIsoLeg1,pZetaCutVar, MEt, ptVeto, leadTrackPt, jetsBtagHE1, jetsBtagHE2;
  Float_t sampleWeight,puWeight;

  std::map<TString,Float_t> vMap;

  for( unsigned iter=0; iter<samples.size(); iter++){

    std::map<std::string,TTree*>::iterator it = tMap.find(samples[iter]);

    TString h1Name = "h1_"+it->first;
    TH1F* h1 = new TH1F( h1Name ,Form("CMS Preliminary 2011    #sqrt{s}=7 TeV L=%.0f pb^{-1}", Lumi) , nBins_ ,xMin_ , xMax_);

    TFile* dummy = new TFile("dummy.root","RECREATE");  
    TCut Cuts = Cuts_;
    TCut hlt = enableHLTmatching_ ? "( ((HLTmatch==2 && run<=163261) || (HLTmatch==1 && run>163261)) && ((HLTmu==1 && run<=163261) || (HLTx==1 && run>163261)) )" : "( ((HLTmu==1 && run<=163261) || (HLTx==1 && run>163261)) )";

    if((it->first).find("Data")!=string::npos) Cuts = Cuts_ && hlt;
    TTree* currentTree = (TTree*)(it->second)->CopyTree(Cuts);
    Int_t counter = 0;

    currentTree->SetBranchAddress( "pt1", &pt1 );
    currentTree->SetBranchAddress( "pt2", &pt2 );
    currentTree->SetBranchAddress( "Deta",&Deta );
    currentTree->SetBranchAddress( "Mjj", &Mjj );
    currentTree->SetBranchAddress( "diTauSVFitPt",&diTauSVFitPt);
    currentTree->SetBranchAddress( "diTauSVFitEta",&diTauSVFitEta);
    currentTree->SetBranchAddress( "diTauSVFitMass",&diTauSVFitMass);
    currentTree->SetBranchAddress( "diTauVisPt",&diTauVisPt);
    currentTree->SetBranchAddress( "diTauVisEta",&diTauVisEta);
    currentTree->SetBranchAddress( "diTauVisMass",&diTauVisMass);
    currentTree->SetBranchAddress( "ptL1",  &ptL1 );
    currentTree->SetBranchAddress( "ptL2",  &ptL2 );
    currentTree->SetBranchAddress( "etaL1", &etaL1 );
    currentTree->SetBranchAddress( "etaL2", &etaL2 );
    currentTree->SetBranchAddress( "combRelIsoLeg1DBeta",&combRelIsoLeg1DBeta);
    currentTree->SetBranchAddress( "combRelIsoLeg1",&combRelIsoLeg1);
    currentTree->SetBranchAddress( "diTauCharge",&diTauCharge);
    currentTree->SetBranchAddress( "MtLeg1",&MtLeg1);
    currentTree->SetBranchAddress( "pZetaCutVar",&pZetaCutVar);
    currentTree->SetBranchAddress( "numPV",&numPV);
    currentTree->SetBranchAddress( "sampleWeight",&sampleWeight);
    currentTree->SetBranchAddress( "puWeight",&puWeight);
    currentTree->SetBranchAddress( "ptVeto",&ptVeto);
    currentTree->SetBranchAddress( "MEt",&MEt);
    currentTree->SetBranchAddress( "leadTrackPt",&leadTrackPt);
    currentTree->SetBranchAddress( "jetsBtagHE1",&jetsBtagHE1);
    currentTree->SetBranchAddress( "jetsBtagHE2",&jetsBtagHE2);

    for (Long64_t ievt=0; ievt<currentTree->GetEntries();ievt++) {

      currentTree->GetEntry(ievt);

      if (ievt%10000 == 0){
	std::cout << (it->first) << " ---> processing event: " << ievt << " ..." <<std::endl;
      }

     
      vMap["diTauSVFitPt"]  = diTauSVFitPt;
      vMap["diTauSVFitEta"] = diTauSVFitEta;
      vMap["diTauSVFitMass"]= diTauSVFitMass;
      vMap["diTauVisPt"]    = diTauVisPt;
      vMap["diTauVisEta"]   = diTauVisEta;
      vMap["diTauVisMass"]  = diTauVisMass;
      vMap["ptL1"]  = ptL1;
      vMap["ptL2"]  = ptL2;
      vMap["etaL1"] = etaL1;
      vMap["etaL2"] = etaL2;
      vMap["diTauCharge"]= Float_t(diTauCharge);
      vMap["MtLeg1"]= MtLeg1;
      vMap["pZetaCutVar"] = pZetaCutVar;
      vMap["numPV"]= numPV;
      vMap["combRelIsoLeg1"]= combRelIsoLeg1;
      vMap["combRelIsoLeg1DBeta"]= combRelIsoLeg1DBeta;
      vMap["sampleWeight"]= sampleWeight;
      vMap["puWeight"]= puWeight;
      vMap["puWeight"]= puWeight;
      vMap["jetsBtagHE1"]= jetsBtagHE1;
      vMap["jetsBtagHE2"]= jetsBtagHE2;
      vMap["leadTrackPt"]= leadTrackPt;

      vMap["pt1"]= pt1;
      vMap["pt2"]= pt2;
      vMap["Deta"]= Deta;
      vMap["Mjj"]= Mjj;
      vMap["ptVeto"]= ptVeto;

      if((it->first).find("Data")==string::npos) sampleWeight*=(Lumi/1000*hltEff_*puWeight);

      counter++;
      h1->Fill( vMap[variable_], sampleWeight);
    
    }// end loop


    if( (it->first).find("ZfakeTau")!=string::npos ) {
      h1->SetFillColor(7);
      leg->AddEntry(h1,"Z+jets, fake-#tau","F");
    }
    if( (it->first).find("Ztautau")!=string::npos ) {
      h1->SetFillColor(kRed);
      leg->AddEntry(h1,"Z+jets, genuine-#tau","F");
    }
    if( (it->first).find("TTbar")!=string::npos ) {
      h1->SetFillColor(kBlue);
      leg->AddEntry(h1,"t#bar{t}+jets","F");
    }
    if( (it->first).find("SingleTop")!=string::npos ) {
      h1->SetFillColor(29);
      leg->AddEntry(h1,"single-t","F");
    }
    if( (it->first).find("Wjets")!=string::npos ) {
      h1->SetFillColor(kGreen);
      leg->AddEntry(h1,"W+jets","F");
    }
    if( (it->first).find("DiBoson")!=string::npos ) {
      h1->SetFillColor(38);
      leg->AddEntry(h1,"Di-Boson","F");
    }
    if( (it->first).find("QCD")!=string::npos ) {
      h1->SetFillColor(42);
      leg->AddEntry(h1,"QCD-multijets","F");
    }
    if((it->first).find("qqH115")!=string::npos){
      hSgn1 = (TH1F*)h1->Clone("hSgn1");
      hSgn1->Scale(magnifySgn_);
      hSgn1->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3004);
      h1->SetLineColor(kBlack);
      leg->AddEntry(h1,Form("VBF H(115) X %.0f",magnifySgn_),"F");
    }
    if((it->first).find("ggH115")!=string::npos){
      hSgn2 = (TH1F*)h1->Clone("hSgn2");
      hSgn2->Scale(magnifySgn_);
      hSgn2->SetLineWidth(2);
      h1->SetFillColor(kBlack);
      h1->SetFillStyle(3005);
      h1->SetLineColor(kBlack);
      leg->AddEntry(h1,Form("GGF H(115) X %.0f",magnifySgn_),"F");
    }
    if((it->first).find("Data")!=string::npos){
      hData = (TH1F*)h1->Clone("hData");
      hData->Sumw2();
      hData->SetMarkerStyle(20);
      hData->SetMarkerSize(1.2);
      hData->SetMarkerColor(kBlack);
      hData->SetLineColor(kBlack);
      hData->SetXTitle(XTitle_+" ("+Unities_+")");
      hData->SetYTitle(Form(" Events/(%.0f %s)", hData->GetBinWidth(1), Unities_.Data() ) );
      hData->SetTitleSize(0.04,"X");
      hData->SetTitleSize(0.05,"Y");
      hData->SetTitleOffset(0.95,"Y");
      leg->AddEntry(hData,"DATA","P");
    }

    if(iter==0) hSiml=(TH1F*)h1->Clone("hSiml");
    else if((it->first).find("Data")==string::npos) hSiml->Add(h1);

    if((it->first).find("Data")==string::npos) aStack->Add(h1);

    if(VERBOSE) cout<<(it->first) << " ==> " 
		   << h1->Integral() << " +/- " 
		   << TMath::Sqrt(h1->GetEntries())*(h1->Integral()/h1->GetEntries())
		   << endl;
  }

  // all signal summed together:
  hSgn = (TH1F*)hSgn1->Clone("hSgn");
  hSgn->Add(hSgn1,hSgn2,1,1);

  if(VERBOSE) cout<< "S/sqrt(B) ==> " 
		  << hSgn->Integral()/ TMath::Sqrt(hSiml->Integral()) << " +/- " 
		  << (1./2)*TMath::Sqrt(hSiml->GetEntries())*(hSiml->GetSumOfWeights())/hSiml->Integral()*( hSgn->Integral()/ TMath::Sqrt(hSiml->Integral())  )
		  << endl;

  hData->SetXTitle(XTitle_+" ("+Unities_+")");
  hData->SetYTitle(Form(" Events/(%.1f %s)", hData->GetBinWidth(1), Unities_.Data() ) );
  hData->SetTitleSize(0.04,"X");
  hData->SetTitleSize(0.05,"Y");
  hData->SetTitleOffset(0.95,"Y");

  hData->Draw("P");
  aStack->Draw("HISTSAME");
  hData->Draw("PSAME");
  //hSgn1->Draw("HISTSAME");
  //hSgn2->Draw("HISTSAME");

  TH1F* hStack = (TH1F*)aStack->GetHistogram();
  hStack->SetXTitle(XTitle_+" ("+Unities_+")");
  hStack->SetYTitle(Form(" Events/(%.0f %s)", hStack->GetBinWidth(1), Unities_.Data() ) );
  hStack->SetTitleSize(0.04,"X");
  hStack->SetTitleSize(0.05,"Y");
  hStack->SetTitleOffset(0.95,"Y");
  //aStack->GetYaxis()->SetRangeUser(0.0,std::max(hData->GetMaximum(),hStack->GetMaximum())*1.1);
  leg->Draw();


}