//--------------------------------------------------------------------------------------------------
// Get Total Number of Events in the sample
//--------------------------------------------------------------------------------------------------
Double_t getNormalizationWeight(TString filename, TString datasetName) {
  // Get Normalization Weight Factor

  //Get Number of Events in the Sample
  TFile *file = new TFile(filename.Data(),"READ");
  if (!file) {
    cout << "Could not open file " << filename << endl;
    return 0;
  }

  //TDirectory *dir = (TDirectory*)file->FindObjectAny("AnaFwkMod");
  //if (!dir) {
  //  cout << "Could not find directory AnaFwkMod"
  //       << " in file " << filename << endl;
  //  delete file;
  //  return 0;
  //}

  TH1D *hist = (TH1D*) gROOT->FindObject("hDAllEvents");
  if (!hist) {
    cout << "Could not find histogram hDAllEvents in directory AnaFwkMod"
         << " in file " << filename << endl;
    //delete dir;
    delete file;
    return 0;
  }
  Double_t NEvents = hist->Integral();
  cout << "Original events in the sample: " << NEvents << endl;

  //Get CrossSection
  mithep::SimpleTable xstab("$CMSSW_BASE/src/MitPhysics/data/xs.dat");
  Double_t CrossSection = xstab.Get(datasetName.Data());
  Double_t Weight = CrossSection / NEvents;
  // weight for data is always 1 (-1 to make a trick for fakes)
  if(CrossSection < 0) Weight = -1.0;

  // Only gg->H and qqH samples
  if(datasetName.Contains("-gf-") ||
     datasetName.Contains("-vbf-")){
    // Only high mass samples
    if(datasetName.Contains("h250") || datasetName.Contains("h300") || datasetName.Contains("h350") || datasetName.Contains("h400") || 
       datasetName.Contains("h450") || datasetName.Contains("h500") || datasetName.Contains("h550") || datasetName.Contains("h600") ||
       datasetName.Contains("h700") || datasetName.Contains("h800") || datasetName.Contains("h900") || datasetName.Contains("h1000")){
      TH1D *histBeforeWeight = (TH1D*) gROOT->FindObject("hDHKFactor_1");
      TH1D *histAfterWeight  = (TH1D*) gROOT->FindObject("hDHKFactor_2");
      cout << "Nevents before/after reweighting: " << histBeforeWeight->GetSumOfWeights() << " " << 
                                                      histAfterWeight->GetSumOfWeights() << endl;
      Weight = Weight * histBeforeWeight->GetSumOfWeights() / histAfterWeight->GetSumOfWeights();
    }
  }

  //delete dir;
  delete file;
  return Weight;

}
Пример #2
0
void NTupleSS() {
    double Lumi = 19700.;
    double signal_weight = 2.39163;//Lumi/(3263180./1177.3);
    double ttbar_weight  = Lumi / (4246440. / 23.64);
    double tautau_weight = Lumi / (3297032. / 1966.7);
    double tbarw_weight  = Lumi / (493460. / 11.1);
    double tw_weight     = Lumi / (497658. / 11.1);
    double ww_weight     = Lumi / (10000430. / 54.94);
    double wz_weight     = Lumi / (10000280. / 33.21);
    double zz_weight     = Lumi / (9799908. / 17.7);

    TH1D* Data = GetDataPhiStar();
    TH1D* h_ee    = GetBGPhiStar(File_Signal_reco,    signal_weight);
    TH1D* h_zz    = GetBGPhiStar(File_zz,    zz_weight);
    TH1D* h_tt    = GetBGPhiStar(File_tt,    ttbar_weight);
    TH1D* h_tautau = GetBGPhiStar(File_tautau, tautau_weight);
    TH1D* h_tbarw = GetBGPhiStar(File_tbarw, tbarw_weight);
    TH1D* h_tw    = GetBGPhiStar(File_tw,    tw_weight);
    TH1D* h_ww    = GetBGPhiStar(File_ww,    ww_weight);
    TH1D* h_wz    = GetBGPhiStar(File_wz,    wz_weight);
    //  TH1D* h_zz    =GetBGPhiStar(File_zz,    zz_weight);

    double data_sel = Data->GetSumOfWeights();
    double ee_sel = h_ee->GetSumOfWeights();
    double tt_sel = h_tt->GetSumOfWeights();
    double tautau_sel = h_tautau->GetSumOfWeights();
    double tbarw_sel = h_tbarw->GetSumOfWeights();
    double tw_sel = h_tw->GetSumOfWeights();
    double ww_sel = h_ww->GetSumOfWeights();
    double wz_sel = h_wz->GetSumOfWeights();
    double zz_sel = h_zz->GetSumOfWeights();

    // double t_bg=ee_sel+tt_sel+tautau_sel+tbarw_sel+tw_sel+ww_sel+wz_sel+zz_sel;
    double t_bg = ee_sel + tt_sel + tautau_sel + tbarw_sel + tw_sel + ww_sel +
                  wz_sel + zz_sel;
    cout << "total left:" << data_sel - t_bg;
    cout << "Data: " << data_sel << "  ee: " << ee_sel << "  tt: " << tt_sel <<
         "  tautau: " << tautau_sel << "  tbarw: " << tbarw_sel << "  tw: " << tw_sel <<
         " singletop: " << tbarw_sel + tw_sel << "  ww: " << ww_sel << "  wz: " << wz_sel
         << "  zz: " << zz_sel << endl;
    cout << "ratio:"          << "  ee: " << ee_sel / data_sel << "  tt: " << tt_sel
         / data_sel << "  tautau: " << tautau_sel / data_sel << "  tbarw: " << tbarw_sel
         / data_sel << "  tw: " << tw_sel / data_sel << " singletop: " <<
         (tbarw_sel + tw_sel) / data_sel << "  ww: " << ww_sel / data_sel << "  wz: " <<
         wz_sel / data_sel << "  zz: " << zz_sel / data_sel << "data: " <<
         (data_sel - t_bg) / data_sel << endl;

    TH1D* h_qcd  = (TH1D*)Data->Clone();
    h_qcd->Add(h_ee, -1.0);
    h_qcd->Add(h_tt, -1.0);
    h_qcd->Add(h_tautau, -1.0);
    h_qcd->Add(h_tbarw, -1.0);
    h_qcd->Add(h_tw, -1.0);
    h_qcd->Add(h_ww, -1.0);
    h_qcd->Add(h_wz, -1.0);
    h_qcd->Add(h_zz, -1.0);

    h_qcd->Draw();
    cout << "norm=" << h_qcd->GetSumOfWeights() << endl;;
}
Пример #3
0
double getweight(TFile *file, double xsec) {
 
  TDirectory *dir = (TDirectory*)file->FindObjectAny("AnaFwkMod");
  TH1D *hallevts = (TH1D*)dir->Get("hDTotalMCWeight");
  
  return xsec/hallevts->GetSumOfWeights();
  
}
Пример #4
0
void addn2() {

  // open existing f1:

  char* fn[99];
  int ni;

  // SR90 maps, mod D003

  ni = -1;
  ni++; fn[ni] = "SR90-map-00a.root";
  ni++; fn[ni] = "SR90-map-00b.root";
  ni++; fn[ni] = "SR90-map-01a.root";
  ni++; fn[ni] = "SR90-map-01b.root";
  ni++; fn[ni] = "SR90-map-02.root";
  ni++; fn[ni] = "SR90-map-03.root";
  ni++; fn[ni] = "SR90-map-05a.root";
  ni++; fn[ni] = "SR90-map-05b.root";
  ni++; fn[ni] = "SR90-map-07a.root";
  ni++; fn[ni] = "SR90-map-07b.root";
  ni++; fn[ni] = "SR90-map-07c.root";
  ni++; fn[ni] = "SR90-map-07d.root";

  // direct X-rays 9.4.2014 module D0003

  ni = -1;
  ni++; fn[ni] = "X-ray-20-modtd40000.root";
  ni++; fn[ni] = "X-ray-20-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-27-vthr60-modtd1000.root";
  ni++; fn[ni] = "X-ray-35-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-close-modtd65000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-0p1mA-modtd10000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-midpos-halfcur-modtd40000.root";
  ni++; fn[ni] = "X-ray-35-vthr60-modtd40000.root";

  int nmax = ni;

  TFile f1(fn[0]);

  if( f1.IsZombie() ) {
    cout << "Error opening " << fn[0] << endl;
    return;
  }
  cout << "opened " << fn[0] << endl;

  //--------------------------------------------------------------------
  // create f0:

  TFile f0("fileA.root", "RECREATE");
  cout << "created ";
  gDirectory->pwd();

  /*
  TFile options:  
  NEW or CREATE   create a new file and open it for writing,
                  if the file already exists the file is
                  not opened.
  RECREATE        create a new file, if the file already
                  exists it will be overwritten.
  UPDATE          open an existing file for writing.
                  if no file exists, it is created.
  READ            open an existing file for reading (default).
  NET             used by derived remote file access
                  classes, not a user callable option
  WEB             used by derived remote http access
                  class, not a user callable option
  "" (default), READ is assumed.
  */

  //--------------------------------------------------------------------
  // copy f1 to f0:

  f1.cd();

  cout << "keys:\n";
  f1.GetListOfKeys()->Print();

  cout << "pwd: ";
  f1.pwd();

  cout << "ls: \n";
  f1.ls();

  // f1 has sub-dir:

  cout << "First: " << f1.GetListOfKeys()->First()->GetName() << endl;
  cout << "First: " << f1.GetListOfKeys()->First()->ClassName() << endl;
  char* dir1 = f1.GetListOfKeys()->First()->GetName();
  cout << "cd to " << dir1 << endl;
  f1.cd( dir1 );
  cout << "we are in ";
  gDirectory->pwd();

  gDirectory->ReadAll(); // load histos

  TList * lst = gDirectory->GetList();
  cout << lst->GetName() << endl;
  cout << lst->GetTitle() << endl;
  cout << "size    " << lst->GetSize() << endl;
  cout << "entries " << lst->GetEntries() << endl;
  cout << "last    " << lst->LastIndex() << endl;

  TIterator *iter = lst->MakeIterator();
  int ii = 0;
  TObject *obj;
  TH1D *h;
  TH1D *h0;
  TH2D *H;
  TH2D *H0;

  while( obj = iter->Next() ){
    ii++;
    cout << setw(4) << ii << ": ";
    cout << obj->ClassName() << " ";
    cout << obj->InheritsFrom("TH1D") << " ";
    cout << obj->GetName() << " \"";
    cout << obj->GetTitle() << "\"";
    cout << endl;
    //    if( obj->ClassName() == "TH1D" ){
    if( obj->InheritsFrom("TH1D") ){
      h = (TH1D*) obj;
      cout << "       1D";
      cout << h->GetNbinsX() << " bins, ";
      cout << h->GetEntries() << " entries, ";
      cout << h->GetSumOfWeights() << " inside, ";
      cout << h->GetBinContent(0) << " under, ";
      cout << h->GetBinContent(h->GetNbinsX()+1) << " over";
      cout << endl;

      f0.cd(); // output file

      //      TH1D* h0 = (TH1D*) h->Clone();
      h0 = h; // copy
      h0->Write(); // write to file f0
      
      f1.cd(); // back to file 1 for the loop
    }
    else{

      if( obj->InheritsFrom("TH2D") ){

	H = (TH2D*) obj;
	cout << "       2D";
	cout << H->GetNbinsX() << " bins, ";
	cout << H->GetEntries() << " entries, ";
	cout << H->GetSumOfWeights() << " inside, ";
	cout << H->GetBinContent(0) << " under, ";
	cout << H->GetBinContent(H->GetNbinsX()+1) << " over";
	cout << endl;
	
	f0.cd(); // output file
	
	H0 = H; // copy
	H0->Write(); // write to file f0
	
	f1.cd(); // back to file 1 for the loop
      }
      else cout << "other class " << obj->ClassName() << endl;
    }
  }
  cout << "copied " << ii << endl;
  cout << "f1 " << f1.GetName() << " close = " << f1.Close() << endl;
    
  f0.cd();
  cout << "we are in ";
  gDirectory->pwd();

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " write = " << f0.Write() << endl;

  cout << "f0 " << f0.GetName() << " size  = " << f0.GetSize() << endl;

  cout << "f0 " << f0.GetName() << " close = " << f0.Close() << endl;

  f0.Delete();

  //--------------------------------------------------------------------
  // list of files 2:

  bool lAB = true;

  for( int nn = 1; nn <= nmax; ++nn ){

    cout << "\n\n";
    cout << "loop " << nn << ": fn = " << fn[nn] << endl;
    cout << "lAB = " << lAB << endl;

    if( lAB ) { // A+2 -> B
      char* fn3 = "fileA.root";
      char* fn4 = "fileB.root";
    }
    else{ // B+2 -> A
      char* fn3 = "fileB.root";
      char* fn4 = "fileA.root";
    }

    // create f4:

    TFile f4( fn4, "recreate" );
    if( f4.IsZombie() ) {
      cout << "Error creating f4\n";
      return;
    }
    cout << "created f4   = " << f4.GetName() << endl;

    // re-open as f3:

    TFile f3( fn3 );
    if( f3.IsZombie() ) {
      cout << "Error opening f3\n";
      return;
    }
    cout << "re-opened f3 = " << f3.GetName() << endl;

    lAB = !lAB;
    cout << "lAB = " << lAB << " for next loop\n";

    cout << "f4 = " << f4.GetName() << endl;
    cout << "f3 = " << f3.GetName() << endl;

    f3.cd();
    gDirectory->ReadAll(); // load histos into f3 memory

    //    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;
    cout << "f3 list size = " << gDirectory->GetList()->GetSize() << endl;

    TFile f2(fn[nn]);
    //    TFile *f2 = new TFile(fn[nn]);

    if( f2.IsZombie() ) {
    //    if( f2 == NULL ) {
      cout << "Error opening " << fn[nn] << endl;
      return;
    }
    cout << "opened " << fn[nn] << endl;

    // f2 has sub-dir:

    f2.cd( f2.GetListOfKeys()->First()->GetName() );
    cout << "we are in ";
    gDirectory->pwd();

    gDirectory->ReadAll(); // load histos into f2 memory

    // loop over f2:

    cout << "f2 list size = " << gDirectory->GetList()->GetSize() << endl;

    int jj = 0;
    TObject *ob2;
    TH1D *h2;
    TH1D *h3;
    TH2D *H2;
    TH2D *H3;

    TIterator *ite2 = gDirectory->GetList()->MakeIterator();

    while( ob2 = ite2->Next() ){

      jj++;

      //      if( jj > 9 ) continue;

      cout << jj << ". ";
      cout << "ob2 is ";
      cout << ob2->GetName() << " ";
      cout << ob2->ClassName() << " ";
      cout << ob2->GetTitle();
      cout << endl;

      if( ob2->InheritsFrom("TH1D") ) {

	h2 = (TH1D*) ob2;
	cout << "h2 " << h2->GetName() << "  " << h2->GetNbinsX() << " bins\n";
	cout << "h2 " << h2->GetName() << "  " << h2->GetEntries() << " entries\n";
	char* hnm2 = h2->GetName();

	// search in f3:

	cout << "search for " << hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	h3 = (TH1D*) gDirectory->GetList()->FindObject(hnm2);
	if( h3 == NULL ) {
	  cout << "h3 is null\n" ;
	  continue;
	}
	
	cout << "found h3 = ";
	cout << h3->GetName() << "  ";
	cout << h3->ClassName() << "  ";
	cout << h3->GetTitle();
	cout << endl;
	cout << "h3  " << h3->GetName() << "  " << h3->GetNbinsX() << " bins\n";
	cout << "h3  " << h3->GetName() << "  " << h3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();
	//TH1D h4 = *h3 + *h2;
	TH1D* h4 = (TH1D*) h3->Clone();
	h4->Add(h2);
	
	cout << "h4  " << h4->GetEntries() << " entries\n";
	cout << "h4  ";
	cout << h4->GetName() << " ";
	cout << h4->ClassName() << " ";
	cout << h4->GetTitle();
	cout << endl;
	cout << "h4 dir " << h4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );

      }//1D

      if( ob2->InheritsFrom("TH2D") ) {

	H2 = (TH2D*) ob2;
	cout << "H2 " << H2->GetName() << "  " << H2->GetNbinsX() << " bins\n";
	cout << "H2 " << H2->GetName() << "  " << H2->GetEntries() << " entries\n";
	char* Hnm2 = H2->GetName();

	// search in f3:

	cout << "search for " << Hnm2 << " in f3\n";
	f3.cd();
	cout << "we are in ";
	gDirectory->pwd();
	
	H3 = (TH2D*) gDirectory->GetList()->FindObject(Hnm2);
	if( H3 == NULL ) {
	  cout << "H3 is null\n" ;
	  continue;
	}
	
	cout << "found H3 = ";
	cout << H3->GetName() << "  ";
	cout << H3->ClassName() << "  ";
	cout << H3->GetTitle();
	cout << endl;
	cout << "H3  " << H3->GetName() << "  " << H3->GetNbinsX() << " bins\n";
	cout << "H3  " << H3->GetName() << "  " << H3->GetEntries() << " entries\n";

	// add:

	f4.cd();
	cout << "we are in ";
	gDirectory->pwd();

	TH2D* H4 = (TH2D*) H3->Clone();
	H4->Add(H2);
	
	cout << "H4  " << H4->GetEntries() << " entries\n";
	cout << "H4  ";
	cout << H4->GetName() << " ";
	cout << H4->ClassName() << " ";
	cout << H4->GetTitle();
	cout << endl;
	cout << "H4 dir " << H4->GetDirectory()->GetName() << endl;
	cout << "f4 size " << f4.GetSize() << endl;

	// back to f2 for next iter:

	f2.cd( f2.GetListOfKeys()->First()->GetName() );
      }//2D

    } //while

    cout << "processed " << jj << endl;
    cout << "f4 " << f4.GetName() << " size " << f4.GetSize() << endl;

    //  cout << "f4 map:\n";
    //  f4.Map();

    cout << "f4 " << f4.GetName() << " write = " << f4.Write() << endl;

    cout << "f4 " << f4.GetName() << " size  = " << f4.GetSize() << endl;
    
  }// loop over files 2

  cout << endl;
  cout << "combined " << nmax + 1 << " files\n";
  cout << "Final file is " << f4.GetName() << endl;

  f2.Close();
  f3.Close();
  f4.Close();

}
Пример #5
0
void compIsol(int varnum)
{
  TString varname, vartitle;
  if(varnum==1) {
    varname="hHEIsoPt";
    vartitle="H/E Isolation";
  }
  if(varnum==2) {
    varname="hHcalIsoPt";
    vartitle="HCAL Isolation";
  }
  if(varnum==3) {
    varname="hEcalIsoPt";
    vartitle="ECAL Isolation";
  }
  if(varnum==4) {
    varname="hTrkIsoPt";
    vartitle="Track Isolation";
  }
  if(varnum==5) {
    varname="hJetEt";
    vartitle="Jet E_{T} [GeV]";
  }
  if(varnum==6) {
    varname="hNJets";
    vartitle="Number of Jets";
  }
  
  
  TH1D* hBorn;
  TH1D* hADD;
  if(varnum<=4) {
    TH2D* hBorn2d = dynamic_cast<TH2D*>(GetPlot(1, varname));
    TH2D* hADD2d = dynamic_cast<TH2D*>(GetPlot(3, varname));
    hBorn = hBorn2d->ProjectionX(varname+"born");
    hADD = hADD2d->ProjectionX(varname+"add");
    cout << "asdf" << endl;
  } else {
    hBorn = dynamic_cast<TH1D*>(GetPlot(1, varname));
    hADD = dynamic_cast<TH1D*>(GetPlot(3, varname));
  }
  
  hBorn->Scale(1/hBorn->GetSumOfWeights());
  hADD->Scale(1/hADD->GetSumOfWeights());

  hBorn->SetLineColor(kBlue+2);
  hADD->SetLineColor(kCyan+4);
  hBorn->SetFillColor(0);
  hADD->SetFillColor(0);
  hBorn->SetLineStyle(1);
  hADD->SetLineStyle(2);
  
  //  hBorn->SetStats(0);
  //  hADD->SetStats(0);

  gPad->SetLogy(1);
  
  hBorn->GetXaxis()->SetTitle(vartitle);
  hBorn->GetYaxis()->SetTitle("Normalized Units");
  hBorn->SetTitle("Leading Photons in Pythia/Sherpa Samples");

  hBorn->Draw();
  hADD->Draw("sames");

  hBorn->SetMaximum(1);

  gPad->Update();
  TPaveStats *st1=(TPaveStats*)hBorn->GetListOfFunctions()->FindObject("stats");
  TPaveStats *st2=(TPaveStats*)hADD->GetListOfFunctions()->FindObject("stats");
  st1->SetName("Born");
  st2->SetName("ADD");
  st1->SetOptStat(101100);
  st2->SetOptStat(101100);
  st1->SetX1NDC(.25);
  st1->SetX2NDC(.55);
  st1->SetY1NDC(.56);
  st1->SetY2NDC(.80);
  st2->SetX1NDC(.56);
  st2->SetX2NDC(.86);
  st2->SetY1NDC(.56);
  st2->SetY2NDC(.80);

  TLegend* leg=new TLegend(.25,.78,.55,.85);
  leg->AddEntry(hBorn, "Pythia (Born)", "l");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetTextSize(0.045);
  leg->Draw();

  TLegend* leg=new TLegend(.56,.78,.86,.85);
  leg->AddEntry(hADD, "Sherpa (ADD)", "l");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetTextSize(0.045);
  leg->Draw();

  gPad->Update();
  

  return;
}
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 applyGoodRunSelection = cfg.get<bool>("ApplyGoodRunSelection");

	// pile up reweighting
	const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");

	//const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");
	const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");

	// 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 double etaMuonCut     = cfg.get<double>("etaMuonCut");
	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

	// trigger
	const bool applyTrigger = cfg.get<bool>("ApplyTrigger");
	const string muonTriggerName  = cfg.get<string>("MuonTriggerName");
	const string muonFilterName   = cfg.get<string>("MuonFilterName");
	const string muon17FilterName = cfg.get<string>("Muon17FilterName"); 
	const string muon8FilterName = cfg.get<string>("Muon8FilterName"); 
	const string singleMuonFilterName = cfg.get<string>("SingleMuonFilterName");
	const float singleMuonTriggerPtCut = cfg.get<float>("SingleMuonTriggerPtCut");
	const float singleMuonTriggerEtaCut = cfg.get<float>("SingleMuonTriggerEtaCut");


	TString MuonTriggerName(muonTriggerName);
	TString MuonFilterName(muonFilterName);

	TString Muon17FilterName(muon17FilterName);
	TString Muon8FilterName(muon8FilterName);
	TString SingleMuonFilterName(singleMuonFilterName);

	const double leadchargedhadrcand_dz = cfg.get<double>("leadchargedhadrcand_dz");
	const double leadchargedhadrcand_dxy = cfg.get<double>("leadchargedhadrcand_dxy");

	const double etaJetCut   = cfg.get<double>("etaJetCut");
	const double ptJetCut   = cfg.get<double>("ptJetCut");


	// topological cuts
	const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
	const float dPhileptonsCut = cfg.get<float>("dPhileptonsCut");
	const float DRTrigMatch    = cfg.get<float>("DRTrigMatch"); 
	const double dRleptonsCutmutau   = cfg.get<double>("dRleptonsCutmutau");
	const double dZetaCut       = cfg.get<double>("dZetaCut");
	const double deltaRTrigMatch = cfg.get<double>("DRTrigMatch");
	const bool oppositeSign    = cfg.get<bool>("oppositeSign");
	const bool isIsoR03 = cfg.get<bool>("IsIsoR03");

	// tau
	const double taupt    = cfg.get<double>("taupt");
	const double taueta    = cfg.get<double>("taueta");
	const double decayModeFinding    = cfg.get<double>("decayModeFinding");
	const double   decayModeFindingNewDMs  = cfg.get<double>("decayModeFindingNewDMs");
	const double   againstElectronVLooseMVA5  = cfg.get<double>("againstElectronVLooseMVA5");
	const double   againstMuonTight3  = cfg.get<double>("againstMuonTight3");
	const double   vertexz =  cfg.get<double>("vertexz");
	const double   byCombinedIsolationDeltaBetaCorrRaw3Hits = cfg.get<double>("byCombinedIsolationDeltaBetaCorrRaw3Hits");




	// 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");

	// lepton scale factors
	const string muonSfDataBarrel = cfg.get<string>("MuonSfDataBarrel");
	const string muonSfDataEndcap = cfg.get<string>("MuonSfDataEndcap");
	const string muonSfMcBarrel = cfg.get<string>("MuonSfMcBarrel");
	const string muonSfMcEndcap = cfg.get<string>("MuonSfMcEndcap");

	const string jsonFile = cfg.get<string>("jsonFile");
	string TrigLeg  ;
	if (!isData) TrigLeg  = cfg.get<string>("Mu17LegMC");
	if (isData) TrigLeg  = cfg.get<string>("Mu18LegData");
  	const string Region  = cfg.get<string>("Region");
  	const string Sign  = cfg.get<string>("Sign");
	
	TString MainTrigger(TrigLeg);
	// **** end of configuration

	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();
		}
	}
	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+"_"+Region+"_"+Sign);
	std::cout <<TStrName <<std::endl;  
  	datasetName = rootFileName.c_str();

	TFile * file ;//= new TFile(era+"/"+TStrName+TString(".root"),"update");
  	if (isData) file = new TFile(era+"/"+TStrName+TString("_DataDriven.root"),"update");
  	if (!isData) file = new TFile(era+"/"+TStrName+TString(".root"),"update");
	file->cd("");
	/*
	// file name and tree name
	std::string rootFileName(argv[2]);
	std::ifstream fileList(argv[2]);
	std::ifstream fileList0(argv[2]);
	std::string ntupleName("makeroottree/AC1B");

	TString TStrName(rootFileName);
	TString era=argv[3];
	std::cout <<TStrName <<std::endl;  

	TFile * file = new TFile(TStrName+TString(".root"),"recreate");
	file->cd("");
	*/
	std::string initNtupleName("initroottree/AC1B");
	TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
	TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);
	TH1D * histWeightsSkimmedH = new TH1D("histWeightsSkimmedH","",1,-0.5,0.5);

	// Histograms after selecting unique dimuon pair
	TH1D * massSelH = new TH1D("massSelH","",200,0,200);
	TH1D * metSelH  = new TH1D("metSelH","",200,0,400);

	TH1D * hDiJetmet = new TH1D("hDiJetmet","",200,0,400);
	TH1D * hDiJetmass = new TH1D("hDiJetmass","",500,0,1000);
	TH1D * hHT_ = new TH1D("hHT_","",800,0,1600);
	TH1D * metAll  = new TH1D("metAll","",200,0,400);

	TH1D * muon1PtH = new TH1D("muon1PtH","",200,0,400);
	TH1D * muon2PtH = new TH1D("muon2PtH","",200,0,400);

	TH1F * NumberOfVerticesH = new TH1F("NumberOfVerticesH","",51,-0.5,50.5);


	//*****  create eta histogram with eta ranges associated to their names (eg. endcap, barrel)   ***** //

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


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

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

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


	PileUp * PUofficial = new PileUp();

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


	TFile *f10= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataBarrel);  // mu SF barrel data
	TFile *f11 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataEndcap); // mu SF endcap data
	TFile *f12= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcBarrel);  // mu SF barrel MC
	TFile *f13 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcEndcap); // mu SF endcap MC 

	TGraphAsymmErrors *hEffBarrelData = (TGraphAsymmErrors*)f10->Get("ZMassBarrel");
	TGraphAsymmErrors *hEffEndcapData = (TGraphAsymmErrors*)f11->Get("ZMassEndcap");
	TGraphAsymmErrors *hEffBarrelMC = (TGraphAsymmErrors*)f12->Get("ZMassBarrel");
	TGraphAsymmErrors *hEffEndcapMC = (TGraphAsymmErrors*)f13->Get("ZMassEndcap");

	double * dataEffBarrel = new double[10];
	double * dataEffEndcap = new double[10];
	double * mcEffBarrel = new double[10];
	double * mcEffEndcap = new double[10];

	dataEffBarrel = hEffBarrelData->GetY();
	dataEffEndcap = hEffEndcapData->GetY();
	mcEffBarrel = hEffBarrelMC->GetY();
	mcEffEndcap = hEffEndcapMC->GetY();
	double Weight=0;
	int nTotalFiles = 0;
	int nominator=-1;int denominator = -1;


	file->cd();
	TH1D * hMT = new TH1D("hMT","",20,0,200);
	TH1D * hMass = new TH1D("hMass","",20,0,200);
	TH1D * hRatioSum = new TH1D("hRatioSum","",10,0,1);
	TH1D * hDPhi = new TH1D("hDPhi","",70,0,3.5);

	int nPtBins = 3;
	//float ptBins[6] = {19,25,30,40,60,1000};
	float ptBins[4] = {19,25,40,1000};


/*
	TString PtBins[5] = {"Pt19to25",
		"Pt25to30",
		"Pt30to40",
		"Pt40to60",
		"PtGt60"};//,		       "Pt100to150",		       "Pt150to200",		        "PtGt200"};
*/
	TString PtBins[3] = {"Pt19to25",
		"Pt25to40",
		"PtGt40"};//,		       "Pt100to150",		       "Pt150to200",		        "PtGt200"};


//int nEtaBins = 3;
int nEtaBins = 1;
int nCuts = 4;
//float etaBins[4] = {0,0.9,1.2,2.4}; 
//float etaBins[3] = {0,1.48,2.4}; 
float etaBins[2] = {0,2.4}; 

TString EtaBins[1] = {
	//"EtaLt0p9",
	//"Eta0p9to1p2",
	//"EtaGt1p2"};
	"EtaLt2p4"};

TString Cuts[4] = {"Ratio","mT","DPhi","All"};
/////first stands for the Eta bin, second array for the cut 
TH1D * FakeRatePtIncLoose[1][4];
TH1D * FakeRatePtIncTight[2][4];


//TH1D * FakeRatePt[3][7];
//TH1D * FakeRateNV[3][7];
//TH1D * FakeRateEta[3][7];


TH1D * etaBinsH = new TH1D("etaBinsH", "etaBinsH", nEtaBins, etaBins);
etaBinsH->Draw();
etaBinsH->GetXaxis()->Set(nEtaBins, etaBins);
for (int i=0; i<nEtaBins; i++){ etaBinsH->GetXaxis()->SetBinLabel(i+1, EtaBins[i]);}


for (int iEta=0; iEta<nEtaBins; ++iEta) {
	for (int iCut=0; iCut<nCuts; ++iCut) {
		FakeRatePtIncLoose[iEta][iCut] = new TH1D("FakeRatePtIncLoose"+EtaBins[iEta]+Cuts[iCut],"",nPtBins,ptBins);
		FakeRatePtIncTight[iEta][iCut] = new TH1D("FakeRatePtIncTight"+EtaBins[iEta]+Cuts[iCut],"",nPtBins,ptBins);

	}

	//for (int iPt=0; iPt<nPtBins; ++iPt) {
	//  FakeRatePt[iEta][iPt] = new TH1D("FakeRatePt"+EtaBins[iEta]+PtBins[iPt],"",100,0,1000);
	//  FakeRateNV[iEta][iPt] = new TH1D("FakeRateNV"+EtaBins[iEta]+PtBins[iPt],"",50,0,50);
	//  FakeRateEta[iEta][iPt] = new TH1D("FakeRateEta"+EtaBins[iEta]+PtBins[iPt],"",80,-4,4);
	// }

}





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


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

unsigned int RunMin = 9999999;
unsigned int RunMax = 0;
  ifstream ifs("xsecs");
  string line;

  while(std::getline(ifs, line)) // read one line from ifs
    {

      fact=fact2=1;
      istringstream iss(line); // access line as a stream

      // we only need the first two columns
      string dt,st1,st2;st1="stau2_1";st2="stau5_2";
      iss >> dt >> xs >> fact >> fact2;
      //datasetName = dt.c_str();
      //ifs >> dt >> xs; // no need to read further
      //cout<< " "<<dt<<"  "<<endl;
      //cout<< "For sample ========================"<<dt<<" xsecs is "<<xs<<" XSec "<<XSec<<"  "<<fact<<"  "<<fact2<<endl;
      //if (dt==argv[2]) {
      //if (std::string::npos != dt.find(argv[2])) {
      if (  dt == argv[2]) {
	XSec= xs*fact*fact2;
	cout<<" Found the correct cross section "<<xs<<" for Dataset "<<dt<<" XSec "<<XSec<<endl;
      }
      /*
	if ( argv[2] == st1) {ChiMass=100;mIntermediate=200;}
	else if (argv[2] == st2) {ChiMass=200;mIntermediate=500;}
      */
      if (isData) XSec=1.;
      ChiMass=0.0;
    }

  if (XSec<0&& !isData) {cout<<" Something probably wrong with the xsecs...please check  - the input was "<<argv[2]<<endl;return 0;}
	
  xsecs=XSec;

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::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();
//----Attention----//
//if(XSec!=1) nTotalFiles=20;
//nTotalFiles=5;

if (argv[4] != NULL  && atoi(argv[4])< nTotalFiles) nTotalFiles=atoi(argv[4]);

cout<<" There are in total "<<nTotalFiles<<endl;
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 //
	for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) { 

		analysisTree.GetEntry(iEntry);
		nEvents++;

		if (nEvents%50000==0) 
			cout << "      processed " << nEvents << " events" << endl; 

		float weight = 1;

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

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

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

		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) {

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

			}
/*
			if (applyTauTauSelection) {
				unsigned int nTaus = 0;
				if (analysisTree.gentau_count>0) {
					//	  cout << "Generated taus present" << endl;
					for (unsigned int itau = 0; itau < analysisTree.gentau_count; ++itau) {
						//	    cout << itau << "  : pt = " 
						//		 << analysisTree.gentau_visible_pt[itau] 
						//		 << "   eta = " <<  analysisTree.gentau_visible_eta[itau]
						//		 << "   mother = " << int(analysisTree.gentau_mother[itau]) << endl;
						if (int(analysisTree.gentau_mother[itau])==3) nTaus++;

					}
				}
				bool notTauTau = nTaus < 2;
				//	  std::cout << "nTaus = " << nTaus << std::endl;

				if (selectZToTauTauMuMu&&notTauTau) { 
					//	    std::cout << "Skipping event..." << std::endl;
					//	    cout << endl;
					continue;
				}
				if (!selectZToTauTauMuMu&&!notTauTau) { 
					//	    std::cout << "Skipping event..." << std::endl;
					//	    cout << endl;
					continue;
				}
				//	  cout << endl;
			}*/
		}

		if (isData && applyGoodRunSelection){


			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) 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;
			//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
			//std::remove("myinputfile");
		}     
		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);
			unsigned int nMainTrigger = 0;
			bool isMainTrigger = false;

		unsigned int nMuonFilter = 0;

			unsigned int nfilters = analysisTree.run_hltfilters->size();
			//  std::cout << "nfiltres = " << nfilters << std::endl;
			for (unsigned int i=0; i<nfilters; ++i) {
				//	std::cout << "HLT Filter : " << i << " = " << analysisTree.run_hltfilters->at(i) << std::endl;
				TString HLTFilter(analysisTree.run_hltfilters->at(i));
				if (HLTFilter==MainTrigger) {
					nMainTrigger = i;
					isMainTrigger = true;
					nMuonFilter = i;
				}



			}

			if (!isMainTrigger) {
				std::cout << "Fail on main HLT Filter " << MainTrigger << " not found" << std::endl;
				return(-1);
			}



/*

		bool isTriggerMuon = false;
		for (std::map<string,int>::iterator it=analysisTree.hltriggerresults->begin(); it!=analysisTree.hltriggerresults->end(); ++it) {
			TString trigName(it->first);
			if (trigName.Contains(MuonTriggerName)) {
				//	  std::cout << it->first << " : " << it->second << std::endl;
				if (it->second==1)
					isTriggerMuon = true;
			}
		}

		if (applyTrigger && !isTriggerMuon) continue;

		unsigned int nMuonFilter = 0;
		bool isMuonFilter = false;

		unsigned int nMuon17Filter = 0;
		bool isMuon17Filter = false;

		unsigned int nMuon8Filter = 0;
		bool isMuon8Filter = false;

		unsigned int nSingleMuonFilter = 0;
		bool isSingleMuonFilter = false;

		unsigned int nfilters = analysisTree.run_hltfilters->size();
		for (unsigned int i=0; i<nfilters; ++i) {
			TString HLTFilter(analysisTree.run_hltfilters->at(i));
			if (HLTFilter==MuonFilterName) {
				nMuonFilter = i;
				isMuonFilter = true;
			}
			if (HLTFilter==Muon17FilterName) {
				nMuon17Filter = i;
				isMuon17Filter = true;
			}
			if (HLTFilter==Muon8FilterName) {
				nMuon8Filter = i;
				isMuon8Filter = true;
			}
			if (HLTFilter==SingleMuonFilterName) {
				nSingleMuonFilter = i;
				isSingleMuonFilter = true;
			}
		}
		if (!isMuonFilter) {
			cout << "Filter " << MuonFilterName << " not found " << endl;
			exit(-1);
		}
		if (!isMuon17Filter) {
			cout << "Filter " << Muon17FilterName << " not found " << endl;
			exit(-1);
		}
		if (!isMuon8Filter) {
			cout << "Filter " << Muon8FilterName << " not found " << endl;
			exit(-1);
		}
		if (!isSingleMuonFilter) {
			cout << "Filter " << SingleMuonFilterName << " not found " << endl;
			exit(-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;

		// muon selection

		vector<unsigned int> allMuons; allMuons.clear();
		vector<unsigned int> idMuons; idMuons.clear();
		vector<unsigned int> isoMuons; isoMuons.clear();
		vector<float> isoMuonsValue; isoMuonsValue.clear();
		vector<bool> isMuonPassedIdIso; isMuonPassedIdIso.clear();
		vector<bool> isMuonMatched23Filter; isMuonMatched23Filter.clear();
		vector<bool> isMuonMatched17Filter; isMuonMatched17Filter.clear();
		vector<bool> isMuonMatched8Filter; isMuonMatched8Filter.clear();
		vector<bool> isMuonMatchedSingleMuFilter; isMuonMatchedSingleMuFilter.clear();

		for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
			allMuons.push_back(im);
			bool muPassed    = true;
			bool mu23Matched = false;
			bool mu17Matched = false;
			bool mu8Matched  = false;
			bool muSingleMatched = false;
			if (analysisTree.muon_pt[im]<5) muPassed = false;
			if (fabs(analysisTree.muon_eta[im])>etaMuonLowCut) muPassed = false;
			if (fabs(analysisTree.muon_dxy[im])>dxyMuonCut) muPassed = false;
			if (fabs(analysisTree.muon_dz[im])>dzMuonCut) muPassed = false;
			if (!analysisTree.muon_isMedium[im]) muPassed = false;
			if (muPassed) idMuons.push_back(im);
			float absIso = analysisTree.muon_r03_sumChargedHadronPt[im];
			float neutralIso = analysisTree.muon_r03_sumNeutralHadronEt[im] + 
				analysisTree.muon_r03_sumPhotonEt[im] - 
				0.5*analysisTree.muon_r03_sumPUPt[im];
			neutralIso = TMath::Max(float(0),neutralIso); 
			absIso += neutralIso;
			float relIso = absIso/analysisTree.muon_pt[im];
			if (relIso>isoMuonCut) muPassed = false;
			if (muPassed && analysisTree.muon_pt[im]>ptMuonLowCut) { 
				isoMuons.push_back(im);
				isoMuonsValue.push_back(relIso);
			}

			isMuonPassedIdIso.push_back(muPassed);


			for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
				if (analysisTree.trigobject_filters[iT][nMainTrigger]) { // Mu17 Leg
					double dRtrig = deltaR(analysisTree.muon_eta[im],analysisTree.muon_phi[im],
							analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
					if (dRtrig>deltaRTrigMatch) continue;
					//if (!isData && analysisTree.trigobject_filters[iT][nMainTrigger] && analysisTree.trigobject_pt[iT]>18) 
					isMainTrigger = true;

				}
			}

			if (!isMainTrigger) continue;


/*
			//	cout << "pt:" << analysisTree.muon_pt[im] << "  passed:" << muPassed << endl;
			for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
				float dRtrig = deltaR(analysisTree.muon_eta[im],analysisTree.muon_phi[im],
						analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
				if (dRtrig>DRTrigMatch) continue;
				if (analysisTree.trigobject_filters[iT][nMuon17Filter] && analysisTree.trigobject_pt[iT]>23.0) 
					mu23Matched = true;
				if (analysisTree.trigobject_filters[iT][nMuon17Filter] && analysisTree.trigobject_pt[iT]>17.0)
					mu17Matched = true;
				if (analysisTree.trigobject_filters[iT][nSingleMuonFilter] && analysisTree.trigobject_pt[iT]>singleMuonTriggerPtCut)
					muSingleMatched = true;
				if (analysisTree.trigobject_filters[iT][nMuon8Filter] && analysisTree.trigobject_pt[iT]>8.0) 
					mu8Matched = true;

			}
			isMuonMatched23Filter.push_back(mu23Matched);
			isMuonMatched17Filter.push_back(mu17Matched);
			isMuonMatched8Filter.push_back(mu8Matched);
			isMuonMatchedSingleMuFilter.push_back(muSingleMatched);*/
		}


		unsigned int indx1 = 0;
		unsigned int indx2 = 0;
		bool isIsoMuonsPair = false;
		float isoMin = 9999;
		if (isoMuons.size()>0) {
			for (unsigned int im1=0; im1<isoMuons.size(); ++im1) {
				unsigned int index1 = isoMuons[im1];
				bool isMu1matched = false;
				for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
					float dRtrig = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
							analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
					if (dRtrig>DRTrigMatch) continue;
					if (analysisTree.trigobject_filters[iT][nMainTrigger] && 
							analysisTree.muon_pt[index1] > ptMuonHighCut &&
							fabs(analysisTree.muon_eta[index1]) < etaMuonHighCut) 
						isMu1matched = true;
				}
				if (isMu1matched) {
					for (unsigned int iMu=0; iMu<allMuons.size(); ++iMu) {
						unsigned int indexProbe = allMuons[iMu];
						if (index1==indexProbe) continue;
						float q1 = analysisTree.muon_charge[index1];
						float q2 = analysisTree.muon_charge[indexProbe];
						if (q1*q2>0) continue;
						float dR = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
								analysisTree.muon_eta[indexProbe],analysisTree.muon_phi[indexProbe]);
						if (dR<dRleptonsCut) continue; 
						float dPhi = dPhiFrom2P(analysisTree.muon_px[index1],analysisTree.muon_py[index1],
								analysisTree.muon_px[indexProbe],analysisTree.muon_py[indexProbe]);
						if (dPhi>dPhileptonsCut) continue;
						TLorentzVector muon1; muon1.SetXYZM(analysisTree.muon_px[index1],
								analysisTree.muon_py[index1],
								analysisTree.muon_pz[index1],
								muonMass);
						TLorentzVector muon2; muon2.SetXYZM(analysisTree.muon_px[indexProbe],
								analysisTree.muon_py[indexProbe],
								analysisTree.muon_pz[indexProbe],
								muonMass);


						float mass = (muon1+muon2).M();
					}
				}
				for (unsigned int im2=im1+1; im2<isoMuons.size(); ++im2) {
					unsigned int index2 = isoMuons[im2];
					float q1 = analysisTree.muon_charge[index1];
					float q2 = analysisTree.muon_charge[index2];
					bool isMu2matched = false;
					for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
						float dRtrig = deltaR(analysisTree.muon_eta[index2],analysisTree.muon_phi[index2],
								analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
						if (dRtrig>DRTrigMatch) continue;
						if (analysisTree.trigobject_filters[iT][nMainTrigger] && 
								analysisTree.muon_pt[index2] > ptMuonHighCut &&
								fabs(analysisTree.muon_eta[index2]) < etaMuonHighCut) 
							isMu2matched = true;
					}
					bool isPairSelected = q1*q2 > 0;
					if (oppositeSign) isPairSelected = q1*q2 < 0;
					bool isTriggerMatch = (isMu1matched || isMu2matched);
					float dRmumu = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
							analysisTree.muon_eta[index2],analysisTree.muon_phi[index2]);
					if (isTriggerMatch && isPairSelected && dRmumu>dRleptonsCut) {
						bool sumIso = isoMuonsValue[im1]+isoMuonsValue[im2];
						if (sumIso<isoMin) {
							isIsoMuonsPair = true;
							isoMin = sumIso;
							if (analysisTree.muon_pt[index1]>analysisTree.muon_pt[index2]) {
								indx1 = index1;
								indx2 = index2;
							}
							else {
								indx2 = index1;
								indx1 = index2;
							}
						}
					}
				}
			}
		}
		if (isIsoMuonsPair) {      
			//match to genparticles

			double isoTauMin = 999;
			bool tau_iso = false;
			bool isTight = false;
			bool isLoose = false;
			unsigned tau_loose=-1;
			vector<int> tau; tau.clear();


			for (unsigned  int it = 0; it<analysisTree.tau_count; ++it) {

				if (analysisTree.tau_pt[it] < ptMuonLowCut || fabs(analysisTree.tau_eta[it])> etaMuonCut) continue;
				if (analysisTree.tau_decayModeFindingNewDMs[it]<decayModeFindingNewDMs) continue;
				if ( fabs(analysisTree.tau_leadchargedhadrcand_dz[it])> leadchargedhadrcand_dz) continue;
				double  tauIso = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it];

				isLoose  = true;
				tau_loose = int(it);

				if (analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits [it]> 0.5  && analysisTree.tau_againstElectronVLooseMVA5[it]>againstElectronVLooseMVA5 
						&& analysisTree.tau_againstMuonTight3[it]>againstMuonTight3) {isTight = true;	  tau_tight = int(it);}




			}


			if (!isLoose) continue;
			TLorentzVector JetsV;

			JetsMV.clear();
			int countjets=0;
			for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
				float absJetEta = fabs(analysisTree.pfjet_eta[jet]);

				if (analysisTree.pfjet_pt[jet] < 19) continue;
				if (absJetEta > etaJetCut) continue;
				//if (fabs(analysisTree.pfjet_pt[jet])<ptJetCut) continue;
				bool  looseJetID = looseJetiD(analysisTree,jet);
				if (!looseJetID) continue;	  

				double dRmuJet1 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
						analysisTree.muon_eta[indx1],analysisTree.muon_phi[indx1]);

				if (dRmuJet1 < 0.5) continue;
				double dRmuJet2 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
						analysisTree.muon_eta[indx2],analysisTree.muon_phi[indx2]);

				if (dRmuJet2 < 0.5) continue;

				JetsV.SetPxPyPzE(0.,0.,0.,0.);
				JetsV.SetPxPyPzE(analysisTree.pfjet_px[jet], analysisTree.pfjet_py[jet], analysisTree.pfjet_pz[jet], analysisTree.pfjet_e[jet]);
				JetsMV.push_back(JetsV);	
				countjets++;
			}
			sort(JetsMV.begin(), JetsMV.end(),ComparePt);

			if (countjets ==0) continue;



			double dPhi=-1;double MT=-1 ; double RatioSums=-1;


			double met = sqrt ( analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
			// w = mu+MET
			// ptW - ptJ/ptW+ptJ      
			//
			//

			TLorentzVector muon1; muon1.SetXYZM(analysisTree.muon_px[indx1],
					analysisTree.muon_py[indx1],
					analysisTree.muon_pz[indx1],
					muonMass);
			TLorentzVector muon2; muon2.SetXYZM(analysisTree.muon_px[indx2],
					analysisTree.muon_py[indx2],
					analysisTree.muon_pz[indx2],
					muonMass);
			TLorentzVector DiM = muon1+muon2;

			RatioSums = analysisTree.tau_pt[tau_loose]/DiM.Pt();


			TLorentzVector MetV; 
			MetV.SetPx(analysisTree.pfmet_ex); 
			MetV.SetPy(analysisTree.pfmet_ey);

			TLorentzVector tauV;  tauV.SetPtEtaPhiM(analysisTree.tau_pt[tau_loose], analysisTree.tau_eta[tau_loose], analysisTree.tau_phi[tau_loose], tauMass);

			TLorentzVector DiL = DiM  + tauV;

			//dPhi = dPhiFrom2P( DiM.Px(), DiM.Py(), MetV.Px(),  MetV.Py() );
			dPhi = dPhiFrom2P( DiM.Px(), DiM.Py(), analysisTree.tau_px[tau_loose],analysisTree.tau_py[tau_loose]);
			MT = TMath::Sqrt(2*DiM.Pt()*MetV.Pt()*(1-TMath::Cos(dPhi)));


			hRatioSum->Fill(RatioSums,weight);
			hMT->Fill(MT,weight);
			hMass->Fill(DiM.M(),weight);
			hDPhi->Fill(dPhi, weight);


			//if (tau.size()==0 || !tau_iso ) continue;

			//cout<<"  "<<endl;
			if (isLoose) denominator++;
			if (isTight) nominator++;

			if (isLoose){
				float ptProbe = TMath::Min(float(analysisTree.tau_pt[tau_loose]),float(ptBins[nPtBins]-0.1));
				float absEtaProbe = fabs(analysisTree.tau_eta[tau_loose]);
				int ptBin = binNumber(ptProbe,nPtBins,ptBins);
				if (ptBin<0) continue;
				int etaBin = binNumber(absEtaProbe,nEtaBins,etaBins);
				if (etaBin<0) continue;

				//cout<< "filling here  "<<analysisTree.tau_pt[tau_loose]<<"  "<<ptBin<<"  "<<etaBin<<"  "<<weight<<endl;
				//FakeRatePt[etaBin][ptBin]->Fill(analysisTree.tau_pt[tau_loose],weight);

				bool bRatio = (RatioSums < 1.2  && RatioSums > 0.8);
				bool bMass = (DiM.M() < 120 && DiM.M() > 60);
				if (isLoose){
					if (bRatio) FakeRatePtIncLoose[etaBin][0]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass && bRatio) FakeRatePtIncLoose[etaBin][1]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (dPhi > 2.5  && bRatio) FakeRatePtIncLoose[etaBin][2]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && dPhi > 2.5 && bRatio) FakeRatePtIncLoose[etaBin][3]->Fill(analysisTree.tau_pt[tau_loose],weight);

				}

				if (isTight) 

				{	
					if (bRatio) FakeRatePtIncTight[etaBin][0]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && bRatio) FakeRatePtIncTight[etaBin][1]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (dPhi > 2.5 && bRatio) FakeRatePtIncTight[etaBin][2]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && dPhi > 2.5 && bRatio) FakeRatePtIncTight[etaBin][3]->Fill(analysisTree.tau_pt[tau_loose],weight);

				}

				//FakeRateEta[etaBin][ptBin]->Fill(analysisTree.tau_eta[tau_loose],weight);
				//FakeRateNV[etaBin][ptBin]->Fill(analysisTree.tau_vertexz[tau_loose],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->cd();
hxsec->Fill(XSec);
hxsec->Write();
inputEventsH->Write();
histWeightsH->Write();
file->Write();
file->Close();
delete file;

}
Пример #7
0
void
//Impose (TDirectory * target, TList * sourcelist, string & np_title_, vector<string> titles,vector<float> xsecs)
Impose (TList * sourcelist, string & np_title_, vector<string> titles,vector<float> xsecs, TString &variable)
{
	cout << "	" << "========================================================" << endl;
	cout << "	" << "This is a macro to superimpose plots of different root files." << endl;
	cout << "	" << "Only TH2Dobjects are superimposed." << endl;
	float Lumi=1;


	Lumi = 15712.;
	bool norm_=false;
        int MaxEventsBin = 10;
	cout<<titles[0]<<"   "<<titles.size()<<endl;

	//not really useful if plots already weighted to lumi - usefull is plots are in a.u.
	vector <float > lumiweights;
	lumiweights.clear();
//	for (unsigned int kk=0; kk<signal_names.size();kk++){
//		cout<<" HERE is some signal  ===============================================  "<<signal_names[kk]<<"  "<<signalnames[kk]<<endl;
//	}

	TH2D* allbkg, *htt,*hstop,*hwj,*hdyj,*hrare,*hdib,*hqcd,*httx, *hrest;

	TFile *first_source = (TFile *) sourcelist->First ();
	first_source->cd ("mutau");

	TH1D* eventCount = (TH1D*)first_source->Get("mutau/histWeightsH");
	//TH1D* eventCount = (TH1D*)first_source->Get("mutau/inputEventsH");
	//TH1D* hxsec = (TH1D*)first_source->Get("mutau/xsec");
	float nGen = eventCount->GetSumOfWeights();
	float xsec = 1;//hxsec->GetMean();
	float norm = xsec*Lumi/nGen;

	norm =1;
	lumiweights.push_back(float(norm));


	//cout<< " for first source file, there where "<<nGen<<" events with xsec "<<xsec<<" weight "<<lumiweights[0]<<endl;//" weight "<<float(xsec*Lumi/nGen)<<"  norm "<<norm<<endl;

	TDirectory *current_sourcedir = gDirectory;
	//gain time, do not add the objects in the list in memory
	Bool_t status = TH1::AddDirectoryStatus ();
	TH1::AddDirectory (kFALSE);
	// loop over all keys in this directory
	TChain *globChain = 0;
	TIter nextkey (current_sourcedir->GetListOfKeys ());
	//TIter nextkey (((TDirectory *) current_sourcedir->Get ("ana"))->GetListOfKeys ());
	TKey *key, *oldkey = 0;
	while ((key = (TKey *) nextkey ())) {
	//variable="met_MTsum_16";

	int count=0;
		count++;
		//if (count>20) break;
		//keep only the highest cycle number for each key
		//        if (oldkey && !strcmp (oldkey->GetName (), key->GetName ()))
		//            continue;

		// read object from first source file and create a canvas
		// first_source->cd (path);
		first_source->cd ("mutau");
		TObject *obj = key->ReadObj ();

		//string nn = obj->GetName();
		// if (std::string::npos == nn.find("Cut")) continue;
		//cout<<obj->GetName()<<endl;



		string nn = obj->GetName();
		bool flcont = true;
		bool NormTT = false;
		if (string::npos != nn.find("_9") || string::npos != nn.find("_10") || string::npos != nn.find("_11") || string::npos != nn.find("_12") || string::npos != nn.find("_13") || string::npos != nn.find("_14") || string::npos != nn.find("_15") || string::npos != nn.find("_16") || string::npos != nn.find("_18") || string::npos != nn.find("_18") || string::npos != nn.find("_18")) NormTT = true;
		//if ( string::npos != nn.find("_11") || string::npos != nn.find("_12") || string::npos != nn.find("_13") || string::npos != nn.find("_14")) NormTT = true;
		NormTT=true;
		//if ( string::npos == nn.find("CutFlowUnW")) flcont=false;
		//if (string::npos == nn.find(""+variable) ) flcont=false;
		if (string::npos == nn.find(variable) ) continue;
		//		if (!flcont) continue;
		if (obj->IsA ()->InheritsFrom ("TTree") ) continue;
		//	if (obj->IsA ()->InheritsFrom ("TH1") ) continue;
		if (obj->IsA ()->InheritsFrom ("TH2") ) {

			cout<<"=================================================== OK for variable "<<variable<<endl;


			TH2D* hh[1500];
			TH2D* hsignal[1500];
			TH2D* h1 = (TH2D*) obj;

			ModifyHist (h1,1,Lumi,lumiweights[0],titles[0],norm_);
			TFile *nextsource = (TFile *) sourcelist->After (first_source);

			int cl, countsignal;
			h1->SetStats(000000);
			cl=1;
			countsignal=1;

			hh[cl]=h1;

			THStack *hs = new THStack(h1->GetName(),h1->GetTitle());



			string sn="stau";
			string sdata="Single";
			string sdata2="MuonEG";
			string cc1="C1";



			while (nextsource) {

			string fname= nextsource->GetName();


				bool flagg= false;

				if (std::string::npos != fname.find(sn) || std::string::npos != fname.find(cc1) || std::string::npos != fname.find(sdata)    ) 	flagg=true;

				//if (flagg) cout<<"=============================================================== "<<fname<<endl;
				// make sure we are at the correct directory level by cd'ing to path
				nextsource->cd("mutau");
				TH1D* eventCountt ;
				
				  if  ( std::string::npos == fname.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") || !NormTT) eventCountt = (TH1D*)nextsource->Get("mutau/histWeightsH");
				  if ( NormTT && std::string::npos != fname.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") ) eventCountt = (TH1D*)nextsource->Get("mutau/histTopPt");

				
				TH1D* hxsecc = (TH1D*)nextsource->Get("mutau/xsec");
				float xsecc = xsecs[cl];

				float nGenn = eventCountt->GetSumOfWeights();
				float normm = float(xsecc*Lumi) / float(nGenn)  ;
				if (std::string::npos != fname.find("DataDriven")) normm=1.;

				lumiweights.push_back(normm);

				TKey *key2 = (TKey *) gDirectory->GetListOfKeys ()->FindObject (h1->GetName ());

				if (key2) {
					cl++;
					countsignal++;
					TH2D *h2;

					h2 = (TH2D*) key2->ReadObj ();
					ModifyHist (h2, cl,Lumi,lumiweights[cl-1],titles[cl-1],norm_);
					h2->SetStats(0);
					hh[cl] = h2;

					if (cl==2){
						allbkg  = (TH2D*) h2->Clone();
						allbkg->Reset();
						htt  = (TH2D*) h2->Clone();
						httx  = (TH2D*) h2->Clone();
						hstop  = (TH2D*) h2->Clone();
						hwj  = (TH2D*) h2->Clone();
						hdyj  = (TH2D*) h2->Clone();
						hrare  = (TH2D*) h2->Clone();
						hdib  = (TH2D*) h2->Clone();
						hqcd  = (TH2D*) h2->Clone();
						hrest  = (TH2D*) h2->Clone();

						htt->Reset();
						httx->Reset();
						hstop->Reset();
						hdyj->Reset();
						hwj->Reset();
						hrare->Reset();
						hdib->Reset();
						hqcd->Reset();
						hrest->Reset();


					}



					string  hn_ = obj->GetName();
					cout<<"  "<<fname<<endl;

						if (std::string::npos != fname.find(sn) || std::string::npos != fname.find(cc1) || std::string::npos != fname.find(sdata) ||  std::string::npos != fname.find(sdata2)  )
							flagg=true;


						string  title_ = fname;
							//cout<<"  "<<fname<<endl;

			int col = 0;
						if (!flagg)
						{
			if (std::string::npos != title_.find("wJets")|| std::string::npos != title_.find("WJetsToLNu") || std::string::npos != title_.find("W1JetsToLNu") || std::string::npos != title_.find("W2JetsToLNu") 
			|| std::string::npos != title_.find("W3JetsToLNu") || std::string::npos != title_.find("W4JetsToLNu"))  { col=mycolorwjet ; hwj->Add(h2); hwj->SetLineColor(col);}
			if (std::string::npos != title_.find("TT_TuneCUETP8M1_13TeV-powheg-pythia8") || std::string::npos != title_.find("TTPow")) { col= mycolortt;htt->Add(h2); htt->SetLineColor(col) ;}
			if (std::string::npos != title_.find("QCD"))  {col= mycolorqcd;hqcd->Add(h2); hqcd->SetLineColor(col); cout<<" QCD ======================== "<<hqcd->GetSumOfWeights()<<endl;}
			if (std::string::npos != title_.find("DYJets") || std::string::npos != title_.find("DY1Jets") 
			|| std::string::npos != title_.find("DY2Jets") || std::string::npos != title_.find("DY3Jets") || std::string::npos != title_.find("DY4Jets"))  {col= mycolordyj;hdyj->Add(h2); hdyj->SetLineColor(col);}
			if (std::string::npos != title_.find("ST_") || std::string::npos != title_.find("channel") )  {col= mycolortt; hstop->Add(h2);hstop->SetLineColor(col);}
			if ( std::string::npos != title_.find("WW") || std::string::npos != title_.find("ZZ") ||  std::string::npos != title_.find("WZ") || std::string::npos != title_.find("WG") || std::string::npos != title_.find("ZG") ) {col=mycolorvv; hdib->Add(h2); hdib->SetLineColor(col);}
			if ( std::string::npos != title_.find("TTW") || std::string::npos != title_.find("TTZ") || std::string::npos != title_.find("tZq") || std::string::npos != title_.find("TG") || std::string::npos != title_.find("tG") || std::string::npos != title_.find("TTG") || std::string::npos != title_.find("ttW") || std::string::npos != title_.find("ttZ") || std::string::npos != title_.find("tZ") || std::string::npos != title_.find("TTT_") ) {col=mycolorttx ;httx->Add(h2);   httx->SetLineColor(col);}


							//cout<<" will add histogram "<<h2->GetName()<< " for "<<titles[cl-1]<<"  "<<fname<<"  cl  "<<cl<<endl;
							hs->Add(h2);
							allbkg->Add(h2);
						}

				}


				nextsource = (TFile *) sourcelist->After (nextsource);
			}				// while ( nextsource )
		}


		cout<<" Will now extract and save the 1D "<<endl;
		//const char *s1;
		TString s1;
		TH1D * histbkg;
		string n = obj->GetName();
		vector<float> scales;
		bool b_scale=true;
		if (std::string::npos != n.find(variable) && obj)
		{
			TH2D *hsum = ((TH2D*)(hs->GetStack()->Last())); // the "SUM"
			scales.push_back(40000.);
			for (int sc = 0 ; sc<scales.size();sc++){
	

				float scale = float(scales[sc])/float(Lumi);

				//stringstream ss (stringstream::in | stringstream::out);

	
				TString lumistring = "40invfb";
				TString smFilename = "Templates_"+variable+"_"+lumistring+"_mt_C1C1.root";
				//TString smFilename = "Templates_mt.root";
				TFile *smFile = TFile::Open (smFilename, "recreate");


				smFile->cd();
				//if (sc==0) smFile->mkdir("mt");
				smFile->cd();
				allbkg = hsum;
				allbkg->SetMinimum(0.1);
				allbkg->SetLineColor(kRed);
				allbkg->SetMarkerColor(kRed);
				allbkg->SetFillColor(kRed);
				allbkg->SetFillStyle(3011);
				allbkg->SetMinimum(0.1);
				s1 = "data_obsMC_" + variable;
				//s1 = "data_obsMC";
				allbkg->SetName(s1);
				cout<<" Total Integral before scaling up - "<<allbkg->GetSumOfWeights()<<"  "<<variable<<" data "<<hh[1]->GetSumOfWeights()<<" tt "<<
					htt->GetSumOfWeights()<<" dy "<<hdyj->GetSumOfWeights()<<" wj "<<hwj->GetSumOfWeights()<<" stop "<<hstop->GetSumOfWeights()<<
					" vv "<<hdib->GetSumOfWeights()<<" qcd "<<hqcd->GetSumOfWeights()<<endl;
	if(b_scale)		allbkg->Scale(scale);
				cout<<" Total Integral after scaling up - "<<allbkg->GetSumOfWeights()<<"  "<<variable<<endl;
				allbkg->Write();


				histbkg = Unroll(allbkg,s1,1.);
				s1 = "1D_allbkg_" + variable;
				//s1 = "1D_data_obsMC";//_" + variable+"_"+lumistring;
				histbkg->SetName(s1);
				histbkg->SetMarkerColor(kRed);
				histbkg->SetLineColor(kRed);
				histbkg->Write();
	 if(b_scale){
				htt->Scale(scale);
				hwj->Scale(scale);
				hdyj->Scale(scale);
				hstop->Scale(scale);
				hdib->Scale(scale);
				hqcd->Scale(scale);
				httx->Scale(scale);
	 }

				htt->SetMinimum(0.1);
				hdyj->SetMinimum(0.1);
				hwj->SetMinimum(0.1);
				httx->SetMinimum(0.1);
				hstop->SetMinimum(0.1);
				hdib->SetMinimum(0.1);
				hqcd->SetMinimum(0.1);

				s1 = "tt_"+variable;
				htt->SetName(s1);
				htt->Write();
				histbkg = Unroll(htt,s1,1.);
				s1 = "1D_tt_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "wj_"+variable;
				hwj->SetName(s1);
				hwj->Write();
				histbkg =Unroll(hwj,s1,1.);
				s1 = "1D_wj_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "dyj_"+variable;
				hdyj->SetName(s1);
				hdyj->Write();
				histbkg =Unroll(hdyj,s1,1.);
				s1 = "1D_dyj_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "sT_"+variable;
				hstop->SetName(s1);
				hstop->Write();
				histbkg =Unroll(hstop,s1,1.);
				s1 = "1D_sT_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "dib_"+variable;
				hdib->SetName(s1);
				hdib->Write();
				histbkg =Unroll(hdib,s1,1.);
				s1 = "1D_dib_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "ttx_"+variable;
				httx->SetName(s1);
				httx->Write();
				histbkg =Unroll(httx,s1,1.);
				s1 = "1D_ttx_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				s1 = "qcd_"+variable;
				hqcd->SetName(s1);
				hqcd->Write();
				histbkg =Unroll(hqcd,s1,1.);
				s1 = "1D_qcd_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();

				//rest of bkg hold all but ttjets and wjets background	
				s1 = "rest_bkg_"+variable;
				//hrest->Add(hdyj,1);
				//hrest->Add(httj,1);
				//hrest->Add(hwj,1);
				hrest->Add(hstop,1);
				hrest->Add(hdib,1);
				hrest->Add(hqcd,1);
				hrest->Add(httx,1);
				hrest->SetName(s1);
				hrest->Write();
				histbkg =Unroll(hrest,s1,1.);
				s1 = "1D_rest_bkg_"+variable;
				histbkg->SetName(s1);
				histbkg->Write();
				

				hh[1]->SetMinimum(0.1);
				hh[1]->SetLineColor(kBlack);
				hh[1]->SetFillColor(kBlack);
				hh[1]->SetMarkerColor(kBlack);
				s1 = "data_obs_"+variable;
				hh[1]->SetName(s1);

	if(b_scale)	hh[1]->Scale(scale);
				hh[1]->Write();
				histbkg =Unroll(hh[1],s1,1.);
				//histbkg =Unroll(allbkg,s1,1.);
				s1 = "1D_data_obs_";
				s1 = "data_obs";
				histbkg->SetName(s1);
				histbkg->Write();

				for (unsigned int ij=0;ij<signal_names.size();++ij){
					//cout<<" again  "<<signal_names[ij]<<endl;
					//cout<<" again  "<<hh[ij+2]->GetName()<<"  "<<ij<<"  "<<signal_names[ij].c_str()<<endl;
					TString ss1 = signal_names[ij].c_str();
					s1 = "1D_"+ss1 +"_"+variable;
	if(b_scale)			hh[ij+2]->Scale(scale);
					histbkg = Unroll(hh[ij+2],s1,1.);
					smFile->cd();
					histbkg->SetName(s1);
					histbkg->SetMarkerColor(kBlue);
					histbkg->SetLineColor(kBlue);
					histbkg->Write();

				}
				smFile->SaveSelf (kTRUE);
				smFile->Close();
				delete smFile;
			}//loop over different predictions

		}///find variable





			}

	//delete c1;
	// save modifications to target file
	//target->SaveSelf (kTRUE);
	TH1::AddDirectory (status);
	cout << "	" << "========================================================" << endl;
	cout<< " Ended SuperImpose of files.... " <<endl;




}
Пример #8
0
mainClass(int luminosity){//constructor
//Importnat
//make sure this initialization of the 
//maps is the same as that in main.cpp
     cutname[0]="RA2nocut";
    cutname[1]="RA2Asys";
    cutname[2]="RA2Inc3Jetcut";
    cutname[3]="RA2HT500cut";
    cutname[4]="RA2MHT200cut";
    cutname[5]="RA2delphicut";
    cutname[6]="RA2noleptoncut";
    cutname[7]="noPhotoncut";
    cutname[8]="RA2Inc4Jetcut";
    cutname[9]="RA2Inc5Jetcut";
    cutname[10]="RA2Inc6Jetcut";
    cutname[11]="RA2allbutHT2500cut";
    cutname[12]="RA2allbutMHT1000cut";
    cutname[13]="RA2allcut";
    cutname[14]="RA2noleptoncutMHT1000";
    cutname[15]="RA2noleptoncutBtag2";
    cutname[16]="RA2noleptoncutBtag2MHT1000";
    cutname[17]="RA2Inc4JetcutMHT1000";
    cutname[18]="RA2Inc4JetcutBtag2";
    cutname[19]="RA2Inc4JetcutBtag2MHT1000";
    cutname[20]="RA2Inc5JetcutMHT1000";
    cutname[21]="RA2Inc5JetcutBtag2";
    cutname[22]="RA2Inc5JetcutBtag2MHT1000";
    cutname[23]="RA2Inc6JetcutMHT1000";
    cutname[24]="RA2Inc6JetcutBtag2";
    cutname[25]="RA2Inc6JetcutBtag2MHT1000";


    sigtype[0]="allEvents";
    sigtype[1]="glgl";

    BJtype[0]="allEvents";
    BJtype[1]="W";
    BJtype[2]="Wlv";
    BJtype[3]="Wjj";
    BJtype[4]="Z";
    BJtype[5]="Zll";
    BJtype[6]="Zvv";
    BJtype[7]="Zjj";
    BJtype[8]="photon";
    BJtype[9]="H";

   TTtype[0]="allEvents";
   TTtype[1]="TTbar";
   TTtype[2]="TTSingLep";
   TTtype[3]="TTdiLep";
   TTtype[4]="TThadronic";



  //KH
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtagLoose";
  histname[5]="NBtagTight";
  histname[6]="BtagLoose1Pt";
histname[7]="BtagLoose1Eta";
histname[8]="BtagLoose1Phi";
histname[9]="BtagLoose2Pt";
histname[10]="BtagLoose2Eta";
histname[11]="BtagLoose2Phi";
histname[12]="BtagTight1Pt";
histname[13]="BtagTight1Eta";
histname[14]="BtagTight1Phi";
histname[15]="BtagTight2Pt";
histname[16]="BtagTight2Eta";
histname[17]="BtagTight2Phi";

  ///end of initialization of the maps

yieldmap.clear();



//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section//Signal Section

  //build a vector of scale factors
  //first load the cross sections into a vector
//Sig_xs_vec.push_back(0.757); /// v1
//Sig_xs_vec.push_back(1.12); // v2
//Sig_xs_vec.push_back(1.15); // v3
//Sig_xs_vec.push_back(1.14); // M(Stop,LSP)=(450,410) and also M(Stop,LSP)=(450,440)
//Sig_xs_vec.push_back(2.18); // M(Stop,LSP)=(400,390) and also M(Stop,LSP)=(400,360)
//Sig_xs_vec.push_back(4.41); // M(Stop,LSP)=(350,340) and also M(Stop,LSP)=(350,310)
//Sig_xs_vec.push_back(0.009635); //STOCv4
Sig_xs_vec.push_back(1.58); //StauC

  double Sig_numberofevents =0;//this will use GetSumOfWeights() 
  const int Sig_nHT = 1;   // Total number of HT bin samples
  const int nHist = 18; // Number of histograms in each TDirectory


  for(int i=1; i<=Sig_nHT ; i++){
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"../Results/results_PhaseII4_StauC_14TEV_140PileUp.root");
  file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*Sig_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    Sig_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=Sig_nHT; i++){
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"../Results/results_PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"../Results/results_PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"../Results/results_PhaseII4_StauC_14TEV_140PileUp.root");
Sig_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

tempstack = new THStack("stack","Binned Sample Stack");
//sprintf(tempname,"PhaseII4_Stop_CharmLSP_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv2_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv3_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc450410_14TEV_140PileUp_00.root");  
//sprintf(tempname,"PhaseII4_t2cc450440_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc400390_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc400360_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc350340_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_t2cc350310_14TEV_140PileUp_00.root");
//sprintf(tempname,"PhaseII4_Stop_CharmLSPv4_14TEV_140PileUp_00.root");
sprintf(tempname,"PhaseII4_StauC_14TEV_140PileUp.root");
file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=sigtype.begin(); itt!=sigtype.end();itt++){        // loop over different event types
    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<Sig_nHT ; i++){                                                  // loop over different HT bins
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) Sig_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(Sig_scalevec[i]);
if(histname[j]=="MHT"){
Sig_numberofevents+=(double)temphist->GetSumOfWeights();
} 
temphist->SetFillColor(i+2);
tempstack->Add(temphist);


               }//end of loop over HTbins 1..7
if(histname[j]=="MHT"){
if(itt->second=="allEvents"){
yieldmap[c].push_back(Sig_numberofevents);
}

}
Sig_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
 c+=1;   }//end of loop over cutnames
  }//end of loop over event types
file->Close();

//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section//BJ Section

 //build a vector of scale factors
  //first load the cross sections into a vector
  BJ_xs_vec.push_back(34409.92339);
  BJ_xs_vec.push_back(2642.85309);
  BJ_xs_vec.push_back(294.12311);
  BJ_xs_vec.push_back(25.95000);
  BJ_xs_vec.push_back(2.42111);
  BJ_xs_vec.push_back(0.22690);
  BJ_xs_vec.push_back(0.02767);

  double BJ_numberofevents =0;
  const int bjnHT = 7;   // Total number of HT bin samples


  for(int i=1; i<=bjnHT ; i++){
    sprintf(tempname,"../Results/results_PhaseII4_BJ_14TEV_HT%d_140PileUp.root",i);
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*BJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    BJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=bjnHT; i++){
sprintf(tempname,"../Results/results_PhaseII4_BJ_14TEV_HT%d_140PileUp.root",i);
BJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

//tempstack = new THStack("stack","Binned Sample Stack");
sprintf(tempname,"PhaseII4_BJ_14TEV_140PileUp.root");
//file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=BJtype.begin(); itt!=BJtype.end();itt++){        // loop over different event types
//    cdtoitt = file->mkdir((itt->second).c_str());
//    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
//      cdtoit =  cdtoitt->mkdir((it->second).c_str());
//      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<bjnHT ; i++){                                                  // loop over different HT bins
//cout << "================================" << endl;
//cout << "HT#: " <<i << ", BJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) BJ_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(BJ_scalevec[i]);
if(histname[j]=="MHT"){
BJ_numberofevents+=(double)temphist->GetSumOfWeights();
}
temphist->SetFillColor(i+2);
//tempstack->Add(temphist);
               }//end of loop over HTbins 1..7
if(histname[j]=="MHT"){
if(itt->second=="Wlv" || itt->second=="Zvv"){
yieldmap[c].push_back(BJ_numberofevents);
}

}
BJ_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
  //      tempstack->Write(tempname);
  //      delete tempstack;
  //      tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
c+=1;    }//end of loop over cutnames
  }//end of loop over event types
//file->Close();


//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section//TTbar Section

  //build a vector of scale factors
  //first load the cross sections into a vector
  TT_xs_vec.push_back(530.89358);
  TT_xs_vec.push_back(42.55351);
  TT_xs_vec.push_back(4.48209);
  TT_xs_vec.push_back(0.52795);
  TT_xs_vec.push_back(0.05449);

  double TT_numberofevents =0;
  const int ttnHT = 5;   // Total number of HT bin samples


  for(int i=1; i<=ttnHT ; i++){
    sprintf(tempname,"../Results/results_PhaseII4_TT_14TEV_HT%d_140PileUp.root",i);
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/RA2nocut/MHT_RA2nocut_allEvents");
    tempvalue = (luminosity*TT_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    TT_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=ttnHT; i++){
sprintf(tempname,"../Results/results_PhaseII4_TT_14TEV_HT%d_140PileUp.root",i);
TT_inputfilevec.push_back(TFile::Open(tempname,"R"));
}

//tempstack = new THStack("stack","Binned Sample Stack");
sprintf(tempname,"PhaseII4_TT_14TEV_140PileUp.root");
//file = new TFile(tempname,"RECREATE");
 for(map<int , string >::iterator itt=TTtype.begin(); itt!=TTtype.end();itt++){        // loop over different event types
//    cdtoitt = file->mkdir((itt->second).c_str());
//    cdtoitt->cd();
int c=0;
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
//      cdtoit =  cdtoitt->mkdir((it->second).c_str());
//      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<ttnHT ; i++){                                                  // loop over different HT bins
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) TT_inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(TT_scalevec[i]);
if(histname[j]=="MHT"){
TT_numberofevents+=(double)temphist->GetSumOfWeights();
}
temphist->SetFillColor(i+2);
//tempstack->Add(temphist);
               }//end of loop over HTbins 1..5
if(histname[j]=="MHT"){
if(itt->second=="allEvents"){
yieldmap[c].push_back(TT_numberofevents);
}

}
TT_numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
//        tempstack->Write(tempname);
//        delete tempstack;
//        tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
c+=1;   }//end of loop over cutnames
  }//end of loop over event types
//file->Close();



///write the output in a file
fstream ff;
ff.open("CutFlow.txt", std::fstream::out);
ff << " Cut Name,    " << "  Signal,      " << "  Wlv,      " << "  Zvv,     " << "  TTbar,      "<< "    Total BG,   " << " % Signal/Background,   "  <<  "    Significance " << endl; 
double totalBG=0, delWlv=0, delZvv=0, delTT=0, delB=0, delBsquare=0;
for(int i=0; i<yieldmap.size(); i++){
totalBG=(double) (yieldmap[i].at(1)+yieldmap[i].at(2)+yieldmap[i].at(3));
delWlv= 0.08*yieldmap[i].at(1);///uncrtainty for Wlv is 8%
delZvv= 0.05*yieldmap[i].at(2);
delTT= 0.5*yieldmap[i].at(3);///uncrtainty for TTbar is 50%
delBsquare=pow(delWlv,2)+pow(delZvv,2)+pow(delTT,2);///delta_background = sqrt(delWlv^2+delZvv^2+delTT^2)
ff << "  " <<cutname[i]<<",     " << yieldmap[i].at(0) << ",     " << yieldmap[i].at(1) <<",     " << yieldmap[i].at(2) <<",     " <<yieldmap[i].at(3) << ",      "<< totalBG << ",      " << yieldmap[i].at(0)/totalBG*100  <<  ",       " << yieldmap[i].at(0)/sqrt(delBsquare+totalBG+yieldmap[i].at(0))  <<endl;  
}
ff.close();

/*
///write the output in a file
fstream ff;
ff.open("CutFlow.txt", std::fstream::out);
ff << " Cut Name,    " << "  Signal,      "  << endl; 
for(int i=0; i<yieldmap.size(); i++){
ff << "  " <<cutname[i]<<",     " << yieldmap[i].at(0) << endl;  
}
ff.close();
*/
}//end of the constructor
void ProduceDatacards_em(int nBins = 35,
			 float xmin = 0,
			 float xmax = 350,
			 bool pileUp = false) {

  double lumi = 2092;
  double normSS = 1.06;
    
  // sample names
  TString sampleNames[20] = {
    "MuEG_2015D", // data
    "DYJetsToLL_M-50_MG", // isZTT (ZTT)
    "DYJetsToLL_M-50_MG", // !isZTT (ZLL)
    "WJetsToLNu_MG", 
    "TTPowHeg",  
    "ST_t-channel_top_4f_leptonDecays",  
    "ST_t-channel_antitop_4f_leptonDecays",
    "ST_tW_antitop_5f_inclusiveDecays",
    "ST_tW_top_5f_inclusiveDecays",
    "VVTo2L2Nu",
    "WWToLNuQQ",
    "WZTo2L2Q",
    "WZTo1L1Nu2Q",
    "WZTo1L3Nu",
    "WZJets",
    "ZZTo4L",
    "ZZTo2L2Q",
    "",
    "",
    ""};

  double xsec[20] = {1, // data (0)
		     6025.2, // DY (1)
		     6025.2, // DY (2)
		     61526.7, // WJets (3)
		     831.76, // TT (4)
		     136.95, // ST_t-channel_top (5)
		     80.95,  // ST_t-channel_antitop (6)
		     35.6, // ST_tW_antitop (7)
		     35.6, // ST_tW_top_5f (8)
		     11.95,  // VV (9)
		     49.997, // WWToLNuQQ (10)
		     5.595, // WZTo2L2Q (11)
		     10.71, // WZTo1L1Nu2Q (12)
		     3.05, // WZTo1L3Nu (13)
		     5.26, // WZJets (3L1Nu) (14)
		     1.212, // ZZTo4L (15)
		     3.22, // ZZTo2L2Q (16)
		     0, //
		     0, //
		     0}; // 
  
  TString cuts[20];
  TString cutsSS[20];
  for (int i=0; i<20; ++i) {
    cuts[i] = "mcweight*(os>0.5)";
    cutsSS[i] = "mcweight*(os<0.5)";
  }

  cuts[0] = "os>0.5";
  cuts[1] = "mcweight*(os>0.5&&isZTT)";
  cuts[2] = "mcweight*(os>0.5&&!isZTT)";

  cutsSS[0] = "os<0.5";
  cutsSS[1] = "mcweight*(os<0.5&&isZTT)";
  cutsSS[2] = "mcweight*(os<0.5&&!isZTT)";
  
  if (pileUp) {
    for (int i=1; i<20; ++i) {
      cuts[i] = "puweight*" + cuts[i];
      cutsSS[i] = "puweight*" + cutsSS[i];
    }
  }

  TH1D * hist[20];
  TH1D * histSS[20];

  for (int i=0; i<17; ++i) {
    std::cout << sampleNames[i] << std::endl;
    TFile * file = new TFile(sampleNames[i]+".root");
    TH1D * histWeightsH = (TH1D*)file->Get("histWeightsH");
    TTree * tree = (TTree*)file->Get("TauCheck");
    double norm = xsec[i]*lumi/histWeightsH->GetSumOfWeights();
    TString histName = sampleNames[i] + "_mvis";
    TString histNameSS = sampleNames[i] + "_mvis_os";
    hist[i] = new TH1D(histName,"",nBins,xmin,xmax);
    histSS[i] = new TH1D(histNameSS,"",nBins,xmin,xmax);
    hist[i]->Sumw2();
    histSS[i]->Sumw2();
    tree->Draw("m_vis>>"+histName,cuts[i]);
    tree->Draw("m_vis>>"+histNameSS,cutsSS[i]);
    if (i>0) {
      for (int iB=1; iB<=nBins; ++iB) {
	double x = hist[i]->GetBinContent(iB);
	double e = hist[i]->GetBinError(iB);
    	hist[i]->SetBinContent(iB,norm*x);
    	hist[i]->SetBinError(iB,norm*e);
	double xSS = histSS[i]->GetBinContent(iB);
	double eSS = histSS[i]->GetBinError(iB);
    	histSS[i]->SetBinContent(iB,norm*xSS);
    	histSS[i]->SetBinError(iB,norm*eSS);
      }
    }
  }

  //  adding up single top and VV backgrounds
  for (int iH=6; iH<17; ++iH) {
    hist[5]->Add(hist[5],hist[iH]);
    histSS[5]->Add(histSS[5],histSS[iH]);
  }

  // subtracting background from SS
  for (int iH=1; iH<6; ++iH) {
    histSS[0]->Add(histSS[0],histSS[iH],1,-1);
  }

  for (int iB=1; iB<=nBins; ++iB) {
    double x = histSS[0]->GetBinContent(iB);
    double e = histSS[0]->GetBinError(iB);
    histSS[0]->SetBinContent(iB,normSS*x);
    histSS[0]->SetBinError(iB,normSS*e);
  }
  TString suffix("");
  if (!pileUp)
    suffix = "_noPU";

  TFile * file = new TFile("htt_em.inputs-sm-13TeV-mvis"+suffix+".root","recreate"); 
  file->mkdir("em_inclusive");
  file->cd("em_inclusive");
  TH1D * data_obs = (TH1D*)hist[0]->Clone("data_obs");
  TH1D * QCD = (TH1D*)histSS[0]->Clone("QCD");
  TH1D * ZTT = (TH1D*)hist[1]->Clone("ZTT");
  TH1D * ZLL = (TH1D*)hist[2]->Clone("ZLL");
  TH1D * W = (TH1D*)hist[3]->Clone("W");
  TH1D * TT = (TH1D*)hist[4]->Clone("TT");
  TH1D * VV = (TH1D*)hist[5]->Clone("VV");
  file->Write();
  file->Close();
  

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

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

//  using namespace std;

  //const int CutNumb = 8;
  //string CutList[CutNumb]={"No cut","Trigger","1l","lept-Veto","b-Veto","MET $>$ 50","MET $>$ 100","dPhi $>$ 1"};

  // **** configuration
  Config cfg(argv[1]);
  string Channel="mutau";

  // kinematic cuts on electrons
  bool fillplots= false;
  bool Wtemplate= true;
  const bool isData = cfg.get<bool>("IsData");
  const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");
  const bool applyPUreweighting_vertices = cfg.get<bool>("ApplyPUreweighting_vertices");
  const bool applyPUreweighting_official = cfg.get<bool>("ApplyPUreweighting_official");
  const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");
  const bool InvertTauIso = cfg.get<bool>("InvertTauIso");
  const bool InvertLeptonIso = cfg.get<bool>("InvertLeptonIso");
  const bool InvertMET = cfg.get<bool>("InvertMET");
  const double ptElectronLowCut   = cfg.get<double>("ptElectronLowCut");
  const double ptElectronHighCut  = cfg.get<double>("ptElectronHighCut");
  const double etaElectronCut     = cfg.get<double>("etaElectronCut");
  const double dxyElectronCut     = cfg.get<double>("dxyElectronCut");
  const double dzElectronCut      = cfg.get<double>("dzElectronCut");
  const double isoElectronLowCut  = cfg.get<double>("isoElectronLowCut");
  const double isoElectronHighCut = cfg.get<double>("isoElectronHighCut");
  const bool applyElectronId     = cfg.get<bool>("ApplyElectronId");

  // vertex cuts
  const double ndofVertexCut  = cfg.get<double>("NdofVertexCut");   
  const double zVertexCut     = cfg.get<double>("ZVertexCut");
  const double dVertexCut     = cfg.get<double>("DVertexCut");
  // kinematic cuts on muons
  const double ptMuonLowCut   = cfg.get<double>("ptMuonLowCut");
  const double ptMuonHighCut  = cfg.get<double>("ptMuonHighCut");
  const double etaMuonCut     = cfg.get<double>("etaMuonCut");
  const double dxyMuonCut     = cfg.get<double>("dxyMuonCut");
  const double dzMuonCut      = cfg.get<double>("dzMuonCut");
  const double isoMuonLowCut  = cfg.get<double>("isoMuonLowCut");
  const double isoMuonHighCut = cfg.get<double>("isoMuonHighCut");
  const double isoMuonHighCutQCD = cfg.get<double>("isoMuonHighCutQCD");
  const bool applyMuonId     = cfg.get<bool>("ApplyMuonId");
 
  const double ptTauLowCut = cfg.get<double>("ptTauLowCut"); 
  const double etaTauCut = cfg.get<double>("etaTauCut"); 

  const string dataBaseDir = cfg.get<string>("DataBaseDir");

  string TrigLeg  ;
   if (!isData) TrigLeg  = cfg.get<string>("Mu17LegMC");
   if (isData) TrigLeg  = cfg.get<string>("Mu18LegData");
  const string Mu17Tau20MuLegA  = cfg.get<string>("Mu17Tau20MuLegA");
  const string Mu17Tau20MuLegB  = cfg.get<string>("Mu17Tau20MuLegB");
  const string Mu17Tau20TauLegA  = cfg.get<string>("Mu17Tau20TauLegA");
  const string Mu17Tau20TauLegB  = cfg.get<string>("Mu17Tau20TauLegB");
 
  const string SingleMuonTriggerFile  = cfg.get<string>("Muon17TriggerEff");
  const float singleMuonTriggerPtCut = cfg.get<float>("SingleMuonTriggerPtCut");
  const float singleMuonTriggerEtaCut = cfg.get<float>("SingleMuonTriggerEtaCut");

  const string Region  = cfg.get<string>("Region");
  const string Sign  = cfg.get<string>("Sign");


  const double leadchargedhadrcand_dz = cfg.get<double>("leadchargedhadrcand_dz");
  const double leadchargedhadrcand_dxy = cfg.get<double>("leadchargedhadrcand_dxy");



  // kinematic cuts on Jets
  const double etaJetCut   = cfg.get<double>("etaJetCut");
  const double ptJetCut   = cfg.get<double>("ptJetCut");
  
  
  // topological cuts
  const double dRleptonsCutmutau   = cfg.get<double>("dRleptonsCutmutau");
  const double dZetaCut       = cfg.get<double>("dZetaCut");
  const double deltaRTrigMatch = cfg.get<double>("DRTrigMatch");
  const bool oppositeSign    = cfg.get<bool>("oppositeSign");
  const bool isIsoR03 = cfg.get<bool>("IsIsoR03");
 
  // tau
  const double taupt    = cfg.get<double>("taupt");
  const double taueta    = cfg.get<double>("taueta");
  const double decayModeFinding    = cfg.get<double>("decayModeFinding");
  const double   decayModeFindingNewDMs  = cfg.get<double>("decayModeFindingNewDMs");
  const double   againstElectronVLooseMVA5  = cfg.get<double>("againstElectronVLooseMVA5");
  const double   againstMuonTight3  = cfg.get<double>("againstMuonTight3");
  const double   vertexz =  cfg.get<double>("vertexz");
  const double   byCombinedIsolationDeltaBetaCorrRaw3Hits = cfg.get<double>("byCombinedIsolationDeltaBetaCorrRaw3Hits");
  

  const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
  const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");
  
  // 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");

  // lepton scale factors
  const string muonSfDataBarrel = cfg.get<string>("MuonSfDataBarrel");
  const string muonSfDataEndcap = cfg.get<string>("MuonSfDataEndcap");
  const string muonSfMcBarrel = cfg.get<string>("MuonSfMcBarrel");
  const string muonSfMcEndcap = cfg.get<string>("MuonSfMcEndcap");
  
  const string jsonFile = cfg.get<string>("jsonFile");

  string cmsswBase = (getenv ("CMSSW_BASE"));
  string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;

  const string MuonIdIsoFile = cfg.get<string>("MuonIdIsoEff");
  const string TauFakeRateFile = cfg.get<string>("TauFakeRateEff");

  // 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); ) {
	  //std::fstream inputFileStream("temp", std::ios::in);
           periods.push_back(Period());
           std::stringstream ss(s);
           ss >> periods.back();
          }
  }

  TString MainTrigger(TrigLeg);
  TString Muon17Tau20MuLegA (Mu17Tau20MuLegA );
  TString Muon17Tau20MuLegB (Mu17Tau20MuLegB );
  TString Muon17Tau20TauLegA (Mu17Tau20TauLegA );
  TString Muon17Tau20TauLegB (Mu17Tau20TauLegB );



  const double Lumi   = cfg.get<double>("Lumi");
  const double bTag   = cfg.get<double>("bTag");
  const double metcut = cfg.get<double>("metcut");
 
  CutList.clear();
  CutList.push_back("No cut");
  CutList.push_back("No cut after PU");
  CutList.push_back("$\\mu$");
  CutList.push_back("$\\tau_h$");
  CutList.push_back("Trigger");
  CutList.push_back("2nd $\\ell$-Veto");
  CutList.push_back("3rd $\\ell$-Veto");
  CutList.push_back("Lepton SF");
  CutList.push_back("TauFakeRate");
  CutList.push_back("topPtRwgt");
  CutList.push_back("${M}_T>60");
  CutList.push_back("$ E_T^{\\rm miss}>$ 100");
  CutList.push_back("Jets $<$3");
  CutList.push_back("b-Veto");
  CutList.push_back("$40<\\rm{Inv}_M<80");
  CutList.push_back("$1.5<\\Delta R<4$");
 

  int CutNumb = int(CutList.size());
  xs=1;fact=1;fact2=1;
 
  unsigned int RunMin = 9999999;
  unsigned int RunMax = 0;
        
  ifstream ifs("xsecs");
  string line;

  while(std::getline(ifs, line)) // read one line from ifs
    {
		
      fact=fact2=1;
      istringstream iss(line); // access line as a stream

      // we only need the first two columns
      string dt,st1,st2;st1="stau2_1";st2="stau5_2";
      iss >> dt >> xs >> fact >> fact2;
      //ifs >> dt >> xs; // no need to read further
      //cout<< " "<<dt<<"  "<<endl;
      //cout<< "For sample ========================"<<dt<<" xsecs is "<<xs<<" XSec "<<XSec<<"  "<<fact<<"  "<<fact2<<endl;
      //if (dt==argv[2]) {
      //if (std::string::npos != dt.find(argv[2])) {
      if (  dt == argv[2]) {
	XSec= xs*fact*fact2;
	cout<<" Found the correct cross section "<<xs<<" for Dataset "<<dt<<" XSec "<<XSec<<endl;
      }
      /*
  	if ( argv[2] == st1) {ChiMass=100;mIntermediate=200;}
	else if (argv[2] == st2) {ChiMass=200;mIntermediate=500;}
	*/
      if (isData) XSec=1.;
	ChiMass=0.0;
    }

  if (XSec<0&& !isData) {cout<<" Something probably wrong with the xsecs...please check  - the input was "<<argv[2]<<endl;return 0;}

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

  cout<<" ChiMass is "<<ChiMass<<"  "<<mIntermediate<<endl;
  bool doThirdLeptVeto=true;
  bool doMuVeto=true;

  //CutList[CutNumb]=CutListt[CutNumb];
  char ff[100];

	
  sprintf(ff,"%s/%s",argv[3],argv[2]);

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

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

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


  vertexDataH->Scale(1/normVertexData);
  vertexMcH->Scale(1/normVertexMc);
 
  PileUp * PUofficial = new PileUp();

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


  TFile *f10= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataBarrel);  // mu SF barrel data
  TFile *f11 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataEndcap); // mu SF endcap data
  TFile *f12= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcBarrel);  // mu SF barrel MC
  TFile *f13 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcEndcap); // mu SF endcap MC 
  
  TGraphAsymmErrors *hEffBarrelData = (TGraphAsymmErrors*)f10->Get("ZMassBarrel");
  TGraphAsymmErrors *hEffEndcapData = (TGraphAsymmErrors*)f11->Get("ZMassEndcap");
  TGraphAsymmErrors *hEffBarrelMC = (TGraphAsymmErrors*)f12->Get("ZMassBarrel");
  TGraphAsymmErrors *hEffEndcapMC = (TGraphAsymmErrors*)f13->Get("ZMassEndcap");
  
  double * dataEffBarrel = new double[10];
  double * dataEffEndcap = new double[10];
  double * mcEffBarrel = new double[10];
  double * mcEffEndcap = new double[10];
  
  dataEffBarrel = hEffBarrelData->GetY();
  dataEffEndcap = hEffEndcapData->GetY();
  mcEffBarrel = hEffBarrelMC->GetY();
  mcEffEndcap = hEffEndcapMC->GetY();


// Lepton Scale Factors 

  TH1D * MuSF_IdIso_Mu1H = new TH1D("MuIdIsoSF_Mu1H", "MuIdIsoSF_Mu1", 100, 0.5,1.5);

  ScaleFactor * SF_muonIdIso; 
  if (applyLeptonSF) {
    SF_muonIdIso = new ScaleFactor();
    SF_muonIdIso->init_ScaleFactor(TString(cmsswBase)+"/src/"+TString(MuonIdIsoFile));
  }
	ScaleFactor * SF_muonTrigger = new ScaleFactor();
	SF_muonTrigger->init_ScaleFactor(TString(cmsswBase)+"/src/"+TString(SingleMuonTriggerFile));

  ////////
  cout<<" Will try to initialize the TFR now.... "<<endl;
  ScaleFactor * SF_TFR; 
  bool applyTFR = true;
  if (applyTFR) {
    SF_TFR = new ScaleFactor();
    SF_TFR->init_ScaleFactorb(TString(cmsswBase)+"/src/"+TString(TauFakeRateFile),applyTFR);
  }


  double Weight=0;
  int nTotalFiles = 0;
  int iCut=0;
  double CFCounter[CutNumb];
  double statUnc[CutNumb];
  int iCFCounter[CutNumb];
  for (int i=0;i < CutNumb; i++){
    CFCounter[i] = 0;
    iCFCounter[i] = 0;
    statUnc[i] =0;
  }
  // file name and tree name
  std::string rootFileName(argv[2]);
  //std::ifstream fileList(argv[2]);
  std::ifstream fileList(ff);
  //std::ifstream fileList0(argv[2]);
  std::ifstream fileList0(ff);
  std::string ntupleName("makeroottree/AC1B");
  std::string initNtupleName("initroottree/AC1B");
  
  TString era=argv[3];
  TString invMuStr,invTauStr,invMETStr;
  if(InvertLeptonIso) invMuStr = "_InvMuIso_";
  if(InvertTauIso) invTauStr = "_InvTauIso_";
  if(InvertMET) invMETStr = "_InvMET_";

  TString TStrName(rootFileName+invMuStr+invTauStr+invMETStr+"_"+Region+"_"+Sign);
  std::cout <<" The filename will be "<<TStrName <<std::endl;  

  // output fileName with histograms
  TFile * file;
  if (isData) file = new TFile(era+"/"+TStrName+TString("_DataDriven.root"),"update");
  if (!isData) file = new TFile(era+"/"+TStrName+TString(".root"),"update");
  file->mkdir(Channel.c_str());
  file->cd(Channel.c_str());

  int nFiles = 0;
  int nEvents = 0;
  int selEvents = 0;

  int selEventsAllMuons = 0;
  int selEventsIdMuons = 0;
  int selEventsIsoMuons = 0;
      bool lumi=false;
      bool isLowIsoMu=false;
      bool isHighIsoMu = false;
      bool isLowIsoTau=false;
      bool isHighIsoTau = false;


  std::string dummy;
  // count number of files --->
  while (fileList0 >> dummy) nTotalFiles++;
 
  SetupHists(CutNumb); 
  if (argv[4] != NULL  && atoi(argv[4])< nTotalFiles) nTotalFiles=atoi(argv[4]);
  //if (nTotalFiles>50) nTotalFiles=50;
  //nTotalFiles = 10;
  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);



    

	//	    if (std::string::npos != rootFileName.find("TTJetsLO") || std::string::npos != rootFileName.find("TTPow"))
    	
			    
			    //numberOfEntries = 1000;

    // numberOfEntries = 1000;
    for (Long64_t iEntry=0; iEntry<numberOfEntries; ++iEntry) { 
     
      Float_t weight = 1;
      Float_t puweight = 1;
      //float topptweight = 1;
      analysisTree.GetEntry(iEntry);
      nEvents++;
    
      iCut = 0;
      
    //std::cout << "      number of entries in Tree = " << numberOfEntries <<" starting weight "<<weight<< std::endl;
     
      if (nEvents%50000==0) 
	cout << "      processed " << nEvents << " events" << endl; 
     
      if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
      if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
      double dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
		       analysisTree.primvertex_y*analysisTree.primvertex_y);
      if (dVertex>dVertexCut) continue;
      if (analysisTree.primvertex_count<2) continue;  

      //isData= false;
      bool lumi=false;
      isLowIsoMu=false;
      isHighIsoMu = false;
      isLowIsoTau=false;
      isHighIsoTau = false;

    Float_t genweights;
    float topPt = 0;
    float antitopPt = 0;
    bool isZTT = false;

    if(!isData) 
    {
 /*   TTree *genweightsTree = (TTree*)file_->Get("initroottree/AC1B");
	     
    genweightsTree->SetBranchAddress("genweight",&genweights);
    Long64_t numberOfEntriesInit = genweightsTree->GetEntries();
    for (Long64_t iEntryInit=0; iEntryInit<numberOfEntriesInit; ++iEntryInit) { 
      genweightsTree->GetEntry(iEntryInit);
	histWeightsH->Fill(0.,genweights);
    }
   */ /*
	for (unsigned int igent=0; igent < analysisTree.gentau_count; ++igent) {
	  if (analysisTree.gentau_isPrompt[igent]) isZTT = true; 
	}
*/
	for (unsigned int igen=0; igen<analysisTree.genparticles_count; ++igen) {
	   // 		cout<< "  info = " <<  int(analysisTree.genparticles_count) <<"  "<<int(analysisTree.genparticles_pdgid[igen])<<endl;

	  if (analysisTree.genparticles_pdgid[igen]==6)
	    topPt = TMath::Sqrt(analysisTree.genparticles_px[igen]*analysisTree.genparticles_px[igen]+
				analysisTree.genparticles_py[igen]*analysisTree.genparticles_py[igen]);
	  if (analysisTree.genparticles_pdgid[igen]==-6)
	    antitopPt = TMath::Sqrt(analysisTree.genparticles_px[igen]*analysisTree.genparticles_px[igen]+
				    analysisTree.genparticles_py[igen]*analysisTree.genparticles_py[igen]);

	}    
    
	  weight *= analysisTree.genweight;
	  lumi=true;
        //cout<<"  weight from init "<<genweights<< "  "<<analysisTree.genweight<<"  "<<weight<<endl;
/*
	if (applyPUreweighting) {
	  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 (isData)  {
	XSec = 1.;
	histRuns->Fill(analysisTree.event_run);
///////////////according to dimuons
	int n=analysisTree.event_run;
	int lum = analysisTree.event_luminosityblock;
	
	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) continue;
	//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
      }


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




      if (!lumi) continue;
      JetsMV.clear();
      ElMV.clear();
      TauMV.clear();
      MuMV.clear();
      LeptMV.clear();
      mu_index=-1;
      tau_index=-1;
      el_index=-1;
      double MET = sqrt ( analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
      
      METV.SetPx(analysisTree.pfmet_ex);	      
      METV.SetPy(analysisTree.pfmet_ey);
      METV.SetPz(analysisTree.pfmet_ez);
      METV.SetPhi(analysisTree.pfmet_phi);
    
      
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;
	



 
      for (unsigned int ijj = 0; ijj<analysisTree.pfjet_count; ++ijj) {
	JetsV.SetPxPyPzE(analysisTree.pfjet_px[ijj], analysisTree.pfjet_py[ijj], analysisTree.pfjet_pz[ijj], analysisTree.pfjet_e[ijj]);
	JetsMV.push_back(JetsV);
      } 


      for (unsigned int imm = 0; imm<analysisTree.muon_count; ++imm) {
	MuV.SetPtEtaPhiM(analysisTree.muon_pt[imm], analysisTree.muon_eta[imm], analysisTree.muon_phi[imm], muonMass);
	MuMV.push_back(MuV);
	//	mu_index=0;
      }

      for (unsigned int ie = 0; ie<analysisTree.electron_count; ++ie) {
	ElV.SetPtEtaPhiM(analysisTree.electron_pt[ie], analysisTree.electron_eta[ie], analysisTree.electron_phi[ie], electronMass);
	ElMV.push_back(ElV);
	//	el_index=0;
      }
   
      for (unsigned int itt = 0; itt<analysisTree.tau_count; ++itt) {
	TauV.SetPtEtaPhiM(analysisTree.tau_pt[itt], analysisTree.tau_eta[itt], analysisTree.tau_phi[itt], tauMass);
	TauMV.push_back(TauV);
	//	tau_index=0;
      }

	 if (!isData )
	 	{
	if (applyPUreweighting)	 {
		puweight = float(PUofficial->get_PUweight(double(analysisTree.numtruepileupinteractions)));
	         weight *=puweight;      
		}
	}
      

      // vector <string> ss; ss.push_back(.c_str());
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

 
      //selecTable.Fill(1,0, weight );      
      bool trigAccept = false;
      
      unsigned int nMainTrigger = 0;
      bool isMainTrigger = false;
      
      

      unsigned int nfilters = analysisTree.run_hltfilters->size();
      //  std::cout << "nfiltres = " << nfilters << std::endl;
      for (unsigned int i=0; i<nfilters; ++i) {
	//	std::cout << "HLT Filter : " << i << " = " << analysisTree.run_hltfilters->at(i) << std::endl;
	TString HLTFilter(analysisTree.run_hltfilters->at(i));
	if (HLTFilter==MainTrigger) {
	  nMainTrigger = i;
	  isMainTrigger = true;
	}
      

      
      }


      if (!isMainTrigger) {
	std::cout << "HLT filter for Mu20 " << MainTrigger << " not found" << std::endl;
	return(-1);
      }

      /////now clear the Mu.El.Jets again to fill them again after cleaning
        MuMV.clear();
        ElMV.clear();
        TauMV.clear();
        LeptMV.clear();

      double isoMuMin = 9999;
      bool mu_iso=false;
      vector<int> muons; muons.clear();
      for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
	if (analysisTree.muon_pt[im]<ptMuonLowCut) continue;
	if (fabs(analysisTree.muon_eta[im])>etaMuonCut) continue;
	if (fabs(analysisTree.muon_dxy[im])>dxyMuonCut) continue;
	if (fabs(analysisTree.muon_dz[im])>dzMuonCut) continue;


         double absIso= analysisTree.muon_r03_sumChargedHadronPt[im]
	            + max(analysisTree.muon_r03_sumNeutralHadronEt[im] + analysisTree.muon_r03_sumPhotonEt[im]
	            - 0.5 * analysisTree.muon_r03_sumPUPt[im],0.0);


	double relIso = absIso/analysisTree.muon_pt[im];
 
	if (relIso<isoMuonLowCut) continue;

	if (applyMuonId && !analysisTree.muon_isMedium[im]) continue;

	  //cout<<" after muIso index "<<int(mu_index)<<" pT "<<analysisTree.muon_pt[im]<<" relIso "<<relIso<<" isoMuMin "<<isoMuMin<<" muon_count "<<analysisTree.muon_count<<" im "<<im<<" event "<<iEntry<<endl;
	if (double(relIso)<double(isoMuMin)) {
	  isoMuMin  = relIso;
	  mu_index = int(im);
	  mu_iso=true;
	  //cout<<" after muIso index "<<int(mu_index)<<" pT "<<analysisTree.muon_pt[im]<<" relIso "<<relIso<<" isoMuMin "<<isoMuMin<<" muon_count "<<analysisTree.muon_count<<" im "<<im<<" event "<<iEntry<<endl;
	  muons.push_back(im);
	  MuV.SetPtEtaPhiM(analysisTree.muon_pt[mu_index], analysisTree.muon_eta[mu_index], analysisTree.muon_phi[mu_index], muonMass);
	  MuMV.push_back(MuV);
          LeptMV.push_back(MuV);
	}
	//cout<<" Indexes here  "<<im<<"   "<<mu_index<<endl;

	if (relIso == isoMuMin && im != mu_index) {
	  //cout<<" found a pair  for muons " <<relIso <<" mu_index  "<<mu_index<<"  pT "<<analysisTree.muon_pt[int(mu_index)]<<" new  index "<<im<<"  pT  "<<analysisTree.muon_pt[int(im)]<<" event "<<iEntry<<endl;
	  analysisTree.muon_pt[im] > analysisTree.muon_pt[mu_index] ? mu_index = int(im) : mu_index = mu_index;
	}
   
      }
         if (muons.size()==0 || !mu_iso ) continue;

         double absIso= analysisTree.muon_r03_sumChargedHadronPt[mu_index]
	            + max(analysisTree.muon_r03_sumNeutralHadronEt[mu_index] + analysisTree.muon_r03_sumPhotonEt[mu_index]
	            - 0.5 * analysisTree.muon_r03_sumPUPt[mu_index],0.0);


	double relIso = absIso/analysisTree.muon_pt[mu_index];

	 if (relIso>isoMuonHighCut && !InvertLeptonIso) continue;

	 if (relIso>isoMuonHighCutQCD ) { isHighIsoMu=true ;isLowIsoMu=false;}
	  else    { isHighIsoMu = false;isLowIsoMu=true;}
 

       sort(LeptMV.begin(), LeptMV.end(),ComparePt); 
       if (LeptMV.size() == 0 ) continue; 
	if (InvertLeptonIso && !isHighIsoMu) continue;
	if (!InvertLeptonIso && isHighIsoMu) continue;
	if (InvertLeptonIso && isLowIsoMu) continue;
      

//cout<<"  Iso check  "<<relIso<<" InvertLeptonIso "<<InvertLeptonIso<<" isHighIsoMu "<<isHighIsoMu<<" isLowIsoMu "<<isLowIsoMu<<" cutQCD "<<isoMuonHighCutQCD<<endl;


      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;


      double isoTauMin = 999;
      bool tau_iso = false;
      vector<int> tau; tau.clear();
      for (unsigned int it = 0; it<analysisTree.tau_count; ++it) {

	if (analysisTree.tau_pt[it] < ptTauLowCut || fabs(analysisTree.tau_eta[it])> etaTauCut) continue;
	if (analysisTree.tau_decayModeFindingNewDMs[it]<decayModeFindingNewDMs) continue;
	if ( fabs(analysisTree.tau_leadchargedhadrcand_dz[it])> leadchargedhadrcand_dz) continue;

	if (analysisTree.tau_againstElectronVLooseMVA5[it]<againstElectronVLooseMVA5) continue;
	if (analysisTree.tau_againstMuonTight3[it]<againstMuonTight3) continue;

	//cout<<"  "<<analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[it]<<endl;
	
	if (!InvertTauIso && analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it] > byCombinedIsolationDeltaBetaCorrRaw3Hits ) continue;
	//if (!InvertTauIso && analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[it] < 0.5 ) continue;

	double  tauIso = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it];

	if (tauIso<isoTauMin ) {
	  //      cout<<"  there was a chenge  "<<tauIso<<"  "<<isoTauMin<<" it "<<it<<" tau_index "<<tau_index<<"  "<<analysisTree.tau_count<<endl;
	  isoTauMin  = tauIso;
	  tau_iso=true;
	  tau_index = (int)it;
	  tau.push_back(tau_index);
	  TauV.SetPtEtaPhiM(analysisTree.tau_pt[tau_index], analysisTree.tau_eta[tau_index], analysisTree.tau_phi[tau_index], tauMass);
	  TauMV.push_back(TauV);

	}

continue;

	if (tauIso==isoTauMin && it != tau_index) {
	  //analysisTree.tau_pt[it] > analysisTree.tau_pt[tau_index] ? tau_index = it : tau_index = tau_index;
	  if (analysisTree.tau_pt[it] > analysisTree.tau_pt[tau_index] ) tau_index = (int)it ;
	  //cout<<" found a pair  " <<tauIso <<"  "<<tau_index<<"  "<<it<<endl;
	}
      }
      if (tau.size()==0 || !tau_iso ) continue;

      // cout<< " Lets check  "<<mu_index <<"  "<<tau_index <<"  "<<endl;
      //cout<<"  "<<endl;
////////////////////change to new tau inverted definition 
      double tauIsoI = analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[tau_index];
      if (tauIsoI > 0.5  && InvertTauIso) {isHighIsoTau =true;} 
      //else {isHighIsoTau =false ; isLowIsoTau=true;} 
      //if (isHighIsoTau && tauIso > 2*byCombinedIsolationDeltaBetaCorrRaw3Hits ) continue; 

      if (InvertTauIso && !isHighIsoTau) continue;
      if (!InvertTauIso && isHighIsoTau) continue;
      //if (InvertTauIso && isLowIsoTau) continue;


/*
      continue;
      double isoTauMin = 999;
      bool tau_iso = false;
      vector<int> tau; tau.clear();
      for (unsigned  int it = 0; it<analysisTree.tau_count; ++it) {

	if (analysisTree.tau_pt[it] < ptTauLowCut || fabs(analysisTree.tau_eta[it])> etaTauCut) continue;
	if (analysisTree.tau_decayModeFindingNewDMs[it]<decayModeFindingNewDMs) continue;
	if ( fabs(analysisTree.tau_leadchargedhadrcand_dz[it])> leadchargedhadrcand_dz) continue;
	
	if (analysisTree.tau_againstElectronVLooseMVA5[it]<againstElectronVLooseMVA5) continue;
	if (analysisTree.tau_againstMuonTight3[it]<againstMuonTight3) continue;
	//if (!InvertTauIso && analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it] > byCombinedIsolationDeltaBetaCorrRaw3Hits ) continue;
	cout<<"  "<<analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[it]<<endl;
	//aif (!InvertTauIso && analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[it] < 0.5 ) continue;

	double  tauIso = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it];

	if (tauIso<isoTauMin ) {
	  //      cout<<"  there was a chenge  "<<tauIso<<"  "<<isoTauMin<<" it "<<it<<" tau_index "<<tau_index<<"  "<<analysisTree.tau_count<<endl;
	  isoTauMin  = tauIso;
	  tau_iso=true;
	  tau_index = int(it);
	  tau.push_back(tau_index);
	  TauV.SetPtEtaPhiM(analysisTree.tau_pt[tau_index], analysisTree.tau_eta[tau_index], analysisTree.tau_phi[tau_index], tauMass);
	  TauMV.push_back(TauV);

	}

	if (tauIso==isoTauMin && it != tau_index) {
	  analysisTree.tau_pt[it] > analysisTree.tau_pt[tau_index] ? tau_index = int(it) : tau_index = tau_index;
	  //cout<<" found a pair  " <<tauIso <<"  "<<tau_index<<"  "<<it<<endl;
	}
      }
      if (tau.size()==0 || !tau_iso ) continue;
      double tauIsoI = analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits[tau_index];
      if (tauIsoI > 0.5  && InvertTauIso) {isHighIsoTau =true;} 
      //else {isHighIsoTau =false ; isLowIsoTau=true;} 
      //if (isHighIsoTau && tauIso > 2*byCombinedIsolationDeltaBetaCorrRaw3Hits ) continue; 

      if (InvertTauIso && !isHighIsoTau) continue;
      if (!InvertTauIso && isHighIsoTau) continue;
      //if (InvertTauIso && isLowIsoTau) continue;
*/
  
      double q = analysisTree.tau_charge[tau_index] * analysisTree.muon_charge[mu_index];
  
      if (q>0 && Sign=="OS" ) continue;
      if (q<0 && Sign=="SS" ) continue;

      bool regionB = (q<0 && isLowIsoMu);
      bool regionA = (q>0 && isLowIsoMu);
      bool regionC = (q<0 && isHighIsoMu);
      bool regionD = (q>0 && isHighIsoMu);

      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

	//cout<<"  HOW MANY MUONS DO I HAVE ??  "<<muons.size()<<endl;

	bool isdRLeptonMatched = false;
	for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
	  if (analysisTree.trigobject_filters[iT][nMainTrigger]) { // Mu17 Leg
	    double dRtrig = deltaR(analysisTree.muon_eta[mu_index],analysisTree.muon_phi[mu_index],
				  analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	    if (!isData && analysisTree.trigobject_filters[iT][nMainTrigger] && analysisTree.trigobject_pt[iT]>singleMuonTriggerPtCut && dRtrig<deltaRTrigMatch)
	      isdRLeptonMatched = true;

	    if (isData && dRtrig<deltaRTrigMatch) isdRLeptonMatched=true;
	    
	  }
	}
		
	     if (!isdRLeptonMatched) continue;

	double dR = deltaR(analysisTree.tau_eta[tau_index],analysisTree.tau_phi[tau_index],
			analysisTree.muon_eta[mu_index],analysisTree.muon_phi[mu_index]);

      	if (dR<dRleptonsCutmutau) continue;

   
			double ptMu1 = (double)analysisTree.muon_pt[mu_index];
			double etaMu1 = (double)analysisTree.muon_eta[mu_index];
			float trigweight=1.;


			float Mu17EffData = (float)SF_muonTrigger->get_EfficiencyData(double(ptMu1),double(etaMu1));
			float Mu17EffMC   = (float)SF_muonTrigger->get_EfficiencyMC(double(ptMu1),double(etaMu1));

			if (!isData) {
				if (Mu17EffMC>1e-6)
					trigweight = Mu17EffData / Mu17EffMC;
				weight *= trigweight;
			//	cout<<" Trigger weight "<<trigweight<<endl;
			}




	if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;


      //Set this flag if there is an opposite-charge muon pair in the event with muons separated by DR>0.15 and both passing the loose selection: 
	


      bool MuVeto=false;

      if (doMuVeto){

     	if (muons.size()>1){
	  for (unsigned  int imv = 0; imv<analysisTree.muon_count; ++imv) {
	    if ( imv != mu_index ){
              double absIso= analysisTree.muon_r03_sumChargedHadronPt[imv]
	            + max(analysisTree.muon_r03_sumNeutralHadronEt[imv] + analysisTree.muon_r03_sumPhotonEt[imv]
	            - 0.5 * analysisTree.muon_r03_sumPUPt[imv],0.0);


	     double relIso = absIso/analysisTree.muon_pt[imv];


	      double dRr = deltaR(analysisTree.muon_eta[mu_index],analysisTree.muon_phi[mu_index],
				 analysisTree.muon_eta[imv],analysisTree.muon_phi[imv]);
	        bool OSCharge = false;  
		if ( imv != mu_index  && analysisTree.muon_charge[imv] != analysisTree.muon_charge[mu_index] ) OSCharge=true;

	      //if ( analysisTree.muon_charge[imv] != analysisTree.muon_charge[mu_index] &&  analysisTree.muon_isGlobal[imv] && analysisTree.muon_isTracker[imv] && analysisTree.muon_isPF[imv]  
	      if ( analysisTree.muon_charge[imv] != analysisTree.muon_charge[mu_index] &&  analysisTree.muon_isGlobal[imv] && analysisTree.muon_isTracker[imv] && analysisTree.muon_isPF[imv]  
		   &&  analysisTree.muon_pt[imv]> 15 &&  fabs(analysisTree.muon_eta[imv])< 2.4 && fabs(analysisTree.muon_dxy[imv])<0.045 
		   && fabs(analysisTree.muon_dz[imv] < 0.2 && relIso< 0.3 && analysisTree.muon_isMedium[imv]) && dRr > 0.15 && OSCharge) //removed from last recipe
		MuVeto=true;
	    }
	  }
	}
      }
      if (MuVeto) continue;

      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;



      bool ThirdLeptVeto=false;

      if (doThirdLeptVeto){
  	if (analysisTree.electron_count>0) {
	  for (unsigned int iev = 0; iev<analysisTree.electron_count; ++iev) {

/*
	    double neutralIsoV = analysisTree.electron_r03_sumNeutralHadronEt[iev] + analysisTree.electron_r03_sumNeutralHadronEt[iev] + analysisTree.electron_r03_sumPhotonEt[iev] -  4*TMath::Pi()*(0.3*0.3)*analysisTree.rho;
	    double IsoWithEA =  analysisTree.electron_r03_sumChargedHadronPt[iev] + TMath::Max(double(0), neutralIsoV);
	

*/

           double IsoWithEA = analysisTree.electron_r03_sumChargedHadronPt[iev] 
			   + max(analysisTree.electron_r03_sumNeutralHadronEt[iev] + analysisTree.electron_r03_sumPhotonEt[iev]
		           - 0.5 * analysisTree.electron_r03_sumPUPt[iev], 0.0) ;

           double relIsoV = IsoWithEA/analysisTree.electron_pt[iev];


	    bool electronMvaId = electronMvaIdWP90(analysisTree.electron_pt[iev], analysisTree.electron_superclusterEta[iev], analysisTree.electron_mva_id_nontrigPhys14[iev]);


	    if ( iev != el_index && analysisTree.electron_pt[iev] > 10 &&  fabs(analysisTree.electron_eta[iev]) < 2.5 && fabs(analysisTree.electron_dxy[iev])<0.045
		 && fabs(analysisTree.electron_dz[iev]) < 0.2 && relIsoV< 0.3 && electronMvaId && analysisTree.electron_pass_conversion[iev] 
		 && analysisTree.electron_nmissinginnerhits[iev] <=1) ThirdLeptVeto=true;

	  }
	}


     	if (analysisTree.muon_count>0){
	  for (unsigned int imvv = 0; imvv<analysisTree.muon_count; ++imvv) {

	    //       if ( imvv != mu_index  && analysisTree.muon_charge[imvv] != analysisTree.muon_charge[mu_index] ){

         double absIso= analysisTree.muon_r03_sumChargedHadronPt[imvv]
	            + max(analysisTree.muon_r03_sumNeutralHadronEt[imvv] + analysisTree.muon_r03_sumPhotonEt[imvv]
	            - 0.5 * analysisTree.muon_r03_sumPUPt[imvv],0.0);

	double relIso = absIso/analysisTree.muon_pt[imvv];


	    if ( imvv != mu_index &&  analysisTree.muon_isMedium[imvv] &&  analysisTree.muon_pt[imvv]> 10 &&  fabs(analysisTree.muon_eta[imvv])< 2.4 && fabs(analysisTree.muon_dxy[imvv])<0.045 
		 && fabs(analysisTree.muon_dz[imvv] < 0.2 && relIso< 0.3 && analysisTree.muon_isMedium[imvv]) ) ThirdLeptVeto=true;
	  }
	}
      }
  
      if (ThirdLeptVeto) continue;


      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

	if (!isData && applyLeptonSF) {

	//leptonSFweight = SF_yourScaleFactor->get_ScaleFactor(pt, eta)	
	  double ptMu1 = (double)analysisTree.muon_pt[mu_index];
	  double etaMu1 = (double)analysisTree.muon_eta[mu_index];
	  double IdIsoSF_mu1 = SF_muonIdIso->get_ScaleFactor(ptMu1, etaMu1);

	
	  MuSF_IdIso_Mu1H->Fill(IdIsoSF_mu1);
	  weight = weight*IdIsoSF_mu1;
	}
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;



       TLorentzVector muVc ;  muVc.SetPtEtaPhiM(analysisTree.muon_pt[mu_index], analysisTree.muon_eta[mu_index], analysisTree.muon_phi[mu_index], muonMass);
       TLorentzVector tauVc;  tauVc.SetPtEtaPhiM(analysisTree.tau_pt[tau_index], analysisTree.tau_eta[tau_index], analysisTree.tau_phi[tau_index], tauMass);
       double MTv = mT(muVc,METV);

	if (!isData && applyTFR) {

	//leptonSFweight = SF_yourScaleFactor->get_ScaleFactor(pt, eta)	

	  double ptTau1 = (double)analysisTree.tau_pt[tau_index];
	  double etaTau1 = (double)analysisTree.tau_eta[tau_index];
	  double TFRSF_mu1 = SF_TFR->get_ScaleFactor(ptTau1, etaTau1);
	
	  MuSF_IdIso_Mu1H->Fill(TFRSF_mu1);
	  weight = weight*TFRSF_mu1;
	  //cout<<"  "<<TFRSF_mu1<<"  for  eta  "<<etaTau1<<  " pT  "<< ptTau1<<endl;
	}

      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

	
	 if (!isData && ( string::npos != filen.find("TTJets")  || string::npos != filen.find("TTPowHeg")) )
	 //if (!isData )
	 	{
	
	if (topPt>0.&&antitopPt>0.) {
	  float topptweight = topPtWeight(topPt,antitopPt);
	//  cout<<"  "<<topPt<<"  "<<antitopPt<<endl;
		weight *= topptweight;
			}

		}

      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

      if (MTv<60 ) continue;
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;


      //	for (unsigned int j=0;j<LeptMV.size();++j) cout<<" j "<<j<<"  "<<LeptMV.at(j).Pt()<<endl;
      //	cout<<""<<endl;
      ////////jets cleaning 
      vector<int> jets; jets.clear();
      TLorentzVector leptonsV, muonJ, jetsLV;
      
      //      continue;
      
      //JetsV.SetPxPyPzE(analysisTree.pfjet_px[ij], analysisTree.pfjet_py[ij], analysisTree.pfjet_pz[ij], analysisTree.pfjet_e[ij]);
      


      //double ETmiss = TMath::Sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
      double ETmiss = METV.Pt();//TMath::Sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
      
      if (InvertMET && ETmiss > 100. ) continue;
      if (!InvertMET && ETmiss < 100. ) continue;  //that is the nominal selection ie MET > 100


      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;


      double ptScalarSum = -1;


      bool btagged= false;
      
    
      		JetsMV.clear();

		float jetEtaCut = 2.4;
      		float DRmax = 0.5;
		int countjets = 0;
	      for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
		float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	
		if (absJetEta > etaJetCut) continue;
                if (fabs(analysisTree.pfjet_pt[jet])<ptJetCut) continue;
	  

	  	//double Dr= deltaR(LeptMV.at(il).Eta(), LeptMV.at(il).Phi(),
	  

		bool isPFJetId = false ; 
		isPFJetId =looseJetiD(analysisTree,jet);

		
		if (!isPFJetId) continue;
		
		//for (unsigned int lep=0;LeptMV.size();lep++){
		//double Dr=(LeptMV.at(lep).Eta(),LeptMV.at(lep).Phi(),
		double Dr=deltaR(analysisTree.muon_eta[mu_index],analysisTree.muon_phi[mu_index],
				analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet]);
		if (  Dr  < DRmax)  continue;

		double Drr=deltaR(analysisTree.tau_eta[tau_index],analysisTree.tau_phi[tau_index],
				analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet]);
		if (  Drr  < DRmax)  continue;


		if (analysisTree.pfjet_btag[jet][0]  > bTag) btagged = true;
		JetsV.SetPxPyPzE(analysisTree.pfjet_px[jet], analysisTree.pfjet_py[jet], analysisTree.pfjet_pz[jet], analysisTree.pfjet_e[jet]);
		JetsMV.push_back(JetsV);
		countjets++;
	      }	 

      if (countjets >2 ) continue;
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

      if (btagged ) continue;
	
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;
  
  
      // pt Scalar

      //cout<<"  "<<mu_index<<"  "<<tau_index<<"   "<<MuMV.at(mu_index).M()<<"  "<<TauMV.at(tau_index).M()<<endl;


      TLorentzVector diL = muVc + tauVc;
      if ( diL.M() < 100 ) continue;
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;

       

     /* if (ETmiss < 100) continue;
      if (ETmiss < 120) continue;
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;
      // topological cut
      //if (DZeta<dZetaCut) continue;
       */


      //double dRr = deltaR(diL.Eta(), diL.Phi(), METV.Eta(), METV.Phi());
            double dRr = deltaR(muVc.Eta(), muVc.Phi(), tauVc.Eta(), tauVc.Phi());

      if (dRr>3 ) continue;
      
      if(fillplots)
      FillMainHists(iCut, weight, ElMV, MuMV, TauMV,JetsMV,METV, ChiMass,mIntermediate,analysisTree, Channel, mu_index,el_index,tau_index);
      CFCounter[iCut]+= weight;
      iCFCounter[iCut]++;
      iCut++;
      FillTree();
      selEvents++;
    } // end of file processing (loop over events in one file)
  
	

    nFiles++;
    delete _tree;
    file_->Close();
    delete file_;
  }
  cout<<"done"<<endl;
	
  cout<<" Total events  "<<nEvents<<"  Will use weight  "<<histWeightsH->GetSumOfWeights()<<" Norm Factor for a Lumi of "<<Lumi<<"/pb is "<<XSec*Lumi/( histWeightsH->GetSumOfWeights())<<endl;
  cout<<" First content "<<CFCounter[0]<<endl;
  cout<<" Run range from -----> "<<RunMin<<" to  "<<RunMax<<endl;
  /*
    for (int i=0;i<CutNumb;++i){
    CFCounter[i] *= double(XSec*Lumi/( histWeights->GetSumOfWeights()));
    if (iCFCounter[i] <0.2) statUnc[i] =0;
    else statUnc[i] = CFCounter[i]/sqrt(iCFCounter[i]);
    }
  */
  //write out cutflow
  ofstream tfile;
  // TString outname = argv[argc-1];
  TString outname=argv[2];
  TString textfilename = "cutflow_"+outname+"_"+Channel+"_"+argv[3]+".txt";
//  tfile.open(textfilename);
//  tfile << "########################################" << endl;
  for(int ci = 0; ci < CutNumb; ci++)
    {
     // tfile << CutList[ci]<<"\t & \t"
//	    << CFCounter[ci]  <<"\t & \t"<< statUnc[ci] <<"\t & \t"<< iCFCounter[ci] << endl;
   
      CutFlowUnW->SetBinContent(1+ci,0);
      CutFlow->SetBinContent(1+ci,0);
      CutFlowUnW->SetBinContent(1+ci,float(CFCounter[ci]) );
  

      CFCounter[ci] *= double(XSec*Lumi/( histWeightsH->GetSumOfWeights()));
     
      CutFlow->SetBinContent(1+ci,float(CFCounter[ci]));
      
      cout << " i "<<ci<<" "<<iCFCounter[ci]<<"  "<<XSec*Lumi/( histWeightsH->GetSumOfWeights())<<"  "<<CutFlowUnW->GetBinContent(1+ci)<<"  "<<CutFlow->GetBinContent(1+ci)<<endl;   
      if (iCFCounter[ci] <0.2) statUnc[ci] =0;
    //else statUnc[i] = CFCounter[i]/sqrt(iCFCounter[i]);
    else statUnc[ci] = sqrt(CFCounter[ci]);
  }
  //ofstream tfile1;
  //TString textfile_Con = "CMG_cutflow_Con_Mu_"+outname+".txt";
  //tfile1.open(textfile_Con);
  //tfile1 << "########################################" << endl;



  //tfile << "Cut efficiency numbers:" << endl;

  //    tfile << " Cut "<<"\t & \t"<<"#Evnts for "<<Lumi/1000<<" fb-1 & \t"<<" Uncertainty \t"<<" cnt\t"<<endl;

 // tfile.close();



  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 = " << selEvents << std::endl;
  std::cout << std::endl;
  

  file->cd(Channel.c_str());
  WriteTree();
  hxsec->Fill(XSec);
  hxsec->Write();
  inputEventsH->Write();
  histWeightsH->Write();
  histRuns->Write();
  CutFlowUnW->Write();
  CutFlow->Write();
  MuSF_IdIso_Mu1H->Write();
  file->Write();
  file->Close();
   
  delete file;
  
}
Пример #11
0
mainClass(int luminosity){//constructor
//Importnat
//make sure this initialization of the 
//maps is the same as that in main.cpp
 
    cutname[0]="nocut";
    cutname[1]="Asys";
    cutname[2]="MET200";
    cutname[3]="jetone";
    cutname[4]="jettwo";
    cutname[5]="3jet";
    cutname[6]="dphi";
    cutname[7]="nolep";
    cutname[8]="MET";
    cutname[9]="pt250";
    cutname[10]="pt300";
    cutname[11]="pt350";
    cutname[12]="pt400";
    cutname[13]="pt450";
    cutname[14]="pt500";
    cutname[15]="pt600";
    cutname[16]="pt700";
    cutname[17]="pt800";
    cutname[18]="pt900";
    cutname[19]="pt1000";
    cutname[20]="pt1100";
    cutname[21]="pt1200";
    cutname[22]="pt1300";
    cutname[23]="pt1400";
    cutname[24]="pt1500";


    type[0]="allEvents";
//    type[1]="W";
  //  type[2]="Wlv";
  //  type[3]="Wjj";
  //  type[4]="Z";
  //  type[5]="Zll";
  //  type[6]="Zvv";
  //  type[7]="Zjj";
  //  type[8]="photon";
//    type[9]="H";
   type[10]="TTbar";
   type[11]="TTSingLep";
   type[12]="TTdiLep";
   type[13]="TThadronic";



  //KH
  histname[0]="weight";
  histname[1]="METAsys";
  histname[2]="MET";
  histname[3]="NJet";
  histname[4]="j1Pt";
  histname[5]="Jet1Eta";
  histname[6]="Jet1Phi";
histname[7]="j2Pt";
histname[8]="Jet2Eta";
histname[9]="Jet2Phi";
histname[10]="j3Pt";
histname[11]="Jet3Eta";
histname[12]="Jet3Phi";
histname[13]="DelPhij1j2";
histname[14]="NLep";
histname[15]="NElec";
histname[16]="NMuon";
histname[17]="NTau";
  ///end of initialization of the maps

  //build a vector of scale factors
  //first load the cross sections into a vector
  xs_vec.push_back(530.89358);
  xs_vec.push_back(42.55351);
  xs_vec.push_back(4.48209);
  xs_vec.push_back(0.52795);
  xs_vec.push_back(0.05449);

  double numberofevents =0;
  const int ttnHT = 5;   // Total number of HT bin samples
  const int nHist = 18; // Number of histograms in each TDirectory


  for(int i=1; i<=ttnHT ; i++){
    sprintf(tempname,"../Results/results_PhaseI_TT_14TEV_HT%d_NoPileUp_00.root",i);
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MET_nocut_allEvents");
    tempvalue = (luminosity*xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());
    scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "normalization scale factor determination done" << std::endl;
for(int i=1; i<=ttnHT; i++){
sprintf(tempname,"../Results/results_PhaseI_TT_14TEV_HT%d_NoPileUp_00.root",i);
inputfilevec.push_back(TFile::Open(tempname,"R"));
}

tempstack = new THStack("stack","Binned Sample Stack");
file = new TFile("stack.root","RECREATE");
 for(map<int , string >::iterator itt=type.begin(); itt!=type.end();itt++){        // loop over different event types
    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();
    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames
      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();
      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms
        for(int i=0; i<ttnHT ; i++){                                                  // loop over different HT bins
sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
temphist = (TH1D *) inputfilevec.at(i)->Get(tempname)->Clone();
temphist->Scale(scalevec[i]);
if(histname[j]=="MET"){numberofevents+=(double)temphist->GetSumOfWeights();} //all the histograms in one directory have the same number of events
//if(histname[j]=="MET"){cout << " temphist->GetSumOfWeights() " << temphist->GetSumOfWeights() << endl;}
/*if(i==0){
cout << "" << endl;
cout << "type: " << (itt->second).c_str() << ",  cutname: " << (it->second).c_str()<< ", histname: " << histname[j].c_str() << ", bin#: " << i << endl;
cout << "temphist->GetEntries():  " << temphist->GetEntries() << endl;
cout << "temphist->GetSumOfWeights(): " << temphist->GetSumOfWeights() << endl;
cout << " ===============================================================" << endl;
}
*/
temphist->SetFillColor(i+2);
          tempstack->Add(temphist);
               }//end of loop over HTbins 1..7
if(histname[j]=="MET"){
cout << " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "type: " << (itt->second).c_str() << ",  cutname: " << (it->second).c_str() << endl;
cout << "Number of events:  " << numberofevents << endl;
cout << " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
}
numberofevents=0;
        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");
      }//end of loop over histograms
    }//end of loop over cutnames
  }//end of loop over event types
file->Close();


}//end of the constructor