Exemplo n.º 1
0
void h2fast(const char *url , Bool_t draw=kFALSE, Long64_t cachesize=10000000, Int_t learn=1) {
// gEnv->SetValue("TFile.DavixLog", 10);
//  gDebug= 0x02;
   TStopwatch sw;
   TTree* T = NULL;
   sw.Start();
   Long64_t oldb = TFile::GetFileBytesRead();
   TFile *f = TFile::Open(url);
  
   if (!f || f->IsZombie()) {
      printf("File h1big.root does not exist\n");
      exit (-1);
   }
   

//   TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);

   T= (TTree*)f->Get("h42");
   Long64_t nentries = T->GetEntries();
   T->SetCacheSize(cachesize);
   TTreeCache::SetLearnEntries(learn);
   TFileCacheRead *tpf = f->GetCacheRead();
   //tpf->SetEntryRange(0,nentries);
   
   if (draw) T->Draw("rawtr","E33>20");
   else {
      TBranch *brawtr = T->GetBranch("rawtr");
      TBranch *bE33   = T->GetBranch("E33");
      Float_t E33; 
      bE33->SetAddress(&E33);
      for (Long64_t i=0;i<nentries;i++) {
         T->LoadTree(i);
         bE33->GetEntry(i);
         if (E33 > 0) brawtr->GetEntry(i);
      } 
   } 
   if (tpf) tpf->Print();
   printf("Bytes read = %lld\n",TFile::GetFileBytesRead()-oldb);
   printf("Real Time = %7.3f s, CPUtime = %7.3f s\n",sw.RealTime(),sw.CpuTime());
   delete T;
   delete f;
}
Exemplo n.º 2
0
int looperCR2lep( analysis* myAnalysis, sample* mySample, int nEvents = -1, bool fast = true) {

	// Benchmark
	TBenchmark *bmark = new TBenchmark();
	bmark->Start("benchmark");

	// Setup
	TChain *chain = mySample->GetChain();
	TString sampleName = mySample->GetLabel();
	const int nSigRegs = myAnalysis->GetSigRegionsAll().size();
	const int nVariations = mySample->IsData() ? 0 : myAnalysis->GetSystematics(false).size();
	bool isFastsim = mySample->IsSignal();
	cout << "\nSample: " << sampleName.Data() << " (CR2L";
	if(      myContext.GetJesDir() == contextVars::kUp )   cout << ", JES up";
	else if( myContext.GetJesDir() == contextVars::kDown ) cout << ", JES down";
	cout << ")" << endl;

	myContext.SetUseRl( true );

	/////////////////////////////////////////////////////////
	// Histograms
	TDirectory *rootdir = gDirectory->GetDirectory("Rint:");  // Use TDirectories to assist in memory management
	TDirectory *histdir = new TDirectory( "histdir", "histdir", "", rootdir );
	TDirectory *systdir = new TDirectory( "systdir", "systdir", "", rootdir );
	TDirectory *zerodir = new TDirectory( "zerodir", "zerodir", "", rootdir );

	TH1::SetDefaultSumw2();

	TH1D* h_bkgtype_sum[nSigRegs][nVariations+1];
	TH1D* h_evttype_sum[nSigRegs][nVariations+1];
	TH2D* h_sigyields[nSigRegs][nVariations+1];

	TH1D* h_bkgtype[nSigRegs][nVariations+1]; // per-file versions for zeroing
	TH1D* h_evttype[nSigRegs][nVariations+1];

	TH1D *h_mt[nSigRegs];
	TH1D *h_met[nSigRegs];
	TH1D *h_mt2w[nSigRegs];
	TH1D *h_chi2[nSigRegs];
	TH1D *h_htratio[nSigRegs];
	TH1D *h_mindphi[nSigRegs];
	TH1D *h_ptb1[nSigRegs];
	TH1D *h_drlb1[nSigRegs];
	TH1D *h_ptlep[nSigRegs];
	TH1D *h_metht[nSigRegs];
	TH1D *h_dphilw[nSigRegs];
	TH1D *h_njets[nSigRegs];
	TH1D *h_nbtags[nSigRegs];
	TH1D *h_ptj1[nSigRegs];
	TH1D *h_j1btag[nSigRegs];
	TH1D *h_modtop[nSigRegs];
	TH1D *h_dphilmet[nSigRegs];
	TH1D *h_mlb[nSigRegs];

	vector<TString> regNames = myAnalysis->GetSigRegionLabelsAll();
	vector<sigRegion*> sigRegions = myAnalysis->GetSigRegionsAll();
	vector<systematic*> variations = myAnalysis->GetSystematics(false);

	for( int i=0; i<nSigRegs; i++ ) {

		TString plotLabel = sampleName + "_" + regNames.at(i);
		systdir->cd();

		for( int j=1; j<=nVariations; j++ ) {
			TString varName = variations.at(j-1)->GetNameLong();
			h_bkgtype_sum[i][j] = new TH1D( "bkgtype_" + plotLabel + "_" + varName, "Yield by background type",  5, 0.5, 5.5);
			h_evttype_sum[i][j] = new TH1D( "evttype_" + regNames.at(i) + "_" + varName, "Yield by event type",  6, 0.5, 6.5);
			h_sigyields[i][j] = new TH2D( "sigyields_" + regNames.at(i) + "_" + varName, "Signal yields by mass point", 37,99,1024, 19,-1,474 );
		}

		histdir->cd();

		h_bkgtype_sum[i][0] = new TH1D( "bkgtype_" + plotLabel, "Yield by background type",  5, 0.5, 5.5);
		h_evttype_sum[i][0] = new TH1D( "evttype_" + regNames.at(i), "Yield by event type",  6, 0.5, 6.5);
		h_sigyields[i][0] = new TH2D( "sigyields_" + regNames.at(i), "Signal yields by mass point", 37,99,1024, 19,-1,474 );

		h_mt[i]       = new TH1D(  "mt_"      + plotLabel, "Transverse mass",          80, 0, 800);
		h_met[i]      = new TH1D(  "met_"     + plotLabel, "MET",                      40, 0, 1000);
		h_mt2w[i]     = new TH1D(  "mt2w_"    + plotLabel, "MT2W",                     50, 0, 500);
		h_chi2[i]     = new TH1D(  "chi2_"    + plotLabel, "Hadronic #chi^{2}",        50, 0, 15);
		h_htratio[i]  = new TH1D(  "htratio_" + plotLabel, "H_{T} ratio",              50, 0, 1);
		h_mindphi[i]  = new TH1D(  "mindphi_" + plotLabel, "min #Delta#phi(j12,MET)",  63, 0, 3.15);
		h_ptb1[i]     = new TH1D(  "ptb1_"    + plotLabel, "p_{T} (b1)",               50, 0, 500);
		h_drlb1[i]    = new TH1D(  "drlb1_"   + plotLabel, "#DeltaR (lep, b1)",        50, 0, 5);
		h_ptlep[i]    = new TH1D(  "ptlep_"   + plotLabel, "p_{T} (lep)",              50, 0, 500);
		h_metht[i]    = new TH1D(  "metht_"   + plotLabel, "MET/sqrt(HT)",             50, 0, 100);
		h_dphilw[i]   = new TH1D(  "dphilw_"  + plotLabel, "#Delta#phi (lep,W)",       63, 0, 3.15);
		h_njets[i]    = new TH1D(  "njets_"   + plotLabel, "Number of jets",           16, -0.5, 15.5);
		h_nbtags[i]   = new TH1D(  "nbtags_"  + plotLabel, "Number of b-tags",          7, -0.5, 6.5);
		h_ptj1[i]     = new TH1D(  "ptj1_"    + plotLabel, "Leading jet p_{T}",        40, 0, 1000);
		h_j1btag[i]   = new TH1D(  "j1btag_"  + plotLabel, "Is leading jet b-tagged?",  2, -0.5, 1.5);
		h_modtop[i]   = new TH1D(  "modtop_"  + plotLabel, "Modified topness",         30, -15., 15.);
		h_dphilmet[i] = new TH1D(  "dphilmet_"+ plotLabel, "#Delta#phi (lep1, MET)",   63, 0., 3.15);
		h_mlb[i]      = new TH1D(  "mlb_"     + plotLabel, "M_{lb}",                   50, 0., 500.);


		for( int j=0; j<=nVariations; j++ ) {

			TAxis* axis = h_bkgtype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "2+lep" );
			axis->SetBinLabel( 2, "1lepW" );
			axis->SetBinLabel( 3, "1lepTop" );
			axis->SetBinLabel( 4, "ZtoNuNu" );
			axis->SetBinLabel( 5, "Other" );

			axis = h_evttype_sum[i][j]->GetXaxis();
			axis->SetBinLabel( 1, "Data" );
			axis->SetBinLabel( 2, "Signals" );
			axis->SetBinLabel( 3, "2+lep" );
			axis->SetBinLabel( 4, "1lepW" );
			axis->SetBinLabel( 5, "1lepTop" );
			axis->SetBinLabel( 6, "ZtoNuNu" );
		}

	}

	TH1D *h_yields_sum = new TH1D( Form("srYields_%s", sampleName.Data()), "Yield by signal region", nSigRegs, 0.5, float(nSigRegs)+0.5);
	for( int i=0; i<nSigRegs; i++ ) h_yields_sum->GetXaxis()->SetBinLabel( i+1, regNames.at(i) );

	// Set up copies of histograms, in order to zero out negative yields
	zerodir->cd();
	TH1D* h_yields = (TH1D*)h_yields_sum->Clone( "tmp_" + TString(h_yields_sum->GetName()) );

	for( int i=0; i<nSigRegs; i++ ) {
		for( int j=0; j<=nVariations; j++ ) {
			h_bkgtype[i][j] = (TH1D*)h_bkgtype_sum[i][j]->Clone( "tmp_" + TString(h_bkgtype_sum[i][j]->GetName()) );
			h_evttype[i][j] = (TH1D*)h_evttype_sum[i][j]->Clone( "tmp_" + TString(h_evttype_sum[i][j]->GetName()) );
		}
	}

	// Set up cutflow variables
	double yield_total = 0;
	double yield_unique = 0;
	double yield_filter = 0;
	double yield_vtx = 0;
	double yield_1goodlep = 0;
	double yield_lepSel = 0;
	double yield_2lepveto = 0;
	double yield_trkVeto = 0;
	double yield_2lepCR = 0;
	double yield_tauVeto = 0;
	double yield_njets = 0;
	double yield_1bjet = 0;
	double yield_METcut = 0;
	double yield_MTcut = 0;
	double yield_dPhi = 0;
	double yield_chi2 = 0;

	int yGen_total = 0;
	int yGen_unique = 0;
	int yGen_filter = 0;
	int yGen_vtx = 0;
	int yGen_1goodlep = 0;
	int yGen_lepSel = 0;
	int yGen_2lepveto = 0;
	int yGen_trkVeto = 0;
	int yGen_tauVeto = 0;
	int yGen_2lepCR = 0;
	int yGen_njets = 0;
	int yGen_1bjet = 0;
	int yGen_METcut = 0;
	int yGen_MTcut = 0;
	int yGen_dPhi = 0;
	int yGen_chi2 = 0;

	////////////////////////////////////////////////////////////////////
	// Set up data-specific filters

	if( mySample->IsData() ) {
		set_goodrun_file_json( "reference-files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt" );
		duplicate_removal::clear_list();
	}


	/////////////////////////////////////////////////////////////////////

	// Loop over events to Analyze
	unsigned int nEventsTotal = 0;
	unsigned int nEventsChain = chain->GetEntries();
	if( nEvents >= 0 ) nEventsChain = nEvents;
	TObjArray *listOfFiles = chain->GetListOfFiles();
	TIter fileIter(listOfFiles);
	TFile *currentFile = 0;

	// File Loop
	while ( (currentFile = (TFile*)fileIter.Next()) ) {

		// Get File Content
		TFile file( currentFile->GetTitle() );
		TString filename = file.GetName();
		TTree *tree = (TTree*)file.Get("t");
		if(fast) TTreeCache::SetLearnEntries(10);
		if(fast) tree->SetCacheSize(128*1024*1024);
		cms3.Init(tree);

		// Load event weight histograms
		TH2F* hNEvts = (TH2F*)file.Get("histNEvts");
		TH3D* hCounterSMS = (TH3D*)file.Get("h_counterSMS");
		TH1D* hCounter = (TH1D*)file.Get("h_counter");
		myHelper.Setup( isFastsim, hCounter, hNEvts, hCounterSMS );

		// Reset zeroing histograms
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				h_bkgtype[i][j]->Reset();
				h_evttype[i][j]->Reset();
			}
		}
		h_yields->Reset();

		// Loop over Events in current file
		if( nEventsTotal >= nEventsChain ) continue;
		unsigned int nEventsTree = tree->GetEntriesFast();
		for( unsigned int event = 0; event < nEventsTree; ++event) {

			// Get Event Content
			if( nEventsTotal >= nEventsChain ) continue;
			if(fast) tree->LoadTree(event);
			cms3.GetEntry(event);
			++nEventsTotal;

			// Progress
			CMS3::progress( nEventsTotal, nEventsChain );

			////////////////////////////////////////////////////////////////////////////////////////////////////////
			// Analysis Code
			// ---------------------------------------------------------------------------------------------------//


			///////////////////////////////////////////////////////////////
			// Special filters to more finely categorize background events
			if(      sampleName == "tt2l"  && gen_nfromtleps_() != 2 ) continue;  //Require 2 leps from top in "tt2l" events
			else if( sampleName == "tt1l"  && gen_nfromtleps_() != 1 ) continue;  //Require 1 lep from top in "tt1l" events

			// Stitch W+NJets samples together by removing the MET<200 events from the non-nupT samples
			if( sampleName.Contains("wjets") && filename.Contains("JetsToLNu_madgraph") && nupt()>=200. ) continue;

			//FastSim anomalous event filter
			if( isFastsim && !context::filt_fastsimjets() ) continue;

			if( !mySample->PassSelections() ) continue;


			/////////////////////////////////
			// Set event weight

			double evtWeight = 1.;

			// Data should have a weight of 1.0
			if( is_data() || mySample->IsData() ) evtWeight = 1.;
			else {

				// Weight background MC using scale1fb
				evtWeight = myAnalysis->GetLumi() * scale1fb();

				// Weight signal MC using xsec and nEvents
				if( mySample->IsSignal() ) {
					myHelper.PrepSignal();
					double nEvtsSample = hNEvts->GetBinContent( hNEvts->FindBin( mass_stop(), mass_lsp() ) );
					evtWeight = myAnalysis->GetLumi() * 1000. * xsec() / nEvtsSample;
				}

				// Apply scale factors to correct the shape of the MC
				evtWeight *= myHelper.TrigEff2l();
				evtWeight *= myHelper.LepSF();
				evtWeight *= myHelper.BtagSF();
				if(  isFastsim ) evtWeight *= myHelper.LepSFfastsim();
				if( !isFastsim ) evtWeight *= myHelper.PileupSF();
				if( mySample->GetLabel() == "tt2l" || filename.Contains("W_5f_powheg_pythia8") ) {
					evtWeight *= myHelper.MetResSF();
					// evtWeight *= myHelper.TopSystPtSF();
				}
				else if( mySample->GetLabel() == "tt1l" || mySample->GetLabel() == "wjets" ) evtWeight *= myHelper.MetResSF();
				if( mySample->GetLabel() == "tt2l" || mySample->GetLabel() == "tt1l" || mySample->IsSignal() ) evtWeight *= myHelper.ISRnJetsSF();

				// Correct event weight when samples are merged together
				if(      filename.Contains("ttbar_diLept_madgraph_pythia8_ext1_25ns") ) evtWeight *= 23198554./(23198554.+5689986.);
				else if( filename.Contains("ttbar_diLept_madgraph_pythia8_25ns") ) evtWeight *= 5689986./(23198554.+5689986.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 4473156./(4473156.+3145334.);
				else if( filename.Contains("t_tW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3145334./(4473156.+3145334.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_25ns") ) evtWeight *= 5029568./(5029568.+3146940.);
				else if( filename.Contains("t_tbarW_5f_powheg_pythia8_noHadDecays_ext1_25ns") ) evtWeight *= 3146940./(5029568.+3146940.);
			}

			// Count the number of events processed
			yield_total += evtWeight;
			yGen_total++;

			// Remove duplicate events in data
			if( is_data() ) {
				duplicate_removal::DorkyEventIdentifier id( run(), evt(), ls() );
				if( is_duplicate(id) ) continue;
				yield_unique += evtWeight;
				yGen_unique++;
			}

			// MET filters, bad event filters, and triggers for data
			if( is_data() ) {
				if( !goodrun( run(), ls() ) ) continue;
				if( !filt_met() ) continue;
				if( !filt_badChargedCandidateFilter() ) continue;
				if( !filt_badMuonFilter() ) continue;
				if( !context::filt_jetWithBadMuon() ) continue;
				if( !filt_pfovercalomet() ) continue;
				if( !HLT_MET() && !HLT_MET110_MHT110() && !HLT_MET120_MHT120() ) {
					if( !(HLT_SingleEl() && (abs(lep1_pdgid())==11 || abs(lep2_pdgid())==11) ) &&
					    !(HLT_SingleMu() && (abs(lep1_pdgid())==13 || abs(lep2_pdgid())==13) ) ) continue;
				}
				yield_filter += evtWeight;
				yGen_filter++;
			}

			// First vertex must be good
			if( nvtxs() < 1 ) continue;
			yield_vtx += evtWeight;
			yGen_vtx++;

			// Must have at least 1 good lepton
			if( ngoodleps() < 1 ) continue;
			yield_1goodlep += evtWeight;
			yGen_1goodlep++;

			// Lep 1 must pass lepton selections
			// if( abs(lep1_pdgid())==11 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 1.4442 ) continue;
			// 	if( !lep1_passMediumID() ) continue;
			// }
			// else if( abs(lep1_pdgid())==13 ) {
			// 	if( lep1_p4().pt() < 20. ) continue;
			// 	if( fabs(lep1_p4().eta()) > 2.4 ) continue;
			// 	if( !lep1_passTightID() ) continue;
			// }
			yield_lepSel += evtWeight;
			yGen_lepSel++;


			///////////////////
			// Make 2-lepton CR

			int countGoodLeps = 0;

			// Count the number of veto leptons
			if( nvetoleps() >= 2 && lep2_p4().pt() > 10. ) countGoodLeps += nvetoleps();

			if( countGoodLeps > 1 ) {
				yield_2lepveto += evtWeight;
				yGen_2lepveto++;
			}

			// If we fail the track veto, count another good lepton
			// if( !PassTrackVeto() ) {
			// 	countGoodLeps++;
			// 	yield_trkVeto += evtWeight;
			// 	yGen_trkVeto++;
			// }

			// If we fail the tau veto, count another good lepton
			// if( !PassTauVeto() ) {
			// 	countGoodLeps++;
			// 	yield_tauVeto += evtWeight;
			// 	yGen_tauVeto++;
			// }

			if( countGoodLeps < 2 ) continue;
			yield_2lepCR += evtWeight;
			yGen_2lepCR++;


			////////////////////
			////////////////////

			// N-jet requirement
			if( context::ngoodjets() < 2 ) continue;
			yield_njets += evtWeight;
			yGen_njets++;

			j1pt = context::ak4pfjets_p4().at(0).pt();

			// B-tag requirement
			if( context::ngoodbtags() < 1 ) continue;
			yield_1bjet += evtWeight;
			yGen_1bjet++;

			j1_isBtag = context::ak4pfjets_passMEDbtag().at(0);

			// Baseline MET cut (with 2nd lepton pT added to MET)
			if( context::Met() < 250. ) continue;
			yield_METcut += evtWeight;
			yGen_METcut++;

			// MT cut (with 2nd lepton pT added to MET)
			if( context::MT_met_lep() < 150. ) continue;
			yield_MTcut += evtWeight;
			yGen_MTcut++;

			// Min delta-phi between MET and j1/j2 (with 2nd lepton pT added to MET)
			if( context::Mindphi_met_j1_j2() < 0.5 ) continue;
			yield_dPhi += evtWeight;
			yGen_dPhi++;

			// Chi^2 cut
			// if( hadronic_top_chi2() >= 10. ) continue;
			yield_chi2 += evtWeight;
			yGen_chi2++;


			//////////////////////////////////////////////////////////
			// Classify event based on number of leptons / neutrinos
			// Order of evaluation matters, because some events fall into multiple categories

			int bkgType = -99;
			if( filename.Contains("ZZTo2L2Nu") && isZtoNuNu() ) bkgType = 1; // Force ZZto2L2Nu to be 2lep
			else if( isZtoNuNu() )     bkgType = 4;   // Z to nu nu
			else if( is2lep() )        bkgType = 1;   // 2 or more leptons
			else if( is1lepFromTop() ) bkgType = 3;   // 1 lepton from top quark
			else if( is1lepFromW() )   bkgType = 2;   // 1 lepton from a W not from top
			else                       bkgType = 5;   // Other

			int evtType = -99;
			if(      mySample->IsData()   ) evtType = 1;
			else if( mySample->IsSignal() ) evtType = 2;
			else                            evtType = 2+bkgType;

			// Quickly calculate some variables
			double metSqHT = context::Met() / sqrt( context::ak4_HT() );

			const TVector3 lepVec( lep1_p4().x(), lep1_p4().y(), lep1_p4().z() );
			const TVector3 metVec( context::Met()*cos(context::MetPhi()), context::Met()*sin(context::MetPhi()), 0 );
			const TVector3 wVec = lepVec + metVec;
			double dPhiLepW = fabs( lepVec.DeltaPhi(wVec) );

			double drLepLeadb = ROOT::Math::VectorUtil::DeltaR( lep1_p4(), context::ak4pfjets_leadMEDbjet_p4() );

			lep1pt = lep1_p4().Pt();

			myMlb = context::Mlb_closestb();

			///////////////////////////////////////////
			// Signal region cuts and histo filling

			// If the event passes the SR cuts, store which background type this event is, and fill histograms
			for( int i=0; i<nSigRegs; i++ ) {

				if( !sigRegions.at(i)->PassAllCuts() ) continue;

				// Make some corrections that depend on the signal region
				double fillWeight = evtWeight;
				bool is_corridor = sigRegions.at(i)->GetLabel().Contains("corr");
				myHelper.SetCorridor( is_corridor );
				if(      !is_data() &&  is_corridor ) fillWeight *= sfhelp::MetResCorrectionCorridor();
				else if( !is_data() && !is_corridor ) fillWeight *= sfhelp::BtagCorrectionTight();

				h_bkgtype[i][0]->Fill( bkgType,                            fillWeight );
				h_evttype[i][0]->Fill( evtType,                            fillWeight );
				if( mySample->IsSignal() ) h_sigyields[i][0]->Fill( mass_stop(), mass_lsp(), fillWeight );

				h_mt[i]->Fill(      context::MT_met_lep(),                 fillWeight );
				h_met[i]->Fill(     context::Met(),                        fillWeight );
				h_mt2w[i]->Fill(    context::MT2W(),                       fillWeight );
				h_chi2[i]->Fill(    hadronic_top_chi2(),                   fillWeight );
				h_htratio[i]->Fill( context::ak4_htratiom(),               fillWeight );
				h_mindphi[i]->Fill( context::Mindphi_met_j1_j2(),          fillWeight );
				h_ptb1[i]->Fill( context::ak4pfjets_leadMEDbjet_p4().pt(), fillWeight );
				h_drlb1[i]->Fill(   drLepLeadb,                            fillWeight );
				h_ptlep[i]->Fill(   lep1_p4().pt(),                        fillWeight );
				h_metht[i]->Fill(   metSqHT,                               fillWeight );
				h_dphilw[i]->Fill(  dPhiLepW,                              fillWeight );
				h_njets[i]->Fill(   context::ngoodjets(),                  fillWeight );
				h_nbtags[i]->Fill(  context::ngoodbtags(),                 fillWeight );
				h_ptj1[i]->Fill(    j1pt,                                  fillWeight );
				h_j1btag[i]->Fill(  j1_isBtag,                             fillWeight );
				h_modtop[i]->Fill(  context::TopnessMod(),                 fillWeight );
				h_dphilmet[i]->Fill( context::lep1_dphiMET(),              fillWeight );
				h_mlb[i]->Fill(     myMlb,                                 fillWeight );

				h_yields->Fill(     double(i+1),                           fillWeight );

				// Special systematic variation histograms
				for( int j=1; j<=nVariations; j++ ) {
					h_bkgtype[i][j]->Fill( bkgType,  fillWeight * variations.at(j-1)->GetWeight() );
					h_evttype[i][j]->Fill( evtType,  fillWeight * variations.at(j-1)->GetWeight() );
					if( mySample->IsSignal() ) h_sigyields[i][j]->Fill( mass_stop(), mass_lsp(), fillWeight * variations.at(j-1)->GetWeight() );
				}

			}

			// ---------------------------------------------------------------------------------------------------//
			////////////////////////////////////////////////////////////////////////////////////////////////////////
		} //End of loop over events in file

		// Clean Up
		delete tree;
		file.Close();

		// Zero negative values in each signal region
		for( int i=0; i<nSigRegs; i++ ) {
			for( int j=0; j<=nVariations; j++ ) {
				bool negsFound = false;

				// First zero any decay modes with negative yields
				for( int k=1; k<= h_bkgtype[i][j]->GetNbinsX(); k++ ) {
					if( h_bkgtype[i][j]->GetBinContent(k) < 0.0 ) {
						h_bkgtype[i][j]->SetBinContent(k, 0.);
						h_bkgtype[i][j]->SetBinError(k, 0.);
						negsFound = true;
					}
					if( h_evttype[i][j]->GetBinContent(k+2) < 0.0 ) {
						h_evttype[i][j]->SetBinContent(k+2, 0.);
						h_evttype[i][j]->SetBinError(k+2, 0.);
					}
				}
				// If any negative yields were found in any decay mode, recalculate the total yield
				if( j==0 && negsFound ) {
					double newYield, newErr;
					newYield = h_bkgtype[i][0]->IntegralAndError( 0, -1, newErr );
					h_yields->SetBinContent(i+1, newYield);
					h_yields->SetBinError(i+1, newErr);
				}
				// Add zeroed histograms to total histograms
				h_bkgtype_sum[i][j]->Add( h_bkgtype[i][j] );
				h_evttype_sum[i][j]->Add( h_evttype[i][j] );
			}
		}
		h_yields_sum->Add( h_yields );

	} // End loop over files in the chain

	cout << "Cutflow yields:                        (yield)  (gen evts)" << endl;

	printf("Total number of events:             %10.2f %9i\n",   yield_total    , yGen_total    );
	if( mySample->IsData() ) {
		printf("Events passing duplicate removal:   %10.2f %9i\n", yield_unique   , yGen_unique   );
		printf("Events passing filters and trigger: %10.2f %9i\n", yield_filter   , yGen_filter   );
	}
	printf("Events with 1st vertex good:        %10.2f %9i\n",   yield_vtx      , yGen_vtx      );
	printf("Events with at least 1 good lepton: %10.2f %9i\n",   yield_1goodlep , yGen_1goodlep );
	printf("Events passing lepton selection:    %10.2f %9i\n",   yield_lepSel   , yGen_lepSel   );

	printf("\nEvents passing 2-lep requirement:   %10.2f %9i\n", yield_2lepCR   , yGen_2lepCR   );
	printf("   Events with veto lepton:         %10.2f %9i\n",   yield_2lepveto , yGen_2lepveto );
	printf("   Events with isolated track:      %10.2f %9i\n",   yield_trkVeto  , yGen_trkVeto  );
	printf("   Events with identified tau:      %10.2f %9i\n\n", yield_tauVeto  , yGen_tauVeto  );

	printf("Events with at least 2 jets:        %10.2f %9i\n",   yield_njets    , yGen_njets    );
	printf("Events with at least 1 b-tag:       %10.2f %9i\n",   yield_1bjet    , yGen_1bjet    );
	printf("Events with MET > 250 GeV:          %10.2f %9i\n",   yield_METcut   , yGen_METcut   );
	printf("Events with MT > 150 GeV:           %10.2f %9i\n",   yield_MTcut    , yGen_MTcut    );
	printf("Events with min dPhi > 0.5:         %10.2f %9i\n",   yield_dPhi     , yGen_dPhi     );
	// printf("Events with chi2 < 10:              %10.2f %9i\n",   yield_chi2     , yGen_chi2     );
	printf("Yield after preselection:           %10.2f %9i\n",   yield_chi2     , yGen_chi2     );

	if ( nEventsChain != nEventsTotal ) {
		cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
	}


	///////////////////////////////////////////////////////////////////////////////
	// Store histograms and clean them up
	TFile* plotfile = new TFile( myAnalysis->GetPlotFileName(), "READ");
	TFile* systfile = new TFile( myAnalysis->GetSystFileName(), "READ");
	TFile* sourcefile;

	// Certain histograms are cumulative across multiple samples. For those histograms, add what the
	// looper has just collected to the cumulative version stored in our output files
	for( int j=0; j<=nVariations; j++ ) {

		if( j==0 ) sourcefile = plotfile;
		else       sourcefile = systfile;

		for( int i=0; i<nSigRegs; i++ ) {

			// Build up cumulative histo of SUSY scan yields
			TH2D* hTemp2 = (TH2D*)sourcefile->Get( h_sigyields[i][j]->GetName() );
			if( hTemp2 != 0 ) h_sigyields[i][j]->Add( hTemp2 );

			// Build up cumulative histo of yields by signal/background type
			TH1D* hTemp = (TH1D*)sourcefile->Get( h_evttype_sum[i][j]->GetName() );
			if( hTemp != 0 ) h_evttype_sum[i][j]->Add( hTemp );
		}
	}
	delete plotfile;
	delete systfile;

	// Take all histograms in histdir and write them to plotfile
	plotfile = new TFile( myAnalysis->GetPlotFileName(), "UPDATE");
	plotfile->cd();
	histdir->GetList()->Write( "", TObject::kOverwrite );
	delete plotfile;

	// Take all histograms in systdir and write them to systfile
	systfile = new TFile( myAnalysis->GetSystFileName(), "UPDATE");
	systfile->cd();
	systdir->GetList()->Write( "", TObject::kOverwrite );
	delete systfile;

	// Cleanup
	zerodir->Close();
	histdir->Close();
	systdir->Close();

	// return
	bmark->Stop("benchmark");
	cout << endl;
	cout << nEventsTotal << " Events Processed" << endl;
	cout << "------------------------------" << endl;
	cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
	cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
	cout << endl;
	delete bmark;
	return 0;
}
Exemplo n.º 3
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  TH1F *samplehisto = new TH1F("samplehisto", "Example histogram", 200,0,200);
  samplehisto->SetDirectory(rootdir);

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      StopBabies10012015::progress( nEventsTotal, nEventsChain );

      // Analysis Code

    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  samplehisto->Draw();
  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 4
0
Int_t runPrefetchReading(bool caching = false)
{
   //const char *options = 0;
   Int_t freq = 1000; 
   Int_t cachesize = -1;
   Float_t percententries = 1.00;
   Float_t percentbranches = 1.00;
   TStopwatch sw;
   
   //set the reading mode to async prefetching
   gEnv->SetValue("TFile.AsyncPrefetching", 1);

   //enable the local caching of blocks
   TString cachedir="file:/tmp/xcache/";
   // or using xrootd on port 2000
   // TString cachedir="root://localhost:2000//tmp/xrdcache1/";
   if (caching) gEnv->SetValue("Cache.Directory", cachedir.Data());
   
   // open the local if any
   TString filename("atlasFlushed.root");
   if (gSystem->AccessPathName(filename,kReadPermission) && filename.Index(":") == kNPOS) {
      // otherwise open the http file
      filename.Prepend("https://root.cern.ch/files/");
      //filename.Prepend("root://cache01.usatlas.bnl.gov//data/test1/");
      //filename.Prepend( "root://pcitdss1401//tmp/" );
      //filename.Prepend("http://www-root.fnal.gov/files/");
      //filename.Prepend("http://oink.fnal.gov/distro/roottest/");
   }
   
   TString library("atlasFlushed/atlasFlushed");
   fprintf(stderr,"Starting to load the library\n");
   gSystem->Load(library);

   fprintf(stderr,"Starting to open the file\n");
   TFile *file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) {
      Error("runPrefetchReading","Could not open the file %s within 30s",filename.Data());
      return 1;
   }
   fprintf(stderr,"The file has been opened, setting up the TTree\n");

   // file->MakeProject("atlasFlushed","*","RECREATE+");

   // Try the known names :)
   const char *names [] = { "E","Events","CollectionTree","ntuple","T" };
   TTree *T = NULL;
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }
   TFile::SetReadaheadSize(0);  // (256*1024);
   Long64_t nentries = T->GetEntries();

   int efirst = 0;
   int elast  = efirst+nentries;
   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }

   //...........................................................................
   // First read, with saving the info in cache
   //...........................................................................
   fprintf(stderr,"Setup done. Starting to read the entries\n");
   TRandom r;
   for (Long64_t i = efirst; i < elast; i++) {
     //if (i%100 == 0 || i>2000) fprintf(stderr,"i.debug = %lld\n",i);
     // if (i==2000) gDebug = 7;
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue; 
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b<nb; b += incr) ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);   
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) { /* waste cpu */ count = sin(cos((double)count)); }
       } else {
         T->GetEntry(i);
       }
     }
   }

   fprintf(stderr,"Done reading for the first pass, now closing the file\n");
   file->Close();
   delete file;

   //...........................................................................
   // Second read, actually reading the data from cache
   //...........................................................................
   fprintf(stderr,"Opening the file for the 2nd pass\n");
   file = TFile::Open( filename, "TIMEOUT=30" );
   if (!file || file->IsZombie()) return 1;
 
   fprintf(stderr,"The file has been opened, setting up the TTree\n");
   // Try the known names :)
   for (unsigned int i = 0; i < sizeof(names)/sizeof(names[0]); ++i) {
      file->GetObject(names[i], T);
      if (T) break;
   }
   if (T==0) {
     Error("runPrefetchReading","Could not find a tree which the conventional names in %s.",filename.Data());
     return 2;
   }

   TFile::SetReadaheadSize(0);  // (256*1024);
   nentries = T->GetEntries();

   efirst = 0;
   elast  = efirst+nentries;

   if (cachesize == -2) {
      gEnv->SetValue("TFile.AsyncReading", 0);
      cachesize = -1;
   }
   T->SetCacheSize(cachesize);

   if (cachesize != 0) {
      T->SetCacheEntryRange(efirst,elast);
      if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         for(int b=0;b < nb; b += incr) T->AddBranchToCache(((TBranch*)T->GetListOfBranches()->At(b)),kTRUE);
      } else {
         T->AddBranchToCache("*");
      }
      T->StopCacheLearningPhase();
   }
      
   fprintf(stderr,"Setup done, starting the 2nd reading.\n");
   for (Long64_t i = efirst; i < elast; i++) {
     if (i % freq == 0){
       // for (Long64_t i=elast-1;i>=efirst;i--) {
       if (i%freq == 0 || i==(elast-1)) fprintf(stderr,"i = %lld\n",i);
       if (r.Rndm() > percententries) continue;
       T->LoadTree(i);
       if (percentbranches < 1.00) {
         int nb = T->GetListOfBranches()->GetEntries();
         int incr = nb * percentbranches;
         
         for(int b=0;b<nb; b += incr) {
           ((TBranch*)T->GetListOfBranches()->At(b))->GetEntry(i);
         }
         
         int count = 0;
         int maxcount = 1000 + 100 ;
         for(int x = 0; x < maxcount; ++x ) {
           /* waste cpu */
           count = sin(cos((double)count));
         }         
       } else {
         T->GetEntry(i);
       }
     }
   }
   fprintf(stderr, "Done with the 2nd reading\n");

   fprintf(stderr, "fPrefetchedBlocks = %lli\n", file->GetCacheRead()->GetPrefetchedBlocks());

   fprintf(stderr, "Delete tmp directory: /tmp/xcache\n" );
   if (caching) system( "rm -r /tmp/xcache" );
   
   file->Close();
   delete file;
   return 0;
}
Exemplo n.º 5
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
////////////////////////////////////////////////////////////////////////////////////////////
int mt2_l_bin = 0;
int mt2_h_bin = 200;
int mt2_n_bin = 20;

int mt_l_bin = 0;
int mt_h_bin = 300;
int mt_n_bin = 30;

int met_l_bin = 0;
int met_h_bin = 225;
int met_n_bin = 45;

int jet_n_bin = 10;
int jet_h_bin = 10;

	TH1F   *fake_wpt_h = new TH1F("fake_w_pt_","fake_W_pt",50,0,100);
	TH1F   *landau_h = new TH1F("landau_h_","landau_H",60,0,mt_h_bin);
	TH1F   *gammaM_h = new TH1F("gammaM_","gamma",120,1,6);

	TH1F *mt2_h_data = new TH1F("mt2_data_","MT2_data",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data = new  TH1F("mt_data_", "MT_data",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data = new TH1F("met_data_","met_data",met_n_bin,0,met_h_bin);
	TH1F   *jets_data= new TH1F("jets_data_","Jets_data",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt = new     TH1F("data_w_pt_","data_W_pt",60,0,mt_h_bin);
	TH1F   *data_lep_pt = new     TH1F("data_lep_pt_","data_Lep_pt",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar = new TH1F("mt2_ttbar_","MT2_ttbar",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar = new  TH1F("mt_ttbar_", "MT_ttbar",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar = new TH1F("met_ttbar_","met_ttbar",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar  = new TH1F("jets_ttbar_","Jets_ttbar",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt = new     TH1F("ttbar_w_pt_","ttbar_W_pt",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt = new     TH1F("ttbar_lep_pt_","ttbar_Lep_pt",60,0,mt_h_bin);

	TH1F *mt2_h_wjets = new TH1F("mt2_wjets_","MT2_wjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets = new  TH1F("mt_wjets_", "MT_wjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets = new TH1F("met_wjets_","met_wjets",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets  = new TH1F("jets_wjets_","Jets_wjets",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt = new     TH1F("wjets_w_pt_","wjets_W_pt",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt = new     TH1F("wjets_lep_pt_","wjets_Lep_pt",60,0,mt_h_bin);

	wjets_lep_pt->SetLineColor(kRed);
	data_lep_pt->SetLineColor(kYellow);
	ttbar_lep_pt->SetLineColor(kCyan);

	wjets_lep_pt->SetLineWidth(4);
	 data_lep_pt->SetLineWidth(4);
	ttbar_lep_pt->SetLineWidth(4);

////MUONS////
	TH1F *mt2_h_data_mu = new TH1F("mt2_data_mu_","MT2_data_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data_mu = new  TH1F("mt_data_mu_", "MT_data_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data_mu = new TH1F("met_data_mu_","met_data_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_data_mu= new TH1F("jets_data_mu_","Jets_data_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt_mu = new     TH1F("data_w_pt_mu_","data_W_pt_mu",60,0,mt_h_bin);
	TH1F   *data_lep_pt_mu = new     TH1F("data_lep_pt_mu_","data_Lep_pt_mu",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar_mu = new TH1F("mt2_ttbar_mu_","MT2_ttbar_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar_mu = new  TH1F("mt_ttbar_mu_", "MT_ttbar_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar_mu = new TH1F("met_ttbar_mu_","met_ttbar_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar_mu  = new TH1F("jets_ttbar_mu_","Jets_ttbar_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt_mu = new     TH1F("ttbar_w_pt_mu_","ttbar_W_pt_mu",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt_mu = new     TH1F("ttbar_lep_pt_mu_","ttbar_Lep_pt_mu",60,0,mt_h_bin);

	TH1F *mt2_h_wjets_mu = new TH1F("mt2_wjets_mu_","MT2_wjets_mu",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets_mu = new  TH1F("mt_wjets_mu_", "MT_wjets_mu",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets_mu = new TH1F("met_wjets_mu_","met_wjets_mu",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets_mu  = new TH1F("jets_wjets_mu_","Jets_wjets_mu",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt_mu = new     TH1F("wjets_w_pt_mu_","wjets_W_pt_mu",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt_mu = new     TH1F("wjets_lep_pt_mu_","wjets_Lep_pt_mu",60,0,mt_h_bin);

////ELECTRONS////
	TH1F *mt2_h_data_el = new TH1F("mt2_data_el_","MT2_data_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_data_el = new  TH1F("mt_data_el_", "MT_data_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_data_el = new TH1F("met_data_el_","met_data_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_data_el= new TH1F("jets_data_el_","Jets_data_el",jet_n_bin,0,jet_h_bin);
	TH1F   *data_w_pt_el = new     TH1F("data_w_pt_el_","data_W_pt_el",60,0,mt_h_bin);
	TH1F   *data_lep_pt_el = new     TH1F("data_lep_pt_el_","data_Lep_pt_el",60,0,mt_h_bin);

	TH1F *mt2_h_ttbar_el = new TH1F("mt2_ttbar_el_","MT2_ttbar_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttbar_el = new  TH1F("mt_ttbar_el_", "MT_ttbar_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttbar_el = new TH1F("met_ttbar_el_","met_ttbar_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_ttbar_el  = new TH1F("jets_ttbar_el_","Jets_ttbar_el",jet_n_bin,0,jet_h_bin);
	TH1F   *ttbar_w_pt_el = new     TH1F("ttbar_w_pt_el_","ttbar_W_pt_el",60,0,mt_h_bin);
	TH1F   *ttbar_lep_pt_el = new     TH1F("ttbar_lep_pt_el_","ttbar_Lep_pt_el",60,0,mt_h_bin);

	TH1F *mt2_h_wjets_el = new TH1F("mt2_wjets_el_","MT2_wjets_el",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wjets_el = new  TH1F("mt_wjets_el_", "MT_wjets_el",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wjets_el = new TH1F("met_wjets_el_","met_wjets_el",met_n_bin,0,met_h_bin);
	TH1F   *jets_wjets_el  = new TH1F("jets_wjets_el_","Jets_wjets_el",jet_n_bin,0,jet_h_bin);
	TH1F   *wjets_w_pt_el = new     TH1F("wjets_w_pt_el_","wjets_W_pt_el",60,0,mt_h_bin);
	TH1F   *wjets_lep_pt_el = new     TH1F("wjets_lep_pt_el_","wjets_Lep_pt_el",60,0,mt_h_bin);
/*
  TFile* f1 = new TFile("/home/users/sanil/single/may15hists/data_w_pt.root");
  TH1F* wp_dist   = (TH1F*) f1->Get("w_pt_"); // 
  f1->Close();
	TH1F *mt2_h_wwjets = new TH1F("mt2_wwjets_","MT2_wwjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_wwjets = new  TH1F("mt_wwjets_", "MT_wwjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_wwjets = new TH1F("met_wwjets_","met_wwjets",met_n_bin,0,met_h_bin);
	TH1F   *jets_wwjets = new TH1F("jets_wwjets_","Jets_wwjets",jet_n_bin,0,jet_h_bin);

	TH1F *mt2_h_ttwjets = new TH1F("mt2_ttwjets_","MT2_ttwjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttwjets = new  TH1F("mt_ttwjets_", "MT_ttwjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttwjets = new TH1F("met_ttwjets_","met_ttwjets",met_n_bin,0,met_h_bin);

	TH1F *mt2_h_ttzjets = new TH1F("mt2_ttzjets_","MT2_ttzjets",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_ttzjets = new  TH1F("mt_ttzjets_", "MT_ttzjets",mt_n_bin,0,mt_h_bin);
	TH1F   *met_ttzjets = new TH1F("met_ttzjets_","met_ttzjets",met_n_bin,0,met_h_bin);

	TH1F *mt2_h_dy = new TH1F("mt2_dy_","MT2_dy",mt2_n_bin,0,mt2_h_bin);
	TH1F  *mt_h_dy = new  TH1F("mt_dy_", "MT_dy",mt_n_bin,0,mt_h_bin);
	TH1F   *met_dy = new TH1F("met_dy_","met_dy",met_n_bin,0,met_h_bin);
*/


////////////// RANDOM NUMBERS GET W momentum


TRandom1  d;  
TRandom3 rx;
TRandom3 ry;

//mt2_h_data->Sumw2();
//mt_h_data ->Sumw2();
//met_data  ->Sumw2();

/////////////////////////////////////////////////////////////////////////////////////////////
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
typedef ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > LorentzVec;
//GLOBAL COUNTERS//
int file_count = 1;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

float mt2_0_counter = 0, //0 bin counter
     mt2_10_counter = 0, //0-10 geV counter
     mt2_20_counter = 0, //10-20 geV counter etc.
     mt2_30_counter = 0,
     mt2_40_counter = 0,
     mt2_50_counter = 0,
     mt2_60_counter = 0,
     mt2_70_counter = 0,
     mt2_80_counter = 0,
     mt2_90_counter = 0,
    mt2_100_counter = 0,
    mt2_110_counter = 0,
    mt2_120_counter = 0,
    mt2_130_counter = 0,
    mt2_140_counter = 0,
    mt2_150_counter = 0,
    mt2_160_counter = 0,
    mt2_170_counter = 0,
    mt2_180_counter = 0,
    mt2_190_counter = 0,
    mt2_200_counter = 0,
    mt2_G200_counter = 0,
    totalEvents = 0;

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("tree");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    single.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {

	float lepton_weight = 0;
	
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      single.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      SL::progress( nEventsTotal, nEventsChain );

      // Analysis Code
//event based variables
	//COUNTERS
	int el_count = 0, mu_count = 0, nJets = 0, nBtags = 0, good_index = -1, mu_index = -1, el_index = -1;

      float metx = met() * cos( metPhi() );
      float mety = met() * sin( metPhi() );

///metPhi correction//

      float cmetx = met() * cos( metPhi() );
      float cmety = met() * sin( metPhi() );
      float shiftx = 0.;
      float shifty = 0.;

      shiftx = (! isRealData()) ? (0.1166 + 0.0200*nvtxs()) : (0.2661 + 0.3217*nvtxs());
      shifty = (! isRealData()) ? (0.2764 - 0.1280*nvtxs()) : (-0.2251 - 0.1747*nvtxs());

      cmetx -= shiftx;
      cmety -= shifty;

	//problem with this metPhi modulation correction right now
	//keep using cmet, too lazy to change all the variables
	float cmet = met();
     	float cmetphi = metPhi();
	 //float cmetphi = atan2( mety , metx );
      //float cmet = sqrt( cmetx*cmetx + cmety*cmety ); // cmet == corrected met
LorentzVector met_vec;
met_vec.SetPxPyPzE(metx,mety,0,0);

float lepy = lr_p4().py();
float lepx = lr_p4().px();

float w_x = sqrt ( metx*metx + lepx*lepx );
float w_y = sqrt ( mety*mety + lepy*lepy );

float w_pt_ = sqrt (w_x*w_x + w_y*w_y); 


//jet looper
      for (unsigned int k = 0; k < jets_p4().size(); k++){
        if (jets_p4().at(k).pt()*jets_p4Correction().at(k) < 30) continue;
        if (fabs(jets_p4().at(k).eta()) > 2.5) continue;
        if (ROOT::Math::VectorUtil::DeltaR(jets_p4().at(k), lr_p4()) < 0.4) continue;
        nJets++;
        if (btagDiscriminant().at(k) < 0.244) continue;
        nBtags++;
      }

       //metPhi Correction//
//////////// SELECTION ///////
//Event Requirements
//muon eta > 2.1
//electron eta > 2.4
if(lr_p4().pt() < 30) continue;
if(nJets < 2) continue;
if(nBtags != 0) continue;
if(cmet < 40 ) continue;
//Event Requirements

//TRIGGER WEIGH//
if(abs(lr_id()) == 13){
lepton_weight = electronTriggerWeight(lr_p4().pt(),lr_p4().eta());
}
else if(abs(lr_id()) == 11){ 
lepton_weight = muonTriggerWeight(lr_p4().pt(),lr_p4().eta());
}

//float w_pt_ = (lr_p4() + met_vec).pt();

//met FILL
if(file_count == 1){
met_data->Fill(cmet);
	if (abs(lr_id()) == 13){
met_data_mu->Fill(cmet);
	}
	if (abs(lr_id()) == 11){
met_data_el->Fill(cmet);
	}
}

else if(file_count == 2){
met_ttbar->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	if (abs(lr_id()) == 13){
met_ttbar_mu->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
	if (abs(lr_id()) == 11){
met_ttbar_el->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
}

else if(file_count == 3){
met_wjets->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	if (abs(lr_id()) == 13){
met_wjets_mu->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
	if (abs(lr_id()) == 11){
met_wjets_el->Fill(cmet,scale_1fb()*lepton_weight*5.2);
	}
}
/*
		\\\~*~*~*~\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|||||/////////////////////////////////////~*~*~*~///
		///~*~*~*~///////////////////////////////////////|||||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~*~*~*~\\\
*/
/////////////    ADD FAKE    ////////////
//W FAKE
//W vector variables
float xw = 0, yw = 0, phiw = 0 , thetaw = 0;
float w_p = -1, w_px = -1, w_py = -1, w_pz = -1;
float b[2];

//lepton vector variables
float xc = 0 , yc = 0, zc = 0;
float r = 40, x = 0, y = 0, phi =0 , theta = 0;
float a[2];
float gammaM;
	//random w momentum from the histogram
	//w_p = d.Landau(95.0291,10.3062);
float rand_pt = d.Landau(40.5,17);

	w_p = rand_pt;

	ry.RndmArray(2,b);
	xw = b[0];
	yw = b[1];

//angles for W vector intial direction
	thetaw = acos(2*xw-1);	   
 	phiw = 2*3.14156265359*(yw-0.5);       

//Change of coordinate to XYZ and scale by magnitude of p
      w_px = w_p* sin(thetaw)* cos(phiw); 
      w_py = w_p* sin(thetaw)* sin(phiw);
      w_pz = w_p* cos(thetaw);
//LEPTON
//Create Lepton fake
	LorentzVector fake_lep, fake_met;
//use TLorentVector to boost
	TLorentzVector lep_boost, met_boost;

//do while eta > 2.4 for the lepton
	do{
//random numbers x,y
//rx TRandom class
	rx.RndmArray(2,a);
	x = a[0];
	y = a[1];

//calculate phi and theta
	phi = (x-0.5)*2*3.14156265359;
	theta = acos(2*y - 1);

//calculate cartesian coordinates of the momentum
	 xc = r*sin(theta)*cos(phi);
	 yc = r*sin(theta)*sin(phi);
	 zc = r*cos(theta);

//lepton momentum and met momentum should be oppositely signed
	lep_boost.SetPxPyPzE(xc,yc,zc,40); 
	met_boost.SetPxPyPzE(-xc,-yc,-zc,40);

//BOOST
//gammaM is gamma * mass, reduces to sqrt(momentum^2 + mass^2)
	float gammaM_ = sqrt(w_p*w_p + 80.2*80.2);
	gammaM = gammaM_;

//Boost lepton
	lep_boost.Boost(w_px / (gammaM), w_py / (gammaM), w_pz / (gammaM) );

		} while  (lep_boost.Eta() > 2.4 ); //make sure lepton is within the eta requirement

//boost the neutrino
	met_boost.Boost(w_px / (gammaM), w_py / (gammaM), w_pz / (gammaM) );

//switch from boost-able TLorentzVector into LorentzVector, 
//some things work different in TLorentzVector
	fake_lep.SetPxPyPzE(lep_boost.Px(),lep_boost.Py(),lep_boost.Pz(),0);
	fake_met.SetPxPyPzE(met_boost.Px(),met_boost.Py(),met_boost.Pz(),0);

//now vector addition using fake_metPhi, metPhi, met, and 40(momentum of the new neutrino)
	float met_x = cos(cmetphi)*cmet;
	float met_y = sin(cmetphi)*cmet;

//real met vector
	LorentzVector real_met;
	real_met.SetPxPyPzE(met_x,met_y,0,0); 

//new met vector
	LorentzVector new_met;
	new_met = real_met + fake_met;
///////////////  END FAKE   ////////////////////////////////////
float fake_W_pt = (fake_lep+fake_met).pt();
if(file_count == 1) fake_wpt_h->Fill(fake_W_pt);
/*
		\\\~*~*~*~\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\|||||/////////////////////////////////////~*~*~*~///
		///~*~*~*~///////////////////////////////////////|||||\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\~*~*~*~\\\
*/

////////  MT //////
float dphi = lr_p4().Phi() - cmetphi;
if(dphi > 3.1415) dphi = 6.28 - dphi;
float MT = sqrt(2 * lr_p4().pt() * cmet *(1 - cos(dphi))); 
////////  MT //////

double mt2_event = MT2(new_met.Pt(),new_met.Phi(), lr_p4(), fake_lep);
////////  MT2 //////
if(file_count == 1){
if(mt2_event == 0)				  mt2_0_counter+=1;
else if(0 < mt2_event && mt2_event <= 10)	 mt2_10_counter+=1; 
else if(10 < mt2_event && mt2_event <= 20)	 mt2_20_counter+=1; 
else if(20 < mt2_event && mt2_event <= 30)	 mt2_30_counter+=1;
else if(30 < mt2_event && mt2_event <= 40)	 mt2_40_counter+=1; 
else if(40 < mt2_event && mt2_event <= 50)	 mt2_50_counter+=1;
else if(50 < mt2_event && mt2_event <= 60)	 mt2_60_counter+=1;
else if(60 < mt2_event && mt2_event <= 70)	 mt2_70_counter+=1;
else if(70 < mt2_event && mt2_event <= 80)	 mt2_80_counter+=1;
else if(80 < mt2_event && mt2_event <= 90)	 mt2_90_counter+=1;
else if(90 < mt2_event && mt2_event <= 100)	mt2_100_counter+=1;
else if(100 < mt2_event && mt2_event <= 110)	mt2_110_counter+=1;
else if(110 < mt2_event && mt2_event <= 120)	mt2_120_counter+=1;
else if(120 < mt2_event && mt2_event <= 130)	mt2_130_counter+=1;
else if(130 < mt2_event && mt2_event <= 140)	mt2_140_counter+=1;
else if(140 < mt2_event && mt2_event <= 150)	mt2_150_counter+=1;
else if(150 < mt2_event && mt2_event <= 160)	mt2_160_counter+=1;
else if(160 < mt2_event && mt2_event <= 170)	mt2_170_counter+=1;
else if(170 < mt2_event && mt2_event <= 180)	mt2_180_counter+=1;
else if(180 < mt2_event && mt2_event <= 190)	mt2_190_counter+=1;
else if(190 < mt2_event && mt2_event <= 200)	mt2_200_counter+=1;
else if( mt2_event > 200)		       mt2_G200_counter+=1;
	} //data

if(file_count == 2 || file_count == 3){
if(mt2_event == 0)			   	  mt2_0_counter += 1*lepton_weight;
else if(0 < mt2_event && mt2_event <= 10)	 mt2_10_counter += 1*lepton_weight; 
else if(10 < mt2_event && mt2_event <= 20)	 mt2_20_counter += 1*lepton_weight; 
else if(20 < mt2_event && mt2_event <= 30)	 mt2_30_counter += 1*lepton_weight;
else if(30 < mt2_event && mt2_event <= 40)	 mt2_40_counter += 1*lepton_weight; 
else if(40 < mt2_event && mt2_event <= 50)	 mt2_50_counter += 1*lepton_weight;
else if(50 < mt2_event && mt2_event <= 60)	 mt2_60_counter += 1*lepton_weight;
else if(60 < mt2_event && mt2_event <= 70)	 mt2_70_counter += 1*lepton_weight;
else if(70 < mt2_event && mt2_event <= 80)	 mt2_80_counter += 1*lepton_weight;
else if(80 < mt2_event && mt2_event <= 90)	 mt2_90_counter += 1*lepton_weight;
else if(90 < mt2_event && mt2_event <= 100)	mt2_100_counter += 1*lepton_weight;
else if(100 < mt2_event && mt2_event <= 110)	mt2_110_counter += 1*lepton_weight;
else if(110 < mt2_event && mt2_event <= 120)	mt2_120_counter += 1*lepton_weight;
else if(120 < mt2_event && mt2_event <= 130)	mt2_130_counter += 1*lepton_weight;
else if(130 < mt2_event && mt2_event <= 140)	mt2_140_counter += 1*lepton_weight;
else if(140 < mt2_event && mt2_event <= 150)	mt2_150_counter += 1*lepton_weight;
else if(150 < mt2_event && mt2_event <= 160)	mt2_160_counter += 1*lepton_weight;
else if(160 < mt2_event && mt2_event <= 170)	mt2_170_counter += 1*lepton_weight;
else if(170 < mt2_event && mt2_event <= 180)	mt2_180_counter += 1*lepton_weight;
else if(180 < mt2_event && mt2_event <= 190)	mt2_190_counter += 1*lepton_weight;
else if(190 < mt2_event && mt2_event <= 200)	mt2_200_counter += 1*lepton_weight;
else if( mt2_event > 200)		       mt2_G200_counter += 1*lepton_weight;
	} //MC 
////////  MT2 //////
float lep_pt = lr_p4().pt();

////////  FILL //////
// JETS, MT, MT2, W_pT
//DATA
if(file_count == 1){
totalEvents+=1;
	data_w_pt->Fill(w_pt_);
	data_lep_pt->Fill(lep_pt);
	jets_data->Fill(nJets);
	mt2_h_data->Fill(mt2_event);
	mt_h_data->Fill(MT);
if (abs(lr_id()) == 13){
	data_lep_pt_mu->Fill(lep_pt);
	mt2_h_data_mu->Fill(mt2_event);
	mt_h_data_mu->Fill(MT);
	jets_data_mu->Fill(nJets);
	}
if (abs(lr_id()) == 11){
	data_lep_pt_el->Fill(lep_pt);
	mt2_h_data_el->Fill(mt2_event);
	mt_h_data_el->Fill(MT);
	jets_data_el->Fill(nJets);
	}
}
//TTBAR
else if(file_count == 2){
totalEvents+=1*lepton_weight*scale_1fb()*5.2;
	ttbar_w_pt->Fill(w_pt_,scale_1fb()*lepton_weight*5.2);
	ttbar_lep_pt->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar->Fill(nJets,scale_1fb()*lepton_weight*5.2);
if (abs(lr_id()) == 13){
	ttbar_lep_pt_mu->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar_mu->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar_mu->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar_mu->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
if (abs(lr_id()) == 11){
	ttbar_lep_pt_el->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_ttbar_el->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_ttbar_el->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_ttbar_el->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
}
//WJETS
else if(file_count == 3){
totalEvents+=1*lepton_weight*scale_1fb()*5.2;
	wjets_w_pt ->Fill(w_pt_,scale_1fb()*lepton_weight*5.2);	
	wjets_lep_pt ->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);	
	mt2_h_wjets->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets ->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets ->Fill(nJets,scale_1fb()*lepton_weight*5.2);
if (abs(lr_id()) == 13){
	wjets_lep_pt_mu->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_wjets_mu->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets_mu->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets_mu->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
if (abs(lr_id()) == 11){
	wjets_lep_pt_el->Fill(lep_pt,scale_1fb()*lepton_weight*5.2);
	mt2_h_wjets_el->Fill(mt2_event,scale_1fb()*lepton_weight*5.2);
	mt_h_wjets_el->Fill(MT,scale_1fb()*lepton_weight*5.2);
	jets_wjets_el->Fill(nJets,scale_1fb()*lepton_weight*5.2);
	}
}
	/////FILL END //////
	}//event 
///////////////// write histograms ////////////
char* date = "may30";
if(file_count == 1){
     TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/data_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_data->Write();
	mt_h_data->Write();
	met_data->Write();
	jets_data->Write();
	data_w_pt->Write();
	data_lep_pt->Write();

	data_lep_pt_mu->Write();
	mt2_h_data_mu->Write();
	mt_h_data_mu->Write();
	met_data_mu->Write();
	data_w_pt_mu->Write();
	jets_data_mu->Write();

	data_lep_pt_el->Write();
	mt2_h_data_el->Write();
	mt_h_data_el->Write();
	met_data_el->Write();
	data_w_pt_el->Write();
	jets_data_el->Write();

	//cout << "DATA mt2 tail:    " << mt2tailCounter << endl;
	cout << endl;
	cout << "DATA totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
else if(file_count == 2){
    TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/ttbar_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_ttbar->Write();
	mt_h_ttbar->Write();
	met_ttbar->Write();
	jets_ttbar->Write();
	ttbar_w_pt->Write();
	ttbar_lep_pt->Write();


	ttbar_lep_pt_mu->Write();
	mt2_h_ttbar_mu->Write();
	mt_h_ttbar_mu->Write();
	met_ttbar_mu->Write();
	ttbar_w_pt_mu->Write();
	jets_ttbar_mu->Write();

	ttbar_lep_pt_el->Write();
	mt2_h_ttbar_el->Write();
	mt_h_ttbar_el->Write();
	met_ttbar_el->Write();
	ttbar_w_pt_el->Write();
	jets_ttbar_el->Write();
	//cout << "ttbar mt2 tail: " << mt2tailCounter*scale_1fb()*lepton_weight*5.2 << endl;
	cout << endl;
	cout << "ttbar totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
else if(file_count == 3){
	//TCanvas *c75 = new TCanvas("c75","c75");
    TFile* fout = new TFile(Form("/home/users/sanil/single/%shists/wjets_sl5_bv_lep30.root",date),"RECREATE");
	mt2_h_wjets->Write();
	mt_h_wjets->Write();
	met_wjets->Write();
	jets_wjets->Write();
	wjets_w_pt->Write();
	wjets_lep_pt->Write();

	wjets_lep_pt_mu->Write();
	mt2_h_wjets_mu->Write();
	mt_h_wjets_mu->Write();
	met_wjets_mu->Write();
	wjets_w_pt_mu->Write();
	jets_wjets_mu->Write();

	wjets_lep_pt_el->Write();
	mt2_h_wjets_el->Write();
	mt_h_wjets_el->Write();
	met_wjets_el->Write();
	wjets_w_pt_el->Write();
	jets_wjets_el->Write();
	//cout << "wjets mt2 tail: " << mt2tailCounter*scale_1fb()*lepton_weight*5.2 << endl;
	cout << endl;
	cout << "wjets totalEvents:    " << totalEvents << endl;
	cout << endl;
  fout->Close();
}
///////////////// write histograms END ////////////
		// +++++++++ //

       	//MT2 count writing//

	///txt output///
if(file_count == 1){
ofstream file_d(Form("/home/users/sanil/single/%shists/lep30data_mt2_bin.txt",date));
	if(!file_d.is_open()){return 0;}
	if( file_d.is_open()){
file_d << "total DATA events: " << totalEvents << endl; 
file_d << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_d << mt2_0_counter   << endl;
file_d << mt2_10_counter  << endl;
file_d << mt2_20_counter  << endl;
file_d << mt2_30_counter  << endl;
file_d << mt2_40_counter  << endl;
file_d << mt2_50_counter  << endl;
file_d << mt2_60_counter  << endl;
file_d << mt2_70_counter  << endl;
file_d << mt2_80_counter  << endl;
file_d << mt2_90_counter  << endl;
file_d << mt2_100_counter << endl;
file_d << mt2_110_counter << endl;
file_d << mt2_120_counter << endl;
file_d << mt2_130_counter << endl;
file_d << mt2_140_counter << endl;
file_d << mt2_150_counter << endl;
file_d << mt2_160_counter << endl;
file_d << mt2_170_counter << endl;
file_d << mt2_180_counter << endl;
file_d << mt2_190_counter << endl;
file_d << mt2_200_counter << endl;
file_d << mt2_G200_counter << endl;
file_d << "^^^ MT2 > 200: " << endl;
	}
}
else if (file_count == 3){
ofstream file_w(Form("/home/users/sanil/single/%shists/lep30wjets_mt2_bin.txt",date));
	if(!file_w.is_open()){return 0;}
	if( file_w.is_open()){
file_w << "total W+Jets events: " << totalEvents << endl; 
file_w << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_w << mt2_0_counter   *scale_1fb()*5.2 << endl;
file_w << mt2_10_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_20_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_30_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_40_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_50_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_60_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_70_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_80_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_90_counter  *scale_1fb()*5.2 << endl;
file_w << mt2_100_counter *scale_1fb()*5.2 << endl;
file_w << mt2_110_counter *scale_1fb()*5.2 << endl;
file_w << mt2_120_counter *scale_1fb()*5.2 << endl;
file_w << mt2_130_counter *scale_1fb()*5.2 << endl;
file_w << mt2_140_counter *scale_1fb()*5.2 << endl;
file_w << mt2_150_counter *scale_1fb()*5.2 << endl;
file_w << mt2_160_counter *scale_1fb()*5.2 << endl;
file_w << mt2_170_counter *scale_1fb()*5.2 << endl;
file_w << mt2_180_counter *scale_1fb()*5.2 << endl;
file_w << mt2_190_counter *scale_1fb()*5.2 << endl;
file_w << mt2_200_counter *scale_1fb()*5.2 << endl;
file_w << mt2_G200_counter*scale_1fb()*5.2 << endl;
file_w << "^^^ MT2 > 200 ^^^" << endl;
	}
}
else if (file_count == 2){
ofstream file_t(Form("/home/users/sanil/single/%shists/lep30ttbar_mt2_bin.txt",date));
	if(!file_t.is_open()){return 0;}
	if( file_t.is_open()){
file_d << "total tt~ events: " << totalEvents << endl; 
file_t << "starts with 0 < MT2 <= 10, and goes on increments of 10 geV; " << endl;
file_t << mt2_0_counter  *scale_1fb()*5.2 << endl;
file_t << mt2_10_counter *scale_1fb()*5.2 << endl;
file_t << mt2_20_counter *scale_1fb()*5.2 << endl;
file_t << mt2_30_counter *scale_1fb()*5.2 << endl;
file_t << mt2_40_counter *scale_1fb()*5.2 << endl;
file_t << mt2_50_counter *scale_1fb()*5.2 << endl;
file_t << mt2_60_counter *scale_1fb()*5.2 << endl;
file_t << mt2_70_counter *scale_1fb()*5.2 << endl;
file_t << mt2_80_counter *scale_1fb()*5.2 << endl;
file_t << mt2_90_counter *scale_1fb()*5.2 << endl;
file_t << mt2_100_counter*scale_1fb()*5.2 << endl;
file_t << mt2_110_counter*scale_1fb()*5.2 << endl;
file_t << mt2_120_counter*scale_1fb()*5.2 << endl;
file_t << mt2_130_counter*scale_1fb()*5.2 << endl;
file_t << mt2_140_counter*scale_1fb()*5.2 << endl;
file_t << mt2_150_counter*scale_1fb()*5.2 << endl;
file_t << mt2_160_counter*scale_1fb()*5.2 << endl;
file_t << mt2_170_counter*scale_1fb()*5.2 << endl;
file_t << mt2_180_counter*scale_1fb()*5.2 << endl;
file_t << mt2_190_counter*scale_1fb()*5.2 << endl;
file_t << mt2_200_counter*scale_1fb()*5.2 << endl;
file_t << mt2_G200_counter*scale_1fb()*5.2 << endl;
file_t << "^^^ MT2 > 200 ^^^" << endl;
	}
	///txt output end///
}
       	//MT2 count writing END//

    // Clean Up
    delete tree;
    file->Close();
    delete file;

	file_count++;
  }	//file_loop
fake_wpt_h->Draw();

  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
	}
Exemplo n.º 6
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();
  vector<int> hbins;  hbins.clear();
  vector<float> hlow; hlow.clear();
  vector<float> hup;  hup.clear();

  histonames.push_back("MT");                       hbins.push_back(18); hlow.push_back( 50.); hup.push_back(500);
  histonames.push_back("MT_harder");                hbins.push_back(18); hlow.push_back( 50.); hup.push_back(500);
  histonames.push_back("MT2W");                     hbins.push_back(20); hlow.push_back(  0.); hup.push_back(500);
  histonames.push_back("MT2W_4j");                  hbins.push_back(20); hlow.push_back(  0.); hup.push_back(500);
  histonames.push_back("MET");                      hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_3j");                   hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_4j");                   hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_hMT2W");                hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MET_hMT2W_4j");             hbins.push_back(26); hlow.push_back(100.); hup.push_back(750);
  histonames.push_back("MinDPhi");                  hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_harder");           hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_3j");               hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("MinDPhi_4j");               hbins.push_back(16); hlow.push_back(  0.); hup.push_back(3.2);
  histonames.push_back("NJets");                    hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("NJets_hard");               hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("NJets_harder");             hbins.push_back(6 ); hlow.push_back(  2.); hup.push_back(8);
  histonames.push_back("tMod");                     hbins.push_back(30); hlow.push_back(-15.); hup.push_back(15);
  histonames.push_back("tMod_2j");                  hbins.push_back(30); hlow.push_back(-15.); hup.push_back(15);

  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    for(unsigned int i = 0; i<histonames.size(); ++i){
      string mapname = histonames[i] + "_"+samplename;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", hbins[i], hlow[i], hup[i]);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }
  }

  
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  
  TH1D* counterhist;
  double count1(0), count2(0);
  double count3(0), count4(0);

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);

    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );
      
      float weight = cms3.scale1fb()*2.26;
      if(event==0) cout << "weight " << weight << " nEvents " << cms3.nEvents() << " filename " << currentFile->GetTitle() << endl;
      
      //ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > metlv;
      //metlv.SetPxPyPzE(pfmet()*TMath::Cos(pfmet_phi()),pfmet()*TMath::Sin(pfmet_phi()),0.,pfmet());
      int NSLeps = 0;
      int NAddVetoLeps = 0;
      if(lep1_is_mu()){
	if(lep1_pt()>20&&fabs(lep1_eta())<2.4) {++NSLeps;}
      } else if (lep1_is_el()){
	if(lep1_pt()>20&&fabs(lep1_eta())<1.4442) {++NSLeps; }
      } if(lep2_is_mu()){
	if(lep2_pt()>20&&fabs(lep2_eta())<2.4) {++NSLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>20&&fabs(lep2_eta())<1.4442) {++NSLeps; }
      }
      if(lep2_is_mu()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps; }
      }


      if(nvtxs()<0)               continue;
      if(ngoodleps()!=1)          continue;
      if(nvetoleps()!=1)          continue;
      if(!PassTrackVeto_v3())     continue;
      if(!PassTauVeto())          continue;
      if(ngoodjets()<2)           continue;
      if(ngoodbtags()<1)          continue;
      if(pfmet()<100)             continue;
      if(mt_met_lep()< 50)        continue;
      //if(pfmet()<250)             continue;
      //if(mt_met_lep()<150)        continue;
      //if(mindphi_met_j1_j2()<0.8) continue;

      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(is2lep() ) samplename = "TTbar2l";
	else if(is1lepFromTop() ) samplename = "TTbar1l";
	else continue;
      }

      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250) histos["MT_"+samplename]->Fill(mt_met_lep(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>350) histos["MT_harder_"+samplename]->Fill(mt_met_lep(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["MT2W_"+samplename]->Fill(MT2W(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["MT2W_4j_"+samplename]->Fill(MT2W(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_3j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150) histos["MET_4j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150 && MT2W()>200) histos["MET_hMT2W_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=4 && mindphi_met_j1_j2()>0.8 && mt_met_lep()>150 && MT2W()>200) histos["MET_hMT2W_4j_"+samplename]->Fill(pfmet(),weight);
      if(ngoodjets()>=2 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=2 && pfmet()>350 && mt_met_lep()>150) histos["MinDPhi_harder_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=3 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_3j_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=4 && pfmet()>250 && mt_met_lep()>150) histos["MinDPhi_4j_"+samplename]->Fill(mindphi_met_j1_j2(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["NJets_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150 && topnessMod()>6.4) histos["NJets_hard_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150 && MT2W()>200)       histos["NJets_hard_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>350 && mt_met_lep()>150 && topnessMod()>6.4) histos["NJets_harder_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=3 && mindphi_met_j1_j2()>0.8 && pfmet()>350 && mt_met_lep()>150 && MT2W()>200)       histos["NJets_harder_"+samplename]->Fill(ngoodjets(),weight);
      if(ngoodjets()>=2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["tMod_"+samplename]->Fill(topnessMod(),weight);
      if(ngoodjets()==2 && mindphi_met_j1_j2()>0.8 && pfmet()>250 && mt_met_lep()>150) histos["tMod_2j_"+samplename]->Fill(topnessMod(),weight);

    }//event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }//file loop
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  string filename = "rootfiles/PASfigure.root";
  TFile *f = new TFile(filename.c_str(),"update");
  f->cd();
  for(map<string,TH1F*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;
  delete f;
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 7
0
int ScanChain( TChain* chain, TString outfile, TString option="", bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  bool noSIP = false;
  if (option.Contains("noSIP")) noSIP = true;

  bool usePtRel = false;
  if (option.Contains("ptRel")) usePtRel = true;

  bool doBonly = false;
  if (option.Contains("doBonly")) doBonly = true;

  bool doConly = false;
  if (option.Contains("doConly")) doConly = true;

  bool doLightonly = false;
  if (option.Contains("doLightonly")) doLightonly = true;

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");

  TH2D *pTrelvsIso_histo_el = new TH2D("pTrelvsIso_histo_el", "pTrel vs Iso (Electrons)", 10, 0., 1., 15, 0., 30.);
  pTrelvsIso_histo_el->SetDirectory(rootdir);
  pTrelvsIso_histo_el->Sumw2();

  TH2D *pTrelvsIso_histo_mu = new TH2D("pTrelvsIso_histo_mu", "pTrel vs Iso (Muons)", 10, 0., 1., 15, 0., 30.);
  pTrelvsIso_histo_mu->SetDirectory(rootdir);
  pTrelvsIso_histo_mu->Sumw2();
  //----------------------

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    ss.Init(tree);
    
    // Loop over Events in current file   //ACTUALLY A LEPTON "EVENT" LOOP
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      ss.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      lepfilter::progress( nEventsTotal, nEventsChain );
	  
      // Analysis Code
	  float weight = ss.scale1fb()*10.0;
	  if(ss.scale1fb() > 100000.) continue;  //excludes 5to10 and 10to20 EM Enriched
	  
	  bool jetptcut = false;
	  int jetidx = 0;

	  while( (jetidx < ss.jets().size()) && !jetptcut) //check to see if at least one jet w/ pt > 40
	  	{
	  	  if( ss.jets()[jetidx].pt() > 40. )
	  		{jetptcut = true;}
	  	  jetidx++;
	  	}
	  
	  if( !(jetptcut && ss.met() < 20. && ss.mt() < 20) )
	  	{continue;}

	  // if(ss.nFOs() != 1) //if more than 1 FO in event
	  // 	{continue;}
   
	  int nbtags = 0;
	  for(int i = 0; i < ss.jets().size(); i++){
		  if(ss.jets_disc()[i] > 0.814) nbtags++;
		}
	  if (nbtags > 2.) nbtags = 2;

	  if(ss.p4().pt() > 100. || ss.p4().pt() < 10. || fabs(ss.p4().eta()) > 2.4) //What do we want here? 
	  	{continue;}

	  //------------------------------------------------------------------------------------------
	  //---------------------------------Find e = f(Pt,eta)---------------------------------------
	  //------------------------------------------------------------------------------------------

	  //Find ratio of nonprompt leps passing tight to nonprompt leps passing at least loose.  This is the fake rate 
	  // Use lep_passes_id to see if num.  Use FO to see if Fakable Object (denom)
	  //Calculate e=Nt/(Nl) where l->loose  (as opposed to loose-not-tight).
	  
	  //Using gen level info to see if prompt -> no prompt contamination in measurement region
	  //everything else is RECO (p4, id, passes_id, FO, etc.)
	  

	  if( ss.motherID() != 1 && (doBonly==0 || ss.motherID() == -1) && (doConly==0 || ss.motherID() == -2) && (doLightonly==0 || ss.motherID() == 0) )  //if el is nonprompt (GEN info)
		{
		  if( abs( ss.id() ) == 11 ) // it's an el
			{
			  if(ss.FO_NoIso())  pTrelvsIso_histo_el->Fill( ss.iso(), ss.ptrelv1() );
			}
		  if( abs( ss.id() ) == 13 ) // it's a mu
			{
 			  if(ss.FO_NoIso())  pTrelvsIso_histo_mu->Fill( ss.iso(), ss.ptrelv1() );
			}
		} 

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

	}//end event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  pTrelvsIso_histo_el->GetXaxis()->SetTitle("Iso");
  pTrelvsIso_histo_el->GetYaxis()->SetTitle("pTrel");
  pTrelvsIso_histo_mu->GetXaxis()->SetTitle("Iso");
  pTrelvsIso_histo_mu->GetYaxis()->SetTitle("pTrel");

  gStyle->SetOptStat(0);
  gStyle->SetPaintTextFormat("1.3f");

  TCanvas *c9=new TCanvas("c9","B pTrel vs Iso (el)",800,800);
  pTrelvsIso_histo_el->Draw("colz,texte");
  TCanvas *c10=new TCanvas("c10","B pTrel vs Iso (mu)",800,800);
  pTrelvsIso_histo_mu->Draw("colz,texte");

  //---save histos-------//
  TFile *OutputFile = new TFile(outfile,"recreate");
  pTrelvsIso_histo_el->Write();
  pTrelvsIso_histo_mu->Write();

  OutputFile->Close();

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 8
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  // samplehisto->SetDirectory(rootdir);

  TH1F *h_muonCount = new TH1F("h_muonCount", "Number of Muons in this event", 90, 0, 5);

  // MuonTagAndProbe: define the trigger to check here
  vector<string> triggerNames;
  triggerNames.push_back("HLT_IsoMu24");
  triggerNames.push_back("HLT_IsoTkMu24");
  // triggerNames.push_back("HLT_IsoMu20");
  // triggerNames.push_back("HLT_IsoTkMu20");
  // triggerNames.push_back("HLT_Ele27_eta2p1_WPLoose_Gsf");
  // triggerNames.push_back("HLT_Ele22_eta2p1_WPLoose_Gsf");

  // Separate vector to store the pt cut to be used for eta and phi
  vector<float> triggerPtCuts(triggerNames.size(), 50);
  // triggerPtCuts[2] = 25;
  // triggerPtCuts[3] = 25;

  vector<map<histType,TH1F*>> muonHists = creatMuonHists(triggerNames);
  vector<map<histType,TH1F*>> muonHists1 = creatMuonHists(triggerNames, "_1");
  vector<map<histType,TH1F*>> muonHists2 = creatMuonHists(triggerNames, "_2");
  vector<map<histType,TH1F*>> muonHists3 = creatMuonHists(triggerNames, "_3");

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if (nEvents >= 0) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile file( currentFile->GetTitle() );
    TTree *tree = (TTree*)file.Get("t");
    if (fast) TTreeCache::SetLearnEntries(10);
    if (fast) tree->SetCacheSize(128*1024*1024);
    t.Init(tree);

    int evt_num = -1;
    int nMuonCount = 0;
    int isTriggerMuon = 0;
    LorentzVector p4mu;
    LorentzVector tag_p4mu;

    vector<TBranch*> trigBranches = setupTriggerBranches(triggerNames, tree);
    vector<TBranch*> tagTrigBranches = setupTagTriggerBranches(triggerNames, tree);

    // Loop over Events in current file
    if (nEventsTotal >= nEventsChain) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for (unsigned int event = 0; event < nEventsTree; ++event) {

      // Get Event Content
      if (nEventsTotal >= nEventsChain) continue;
      if (fast) tree->LoadTree(event);
      t.GetEntry(event);
      ++nEventsTotal;

      // Progress
      LepTree::progress(nEventsTotal, nEventsChain);

      // Analysis Code

      if (evt_isRealData() && evt_run() < 273423) continue;  // Get runs after fixing the L1 interface problem

      int nevt = evt_event();
      if (nevt != evt_num) {
        h_muonCount->Fill(nMuonCount);
        nMuonCount = 0;
        isTriggerMuon = 0;
      }

      // --- New Tag & Probe ---
      if (abs(id()) != 13) continue;
      if (p4().pt() < 10) continue;
      if (fabs(p4().eta()) > 2.4 ) continue;
      if (charge()*tag_charge() > 0) continue;
      if (tag_p4().pt() < 25) continue;
      if (tag_RelIso03EA() > 0.1) continue;
      if (dilep_mass() < 81.2 || dilep_mass() > 101.2) continue;
      if (!pid_PFMuon()) continue;

      ++nMuonCount;
      // if (nMuonCount > 2) continue;

      for (unsigned int i=0; i<triggerNames.size(); i++) {
        if (getTriggerValue(tagTrigBranches[i], event) <= 0) continue;

        fillTagMuonHists(muonHists[i],  triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillProbeMuonHists(muonHists[i], trigBranches[i], event, triggerPtCuts[i]);

        fillTagMuonHists(muonHists1[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists2[i], triggerPtCuts[i]);
        fillTagMuonHists(muonHists3[i], triggerPtCuts[i]);

        fillDenMuonHists(muonHists1[i], triggerPtCuts[i]);
        if (passes_IsoCut() && passes_leptonID())
          fillNumMuonHists(muonHists1[i], triggerPtCuts[i]);

        if (passes_IsoCut()) {
          fillDenMuonHists(muonHists2[i], triggerPtCuts[i]);
          if (passes_leptonID())
            fillNumMuonHists(muonHists2[i], triggerPtCuts[i]);
        }

        if (passes_leptonID()) {
          fillDenMuonHists(muonHists3[i], triggerPtCuts[i]);
          if (passes_IsoCut())
            fillNumMuonHists(muonHists3[i], triggerPtCuts[i]);
        }
      }

      // End of Analysis Code
    }

    // Clean Up
    delete tree;
    file.Close();
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  // return
  bmark->Stop("benchmark");

  TFile* outfile = new TFile("hists.root", "RECREATE");

  for (unsigned int i=0; i<triggerNames.size(); i++) {
    TDirectory * dir = (TDirectory*) outfile->mkdir(triggerNames[i].c_str());
    dir->cd();
    TDirectory * dir2 = (TDirectory*) dir->mkdir("trigeff");
    dir2->cd();
    writeEfficiencyPlots(muonHists[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID+ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists1[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ID");
    dir2->cd();
    writeEfficiencyPlots(muonHists2[i], triggerNames[i], outfile);
    dir2 = (TDirectory*) dir->mkdir("ISO");
    dir2->cd();
    writeEfficiencyPlots(muonHists3[i], triggerNames[i], outfile);
  }

  h_muonCount->Write();

  outfile->Close();

  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 9
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  int currentrun = -1;
  bool DCSonly = false;//KEEP THIS FALSE
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");

  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();
  vector<int> hbins; hbins.clear();
  vector<float> hlow; hlow.clear();
  vector<float> hup; hup.clear();
  histonames.push_back("Mll");                       hbins.push_back(75); hlow.push_back(  15.); hup.push_back(390);
  histonames.push_back("Mud0");                      hbins.push_back(40); hlow.push_back( -0.4); hup.push_back(0.4);
  histonames.push_back("MudZ");                      hbins.push_back(40); hlow.push_back(  -1.); hup.push_back(1. );
  histonames.push_back("MuIP3d");                    hbins.push_back(40); hlow.push_back( -0.5); hup.push_back(0.5);
  histonames.push_back("MuRelIso03");                hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03EA");              hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03DB");              hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoEA");               hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoDB");               hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso04");                hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuAnnulus04");               hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuRelIso03_MT30");           hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03EA_MT30");         hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso03DB_MT30");         hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoEA_MT30");          hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuMiniIsoDB_MT30");          hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuRelIso04_MT30");           hbins.push_back(50); hlow.push_back(   0.); hup.push_back(2. );
  histonames.push_back("MuAnnulus04_MT30");          hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuID");                      hbins.push_back( 7); hlow.push_back(  -1.); hup.push_back(6. );
  histonames.push_back("MuvalidFraction");           hbins.push_back(25); hlow.push_back(   0.); hup.push_back(1. );
  histonames.push_back("MuisPF");                    hbins.push_back( 5); hlow.push_back(  -1.); hup.push_back(4. );
  histonames.push_back("Mugfit_normchi2");           hbins.push_back(40); hlow.push_back(   0.); hup.push_back(20.);
  histonames.push_back("Mugfit_validSTAHits");       hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10.);
  histonames.push_back("MunumberOfMatchedStations"); hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10.);
  histonames.push_back("Munlayers");                 hbins.push_back(20); hlow.push_back(   0.); hup.push_back(20.);
  histonames.push_back("Muchi2LocalPosition");       hbins.push_back(40); hlow.push_back(   0.); hup.push_back(40.);
  histonames.push_back("MutrkKink");                 hbins.push_back(50); hlow.push_back(   0.); hup.push_back(50.);
  histonames.push_back("MusegmCompatibility");       hbins.push_back(35); hlow.push_back(   0.); hup.push_back(1.4);
  histonames.push_back("MuvalidPixelHits");          hbins.push_back( 5); hlow.push_back(   0.); hup.push_back(5. );
  histonames.push_back("MuPt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("MuEta");                     hbins.push_back(60); hlow.push_back(   3.); hup.push_back(3. );
  histonames.push_back("MuPhi");                     hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("MuCharge");                  hbins.push_back( 6); hlow.push_back(  -2.); hup.push_back(4. );
  histonames.push_back("MT");                        hbins.push_back(45); hlow.push_back(   0.); hup.push_back(450);
  histonames.push_back("ZPt");                       hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("Z_Pt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("ZEta");                      hbins.push_back(50); hlow.push_back(  -5.); hup.push_back(5. );
  histonames.push_back("ZPhi");                      hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("DPhill");                    hbins.push_back(32); hlow.push_back(   0.); hup.push_back(3.2);
  histonames.push_back("DEtall");                    hbins.push_back(50); hlow.push_back(   0.); hup.push_back(5. );
  histonames.push_back("DRll");                      hbins.push_back(32); hlow.push_back(   0.); hup.push_back(6.4);
  histonames.push_back("MyMuPt");                      hbins.push_back(30); hlow.push_back(   0.); hup.push_back(600);
  histonames.push_back("MyMuEta");                     hbins.push_back(60); hlow.push_back(   3.); hup.push_back(3. );
  histonames.push_back("MyMuPhi");                     hbins.push_back(32); hlow.push_back( -3.2); hup.push_back(3.2);
  histonames.push_back("MyMuCharge");                  hbins.push_back( 6); hlow.push_back(  -2.); hup.push_back(4. );
  histonames.push_back("MET");                      hbins.push_back(40); hlow.push_back(   0.); hup.push_back(200);
  histonames.push_back("HT");                      hbins.push_back(40); hlow.push_back(   0.); hup.push_back(400);
  histonames.push_back("NJets");                      hbins.push_back(10); hlow.push_back(   0.); hup.push_back(10);
  histonames.push_back("NBJets");                      hbins.push_back(5); hlow.push_back(   0.); hup.push_back(5);
	      
  for(unsigned int i = 0; i<histonames.size(); ++i){
    int nbins = hbins[i];
    string mapname;
    for(unsigned int j = 0; j<11; ++j){
      string prefix = "";
      if(j==1) prefix = "NJ0_";
      else if(j==2) prefix = "NJ1_";
      else if(j==3) prefix = "NJ2_";
      else if(j==4) prefix = "NJge3_";
      else if(j==5) prefix = "NB0_";
      else if(j==6) prefix = "NBge1_";
      else if(j==7) prefix = "HTge100_";
      else if(j==8) prefix = "METge50_";
      else if(j==9) prefix = "METge25_";
      else if(j==10) prefix = "HTge150_";
      mapname = prefix + histonames[i]+"_"+skimFilePrefix;
      //cout << mapname << endl;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", nbins, hlow[i], hup[i]);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }
  }

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //load json file
  const char* json_fileDCS = "myjsons/json_DCSONLY_Run2015B_snt.txt";
  const char* json_file = "myjsons/json_Golden_246908-251883_snt.txt";
  if(DCSonly) set_goodrun_file(json_fileDCS);
  else        set_goodrun_file(json_file);

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);

    int nleps = 1;
    myevt p;//previous event
    myevt c;//current event
    resetEvent(p);
    resetEvent(c);
    vector<myevt> mu; mu.clear();

    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress(nEventsTotal, nEventsChain );
      if(evt_isRealData()&& !goodrun(evt_run(), evt_lumiBlock()) ) continue;

      //load my struct
      c.evt_pfmet   = evt_pfmet();
      c.evt_pfmetPhi   = evt_pfmetPhi();
      c.evt_trackmet   = evt_trackmet();
      c.evt_trackmetPhi   = evt_trackmetPhi();
      c.evt_pfsumet   = evt_pfsumet();
      c.evt_pfmetSig   = evt_pfmetSig();
      c.evt_event   = evt_event();
      c.evt_lumiBlock   = evt_lumiBlock();
      c.evt_run   = evt_run();
      c.filt_csc   = filt_csc();
      c.filt_hbhe   = filt_hbhe();
      c.filt_hcallaser   = filt_hcallaser();
      c.filt_ecaltp   = filt_ecaltp();
      c.filt_trkfail   = filt_trkfail();
      c.filt_eebadsc   = filt_eebadsc();
      c.evt_isRealData   = evt_isRealData(); 
      c.scale1fb   = scale1fb();
      c.evt_xsec_incl   = evt_xsec_incl();
      c.evt_kfactor   = evt_kfactor();
      c.gen_met   = gen_met();
      c.gen_metPhi   = gen_metPhi();
      c.njets   = njets();
      c.ht   = ht();
      c.jets  = jets();
      c.jets_disc  = jets_disc();
      c.sample  = sample();
      c.nvtx   = nvtx();
      c.HLT_Mu8_TrkIsoVVL   = HLT_Mu8_TrkIsoVVL();
      c.HLT_Mu17_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL();
      c.HLT_Mu24_TrkIsoVVL   = HLT_Mu24_TrkIsoVVL();
      c.HLT_Mu34_TrkIsoVVL   = HLT_Mu34_TrkIsoVVL();
      c.HLT_Mu8   = HLT_Mu8();
      c.HLT_Mu17   = HLT_Mu17();
      c.HLT_Mu24   = HLT_Mu24();
      c.HLT_Mu34   = HLT_Mu34();
      c.HLT_Mu10_CentralPFJet30_BTagCSV0p5PF   = HLT_Mu10_CentralPFJet30_BTagCSV0p5PF();
      c.HLT_IsoMu24_eta2p1   = HLT_IsoMu24_eta2p1();
      c.HLT_IsoTkMu24_eta2p1   = HLT_IsoTkMu24_eta2p1(); 
      c.HLT_IsoMu27   = HLT_IsoMu27();
      c.HLT_IsoTkMu27   = HLT_IsoTkMu27(); 
      c.HLT_Mu45_eta2p1   = HLT_Mu45_eta2p1(); 
      c.HLT_Mu50   = HLT_Mu50();
      c.HLT_Ele8_CaloIdM_TrackIdM_PFJet30   = HLT_Ele8_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele12_CaloIdM_TrackIdM_PFJet30   = HLT_Ele12_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele18_CaloIdM_TrackIdM_PFJet30   = HLT_Ele18_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele23_CaloIdM_TrackIdM_PFJet30   = HLT_Ele23_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele33_CaloIdM_TrackIdM_PFJet30   = HLT_Ele33_CaloIdM_TrackIdM_PFJet30();
      c.HLT_Ele12_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele12_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele18_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele18_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele23_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele23_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele33_CaloIdL_TrackIdL_IsoVL_PFJet30   = HLT_Ele33_CaloIdL_TrackIdL_IsoVL_PFJet30();
      c.HLT_Ele10_CaloIdM_TrackIdM_CentralPFJet30_BTagCSV0p5PF   = HLT_Ele10_CaloIdM_TrackIdM_CentralPFJet30_BTagCSV0p5PF();
      c.HLT_Ele27_eta2p1_WP75_Gsf   = HLT_Ele27_eta2p1_WP75_Gsf();
      c.HLT_Ele27_WP85_Gsf   = HLT_Ele27_WP85_Gsf();
      c.HLT_Ele27_eta2p1_WPLoose_Gsf   = HLT_Ele27_eta2p1_WPLoose_Gsf();
      c.HLT_Ele27_eta2p1_WPTight_Gsf   = HLT_Ele27_eta2p1_WPTight_Gsf();
      c.HLT_Ele32_eta2p1_WP75_Gsf   = HLT_Ele32_eta2p1_WP75_Gsf();
      c.HLT_Ele32_eta2p1_WPLoose_Gsf   = HLT_Ele32_eta2p1_WPLoose_Gsf();
      c.HLT_Ele32_eta2p1_WPTight_Gsf   = HLT_Ele32_eta2p1_WPTight_Gsf();
      c.HLT_Mu8_Ele8_CaloIdM_TrackIdM_Mass8_PFHT300   = HLT_Mu8_Ele8_CaloIdM_TrackIdM_Mass8_PFHT300();
      c.HLT_Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL   = HLT_Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL();
      c.HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL   = HLT_Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL();
      c.HLT_DoubleMu8_Mass8_PFHT300   = HLT_DoubleMu8_Mass8_PFHT300();
      c.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL();
      c.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL   = HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL(); 
      c.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ   = HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ();
      c.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ   = HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ(); 
      c.HLT_DoubleEle8_CaloIdM_TrackIdM_Mass8_PFHT300   = HLT_DoubleEle8_CaloIdM_TrackIdM_Mass8_PFHT300();
      c.HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ   = HLT_Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ();
      c.pid_PFMuon   = pid_PFMuon();
      c.gfit_chi2   = gfit_chi2();
      c.gfit_ndof   = gfit_ndof();
      c.gfit_validSTAHits   = gfit_validSTAHits();
      c.numberOfMatchedStations   = numberOfMatchedStations();
      c.validPixelHits   = validPixelHits();
      c.nlayers   = nlayers();
      c.chi2LocalPosition   = chi2LocalPosition();
      c.trkKink   = trkKink();
      c.validHits   = validHits(); 
      c.lostHits   = lostHits();
      c.exp_outerlayers   = exp_outerlayers();
      c.segmCompatibility   = segmCompatibility();
      c.exp_innerlayers   = exp_innerlayers();
      c.passes_POG_vetoID   = passes_POG_vetoID();
      c.passes_POG_looseID   = passes_POG_looseID();
      c.passes_POG_mediumID   = passes_POG_mediumID();
      c.passes_POG_tightID   = passes_POG_tightID();
      c.ip3d   = ip3d();
      c.ip3derr   = ip3derr(); 
      c.type   = type();
      c.mt   = mt();
      c.ptrelv0   = ptrelv0();
      c.ptrelv1   = ptrelv1();
      c.miniiso   = miniiso();
      c.miniisoDB   = miniisoDB(); 
      c.reliso04   = reliso04();
      c.annulus04   = annulus04();
      c.p4  = p4();
      c.tag_p4  = tag_p4();
      c.dilep_p4  = dilep_p4();
      c.mc_p4  = mc_p4();
      c.mc_motherp4  = mc_motherp4();
      c.id   = id();
      c.idx   = idx();
      c.dxyPV   = dxyPV();
      c.dZ   = dZ();
      c.dxyPV_err   = dxyPV_err();
      c.motherID   = motherID();
      c.mc_id   = mc_id();
      c.RelIso03   = RelIso03();
      c.RelIso03EA   = RelIso03EA();
      c.RelIso03DB   = RelIso03DB();
      c.dilep_mass   = dilep_mass();
      c.dilep_p4   = dilep_p4();
      c.passes_SS_tight_noiso_v3 = passes_SS_tight_noiso_v3();
      c.passes_SS_fo_noiso_v3 = passes_SS_fo_noiso_v3();
      c.passes_POG_looseID = passLooseID(c);
      c.passes_POG_mediumID = passMediumID(c);
      c.passes_POG_tightID = passTightID(c);
     

      float weight = p.scale1fb*0.0403;
      if(skimFilePrefix=="DY_M10_50ns") weight *= 1.11;
      if(p.evt_isRealData) weight = 1.;
      if((skimFilePrefix=="SingleMuon"||skimFilePrefix=="DoubleMuon")&&fabs(weight-1.)>=0.001) cout <<__LINE__<< endl;
      // Analysis Code

      if(sameEvent(p,c)) { ++nleps; }


      if(((!sameEvent(p,c))||(nEventsChain==nEventsTotal)) && mu.size()>0) {

	int nbs = 0;
	int njs = 0;
	float HT = 0;
	double muovind[mu.size()];
	for(unsigned int i = 0; i<mu.size();++i){
	  muovind[i] = -1;
	  float minDR = 9999;
	  if(mu[i].jets.size()!=p.jets.size()) cout << "ERROR " << mu[i].jets.size() << " " << p.jets.size() << endl;
	  for(unsigned int j = 0; j<p.jets.size();++j){
	    float myDR = deltaR(mu[i].p4,p.jets[j]);
	    if(myDR<0.4 && myDR<minDR){
	      minDR = myDR;
	      muovind[i] = j;
	    }
	  }
	}
	for(unsigned int i = 0; i<p.jets.size();++i){
	  bool isoverlap = false;
	  for(unsigned int j = 0; j<mu.size();++j){
	    if(muovind[j]==i){
	      isoverlap = true;
	      break;
	    }
	  }
	  if(isoverlap) continue;
	  if(p.jets[i].Pt()<30) continue;
	  if(fabs(p.jets[i].Eta()>2.4)) continue;
	  ++njs;
	  HT += p.jets[i].Pt();
	  if(p.jets_disc[i]>0.890) ++nbs;
	}
      
	bool triggerbool2mu = false;
	bool triggerbool1mu = false;
	//now I reached full event!
	if(mu.size()>1) mu = sortbypt(mu);
	for(unsigned int i = 0; i<mu.size();++i){
	  if(mu[i].evt_isRealData) triggerbool2mu = triggerbool2mu || mu[i].HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ || mu[i].HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ;
	  if(mu[i].evt_isRealData) triggerbool1mu = triggerbool1mu || mu[i].HLT_IsoMu24_eta2p1 || mu[i].HLT_IsoTkMu24_eta2p1 || mu[i].HLT_IsoMu27 || mu[i].HLT_IsoTkMu27 || mu[i].HLT_IsoMu20 || mu[i].HLT_IsoMu20;
	}
	if(!p.evt_isRealData){ triggerbool2mu = true; triggerbool1mu = true;}
	if(mu.size()==2){
	  triggerbool2mu = triggerbool2mu&&mu[0].p4.Pt()>20.&&fabs(mu[0].p4.Eta())<2.1&&mu[0].p4.Pt()>20.&&fabs(mu[0].p4.Eta())<2.1;//two muons passing nominal trigger w/o iso and dZ
	  triggerbool1mu = triggerbool1mu&&((mu[0].p4.Pt()>30.&&fabs(mu[0].p4.Eta())<2.1)||(mu[1].p4.Pt()>30.&&fabs(mu[1].p4.Eta())<2.1));//one muon passing nominal trigger w/o iso
	  LorentzVector Z = (mu[0].p4+mu[1].p4);
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2&&
	      fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    //cout << "have a dilepton event: Z pt " << Z.Pt() << " and mass " << Z.M() << endl;
	    histos["Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(njs==0) histos["NJ0_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else if(njs==1) histos["NJ1_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else if(njs==2) histos["NJ2_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else histos["NJge3_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(nbs==0)  histos["NB0_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    else  histos["NBge1_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(HT>100.) histos["HTge100_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(HT>150.) histos["HTge150_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(p.evt_pfmet>50.) histos["METge50_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(p.evt_pfmet>25.) histos["METge25_Mll_"+skimFilePrefix]->Fill(Z.M(),weight);
	    if(Z.M()>75.&&Z.M()<105){
	      histos["ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
	      histos["ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
	      histos["ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
	      histos["DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
	      histos["DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
	      histos["DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      histos["MET_"+skimFilePrefix]->Fill(p.evt_pfmet,weight);
	      histos["HT_"+skimFilePrefix]->Fill(HT,weight);
	      histos["NJets_"+skimFilePrefix]->Fill(njs,weight);
	      histos["NBJets_"+skimFilePrefix]->Fill(nbs,weight);
	      if(njs==0){
		histos["NJ0_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ0_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ0_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ0_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ0_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ0_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else if(njs==1){
		histos["NJ1_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ1_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ1_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ1_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ1_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ1_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else if(njs==2){
		histos["NJ2_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJ2_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJ2_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJ2_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJ2_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJ2_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else {
		histos["NJge3_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NJge3_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NJge3_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NJge3_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NJge3_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NJge3_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(nbs==0){
		histos["NB0_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NB0_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NB0_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NB0_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NB0_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NB0_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } else {
		histos["NBge1_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["NBge1_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["NBge1_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["NBge1_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["NBge1_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["NBge1_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(HT>100.){
		histos["HTge100_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["HTge100_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["HTge100_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["HTge100_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["HTge100_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["HTge100_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(HT>150.){
		histos["HTge150_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["HTge150_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["HTge150_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["HTge150_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["HTge150_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["HTge150_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(p.evt_pfmet>50.){
		histos["METge50_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["METge50_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["METge50_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["METge50_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["METge50_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["METge50_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);
	      } if(p.evt_pfmet>25.){
		histos["METge25_ZPt_"+skimFilePrefix]->Fill(Z.Pt(),weight);
		histos["METge25_ZEta_"+skimFilePrefix]->Fill(Z.Eta(),weight);
		histos["METge25_ZPhi_"+skimFilePrefix]->Fill(Z.Phi(),weight);
		histos["METge25_DPhill_"+skimFilePrefix]->Fill(getdphi(mu[0].p4.Phi(),mu[1].p4.Phi()),weight);
		histos["METge25_DEtall_"+skimFilePrefix]->Fill(fabs(mu[0].p4.Eta()-mu[1].p4.Eta()),weight);
		histos["METge25_DRll_"+skimFilePrefix]->Fill(dRbetweenVectors(mu[0].p4,mu[1].p4),weight);	
	      }
	      for(unsigned int i = 0; i<mu.size(); ++i){
		float mucharge = 0; if(mu[i].id==13) mucharge = -1; else if(mu[i].id==-13) mucharge = +1; 
		histos["MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		histos["MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		histos["MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		histos["MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		if(njs==0){
		  histos["NJ0_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ0_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ0_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ0_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else if(njs==1){
		  histos["NJ1_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ1_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ1_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ1_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else if(njs==2){
		  histos["NJ2_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJ2_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJ2_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJ2_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else {
		  histos["NJge3_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NJge3_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NJge3_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NJge3_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(nbs==0){
		  histos["NB0_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NB0_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NB0_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NB0_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} else {
		  histos["NBge1_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["NBge1_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["NBge1_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["NBge1_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(HT>100.){
		  histos["HTge100_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["HTge100_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["HTge100_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["HTge100_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(HT>150.){
		  histos["HTge150_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["HTge150_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["HTge150_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["HTge150_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(p.evt_pfmet>50.){
		  histos["METge50_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["METge50_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["METge50_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["METge50_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		} if(p.evt_pfmet>25.){
		  histos["METge25_MuPt_"+skimFilePrefix]->Fill(mu[i].p4.Pt(),weight);
		  histos["METge25_MuEta_"+skimFilePrefix]->Fill(mu[i].p4.Eta(),weight);
		  histos["METge25_MuPhi_"+skimFilePrefix]->Fill(mu[i].p4.Phi(),weight);
		  histos["METge25_MuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
		}
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		histos["MuRelIso03_"+skimFilePrefix]->Fill(mu[i].RelIso03,weight);
		histos["MuRelIso03EA_"+skimFilePrefix]->Fill(mu[i].RelIso03EA,weight);
		histos["MuRelIso03DB_"+skimFilePrefix]->Fill(mu[i].RelIso03DB,weight);
		histos["MuMiniIsoEA_"+skimFilePrefix]->Fill(mu[i].miniiso,weight);
		histos["MuMiniIsoDB_"+skimFilePrefix]->Fill(mu[i].miniisoDB,weight);
		histos["MuRelIso04_"+skimFilePrefix]->Fill(mu[i].reliso04,weight);
		histos["MuAnnulus04_"+skimFilePrefix]->Fill(mu[i].annulus04,weight);
		if(mu[0].mt>30&&mu[0].mt>30){
		  histos["MuRelIso03_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03,weight);
		  histos["MuRelIso03EA_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03EA,weight);
		  histos["MuRelIso03DB_MT30_"+skimFilePrefix]->Fill(mu[i].RelIso03DB,weight);
		  histos["MuMiniIsoEA_MT30_"+skimFilePrefix]->Fill(mu[i].miniiso,weight);
		  histos["MuMiniIsoDB_MT30_"+skimFilePrefix]->Fill(mu[i].miniisoDB,weight);
		  histos["MuRelIso04_MT30_"+skimFilePrefix]->Fill(mu[i].reliso04,weight);
		  histos["MuAnnulus04_MT30_"+skimFilePrefix]->Fill(mu[i].annulus04,weight);
		}
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_tightID&&mu[1].passes_POG_tightID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		histos["Mud0_"+skimFilePrefix]->Fill(mu[i].dxyPV,weight);
		histos["MudZ_"+skimFilePrefix]->Fill(mu[i].dZ,weight);
		histos["MuIP3d_"+skimFilePrefix]->Fill(mu[i].ip3d,weight);
	      }
	    }
	  }
	  if((triggerbool1mu||triggerbool2mu)&& mu[0].passes_POG_looseID&&mu[1].passes_POG_looseID&&mu[0].miniisoDB<0.2&&mu[1].miniisoDB<0.2&&
	      fabs(mu[0].dZ)<0.1&&fabs(mu[1].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&fabs(mu[1].dxyPV)<0.02){
	    if(Z.M()>75.&&Z.M()<105){
	      for(unsigned int i = 0; i<mu.size(); ++i){
		if(mu[i].passes_POG_tightID) histos["MuID_"+skimFilePrefix]->Fill(3.,weight);
		else if(mu[i].passes_POG_mediumID) histos["MuID_"+skimFilePrefix]->Fill(2.,weight);
		else if(mu[i].passes_POG_looseID) histos["MuID_"+skimFilePrefix]->Fill(1.,weight);
		histos["MuvalidFraction_"+skimFilePrefix]->Fill((float)mu[i].validHits/((float)(mu[i].validHits+mu[i].lostHits+mu[i].exp_innerlayers+mu[i].exp_outerlayers)),weight);
		if(mu[i].gfit_ndof>0) histos["Mugfit_normchi2_"+skimFilePrefix]->Fill(mu[i].gfit_chi2/mu[i].gfit_ndof, weight);
		histos["Mugfit_validSTAHits_"+skimFilePrefix]->Fill(mu[i].gfit_validSTAHits,weight);
		histos["MunumberOfMatchedStations_"+skimFilePrefix]->Fill(mu[i].numberOfMatchedStations,weight);
		histos["MuvalidPixelHits_"+skimFilePrefix]->Fill(mu[i].validPixelHits,weight);
		histos["Munlayers_"+skimFilePrefix]->Fill(mu[i].nlayers,weight);
		histos["Muchi2LocalPosition_"+skimFilePrefix]->Fill(mu[i].chi2LocalPosition,weight);
		histos["MutrkKink_"+skimFilePrefix]->Fill(mu[i].trkKink,weight);
		histos["MusegmCompatibility_"+skimFilePrefix]->Fill(mu[i].segmCompatibility,weight);
	      }
	    }
	  }
	}//2 muons
	else if(mu.size()==1){
	  triggerbool1mu = triggerbool1mu&&((mu[0].p4.Pt()>30.&&fabs(mu[0].p4.Eta())<2.1));//one muon passing nominal trigger w/o iso
	  if(triggerbool1mu&&mu[0].passes_POG_tightID&&mu[0].miniisoDB<0.2&&fabs(mu[0].dZ)<0.1&&fabs(mu[0].dxyPV)<0.02&&mu[0].mt>40){//1 mu events.
	    float mucharge = 0; if(mu[0].id==13) mucharge = -1; else if(mu[0].id==-13) mucharge = +1; 
	    histos["MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	    histos["MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	    histos["MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	    histos["MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	    histos["MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
	    if(njs==0){
	      histos["NJ0_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ0_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ0_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ0_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ0_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);
	    } else if(njs==1){
	      histos["NJ1_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ1_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ1_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ1_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ1_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else if(njs==2){
	      histos["NJ2_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJ2_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJ2_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJ2_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJ2_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else {
	      histos["NJge3_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NJge3_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NJge3_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NJge3_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NJge3_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(nbs==0){
	      histos["NB0_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NB0_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NB0_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NB0_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NB0_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } else {
	      histos["NBge1_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["NBge1_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["NBge1_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["NBge1_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["NBge1_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(HT>100.){
	      histos["HTge100_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["HTge100_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["HTge100_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["HTge100_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["HTge100_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(HT>150.){
	      histos["HTge150_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["HTge150_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["HTge150_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["HTge150_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["HTge150_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(p.evt_pfmet>50.){
	      histos["METge50_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["METge50_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["METge50_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["METge50_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["METge50_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    } if(p.evt_pfmet>25.){
	      histos["METge25_MT_"+skimFilePrefix]->Fill(mu[0].mt,weight);
	      histos["METge25_MyMuPt_"+skimFilePrefix]->Fill(mu[0].p4.Pt(),weight);
	      histos["METge25_MyMuEta_"+skimFilePrefix]->Fill(mu[0].p4.Eta(),weight);
	      histos["METge25_MyMuPhi_"+skimFilePrefix]->Fill(mu[0].p4.Phi(),weight);
	      histos["METge25_MyMuCharge_"+skimFilePrefix]->Fill(mucharge,weight);	      
	    }
	  }
	}
      }
      if(!sameEvent(p,c)){
	//finally start new event.
	if(abs(p.id)==13&&p.passes_POG_tightID&&p.miniisoDB<0.2&&fabs(p.dZ)<0.1&&fabs(p.dxyPV)<0.02&&p.dilep_mass>75.&&p.dilep_mass<105&&p.p4.Pt()>20&&fabs(p.p4.Eta())<2.1) {
	  if((p.evt_isRealData&&(p.HLT_Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ || p.HLT_Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ || p.HLT_IsoMu24_eta2p1 || p.HLT_IsoTkMu24_eta2p1 || p.HLT_IsoMu27 || p.HLT_IsoTkMu27 || p.HLT_IsoMu20 || p.HLT_IsoMu20))||(!p.evt_isRealData)){
	    histos["Z_Pt_"+skimFilePrefix]->Fill(p.dilep_p4.Pt(),weight);
	  }
	}
	mu.clear();
	nleps = 1;
      }
      if(currentrun!=c.evt_run) { cout << "This is run " << c.evt_run << endl; currentrun = c.evt_run; }
      bool skip = false;
      //if(c.evt_run!=251244&&c.evt_run!=251251&&c.evt_run!=251252) skip = true;
      if(abs(c.id)!=13) skip = true;
      else if(c.p4.Pt()<20.) skip = true;
      else if(fabs(c.p4.Eta())>2.1) skip = true;
      else if(!c.passes_POG_looseID) skip = true;
      //else if(fabs(c.dZ)>0.5) skip = true;
      //else if(fabs(c.dxyPV)>0.2) skip = true;
      //else if(c.miniisoDB>0.5) skip = true;
      if(!skip) { mu.push_back(c); }
      p = c;
      resetEvent(c);
    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  for(map<string,TH1F*>::iterator h=histos.begin(); h!=histos.end();++h){
    h->second->SetBinContent(h->second->GetNbinsX(), h->second->GetBinContent(h->second->GetNbinsX() )+ h->second->GetBinContent(h->second->GetNbinsX()+1) );
    h->second->SetBinError(h->second->GetNbinsX(), sqrt(pow(h->second->GetBinError(h->second->GetNbinsX() ),2)+pow(h->second->GetBinError(h->second->GetNbinsX()+1),2) ) );
  }
  for(map<string,TH1F*>::iterator h=histos.begin(); h!=histos.end();++h){
    h->second->SetBinContent(1, h->second->GetBinContent(1 )+ h->second->GetBinContent(0) );
    h->second->SetBinError(1, sqrt(pow(h->second->GetBinError(1 ),2)+pow(h->second->GetBinError(0),2) ) );
  }
  //string filename = "rootfiles/test/Histos_"+skimFilePrefix+".root";
  string filename = "rootfiles/first_20150727/Histos3_"+skimFilePrefix+".root";
  if(DCSonly) filename = "rootfiles/first_20150727/Histos3DCS_"+skimFilePrefix+".root";
  TFile *f = new TFile(filename.c_str(),"RECREATE");
  f->cd();
  for(map<string,TH1F*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;  
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 10
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  //load PUweights
  TFile *fPU = new TFile("puWeights.root","READ");
  TH1D *puWeight     = (TH1D*)fPU->Get("puWeight");
  TH1D *puWeightUp   = (TH1D*)fPU->Get("puWeightUp");
  TH1D *puWeightDown = (TH1D*)fPU->Get("puWeightDown");

  TFile *fxsec = new TFile("xsec_stop_13TeV.root","READ");
  TH1D *hxsec     = (TH1D*)fxsec->Get("stop");

  TFile *f_el_SF       = new TFile("lepsf/kinematicBinSFele.root", "read");
  TFile *f_mu_SF_id    = new TFile("lepsf/TnP_MuonID_NUM_MediumID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_iso   = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  TFile *f_mu_SF_veto_id  = new TFile("lepsf/TnP_MuonID_NUM_LooseID_DENOM_generalTracks_VAR_map_pt_eta.root", "read");
  TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoTight_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_mu_SF_veto_iso = new TFile("lepsf/TnP_MuonID_NUM_MiniIsoLoose_DENOM_LooseID_VAR_map_pt_eta.root");
  //TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns.root", "read");
  TFile *f_vetoLep_eff = new TFile("lepsf/lepeff__ttbar_powheg_pythia8_25ns__SRcuts.root", "read");  
  TH2D *h_el_SF_id_temp      = (TH2D*)f_el_SF->Get("CutBasedMedium");
  TH2D *h_el_SF_iso_temp     = (TH2D*)f_el_SF->Get("MiniIso0p1_vs_AbsEta");
  TH2D *h_el_SF_veto_id_temp  = (TH2D*)f_el_SF->Get("CutBasedVeto");
  TH2D *h_el_SF_veto_iso_temp = (TH2D*)f_el_SF->Get("MiniIso0p4_vs_AbsEta");
  TH2D *h_mu_SF_id_temp      = (TH2D*)f_mu_SF_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_iso_temp     = (TH2D*)f_mu_SF_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_id_temp  = (TH2D*)f_mu_SF_veto_id->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_tag_IsoMu20_pass");
  TH2D *h_mu_SF_veto_iso_temp = (TH2D*)f_mu_SF_veto_iso->Get("pt_abseta_PLOT_pair_probeMultiplicity_bin0_&_tag_combRelIsoPF04dBeta_bin0_&_tag_pt_bin0_&_PF_pass_&_tag_IsoMu20_pass");
  //TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_el");
  //TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_Eff_mu");
  TH2D *h_el_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_el");
  TH2D *h_mu_vetoLepEff_temp = (TH2D*)f_vetoLep_eff->Get("h2_lepEff_vetoSel_rebin_Eff_mu");
  TH2D *h_el_SF_id  = (TH2D*)h_el_SF_id_temp->Clone("h_el_SF_id");
  TH2D *h_el_SF_iso = (TH2D*)h_el_SF_iso_temp->Clone("h_el_SF_iso");
  TH2D *h_mu_SF_id  = (TH2D*)h_mu_SF_id_temp->Clone("h_mu_SF_id");
  TH2D *h_mu_SF_iso = (TH2D*)h_mu_SF_iso_temp->Clone("h_mu_SF_iso");
  TH2D *h_el_SF_veto_id  = (TH2D*)h_el_SF_veto_id_temp->Clone("h_el_SF_veto_id");
  TH2D *h_el_SF_veto_iso = (TH2D*)h_el_SF_veto_iso_temp->Clone("h_el_SF_veto_iso");
  TH2D *h_mu_SF_veto_id  = (TH2D*)h_mu_SF_veto_id_temp->Clone("h_mu_SF_veto_id");
  TH2D *h_mu_SF_veto_iso = (TH2D*)h_mu_SF_veto_iso_temp->Clone("h_mu_SF_veto_iso");
  //This is are the important ones
  TH2D *h_el_vetoLepEff = (TH2D*)h_el_vetoLepEff_temp->Clone("h_el_vetoLepEff");
  TH2D *h_mu_vetoLepEff = (TH2D*)h_mu_vetoLepEff_temp->Clone("h_mu_vetoLepEff");
  TH2D *h_el_SF = (TH2D*)h_el_SF_id->Clone("h_el_SF");
  h_el_SF->Multiply(h_el_SF_iso);
  TH2D *h_el_SF_veto = (TH2D*)h_el_SF_veto_id->Clone("h_el_SF_veto");
  TH2D *h_mu_SF = (TH2D*)h_mu_SF_id->Clone("h_mu_SF");
  h_mu_SF->Multiply(h_mu_SF_iso);
  TH2D *h_mu_SF_veto = (TH2D*)h_mu_SF_veto_id->Clone("h_mu_SF_veto");
  h_mu_SF_veto->Multiply(h_mu_SF_veto_iso);
  TFile *f_el_FS_ID       = new TFile("lepsf/sf_el_mediumCB.root", "read");
  TFile *f_el_FS_Iso      = new TFile("lepsf/sf_el_mini01.root", "read");
  TFile *f_mu_FS_ID       = new TFile("lepsf/sf_mu_mediumID.root", "read");
  TFile *f_mu_FS_Iso      = new TFile("lepsf/sf_mu_mini02.root", "read");
  TH2D *h_el_FS_ID_temp  = (TH2D*)f_el_FS_ID ->Get("histo2D");
  //TH2D *h_el_FS_ID       = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS_ID");
  TH2D *h_el_FS          = (TH2D*)h_el_FS_ID_temp ->Clone("h_el_FS");
  TH2D *h_el_FS_Iso_temp = (TH2D*)f_el_FS_Iso->Get("histo2D");
  //TH2D *h_el_FS_Iso      = (TH2D*)h_el_FS_Iso_temp->Clone("h_el_FS_Iso");
  h_el_FS->Multiply(h_el_FS_Iso_temp);
  TH2D *h_mu_FS_ID_temp  = (TH2D*)f_mu_FS_ID ->Get("histo2D");
  //TH2D *h_mu_FS_ID       = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS_ID");
  TH2D *h_mu_FS          = (TH2D*)h_mu_FS_ID_temp ->Clone("h_mu_FS");
  TH2D *h_mu_FS_Iso_temp = (TH2D*)f_mu_FS_Iso->Get("histo2D");
  //TH2D *h_mu_FS_Iso      = (TH2D*)h_mu_FS_Iso_temp->Clone("h_mu_FS_ID");
  h_mu_FS->Multiply(h_mu_FS_Iso_temp);

  
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH3D*> histos;//use D histos as weights can vary a lot among the signal
  vector<string> histonames; histonames.clear();
  //  vector<int> hbins; hbins.clear();
  //  vector<float> hlow; hlow.clear();
  //  vector<float> hup; hup.clear();

  //lumi, trigger, stats done
  histonames.push_back("SRyield");
  histonames.push_back("SR_Bup_HF");//done
  histonames.push_back("SR_Bdown_HF");
  histonames.push_back("SR_Bup_LF");//done
  histonames.push_back("SR_Bdown_LF");
  histonames.push_back("SR_JESup");
  histonames.push_back("SR_JESdown");
  histonames.push_back("SR_muRFup");
  histonames.push_back("SR_muRFdown");
  //histonames.push_back("SR_PDFup");
  //histonames.push_back("SR_PDFdown");
  histonames.push_back("SR_ISRup");//done preliminary
  histonames.push_back("SR_ISRdown");
  histonames.push_back("SR_PUup");//done preliminary
  histonames.push_back("SR_PUdown");
  histonames.push_back("SR_LepEffup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffdown");
  histonames.push_back("SR_LepEffFSup");//done - I guess we need no renormalization - no fastsim in, no vetoSF
  histonames.push_back("SR_LepEffFSdown");
  histonames.push_back("SR_Xsecup");//done
  histonames.push_back("SR_Xsecdown");
  histonames.push_back("CR1l_sigcontamination");//scaled to signalreg yield
  histonames.push_back("CR2l_sigcontamination");//scaled to signalreg yield
  /*
  histonames.push_back("eventsum");
  histonames.push_back("rawweightsum");
  histonames.push_back("totweightsum");
  histonames.push_back("ISRsum");
  histonames.push_back("BSFsum");
  histonames.push_back("PUweightsum");
  histonames.push_back("xsecsum");
  histonames.push_back("nevtsum");
  histonames.push_back("lepsum");
  histonames.push_back("lepSFsum");
  */
  for(unsigned int i = 0; i<histonames.size(); ++i){
    string mapname = histonames[i];
    if(histos.count(mapname) == 0 ) histos[mapname] = new TH3D(mapname.c_str(), "", 37,99,1024, 19,-1,474, 13, -0.5,12.5);
    //mStop 100-1000, mLSP 0-450, SR 1-12, 9200 bins, SR 0 is non-SR - in case it it needed!!
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
    }

  
  
  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  //get the reweighting histograms
  TIter fileIterFirst(listOfFiles);
  TFile *currentFileFirst = 0;
  TH3D* counterhistSig;
  TH2F* histNEvts;
  bool thisisfirst = true;
  // File Loop for adding correct histograms
  while ( (currentFileFirst = (TFile*)fileIterFirst.Next()) ) {
    TFile *file = new TFile( currentFileFirst->GetTitle() );
    file->cd();
    if(thisisfirst){
      counterhistSig = (TH3D*)file->Get("h_counterSMS");
      counterhistSig->SetDirectory(0); 
      histNEvts = (TH2F*)file->Get("histNEvts");
      histNEvts->SetDirectory(0);
      thisisfirst = false;
    } else {
      TH3D *tempcounterhistSig = (TH3D*)file->Get("h_counterSMS");
      tempcounterhistSig->SetDirectory(0); 
      TH2F *temphistNEvts = (TH2F*)file->Get("histNEvts");
      temphistNEvts->SetDirectory(0);
      counterhistSig->Add(tempcounterhistSig);
      histNEvts->Add(temphistNEvts);
      tempcounterhistSig->Delete();
      temphistNEvts->Delete();
    }
    file->Close();
    delete file;
  }

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );

      // Analysis Code

      float mStop = mass_stop();
      float mLSP = mass_lsp();
      float mCharg = mass_chargino();
      //float xVal = mass_lsp();
      int Nevts = histNEvts->GetBinContent(histNEvts->FindBin(mStop,mLSP));
      double nevts = double(Nevts);
      //float weight = cms3.scale1fb()*2.11;
      double PUweight     = puWeight    ->GetBinContent(puWeight    ->FindBin(pu_ntrue() ) );
      double PUweightUp   = puWeightUp  ->GetBinContent(puWeightUp  ->FindBin(pu_ntrue() ) );
      double PUweightDown = puWeightDown->GetBinContent(puWeightDown->FindBin(pu_ntrue() ) );
      PUweightUp = 1; PUweightDown = PUweight; PUweight = 1; //now PU syst is applying vs not applying
     double ISRnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,19));
      double ISRnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,20));
      double ISRnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,21));
      double ISRweight = weight_ISR();
      double BSFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,14));
      double BSFnormHup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,15));
      double BSFnormLup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,16));
      double BSFnormHdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,17));
      double BSFnormLdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,18));
      double BSFweight = weight_btagsf();
      double muRFnorm = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,1));
      double muRFnormup = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,5));
      double muRFnormdown = counterhistSig->GetBinContent(counterhistSig->FindBin(mStop,mLSP,9));
      if(ISRnorm>0) ISRweight*=nevts/ISRnorm;
      if(ISRnorm<=0||ISRnormup<=0||ISRnormdown<=0){ ISRnormdown=1.; ISRnormup=1.; ISRnorm=1.;}
      if(ISRweight!=weight_ISR()) cout << "ISRw " << ISRweight << " wISR " << weight_ISR() << " nevts " << nevts << " ISRn " << ISRnorm << endl;
      if(BSFnorm>0) BSFweight *=nevts/BSFnorm;
      if(BSFnorm<=0||BSFnormHup<=0||BSFnormLup<=0||BSFnormHdown<=0||BSFnormLdown<=0){
	BSFnorm=1; BSFnormHup=1; BSFnormLup=1; BSFnormHdown=1; BSFnormLdown=1;
      }
      if(muRFnorm<=0||muRFnormup<=0||muRFnormdown<=0){ muRFnormdown=1; muRFnormup=1; muRFnorm=1; }
      //lepSF is done below
      double xsection = hxsec->GetBinContent(hxsec->FindBin(mStop));
      double xsectionerr = hxsec->GetBinError(hxsec->FindBin(mStop));
      //double rawweight = xsec()*2260./nevts;
      //double weight = xsec()*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      double rawweight = xsection*2260./nevts;
      double weight = xsection*2260./nevts*PUweight*ISRweight*BSFweight;//xsec given in pb
      //did put ISRweight which should be ==1
      if(ISRweight!=1) cout << "ISRw " << ISRweight << endl;
      if(event==0) cout << "weight " << weight << " nEvents " << nEventsTree << " filename " << currentFile->GetTitle() << endl;

      int NSLeps = 0;
      int NAddVetoLeps = 0;
      if(lep1_is_mu()){
	if(lep1_pt()>20&&fabs(lep1_eta())<2.4) {++NSLeps;}
      } else if (lep1_is_el()){
	if(lep1_pt()>20&&fabs(lep1_eta())<1.4442) {++NSLeps; }
      } if(lep2_is_mu()){
	if(lep2_pt()>20&&fabs(lep2_eta())<2.4) {++NSLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>20&&fabs(lep2_eta())<1.4442) {++NSLeps; }
      }
      if(lep2_is_mu()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps;}
      } else if (lep2_is_el()){
	if(lep2_pt()>10&&fabs(lep2_eta())<2.4) {++NAddVetoLeps; }
      }
      if(NSLeps<1) continue;//temp
      float lepSF_pt_cutoff = 100.0;
      float lepSF_pt_min    = 10.0;
      double lepSF    = 1.0;
      double lepSF_Up = 1.0;
      double lepSF_Dn = 1.0;
      float lepSF_FS_pt_cutoff = 200.0;
      double lepSF_FS    = 1.0;
      double lepSF_FS_Up = 1.0;
      double lepSF_FS_Dn = 1.0;	
      if(lep1_is_el()){
	int binX = h_el_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_el_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_el_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_el_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_el_SF->GetBinError( binX, binY );
	int bin = h_el_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_el_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_el_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_el_FS->GetBinError(bin);
      }
      if(lep1_is_mu()){
	int binX = h_mu_SF->GetXaxis()->FindBin( std::min(lepSF_pt_cutoff, (float)lep1_p4().Pt()) );
	int binY = h_mu_SF->GetYaxis()->FindBin( fabs(lep1_p4().Eta()) );
	lepSF    = h_mu_SF->GetBinContent( binX, binY );
	lepSF_Up = lepSF + h_mu_SF->GetBinError( binX, binY );
	lepSF_Dn = lepSF - h_mu_SF->GetBinError( binX, binY );
	int bin = h_mu_FS->FindBin(  std::min(lepSF_FS_pt_cutoff, (float)lep1_p4().Pt()), fabs(lep1_p4().Eta()) );
	lepSF_FS = h_mu_FS->GetBinContent(bin);
	lepSF_FS_Up = lepSF_FS + h_mu_FS->GetBinError(bin);
	lepSF_FS_Dn = lepSF_FS + h_mu_FS->GetBinError(bin);
      }
      weight *= (lepSF*lepSF_FS);

      
      if(nvtxs()<0)               continue;
      if(ngoodleps()<1)           continue;//accomodate 2l-CR
      if(nvetoleps()<1)           continue;//accomodate 2l-CR
    //if(!PassTrackVeto_v3())     continue;//accomodate 2l-CR
    //if(!PassTauVeto())          continue;//accomodate 2l-CR
      if(ngoodjets()<2)           continue;
      if(ngoodbtags()<0)          continue;//accomodate 1l-CR
      if(pfmet()<250)             continue;
      if(mt_met_lep()<150)        continue;
      if(mindphi_met_j1_j2()<0.8) continue;


      int SR = -1;
      int compressedSR = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()>=1){//basis for SR 1l, >=1b
	if(ngoodjets()>=4){
	  if(MT2W()<=200){
	    if(pfmet()>325) SR = 2;
	    else SR = 1;
	  } else { //high MT2W
	    if(pfmet()>450) SR = 5;
	    else if(pfmet()>350) SR = 4;
	    else SR = 3;
	  }
	} else if(ngoodjets()==3 && MT2W()>200 && pfmet()>350) {
	  SR = 6;
	} else if(MT2W()>200&&topnessMod()>(-3)) { //2 or 3 jets
	  if(ngoodbtags()==1){
	    if(pfmet()>400) SR = 8;
	    else SR = 7;
	  } else {//ge2 jets
	    if(pfmet()>400) SR = 10;
	    else SR = 9;
	  }
	}
	//compressed region (jets are sorted by pt
	if(ngoodjets()>=5&&ak4pfjets_passMEDbtag()[0]==false&&ak4pfjets_pt()[0]>200.){
	  if(MT2W()<=200) compressedSR = 11;
	  else compressedSR = 12;
	}
      }

      //CR-1l
      int CR1l = -1;
      if(ngoodleps()==1&&nvetoleps()==1&&PassTrackVeto_v3()&&PassTauVeto()&&ngoodbtags()==0&&ngoodjets()>=3&&MT2W()>200){
	if(ngoodjets()==3){
	  CR1l = 1;
	} else {
	  CR1l = 2;
	}
      }
      //CR1l  1 --> SR  6
      //CR1l  2 --> SR  3-5
      float CR1l_1_6 = 0.37*0.18;
      float CR1l_2_3 = 0.55*0.15;
      float CR1l_2_4 = 0.25*0.29;
      float CR1l_2_5 = 0.20*0.40;

      //CR2l = -1;
      int lepind = -1;
      if(ngoodleps()>=2&&NSLeps==2) lepind = 5;
      else if(ngoodleps()==2&&NSLeps==2) lepind = 4;//exactly two leptons,CR4
      else if(ngoodleps()==1&&NSLeps==1&&NAddVetoLeps>=1) lepind = 3;//one lepton, but more than 1 add. loose,1l,>2l
      //else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==2) lepind = 2;//one lepton + 1 add. loose,CR5
      else if(ngoodleps()==1&&NSLeps==1&&nvetoleps()==0&&(!PassTrackVeto_v3()||!PassTauVeto())) lepind = 1;//exactly one lepton, but do not pass track/tau veto - i.e. one additional track or tau, CR6
      int CR2l = -1;
      if((lepind==4||lepind==3||lepind==1)&&ngoodjets()>=3&&ngoodbtags()>=1){
	if(MT2W()<=200) CR2l = 1;
	else CR2l = 2;
      }
      float CR2l_1_1 = 0.61*0.48;
      float CR2l_1_2 = 0.61*0.19;
      float CR2l_2_3 = 0.44*0.39;
      float CR2l_2_4 = 0.44*0.11;
      float CR2l_2_5 = 0.44*0.07;
      float CR2l_2_6 = 0.44*0.11;

      if(SR==(-1)&&CR1l==(-1)&&CR2l==(-1)&&compressedSR==(-1)) continue;
      //implement some sanity checks
      if(CR1l!=(-1)&&CR2l!=(-1)) cout << "WTF CR1l " << CR1l << " CR2l " << CR2l << endl;
      if(SR!=(-1)&&CR1l!=(-1)) cout << "WTF SR " << SR << " CR1l " << CR1l << endl;
      if(SR!=(-1)&&CR2l!=(-1)) cout << "WTF SR " << SR << " CR2l " << CR2l << endl;

      //ISR reweighting, get stop pair using last copy:
      double ISRup = weight_ISRup()/weight_ISR()*ISRnorm/ISRnormup;
      double ISRdown = weight_ISRdown()/weight_ISR()*ISRnorm/ISRnormdown;
      //double XSup = (xsec()+xsec_uncert())/xsec();
      //double XSdown = (xsec()-xsec_uncert())/xsec();
      double XSup = (xsection+xsectionerr)/xsection;
      double XSdown = (xsection-xsectionerr)/xsection;
      double PUup = PUweightUp/PUweight;
      double PUdown = PUweightDown/PUweight;
      double lEffup = lepSF_Up/lepSF;
      double lEffdown = lepSF_Dn/lepSF;
      double lEffFSup = lepSF_FS_Up/lepSF_FS;
      double lEffFSdown = lepSF_FS_Dn/lepSF_FS;
      double BSFHup = weight_btagsf_heavy_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLup = weight_btagsf_light_UP()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFHdown = weight_btagsf_heavy_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double BSFLdown = weight_btagsf_light_DN()/weight_btagsf()*BSFnorm/BSFnormHup;
      double muRFup = genweights().at(4)/genweights().at(0)*muRFnorm/muRFnormup;
      double muRFdown = genweights().at(8)/genweights().at(0)*muRFnorm/muRFnormdown;
      //cout << genweights().at(0) << " " << genweights().at(4) << " " << genweights().at(8) << " " << mStop << " " << mLSP << endl;

      if(CR1l>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(ngoodbtags()>=1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 0b control region, do correlations later during datacard making
	if(CR1l==1){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR1l_1_6);
	} else if(CR1l==2){
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR1l_2_3);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR1l_2_4);
	  histos["CR1l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR1l_2_5);
	}
      } else if(CR2l>0){
	if(nvetoleps()<=1||(nvetoleps()==1&&(!PassTrackVeto_v3()||!PassTauVeto()))) cout << __LINE__ << " " << nvetoleps() << " " << PassTrackVeto_v3() << " " << PassTauVeto() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	//signal contamination in 2l control region, do correlations later during datacard making
	if(CR2l==1){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,1,weight*CR2l_1_1);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,2,weight*CR2l_1_2);
	} else if(CR2l==2){
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,3,weight*CR2l_2_3);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,4,weight*CR2l_2_4);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,5,weight*CR2l_2_5);
	  histos["CR2l_sigcontamination"]->Fill(mStop,mLSP,6,weight*CR2l_2_6);

	}
      } else if(SR>0){
	if(ngoodleps()!=1) cout << __LINE__ << " " << ngoodleps() << endl;
	if(NSLeps!=1) cout << __LINE__ << " " << NSLeps << endl;
	if(nvetoleps()!=1) cout << __LINE__ << " " << nvetoleps() << endl;
	if(!PassTrackVeto_v3())  cout << __LINE__ << endl;
	if(!PassTauVeto())  cout << __LINE__ << endl;
	if(SR<=6&&ngoodjets()<3) cout << __LINE__ << " " << ngoodjets() << endl;
	if(ngoodbtags()<1) cout << __LINE__ << " " << ngoodbtags() << endl;
	/*
	histos["eventsum"]->Fill(mStop,mLSP,SR,1.);
	histos["rawweightsum"]->Fill(mStop,mLSP,SR,rawweight);
	histos["totweightsum"]->Fill(mStop,mLSP,SR,weight);
	histos["ISRsum"]->Fill(mStop,mLSP,SR,ISRweight);
	histos["BSFsum"]->Fill(mStop,mLSP,SR,BSFweight);
	histos["PUweightsum"]->Fill(mStop,mLSP,SR,PUweight);
	histos["xsecsum"]->Fill(mStop,mLSP,SR,xsection);
	histos["nevtsum"]->Fill(mStop,mLSP,SR,nevts);
	histos["lepsum"]->Fill(mStop,mLSP,SR,lepSF);
	histos["lepSFsum"]->Fill(mStop,mLSP,SR,lepSF_FS);
	*/
	//finally - do signal regions!
	histos["SRyield"]->Fill(mStop,mLSP,SR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,SR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,SR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,SR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,SR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,SR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,SR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,SR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,SR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,SR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,SR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,SR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,SR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,SR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,SR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,SR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,SR,weight*muRFdown);
      }
      if(compressedSR>0){
	if(compressedSR<=6) cout << __LINE__ << " " << compressedSR << endl;
	//compressedSR is defined to not overlap with SR - can use same histogram!
	histos["SRyield"]->Fill(mStop,mLSP,compressedSR,weight);
	histos["SR_ISRup"]->Fill(mStop,mLSP,compressedSR,weight*ISRup);
	histos["SR_ISRdown"]->Fill(mStop,mLSP,compressedSR,weight*ISRdown);
	histos["SR_Xsecup"]->Fill(mStop,mLSP,compressedSR,weight*XSup);
	histos["SR_Xsecdown"]->Fill(mStop,mLSP,compressedSR,weight*XSdown);
	histos["SR_PUup"]->Fill(mStop,mLSP,compressedSR,weight*PUup);
	histos["SR_PUdown"]->Fill(mStop,mLSP,compressedSR,weight*PUdown);
	histos["SR_Bup_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHup);
	histos["SR_Bup_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLup);
	histos["SR_Bdown_HF"]->Fill(mStop,mLSP,compressedSR,weight*BSFHdown);
	histos["SR_Bdown_LF"]->Fill(mStop,mLSP,compressedSR,weight*BSFLdown);
	histos["SR_LepEffup"]->Fill(mStop,mLSP,compressedSR,weight*lEffup);
	histos["SR_LepEffdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffdown);
	histos["SR_LepEffFSup"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSup);
	histos["SR_LepEffFSdown"]->Fill(mStop,mLSP,compressedSR,weight*lEffFSdown);
	histos["SR_muRFup"]->Fill(mStop,mLSP,compressedSR,weight*muRFup);
	histos["SR_muRFdown"]->Fill(mStop,mLSP,compressedSR,weight*muRFdown);
      }

    }//event loop
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }//file loop
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }
  
  // Example Histograms
  // samplehisto->Draw();

  /*
  for(map<string,TH3D*>::iterator h=histos.begin(); h!=histos.end();++h){
    //add overflow
    //h->second->SetBinContent(h->second->GetNbinsX(), h->second->GetBinContent(h->second->GetNbinsX() )+ h->second->GetBinContent(h->second->GetNbinsX()+1) );
    //h->second->SetBinError(h->second->GetNbinsX(), sqrt(pow(h->second->GetBinError(h->second->GetNbinsX() ),2)+pow(h->second->GetBinError(h->second->GetNbinsX()+1),2) ) );
    //add underfloe
    //h->second->SetBinContent(1, h->second->GetBinContent(1)+ h->second->GetBinContent(0) );
    //h->second->SetBinError(1, sqrt(pow(h->second->GetBinError(1),2)+pow(h->second->GetBinError(0),2) ) );
  }
  */
  string filename = "rootfiles/signalyields/Histos_"+skimFilePrefix+".root";
  TFile *f = new TFile(filename.c_str(),"RECREATE");
  f->cd();
  for(map<string,TH3D*>::iterator h=    histos.begin(); h!=    histos.end();++h) h->second->Write();
  f->Close();
  cout << "Saved histos in " << f->GetName() << endl;

  f_el_SF->Close();
  f_mu_SF_id->Close();
  f_mu_SF_iso->Close();
  f_mu_SF_veto_id->Close();
  f_mu_SF_veto_iso->Close();
  f_vetoLep_eff->Close();
  f_el_FS_ID->Close();
  f_el_FS_Iso->Close();
  f_mu_FS_ID->Close();
  f_mu_FS_Iso->Close();
  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  delete fPU;//delete PU file
  delete f_el_SF;
  delete f_mu_SF_id;
  delete f_mu_SF_iso;
  delete f_mu_SF_veto_id;
  delete f_mu_SF_veto_iso;
  delete f_vetoLep_eff;
  delete f_el_FS_ID;
  delete f_el_FS_Iso;
  delete f_mu_FS_ID;
  delete f_mu_FS_Iso;
  return 0;
}
Exemplo n.º 11
0
//
// Functions
//
int looper( sampleInfo::ID sampleID, std::vector<analyzer*> analyzers, int nEvents, bool readFast ) {


  //
  // Intro
  //
  cout << "====================================================" << endl;
  cout << endl;
  cout << "  WELCOME TO STOP BABY ANALYZER! " << endl;
  cout << endl;
  cout << "====================================================" << endl;
  cout << endl;


  //
  // Benchmark
  //
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");
  

  //
  // Input SampleInfo
  //
  sampleInfo::sampleUtil sample( sampleID );

  bool sampleIsTTbar = false;
  if( sample.id == sampleInfo::k_ttbar_powheg_pythia8 ||
      sample.id == sampleInfo::k_ttbar_powheg_pythia8_ext4 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromT_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_singleLeptFromTbar_madgraph_pythia8_ext1 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8 ||
      sample.id == sampleInfo::k_ttbar_diLept_madgraph_pythia8_ext1 ) {
    sampleIsTTbar = true;
  }
  
  //
  // Input chain
  //
  TChain *chain = new TChain("t");
  
  cout << "    Processing the following: " << endl;  
  for(int iFile=0; iFile<(int)sample.inputBabies.size(); iFile++) {
    
    // input directory
    string input = sample.baby_i_o.first;
      
    // input file
    input += sample.inputBabies[iFile];
      
    chain->Add( input.c_str() );
    cout << "      " << input << endl; 
  }
  cout << endl;
  
  
  //
  // Output File
  //

  // output dir
  string f_output_name = "";
  f_output_name += sample.baby_i_o.second;

  // output name
  f_output_name += sample.label;
  f_output_name += ".root";

  // output file
  TFile *f_output = new TFile( f_output_name.c_str(), "recreate" );

  // print output location
  cout << "    Output Written to: " << endl;
  cout << "      " << f_output_name << endl;
  cout << endl;


  //
  // JSON File Tools
  //
  const char* json_file = "../StopCORE/inputs/json_files/Cert_271036-284044_13TeV_23Sep2016ReReco_Collisions16_JSON.txt"; // 35.876fb final 2016 run
  if( sample.isData ) set_goodrun_file_json(json_file);
  

  //
  // Event Weight Utilities
  //
  cout << "    Loading eventWeight Utilities..." << endl << endl;
  wgtInfo.setUp( sample.id, useBTagSFs_fromFiles_, useLepSFs_fromFiles_, add2ndLepToMet_ );  
  wgtInfo.apply_cr2lTrigger_sf  = (apply_cr2lTrigger_sf_ && add2ndLepToMet_);
  wgtInfo.apply_bTag_sf         = apply_bTag_sf_;
  wgtInfo.apply_lep_sf          = apply_lep_sf_;
  wgtInfo.apply_vetoLep_sf      = apply_vetoLep_sf_;
  wgtInfo.apply_tau_sf          = apply_tau_sf_;
  wgtInfo.apply_lepFS_sf        = apply_lepFS_sf_;
  wgtInfo.apply_topPt_sf        = apply_topPt_sf_;
  wgtInfo.apply_metRes_sf       = apply_metRes_sf_;
  wgtInfo.apply_metTTbar_sf     = apply_metTTbar_sf_;
  wgtInfo.apply_ttbarSysPt_sf   = apply_ttbarSysPt_sf_;
  wgtInfo.apply_ISR_sf          = apply_ISR_sf_;
  wgtInfo.apply_pu_sf           = apply_pu_sf_;
  wgtInfo.apply_sample_sf       = apply_sample_sf_;


  //
  // Declare genClassification list
  //
  cout << "    Loading genClassyList: ";
  std::vector< genClassyInfo::Util > genClassyList;
  if( sample.isData ) {
    genClassyList.push_back(genClassyInfo::Util(genClassyInfo::k_incl));
  }
  else{
    for(int iGenClassy=0; iGenClassy<genClassyInfo::k_nGenClassy; iGenClassy++) {
      genClassyList.push_back( genClassyInfo::Util(genClassyInfo::ID(iGenClassy)) );
    }
  }
  const int nGenClassy=(int)genClassyList.size();
  cout << nGenClassy << " genClassifications" << endl << endl;

  
  //
  // Declare Systematics
  //
  cout << "    Loading systematicList: ";
  std::vector< sysInfo::Util > systematicList;
  if( sample.isData || analyzeFast_ ) {
    systematicList.push_back(sysInfo::Util(sysInfo::k_nominal));
  }
  else{
    for(int iSys=0; iSys<sysInfo::k_nSys; iSys++) {
      systematicList.push_back( sysInfo::Util(sysInfo::ID(iSys)) );
    }
  }  
  const int nSystematics = (int)systematicList.size();
  cout << nSystematics << " systematics" << endl << endl;


	// Count number of analyzers in the list
	const int nAnalyzers = analyzers.size();



  ////////////////////////
  //                    //
  // Declare Histograms //
  //                    //
  ////////////////////////
  //
  //
  //  For Using DownStream Scripts, please adhere to the conventions:
  //
  //
  //    histogram_name = "your_name_here"+"__"+regionList[i]+"__genClassy_"+genClassyObject.label+"__systematic_"+sysInfoObject.label;
  //
  //
  //  Where regionList is the list of "SR", "CR0b", "CR0b_tightBTagHighMlb" or "CR2l"
  //
  //    And systematicList[0] is the nominal selection
  //
  //    And if there is andditional selection involved in this histogram, please refer to it in "you name here"
  //

  cout << "    Preparing histograms" << endl << endl;


	//
	// Declare yield histograms
	//
  f_output->cd(); // All yield histos will belong to the output file
	for( analyzer* thisAnalyzer : analyzers ) {

		TH1D* h_template = thisAnalyzer->GetYieldTemplate();
		TH3D* h_template_signal = thisAnalyzer->GetYieldTemplateSignal();

		for( int iClassy=0; iClassy<nGenClassy; iClassy++ ) {
			for( int iSys=0; iSys<nSystematics; iSys++ ) {

				int histIndex = iClassy*nSystematics + iSys;

				// Gen and Systematic String
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += thisAnalyzer->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iClassy].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[iSys].label;

				TH1* h_tmp = 0;

				TString yieldname = "h_yields";
				yieldname += reg_gen_sys_name;
				if( sample.isSignalScan ) h_tmp = (TH3D*)h_template_signal->Clone( yieldname );
				else                      h_tmp = (TH1D*)h_template->Clone( yieldname );
				thisAnalyzer->SetYieldHistogram( histIndex, h_tmp );

			} // End loop over systematics
		} // End loop over genClassys
	} // End loop over analyzers

  
  
  

  //
  // Declare non-yield histograms
  //

  int nMassPts = 1;
  if( sample.isSignalScan ) nMassPts = (int)sample.massPtList.size();

  const int nHistosVars = nAnalyzers*nGenClassy*nMassPts;

  // nJets
  TH1D *h_nJets[nHistosVars];
  
  // nBTags
  TH1D *h_nBTags[nHistosVars];
  
  // lep1 pT
  TH1D *h_lep1Pt_incl[nHistosVars];
  
  // lep2 pT
  TH1D *h_lep2Pt_incl[nHistosVars];
  
  // jet pT
  TH1D *h_jetPt_incl[nHistosVars];
  
  // jet1 pT
  TH1D *h_jet1Pt_incl[nHistosVars];
  
  // jet2 pT
  TH1D *h_jet2Pt_incl[nHistosVars];
  
  // DeepCSV jet1 pT
  TH1D *h_deepcsvJet1Pt_incl[nHistosVars];
  
  // DeepCSV jet2 pT
  TH1D *h_deepcsvJet2Pt_incl[nHistosVars];
  
  // met
  TH1D *h_met_incl[nHistosVars];
  TH1D *h_met_lt4j[nHistosVars];
  TH1D *h_met_ge4j[nHistosVars];

  // lep1lep2bbMetPt
  TH1D *h_lep1lep2bbMetPt_incl[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_lt4j[nHistosVars];
  TH1D *h_lep1lep2bbMetPt_ge4j[nHistosVars];

  // mt
  TH1D *h_mt_incl[nHistosVars];
  
  // modTopness
  TH1D *h_modTopness_incl[nHistosVars];
  TH1D *h_modTopness_lt4j[nHistosVars];
  TH1D *h_modTopness_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_incl[nHistosVars];
  TH1D *h_mlb_lt4j[nHistosVars];
  TH1D *h_mlb_ge4j[nHistosVars];

  // mlb
  TH1D *h_mlb_lt0modTopness[nHistosVars];
  TH1D *h_mlb_ge0modTopness[nHistosVars];
  TH1D *h_mlb_ge10modTopness[nHistosVars];
  
  // mlb, met sideband CR
  TH1D *h_mlb_150to250met_incl[nHistosVars];
  TH1D *h_mlb_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_150to250met_ge4j[nHistosVars];

  // ml2b
  TH1D *h_mlb_lep2_incl[nHistosVars];
  TH1D *h_mlb_lep2_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_ge4j[nHistosVars];
  
  // ml2b
  TH1D *h_mlb_lep2_150to250met_incl[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_lt4j[nHistosVars];
  TH1D *h_mlb_lep2_150to250met_ge4j[nHistosVars];

  // Gen ttbar system pT
  TH1D *h_gen_ttbarPt_incl[nHistosVars];
  TH1D *h_gen_ttbarPt_lt4j[nHistosVars];
  TH1D *h_gen_ttbarPt_ge4j[nHistosVars];

  // Gen 2nd lepton ID
  TH1D *h_gen_lep2_id_incl[nHistosVars];
  TH1D *h_gen_lep2_id_lt4j[nHistosVars];
  TH1D *h_gen_lep2_id_ge4j[nHistosVars];

  f_output->cd(); // All non-yield histos will belong to the output file
  
  for(int iReg=0; iReg<nAnalyzers; iReg++) {
    for(int iGen=0; iGen<nGenClassy; iGen++) {
      for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

				// Histo Index
				int iHisto = iReg*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

				int mStop = 0;
				int mLSP  = 0;
				if(sample.isSignalScan) {
					mStop = sample.massPtList[iMassPt].first;
					mLSP  = sample.massPtList[iMassPt].second;
				}

				TString hName = "";
	
				TString reg_gen_sys_name = "__";
				reg_gen_sys_name += analyzers.at(iReg)->GetLabel();
				reg_gen_sys_name += "__genClassy_";
				reg_gen_sys_name += genClassyList[iGen].label;
				reg_gen_sys_name += "__systematic_";
				reg_gen_sys_name += systematicList[0].label;
				if( sample.isSignalScan ) {
					reg_gen_sys_name += "__mStop_";
					reg_gen_sys_name += mStop;
					reg_gen_sys_name += "__mLSP_";
					reg_gen_sys_name += mLSP;
				}

      
				//
				// Njets
				//
				hName = "h_nJets" + reg_gen_sys_name;
				h_nJets[iHisto] = new TH1D( hName, "Number of Selected Jets;nJets", 11, -0.5, 10.5);

				//
				// nBTags
				//
				hName = "h_nBTags" + reg_gen_sys_name;
				h_nBTags[iHisto] = new TH1D( hName, "Number of b-Tagged Jets;nBTags", 5, -0.5, 4.5);


				//
				// lep1Pt
				//

				// Incl Selection
				hName = "h_lep1Pt__inclSelection" + reg_gen_sys_name;
				h_lep1Pt_incl[iHisto] = new TH1D( hName, "Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
	

				//
				// lep2Pt
				//

				// Incl Selection
				hName = "h_lep2Pt__inclSelection" + reg_gen_sys_name;
				h_lep2Pt_incl[iHisto] = new TH1D( hName, "Trailing Lepton p_{T};p_{T} [GeV]", 20.0, 0.0, 200.0 );
      
				//
				// jetPt
				//

				// Incl Selection
				hName = "h_jetPt__inclSelection" + reg_gen_sys_name;
				h_jetPt_incl[iHisto] = new TH1D( hName, "Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				//
				// jet1Pt
				//

				// Incl Selection
				hName = "h_jet1Pt__inclSelection" + reg_gen_sys_name;
				h_jet1Pt_incl[iHisto] = new TH1D( hName, "Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
	

				//
				// jet2Pt
				//

				// Incl Selection
				hName = "h_jet2Pt__inclSelection" + reg_gen_sys_name;
				h_jet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// DeepCSVJet1Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet1Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet1Pt_incl[iHisto] = new TH1D( hName, "Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// DeepCSVJet2Pt
				//

				// Incl Selection
				hName = "h_deepcsvJet2Pt__inclSelection" + reg_gen_sys_name;
				h_deepcsvJet2Pt_incl[iHisto] = new TH1D( hName, "2nd Leading DeepCSV Jet p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
      
	

				//
				// met
				//

				// Incl Selection
				hName = "h_met__inclSelection" + reg_gen_sys_name;
				h_met_incl[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );
      
				// <4j Selection
				hName = "h_met__lt4jSelection" + reg_gen_sys_name;
				h_met_lt4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );

				// >=4j Selection
				hName = "h_met__ge4jSelection" + reg_gen_sys_name;
				h_met_ge4j[iHisto] = new TH1D( hName, "MET;MET [GeV]", 32, 0.0, 800.0 );


	

				//
				// lep1lep2bbMetPt
				//

				// Incl Selection
				hName = "h_lep1lep2bbMetPt__inclSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_incl[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
				// <4j Selection
				hName = "h_lep1lep2bbMetPt__lt4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_lt4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_lep1lep2bbMetPt__ge4jSelection" + reg_gen_sys_name;
				h_lep1lep2bbMetPt_ge4j[iHisto] = new TH1D( hName, "lep1(lep2)bbMet system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );


				//
				// mt
				//

				// Incl Selection
				hName = "h_mt__inclSelection" + reg_gen_sys_name;
				h_mt_incl[iHisto] = new TH1D( hName, "M_{T};M_{T} [GeV]", 24, 0.0, 600.0 );
      
	
				//
				// modTopness
				//

				// Incl Selection
				hName = "h_modTopness__inclSelection" + reg_gen_sys_name;
				h_modTopness_incl[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );
      
				// <4j Selection
				hName = "h_modTopness__lt4jSelection" + reg_gen_sys_name;
				h_modTopness_lt4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

				// >=4j Selection
				hName = "h_modTopness__ge4jSelection" + reg_gen_sys_name;
				h_modTopness_ge4j[iHisto] = new TH1D( hName, "Modified Topness;Modified Topness", 20, -20.0, 20.0 );

      
				//
				// mlb
				//

				// Incl Selection
				hName = "h_mlb__inclSelection" + reg_gen_sys_name;
				h_mlb_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb__ge4jSelection" + reg_gen_sys_name;
				h_mlb_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

      

				//
				// mlb, inclusive nJets, modTopness bins
				//

				// <0 modTopness Selection
				hName = "h_mlb__lt0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_lt0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=0 modTopness Selection
				hName = "h_mlb__ge0modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge0modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// >=10 modTopness Selection
				hName = "h_mlb__ge10modTopnessSelection" + reg_gen_sys_name;
				h_mlb_ge10modTopness[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb, met sideband CR
				//

				// Incl Selection
				hName = "h_mlb_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_150to250met_incl[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{lb};M_{lb} [GeV]", 24, 0.0, 600.0 );


				//
				// mlb_lep2
				//

				// Incl Selection
				hName = "h_mlb_lep2__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



				//
				// mlb_lep2, met CR sideband
				//

				// Incl Selection
				hName = "h_mlb_lep2_150to250met__inclSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_incl[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );
      
				// <4j Selection
				hName = "h_mlb_lep2_150to250met__lt4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_lt4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );

				// >=4j Selection
				hName = "h_mlb_lep2_150to250met__ge4jSelection" + reg_gen_sys_name;
				h_mlb_lep2_150to250met_ge4j[iHisto] = new TH1D( hName, "M_{l2b};M_{l2b} [GeV]", 24, 0.0, 600.0 );



	

				//
				// Gen ttbar pT
				//
				if( !sample.isData ) {
    
					// Incl Selection
					hName = "h_gen_ttbarPt__inclSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_incl[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );
	
					// <4j Selection
					hName = "h_gen_ttbarPt__lt4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_lt4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );

					// >=4j Selection
					hName = "h_gen_ttbarPt__ge4jSelection" + reg_gen_sys_name;
					h_gen_ttbarPt_ge4j[iHisto] = new TH1D( hName, "Gen t#bar{t} system p_{T};p_{T} [GeV]", 24, 0.0, 600.0 );



					//
					// Gen Lep2 ID
					//
      
					// Incl Selection
					hName = "h_gen_lep2_id__inclSelection" + reg_gen_sys_name;
					h_gen_lep2_id_incl[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_incl[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");
	
					// <4j Selection
					hName = "h_gen_lep2_id__lt4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_lt4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_lt4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

					// >=4j Selection
					hName = "h_gen_lep2_id__ge4jSelection" + reg_gen_sys_name;
					h_gen_lep2_id_ge4j[iHisto] = new TH1D( hName, "Gen 2nd Lepton ID;ID", 7, 1.0, 8.0 );
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(1, "ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(2, "mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(3, "lep tau, ele");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(4, "lep tau, mu");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(5, "had tau, 1 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(6, "had tau, 3 prong");
					h_gen_lep2_id_ge4j[iHisto]->GetXaxis()->SetBinLabel(7, "\"other\" tau");

	
				} // end if sample is ttbar
      

      } // end loop over mass pts (1 pt only if not signal scan)
    } // end loop over genClassifications for histogram arrays
  } // end loop over analyzers/regions for histogram arrays


	// Set up cutflow histograms
	TH1D* h_cutflow[nAnalyzers];
	for( int iAna=0; iAna<nAnalyzers; iAna++ ) {

		analyzer* thisAnalyzer = analyzers.at(iAna);
		std::string histName  = "h_cutflow_";
		std::string histTitle = "Cutflow histogram ";
		histName  += thisAnalyzer->GetLabel();
		histTitle += thisAnalyzer->GetLabel();

		h_cutflow[iAna] = selectionInfo::get_cutflowHistoTemplate( thisAnalyzer->GetSelections(), histName, histTitle );
	}


  //////////////////////
  //                  //
  // Loop Over Events //
  //                  //
  //////////////////////
    
  // Event Counters
  cout << "    Loading files to loop over" << endl << endl;
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  
  // Grab list of files
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;
  while ( (currentFile = (TFile*)fileIter.Next()) ) {
    
    
    //////////////////////
    //                  //
    // Get File Content //
    //                  //
    //////////////////////
    
    // Open File and Get Tree
    TFile *file = new TFile( currentFile->GetTitle(), "read" );
    TTree *tree = (TTree*)file->Get("t");
    if(readFast) TTreeCache::SetLearnEntries(10);
    if(readFast) tree->SetCacheSize(128*1024*1024);
    babyAnalyzer.Init(tree);
    
    // Get weight histogram from baby
    wgtInfo.getWeightHistogramFromBaby( file );
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {

      
      ///////////////////////
      //                   //
      // Get Event Content //
      //                   //
      ///////////////////////
   
      // Read Tree
      if( nEventsTotal >= nEventsChain ) continue;
      if(readFast) tree->LoadTree(event);
      babyAnalyzer.GetEntry(event);
      ++nEventsTotal;

      // Progress
      stop_1l_babyAnalyzer::progress( nEventsTotal, nEventsChain );

      
      /////////////////////
      //                 //
      // Check Selection //
      //                 //
      /////////////////////


      // Check JSON
      if( sample.isData && applyjson ) {
	if( !goodrun(run(),ls()) ) continue;
      }
	
      // Check duplicate event
      if( sample.isData ) {
	duplicate_removal::DorkyEventIdentifier id(run(), evt(), ls());
	if( is_duplicate(id) ) continue;
      }

      // Check WNJets genPt
      if( sample.id == sampleInfo::k_W1JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W2JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W3JetsToLNu_madgraph_pythia8 ||
					sample.id == sampleInfo::k_W4JetsToLNu_madgraph_pythia8    ) {
				if( nupt()>200.0 ) continue;
      }

			// Pre-calculate all the event weights
      wgtInfo.getEventWeights();



      /////////////////////////////
      //                         //
      // Compute Event Variables //
      //                         //
      /////////////////////////////

      // Find the gen pT of the ttbar system
      double ttbarPt = -99.9;
      LorentzVector genTTbar_LV;
      int nFoundGenTop=0;
      if( sampleIsTTbar ) {
	
				for(int iGen=0; iGen<(int)genqs_p4().size(); iGen++) {
					if( abs(genqs_id().at(iGen))==6 && genqs_isLastCopy().at(iGen) ) {
						genTTbar_LV += genqs_p4().at(iGen);
						nFoundGenTop++;
					} // end if last copy of top
				} // end loop over gen quarks

				if( nFoundGenTop == 2 ) ttbarPt = genTTbar_LV.Pt();

      } // end if sample is ttbar

      
      // Find the gen ID of the 2nd lepton
      double matched_lep_dr = 0.1;

      int gen2ndLep__idx = -1;
      int gen2ndLep__id = -99;
      int gen2ndLep__tauDecay = -1;
      int fill_bin_genLep2ID = -1;
      if( !sample.isData && is2lep() ) {
	
				// match leading lepton first
				int genLep_matchedTo_selLep__idx = -1;
				for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
					if( abs(genleps_id().at(iGen)) != abs(lep1_pdgid()) ) continue;
					if( !genleps_isLastCopy().at(iGen) ) continue;
					if( !genleps_fromHardProcessFinalState().at(iGen) &&
							!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
					if( ROOT::Math::VectorUtil::DeltaR(genleps_p4().at(iGen), lep1_p4()) < matched_lep_dr ) {
						genLep_matchedTo_selLep__idx = iGen;
						break;
					}
				}

				// If matched selected lepton, find lost gen lepton
				if( genLep_matchedTo_selLep__idx>0 ) {

					for(int iGen=0; iGen<(int)genleps_p4().size(); iGen++) {
						if( iGen == genLep_matchedTo_selLep__idx ) continue;
						if( !genleps_isLastCopy().at(iGen) ) continue;
						if( !genleps_fromHardProcessFinalState().at(iGen) &&
								!genleps_fromHardProcessDecayed().at(iGen)       ) continue;
						gen2ndLep__idx = iGen;
						gen2ndLep__id = genleps_id().at(iGen);
						gen2ndLep__tauDecay = genleps_gentaudecay().at(iGen);
					}

					// If found second lep
					if( gen2ndLep__idx>=0 ) {
	      
						if( abs(gen2ndLep__id)==11 ) fill_bin_genLep2ID = 1;  // "ele";
						if( abs(gen2ndLep__id)==13 ) fill_bin_genLep2ID = 2;  // "mu";
						if( abs(gen2ndLep__id)==15 ) {
							if( gen2ndLep__tauDecay==1 ) fill_bin_genLep2ID = 3;  // "lep tau, ele";
							if( gen2ndLep__tauDecay==2 ) fill_bin_genLep2ID = 4;  // "lep tau, mu";
							if( gen2ndLep__tauDecay==3 ) fill_bin_genLep2ID = 5;  // "had tau, 1 prong";
							if( gen2ndLep__tauDecay==4 ) fill_bin_genLep2ID = 6;  // "had tau, 3 prong";
							if( gen2ndLep__tauDecay==5 ) fill_bin_genLep2ID = 7;  // "\"other\" tau";
						} // end if 2nd lep is tau


					} // end if found 2nd gen lep
				} // end if found first gen lep, matched to selected lepton
      } // end if 2lep event and not data

      // Calculate p4 of (lep1 lep2 b b) system
      LorentzVector lep1lep2bb_TLV(0.0,0.0,0.0,0.0);

      LorentzVector lep1lep2bbMet_TLV(0.0,0.0,0.0,0.0);
      double lep1lep2bbMet_pt = -99.9;

      lep1lep2bb_TLV += lep1_p4();
      if(nvetoleps()>1) lep1lep2bb_TLV += lep2_p4();
      
      int jet1_idx = -1;
      double max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet1_idx = iJet;
					max_deepcsv  = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet1_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet1_idx);
      
      int jet2_idx = -1;
      max_deepcsv = -99.9;
      for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
				if( iJet==jet1_idx ) continue;
				if( ak4pfjets_deepCSV().at(iJet) > max_deepcsv ) {
					jet2_idx = iJet;
					max_deepcsv = ak4pfjets_deepCSV().at(iJet);
				}
      }
      if(jet2_idx>=0) lep1lep2bb_TLV += ak4pfjets_p4().at(jet2_idx);
      
      // Calculate p4 of (lep1 lep2 b b MET) system
      lep1lep2bbMet_TLV = lep1lep2bb_TLV;
      LorentzVector met_TLV( pfmet()*cos(pfmet_phi()), pfmet()*sin(pfmet_phi()), 0.0, pfmet() );
      lep1lep2bbMet_TLV += met_TLV;
    
      lep1lep2bbMet_pt = lep1lep2bbMet_TLV.Pt();

      // Calculate mlb using lep2 instead of lep1
      LorentzVector lep2b_TLV(0.0,0.0,0.0,0.0);
      double minDr = 99.9;
      int minBJetIdx = -99;
      if(nvetoleps()>1) {
				lep2b_TLV += lep2_p4();
				for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) {
					if(!ak4pfjets_passMEDbtag().at(iJet)) continue;
					if(ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4())<minDr) {
						minDr = ROOT::Math::VectorUtil::DeltaR(ak4pfjets_p4().at(iJet),lep2_p4());
						minBJetIdx = iJet;
					}
				} // end loop over jets
				if(minBJetIdx>=0) lep2b_TLV += ak4pfjets_p4().at(minBJetIdx);
      } // end if nvetoleps>1

      int mStop = mass_stop();
      int mLSP  = mass_lsp();



			/////////////////////////////////////////////////////////////
			//                                                         //
			// Loop over all analyzers, genClassy's, systematics, etc. //
			//                                                         //
			/////////////////////////////////////////////////////////////

			// Loop over all analyzers
			for( int iAna=0; iAna<nAnalyzers; iAna++ ) {
				analyzer* thisAnalyzer = analyzers.at(iAna);


				// Make an array of which genClassy's this event passes
				bool passedGenClassies[genClassyInfo::k_nGenClassy];
				for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
					passedGenClassies[thisGenClassy.id] = thisGenClassy.eval_GenClassy();

					// Manually correct the ZZto2L2Nu sample
					if( sample.id==sampleInfo::k_ZZTo2L2Nu_powheg_pythia8 ) {
						if( thisGenClassy.id == genClassyInfo::k_ge2lep ||
								thisGenClassy.id == genClassyInfo::k_incl ) passedGenClassies[thisGenClassy.id] = true;
						else passedGenClassies[thisGenClassy.id] = false;
					}
				}

				// Check if this event passes selections with JES set to nominal
				//  (saves us having to evaluate this for every systematic)
				thisAnalyzer->SetJesType( 0 );
				bool pass_JESnominal = thisAnalyzer->PassSelections();

				// Fill cutflow histogram
				std::vector<bool> cutflow_results = selectionInfo::get_selectionResults( thisAnalyzer->GetSelections() );
				for( uint i=0; i<cutflow_results.size(); i++ ) {
					if( !cutflow_results.at(i) ) break;
					h_cutflow[iAna]->Fill( i+1 );
				}


				// Loop over all systematics in the analyzer
				for( sysInfo::Util thisSystematic : thisAnalyzer->GetSystematics() ) {

					// Check if this event passes selections, and also set the appropriate JES type for future use
					if( thisSystematic.id == sysInfo::k_JESUp ) {
						thisAnalyzer->SetJesType( 1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else if( thisSystematic.id == sysInfo::k_JESDown ) {
						thisAnalyzer->SetJesType( -1 );
						if( !thisAnalyzer->PassSelections() ) continue;
					}
					else {
						thisAnalyzer->SetJesType( 0 );
						if( !pass_JESnominal ) continue;
					}

					// If we've passed selections, then get the event weight and the categories passed
					double weight = thisAnalyzer->GetEventWeight( thisSystematic.id );
					std::vector<int> categories_passed = thisAnalyzer->GetCategoriesPassed();

					// Loop over all the gen classifications that we passed
					for( genClassyInfo::Util thisGenClassy : thisAnalyzer->GetGenClassifications() ) {
						int iGen = thisGenClassy.id;
						if( !passedGenClassies[iGen] ) continue;

						// Get the index for the histogram corresponding to this genClassy and systematic
						int histIndex = iGen*nSystematics + thisSystematic.id;

						// Fill yield histograms
						for( int category : categories_passed ) {
							if( sample.isSignalScan ) {
								TH3D* yieldHisto = (TH3D*)thisAnalyzer->GetYieldHistogram( histIndex );
								yieldHisto->Fill( mStop, mLSP, category, weight );
							}
							else thisAnalyzer->GetYieldHistogram( histIndex )->Fill( category, weight );
						}

						/////////////////////////////////////
						//                                 //
						// Fill other non-yield histograms //
						//                                 //
						/////////////////////////////////////

						if( thisSystematic.id == sysInfo::k_nominal ) {

							for(int iMassPt=0; iMassPt<nMassPts; iMassPt++) {

								if( sample.isSignalScan && mStop!=sample.massPtList[iMassPt].first && mLSP!=sample.massPtList[iMassPt].second ) continue;
								//if(!isnormal(wgt_nominal)) cout << "NaN/inf weight: nEntries=" << wgtInfo.nEvents << ", lepSF=" << wgtInfo.sf_lep << ", vetoLep="<< wgtInfo.sf_vetoLep << ", btagSF=" << wgtInfo.sf_bTag << endl;
								// Histo Index
								int iHisto = iAna*nGenClassy*nMassPts + iGen*nMassPts + iMassPt;

								// Vars
								double nGoodJets = ngoodjets();

								bool add2ndLepToMet = thisAnalyzer->GetAdd2ndLep();

								double mt =         add2ndLepToMet ? mt_met_lep_rl() : mt_met_lep();
								double modTopness = add2ndLepToMet ? topnessMod_rl() : topnessMod();
								double met =        add2ndLepToMet ? pfmet_rl() : pfmet();

								double mlb = Mlb_closestb();
								if( TString(thisAnalyzer->GetLabel()).Contains("CR0b") ) mlb = ( lep1_p4() + ak4pfjets_leadbtag_p4() ).M();

								// Met Sideband CR area, met>=150

								if( met>=150 && met<250 ) {
									// mlb, met sideband CR
									h_mlb_150to250met_incl[iHisto]->Fill( mlb, weight );
									if( nGoodJets<4 )  h_mlb_150to250met_lt4j[iHisto]->Fill( mlb, weight );
									if( nGoodJets>=4 ) h_mlb_150to250met_ge4j[iHisto]->Fill( mlb, weight );
	      
									// mlb_lep2, met sideband CR
									if(nvetoleps()>1 && minBJetIdx>=0) {
										h_mlb_lep2_150to250met_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets<4 )  h_mlb_lep2_150to250met_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
										if( nGoodJets>=4 ) h_mlb_lep2_150to250met_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									}

								} // end if 150<met<250

								// Signal Region Area, met>=250
								if( met<250.0 ) continue;
	    
								// nJets
								h_nJets[iHisto]->Fill( nGoodJets, weight );

								// nBTags
								h_nBTags[iHisto]->Fill( ngoodbtags(), weight );
	    
								// lep1 pT
								h_lep1Pt_incl[iHisto]->Fill( lep1_p4().Pt(), weight );

								// lep2 pT
								if( nvetoleps()>1 ) h_lep2Pt_incl[iHisto]->Fill( lep2_p4().Pt(), weight );

								// jet pT
								for(int iJet=0; iJet<(int)ak4pfjets_p4().size(); iJet++) h_jetPt_incl[iHisto]->Fill( ak4pfjets_p4().at(iJet).Pt(), weight );

								// jet1 pT
								h_jet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(0).Pt(), weight );

								// jet2 pT
								h_jet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(1).Pt(), weight );

								// DeepCSV jet1 pT
								if(jet1_idx>=0) h_deepcsvJet1Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet1_idx).Pt(), weight );

								// DeepCSV jet2 pT
								if(jet2_idx>=0) h_deepcsvJet2Pt_incl[iHisto]->Fill( ak4pfjets_p4().at(jet2_idx).Pt(), weight );

								// met
								h_met_incl[iHisto]->Fill( met, weight );
								if( nGoodJets<4  ) h_met_lt4j[iHisto]->Fill( met, weight );
								if( nGoodJets>=4 ) h_met_ge4j[iHisto]->Fill( met, weight );

								// lep1lep2bbMetPt
								h_lep1lep2bbMetPt_incl[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets<4  ) h_lep1lep2bbMetPt_lt4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );
								if( nGoodJets>=4 ) h_lep1lep2bbMetPt_ge4j[iHisto]->Fill( lep1lep2bbMet_pt, weight );

								// mt
								h_mt_incl[iHisto]->Fill( mt, weight );

								// modTopness
								h_modTopness_incl[iHisto]->Fill( modTopness, weight );
								if( nGoodJets<4  ) h_modTopness_lt4j[iHisto]->Fill( modTopness, weight );
								if( nGoodJets>=4 ) h_modTopness_ge4j[iHisto]->Fill( modTopness, weight );

								// mlb
								h_mlb_incl[iHisto]->Fill( mlb, weight );
								if( nGoodJets<4 )  h_mlb_lt4j[iHisto]->Fill( mlb, weight );
								if( nGoodJets>=4 ) h_mlb_ge4j[iHisto]->Fill( mlb, weight );

								// mlb, modTopness bins
								if(modTopness<0.0)   h_mlb_lt0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=0.0)  h_mlb_ge0modTopness[iHisto]->Fill( mlb, weight );
								if(modTopness>=10.0) h_mlb_ge10modTopness[iHisto]->Fill( mlb, weight );

								// mlb_lep2
								if(nvetoleps()>1 && minBJetIdx>=0) {
									h_mlb_lep2_incl[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets<4 )  h_mlb_lep2_lt4j[iHisto]->Fill( lep2b_TLV.M(), weight );
									if( nGoodJets>=4 ) h_mlb_lep2_ge4j[iHisto]->Fill( lep2b_TLV.M(), weight );
								}

								// Gen TTBar System
								if( sampleIsTTbar ) {
									h_gen_ttbarPt_incl[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets<4 )  h_gen_ttbarPt_lt4j[iHisto]->Fill( ttbarPt, weight );
									if( nGoodJets>=4 ) h_gen_ttbarPt_ge4j[iHisto]->Fill( ttbarPt, weight );
								}

								// Gen 2nd Lep ID
								if( !sample.isData && is2lep() && gen2ndLep__idx>=0 ) {
									h_gen_lep2_id_incl[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()<4 )  h_gen_lep2_id_lt4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
									if( ngoodjets()>=4 ) h_gen_lep2_id_ge4j[iHisto]->Fill( fill_bin_genLep2ID, weight );
								}

							} // end loop over mass points (1 if not signal scan)

						} // End filling of non-yield histograms

					} // End loop over genClassy's

				} // End loop over systematics

			} // End loop over analyzers

		} // End loop over events in tree


    //
    // Clean Up
    //
    delete tree;
    file->Close();
    delete file;

  } // end loop over file list


  //
  // Output Sanitation
  //
  if ( nEventsChain != nEventsTotal ) {
	  cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }


  //
  // Print Selection Cutflow
  //
  cout << "====================================================" << endl;
  cout << endl;
  for(int iAna=0; iAna<nAnalyzers; iAna++) {
	  cout << "    " << analyzers.at(iAna)->GetLabel() << " Cutflow: " << endl;
	  for(int iCut=1; iCut<=(int)h_cutflow[iAna]->GetNbinsX(); iCut++) {
		  cout << "      nEvents pass " << h_cutflow[iAna]->GetXaxis()->GetBinLabel(iCut) << " = " << h_cutflow[iAna]->GetBinContent(iCut) << endl;
	  }
	  cout << endl;
	  cout << endl;
  }
  cout << "====================================================" << endl;


  //
  // Clean stopCORE objects
  //
  wgtInfo.cleanUp(); 


  //
  // Close Output File
  //
  f_output->Write();
  f_output->Close();


  //
  // Clean input chain
  // 
  chain->~TChain();
  if( sample.isData ) duplicate_removal::clear_list();

  //
  // Benchmark Reporting
  //
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  cout << "====================================================" << endl;
    
  //fclose(f_evtList);

  //
  // Return!
  //
  return 0;

} // End of function "looper"
//
// Fucntions
//
void skimThisBaby(TString inPath, TString inFileName, TString inTreeName, TString outPath){

  // Talk to user
  cout << "  Skimming: "<< endl;
  cout << "     " << inPath+inFileName <<endl;
  
  // Load input TChain
  TChain *ch = new TChain(inTreeName);
  TString inFile = inPath;
  inFile += inFileName;
  ch->Add(inFile);
  Long64_t nentries = ch->GetEntries();
  TTreeCache::SetLearnEntries(10);
  ch->SetCacheSize(128*1024*1024);

  // Initialize Branches
  babyAnalyzer.Init(ch->GetTree());
  babyAnalyzer.LoadAllBranches();
  
  // Setup output file name and path
  TString outFileName = outPath;
  outFileName += inFileName;
  outFileName.ReplaceAll("*", "");
  outFileName.ReplaceAll(".root", "_skimmed.root");

  cout << "  Output will be written to: " << endl;
  cout << "      "  << outFileName << endl << endl;

  // Open outputfile and Clone input TTree
  TFile *newfile = new TFile(outFileName, "recreate");
  TTree *newtree  = (TTree*)ch->GetTree()->CloneTree(0);
  if(!newtree) cout << "BAD TTREE CLONE" << endl;

  TH1D *newCounter=NULL;
  
  // Get nEntries
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = ch->GetEntries();
  
  // Grab list of files
  TObjArray *listOfFiles = ch->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  int iFile=0;
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    TTreeCache::SetLearnEntries(10);
    tree->SetCacheSize(128*1024*1024);
    babyAnalyzer.Init(tree);

    if(iFile==0){
      TH1D *temp = (TH1D*)file->Get("h_counter");
      newCounter = (TH1D*)temp->Clone("h_counter");
      newCounter->SetDirectory(newfile);
    }
    //else{
    //TH1D *temp = (TH1D*)file->Get("h_counter");
    //newCounter->Add(temp);
    //}

    // Loop over Events in current file 
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
      
      // Progress
      stop_1l_babyAnalyzer::progress( nEventsTotal, nEventsChain );
    
      // Load Tree
      tree->LoadTree(event);
      babyAnalyzer.GetEntry(event);
      ++nEventsTotal;

      // Selection
      if(nvetoleps()<1) continue;
      if(nvetoleps()<2 && PassTrackVeto_v3() && PassTauVeto()) continue;
      if(ngoodjets()<2) continue;
      if(mt_met_lep()<150.0) continue;
      if(pfmet()<200.0) continue;

      // Turn on all branches on input
      babyAnalyzer.LoadAllBranches();      
      
      // Fill output tree
      newtree->Fill();
    
    } // end loop over entries
   
    iFile++;
  } // end loop over files in TChain

  // Clean up
  //newtree->Print();
  //newtree->AutoSave();
  newfile->Write();
  newfile->Close();
  delete ch;
  delete newfile;

}
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  /*
   // This loads the library
   TMVA::Tools::Instance();

   // to get access to the GUI and all tmva macros
   TString thisdir = gSystem->DirName(gInterpreter->GetCurrentMacroName());
   gROOT->SetMacroPath(thisdir + ":" + gROOT->GetMacroPath());
   gROOT->ProcessLine(".L TMVAGui.C");
*/

  map<string, TH1F*> histos; //massive
  vector<string> histonames; histonames.clear();
  vector<string> histonameshelp; histonameshelp.clear();
  vector<int> histobinn; histobinn.clear();
  vector<double> histobinl; histobinl.clear();
  vector<double> histobinu; histobinu.clear();
  map<string, float> value;

  histonames.push_back("MT2W");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(500.);
  //histonames.push_back("MT2_b_b");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_b");           histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_lb_bq");          histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_bqq");         histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  //histonames.push_back("MT2_l_q");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(300.);
  histonames.push_back("MT2_lb_b_mless");     histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_lb_bq_mless");    histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("MT2_lb_bqq_mless");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MT2_l_qq_mless");     histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("Mlb");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("Mlbb");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("M3b");                histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("MTb");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("MTq");                histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(500.);
  histonames.push_back("MTqmax");             histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTq_boostmax");       histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTq_boost300");       histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  histonames.push_back("MTq_boostLeadJet");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(1500.);
  //histonames.push_back("MTqq");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("Topness");            histobinn.push_back(30); histobinl.push_back(-15.); histobinu.push_back(15.);
  histonames.push_back("MT");                 histobinn.push_back(40); histobinl.push_back(0.); histobinu.push_back(400.);
  histonames.push_back("MET");                histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("HT");                 histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(1000.);
  histonames.push_back("METoverSqrtHT");      histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(40.);
  histonames.push_back("HTratio");            histobinn.push_back(20); histobinl.push_back(0.); histobinu.push_back(1.);
  histonames.push_back("dRLepBJet");          histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(10.);
  histonames.push_back("dRbb");               histobinn.push_back(25); histobinl.push_back(0.); histobinu.push_back(10.);
  histonames.push_back("chi2");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(30.);
  histonames.push_back("NBJets");             histobinn.push_back( 5); histobinl.push_back(0.); histobinu.push_back(5.);
  histonames.push_back("NJets");              histobinn.push_back(10); histobinl.push_back(0.); histobinu.push_back(10.);
  //histonames.push_back("minDPhi");            histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  histonames.push_back("minDPhiJ3");          histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  //histonames.push_back("minDPhiB");           histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);
  //histonames.push_back("pTlb");               histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(600.);
  histonames.push_back("pTlbb");              histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(600.);
  histonames.push_back("pTl");                histobinn.push_back(27); histobinl.push_back(0.); histobinu.push_back(405.);
  histonames.push_back("pTleadj");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("pTleadb");            histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("pTtrailb");           histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  //histonames.push_back("sumak8prunedmass");   histobinn.push_back(30); histobinl.push_back(0.); histobinu.push_back(750.);
  histonames.push_back("DeltaPhiWl");         histobinn.push_back(32); histobinl.push_back(0.); histobinu.push_back(3.2);

  TFile *outfile[3];
  TTree *outtree[3];
  for(unsigned int b = 0; b<histonames.size(); ++b){
    value[histonames[b] ] = -99;
    histonameshelp.push_back(histonames[b]+(string)"/F");
  }
  for(unsigned int b = 0; b<3; ++b){
    string samplename = skimFilePrefix;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    TString fileName = "rootfiles/TestmysmallBDTvartree_"+samplename+".root";
    outfile[b] = new TFile(fileName,"RECREATE");
    outtree[b] = new TTree(samplename.c_str(),"");
    for(unsigned int a = 0; a<histonames.size(); ++a){
      outtree[b]->Branch(histonames[a].c_str(), &value[histonames[a] ], histonameshelp[a].c_str() );
    }
  }



  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
 
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
   
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );

      int sampleid = 0;
      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(cms3.gen_nfromtmus_() + cms3.gen_nfromtels_() + cms3.gen_nfromttaus_() ==2) { samplename = "TTbar2l"; sampleid=1; }
	else if(cms3.gen_nfromtmus_() + cms3.gen_nfromtels_() + cms3.gen_nfromttaus_() ==1) { samplename = "TTbar1l"; sampleid=0; }
	else { samplename = "TTbarH"; sampleid=2; }
      }
      // Analysis Code
      float weight = cms3.scale1fb()*10.;
      int NLeps = cms3.ngoodlep();
      string ds = cms3.dataset();
      float MET = cms3.pfmet();
      float METPhi = cms3.pfmet_phi();
      float METx = MET*TMath::Cos(METPhi);
      float METy = MET*TMath::Sin(METPhi);
      float MT2W = cms3.MT2W_lep1();
      float MT = cms3.MT_MET_lep1();
      float dRLepBJet = cms3.dR_lep1_leadb();
      float chi2 = cms3.chi2();
      //float genmet = cms3.genmet();
      //int NJets = cms3.ak4GoodPFJets();
      //int NBJets = cms3.ak4_nBTags_Med();
      float HT = cms3.ak4_HT();
      float HTratio = cms3.ak4_htratiom();
      int nvtxs = cms3.nvtxs();
      float minDPhi = cms3.mindphi_met_j1_j2();
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > jetslv = cms3.ak4pfjets_p4();
      vector<float> jetsbtag = cms3.ak4pfjets_btag_disc();
      vector<bool> jetsID = cms3.ak4pfjets_loose_pfid();
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > lep1lv = cms3.lep1_p4();
      float lep1pt = cms3.lep1_pt();
      float lep1eta = cms3.lep1_eta();
      //float lep1dr03isoDB = cms3.lep1_relIso03DB();
      bool lep1eIDl = cms3.lep1_is_eleid_loose();
      bool lep1eIDm = cms3.lep1_is_eleid_medium();
      bool lep1mIDt = cms3.lep1_is_muoid_tight();
      bool lep1ismu = cms3.lep1_is_mu();
      bool lep1isel = cms3.lep1_is_el();
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > lep2lv = cms3.lep1_p4();
      float lep2pt = cms3.lep2_pt();
      float lep2eta = cms3.lep2_eta();
      //float lep2dr03isoDB = cms3.lep2_relIso03DB();
      bool lep2eIDl = cms3.lep2_is_eleid_loose();
      bool lep2eIDm = cms3.lep2_is_eleid_medium();
      bool lep2mIDt = cms3.lep2_is_muoid_tight();
      bool lep2ismu = cms3.lep2_is_mu();
      bool lep2isel = cms3.lep2_is_el();
      
      bool trackveto = cms3.PassTrackVeto();
      bool tauveto = cms3.PassTauVeto();

      int NGLeps = 0;
      int NSLeps = 0;
      int NGJets = 0;
      int NGBJets = 0;

      int l1=-1;
      if(lep1ismu){
	//if(lep1pt>20&&fabs(lep1eta)<99&&lep1mIDt) ++NGLeps;
	//if(lep1pt>25&&fabs(lep1eta)<2.1&&lep1mIDt&&lep1dr03isoDB*lep1pt<TMath::Min(5.,0.15*lep1pt)) {++NSLeps; l1 = 1;}
	if(lep1pt>30&&fabs(lep1eta)<2.1&&fabs(cms3.lep1_d0())<0.02&&fabs(cms3.lep1_dz())<0.1&&cms3.lep1_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; }
      } else if (lep1isel){
	//if(lep1pt>20&&fabs(lep1eta)<99&&lep1eIDl) ++NGLeps;
	//if(lep1pt>30&&fabs(lep1eta)<1.442&&lep1eIDm&&lep1dr03isoDB*lep1pt<TMath::Min(5.,0.15*lep1pt)) {++NSLeps; l1 = 1;}
	if(lep1pt>40&&fabs(lep1eta)<2.1&&cms3.lep1_is_phys14_medium_noIso()&&cms3.lep1_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; }
      }
      if(lep2ismu){
	//if(lep2pt>20&&fabs(lep2eta)<99&&lep2mIDt) ++NGLeps;
	//if(lep2pt>25&&fabs(lep2eta)<2.1&&lep2mIDt&&lep2dr03isoDB*lep2pt<TMath::Min(5.,0.15*lep2pt)) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
	if(lep2pt>30&&fabs(lep2eta)<2.1&&fabs(cms3.lep2_d0())<0.02&&fabs(cms3.lep2_dz())<0.1&&cms3.lep2_miniRelIsoDB()<0.1) {++NSLeps; l1 = 1; if(l1!=1) l1 = 2; else l1=-2; }
      } else if (lep2isel){
	//if(lep2pt>20&&fabs(lep2eta)<99&&lep2eIDl) ++NGLeps;
	//if(lep2pt>30&&fabs(lep2eta)<1.442&&lep2eIDm&&lep2dr03isoDB*lep2pt<TMath::Min(5.,0.15*lep2pt)) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
	if(lep2pt>40&&fabs(lep2eta)<2.1&&cms3.lep2_is_phys14_medium_noIso()&&cms3.lep2_miniRelIsoDB()<0.1) {++NSLeps; if(l1!=1) l1 = 2; else l1=-2;}
      }
      NGLeps = NLeps;

      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > leplv;
      if(l1==1) leplv = lep1lv;
      else if(l1==2) leplv = lep2lv;

      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > metlv;
      metlv.SetPxPyPzE(METx,METy,0.,MET);

      //if(NGLeps != NLeps) cout << "NGLeps = " << NGLeps << " NLeps = " << NLeps << endl;
      //NGLeps = NLeps;
      vector<int> jind;
      vector<int> bind;
      ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > jsumlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > jetlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > boostjetlv;
      vector<ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<float> > > bjetlv;
      vector<float> btag;
      int jj1(-1), jj2(-1), jj3(-1);// j1(-1), j2(-1), jm(-1);
      float jj1d(-1), jj2d(-1), jj3d(-1);// jjmm(-1);
      for(unsigned int nj = 0; nj<jetsbtag.size(); ++nj){
	if(jetslv[nj].Pt()<30) continue;
	if(fabs(jetslv[nj].Eta())>2.4) continue;
	if(jetsID[nj]==false) continue;
	jind.push_back(nj);
	jetlv.push_back(jetslv[nj]);
	if(jetslv[nj].Pt()>250) boostjetlv.push_back(jetslv[nj]);
	btag.push_back(jetsbtag[nj]);
	++NGJets;
	if(jetsbtag[nj]>0.814) {++NGBJets; bind.push_back(nj); bjetlv.push_back(jetslv[nj]);}
	if(jetslv[nj].Pt()>jj1d){
	  jj3d = jj2d; jj2d = jj1d; jj1d = jetslv[nj].Pt();
	  jj3 = jj2; jj2 = jj1; jj1 = nj;
	} else if(jetslv[nj].Pt()>jj2d){
	  jj3d = jj2d; jj2d = jetslv[nj].Pt();
	  jj3 = jj2; jj2 = nj;
	} else if(jetslv[nj].Pt()>jj3d){
	  jj3d = jetslv[nj].Pt();
	  jj3 = nj;
	}
      }

      if(nvtxs<0) continue; 
      if(NGLeps!=1) continue; 
      if(NSLeps!=1) continue; 
      if(!trackveto) continue; 
      if(!tauveto) continue; 
      if(NGJets<4) continue;
      //if(NGBJets<1) continue; 
      if(MET<30) continue; 
      //if(MT>80) continue;

      for(unsigned int i = 0; i<histonames.size(); ++i){
	value[histonames[i] ] = -99;//reset values
      }
      //vector<LorentzVector > btaggedjets = JetUtil::BJetSelector(jetlv,btag,0.814,2,3,1);
      vector<LorentzVector > btaggedjets = JetUtil::BJetSelector(jetlv,btag,0.814,2,2,2);

      vector<LorentzVector > dummybjets;dummybjets.clear();
      LorentzVector dummybjet; dummybjet.SetPxPyPzE(0.,0.,0.,0.); dummybjets.push_back(dummybjet);dummybjets.push_back(dummybjet);
      
      //value["MT2W"]                  = CalculateMT2W_(btaggedjets,leplv,MET,METPhi,true);
      value["MT2W"] = MT2W;
      value["Topness"]               = Gettopness_(MET,METPhi,leplv,btaggedjets,1);
      value["MT2_b_b"]               = MT2_b_b_(MET,METPhi,btaggedjets,true, 0);
      value["MT2_lb_b_mless"]        = MT2_lb_b_(MET,METPhi,leplv,btaggedjets,false,0);
      value["MT2_lb_b"]              = MT2_lb_b_(MET,METPhi,leplv,btaggedjets,true ,0);
      value["MT2_lb_bq_mless"]       = MT2_lb_bq_( MET,METPhi,leplv,btaggedjets,jetlv,false,0);
      value["MT2_lb_bq"]             = MT2_lb_bq_( MET,METPhi,leplv,btaggedjets,jetlv,true ,0);
      value["MT2_lb_bqq_mless"]      = MT2_lb_bqq_(MET,METPhi,leplv,btaggedjets,jetlv,false,0);
      value["MT2_lb_bqq"]            = MT2_lb_bqq_(MET,METPhi,leplv,btaggedjets,jetlv,true ,0);
      value["MT2_l_q"]               = MT2_lb_bq_( MET,METPhi,leplv,dummybjets,jetlv,true ,0);
      value["MT2_l_qq_mless"]        = MT2_lb_bqq_(MET,METPhi,leplv,dummybjets,jetlv,true ,0);

      int leadb(-1), trailb(-1);
      for(unsigned int n = 0; n<btaggedjets.size();++n){
	if(leadb<0) leadb = n;
	else if(trailb<0) trailb = n;
	else if(btaggedjets[n].Pt() > btaggedjets[leadb].Pt()){ trailb = leadb; leadb = n; }
	else if(btaggedjets[n].Pt() > btaggedjets[trailb].Pt()){ trailb = n; }
	LorentzVector temp = btaggedjets[n]+leplv;
	if(temp.M()<value["Mlb"]) value["Mlb"] = temp.M();  else if(value["Mlb"]<0) value["Mlb"] = temp.M();
	if(temp.Pt()<value["pTlb"]) value["pTlb"] = temp.Pt();  else if(value["pTlb"]<0) value["pTlb"] = temp.Pt();
	float tmp = getMT(btaggedjets[n],metlv);
	if(tmp<value["MTb"]) value["MTb"] = tmp;  else if(value["MTb"]<0) value["MTb"] = tmp;
	tmp = JetUtil::deltaR(btaggedjets[n],leplv);
	tmp = JetUtil::deltaPhi(btaggedjets[n],metlv);
	if(tmp<value["minDPhiB"]) value["minDPhiB"] = tmp;  else if(value["minDPhiB"]<0) value["minDPhiB"] = tmp;
	for(unsigned int m = n+1; m<btaggedjets.size();++m){
	  temp = btaggedjets[n]+btaggedjets[m]+leplv;
	  if(temp.M()<value["Mlbb"]) value["Mlbb"] = temp.M();  else if(value["Mlbb"]<0) value["Mlbb"] = temp.M();
	  if(temp.Pt()<value["pTlbb"]) value["pTlbb"] = temp.Pt();  else if(value["pTlbb"]<0) value["pTlbb"] = temp.Pt();
	  tmp = JetUtil::deltaR(btaggedjets[n],btaggedjets[m]);
	  if(tmp<value["dRbb"]) value["dRbb"] = tmp;  else if(value["dRbb"]<0) value["dRbb"] = tmp;
	}
      }
      float myleadjpt = -1.;
      int bj1(-1), bj2(-1),bj3(-1);
      for(unsigned int n = 0; n<jetlv.size();++n){
	float tmp = getMT(jetlv[n],metlv);
  	if(tmp<value["MTq"]) value["MTq"] = tmp;  else if(value["MTq"]<0) value["MTq"] = tmp;
  	if(tmp>value["MTqmax"]) value["MTqmax"] = tmp;  else if(value["MTqmax"]<0) value["MTqmax"] = tmp;
	if(jetlv[n].Pt()>250.){ if(tmp>value["MTq_boostmax"]) value["MTq_boostmax"] = tmp;  else if(value["MTq_boostmax"]<0) value["MTq_boostmax"] = tmp; }
	if(jetlv[n].Pt()>300.){ if(tmp<value["MTq_boost300"]) value["MTq_boost300"] = tmp;  else if(value["MTq_boost300"]<0) value["MTq_boost300"] = tmp; }
	if(jetlv[n].Pt()>myleadjpt){ value["MTq_boostLeadJet"] = tmp; myleadjpt = jetlv[n].Pt(); }// else if(value["MTq_boostLeadJet"]<0) value["MTq_boostLeadJet"] = tmp;
	for(unsigned int m = n+1; m<jetlv.size();++m){
	  tmp = getMT(jetlv[n]+jetlv[m],metlv);
	  if(tmp<value["MTqq"]) value["MTqq"] = tmp;  else if(value["MTqq"]<0) value["MTqq"] = tmp;
	}
	if(n<3){
	  tmp = JetUtil::deltaPhi(jetlv[n],metlv);
	  if(tmp<value["minDPhiJ3"]) value["minDPhiJ3"] = tmp;  else if(value["minDPhiJ3"]<0) value["minDPhiJ3"] = tmp;
	}
	float dP1l(-1), dP2l(-1), dP3l(-1);
	if(bj1>0) dP1l = JetUtil::deltaPhi(jetlv[bj1],leplv);
	if(bj2>0) dP2l = JetUtil::deltaPhi(jetlv[bj2],leplv);
	if(bj3>0) dP3l = JetUtil::deltaPhi(jetlv[bj3],leplv);
	if(JetUtil::deltaPhi(jetlv[n],leplv)>dP1l){ bj3 = bj2; bj2 = bj1; bj1 = n;}
	else if(JetUtil::deltaPhi(jetlv[n],leplv)>dP2l){ bj3 = bj2; bj2 = n;}
	else if(JetUtil::deltaPhi(jetlv[n],leplv)>dP3l){ bj3 = n;}
      }

      LorentzVector bjsumlep = jetlv[bj1] + jetlv[bj2] + jetlv[bj3];
      value["M3b"] = bjsumlep.M();

      float prune=0.;
      for(unsigned int n = 0; n<cms3.ak8pfjets_pruned_mass().size();++n) prune += cms3.ak8pfjets_pruned_mass()[n];
      
      //cout << __LINE__<<endl;
      value["sumak8prunedmass"]   = prune;
      value["MT"] = MT;
      value["MET"] = MET;
      value["HT"] = HT;
      if(HT>0) {
	value["METoverSqrtHT"] = MET/TMath::Sqrt(HT);
      }
      value["HTratio"] = HTratio;
      value["dRLepBJet"] = dRLepBJet;
      value["chi2"] = chi2;
      value["NBJets"] = NGBJets;
      value["NJets"] = NGJets;
      value["minDPhi"] = minDPhi;
      value["pTl"] = leplv.Pt();
      value["pTleadj"] = myleadjpt;
      value["pTleadb"] = btaggedjets[leadb].Pt();
      value["pTtrailb"] = btaggedjets[trailb].Pt();
      value["DeltaPhiWl"] = JetUtil::deltaPhi(leplv,metlv+leplv);

      outtree[sampleid]->Fill();


      for(unsigned int i = 0; i<histonames.size(); ++i){
	value[histonames[i] ] = -99;//reset values
      }
    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  for(unsigned int b = 0; b<3; ++b){
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    outfile[b]->cd();
    outtree[b]->Write();
    outfile[b]->Close();
    cout << "Tree for making BDT saved in " << outfile[b]->GetName() << endl;
  }

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
Exemplo n.º 14
0
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {


  set_goodrun_file("Merged_190456-208686_8TeV_PromptReReco_Collisions12_goodruns.txt");

  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  //add hists
  TH1F *h_mll_ee_inc = new TH1F("h_mll_ee_inc", "ee Dilepton Mass", 200,0,200);//200,0,2000
  h_mll_ee_inc->SetDirectory(rootdir);
  h_mll_ee_inc->Sumw2();
  
  TH1F* h_mll_mumu_inc = new TH1F("h_mll_mumu_inc","MuMu Dilepton Mass",200,0,200);
  h_mll_mumu_inc->SetDirectory(rootdir);
  h_mll_mumu_inc->Sumw2();

  TH1F* h_mll_ee_tar = new TH1F("h_mll_ee_tar","ee Dilepton Mass (Targeted)",200,0,200);
  h_mll_ee_tar->SetDirectory(rootdir);
  h_mll_ee_tar->Sumw2();

  TH1F* h_mll_mumu_tar = new TH1F("h_mll_mumu_tar","MuMu Dilepton Mass (Targeted)",200,0,200);
  h_mll_mumu_tar->SetDirectory(rootdir);
  h_mll_mumu_tar->Sumw2();

  TH1F* h_met_ee_inc = new TH1F("h_met_ee_inc","ee MET (Inclusive)",350,0,350);//350,0,350 for all met histos
  h_met_ee_inc->SetDirectory(rootdir);
  h_met_ee_inc->Sumw2();

  TH1F* h_met_mumu_inc = new TH1F("h_met_mumu_inc","mumu MET (Inclusive)",350,0,350);
  h_met_mumu_inc->SetDirectory(rootdir);
  h_met_mumu_inc->Sumw2();

  TH2F* h_met_ll_inc = new TH2F("h_met_ll_inc","ee+mumu MET (Inclusive)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_inc->SetDirectory(rootdir);
  h_met_ll_inc->Sumw2();

  TH2F* h_met_emu2_inc = new TH2F("h_met_emu2_inc","emu MET (Inclusive)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_inc->SetDirectory(rootdir);
  h_met_emu2_inc->Sumw2();

  TH1F* h_met_emu_inc = new TH1F("h_met_emu_inc","emu MET (Inclusive)",350,0,350);
  h_met_emu_inc->SetDirectory(rootdir);
  h_met_emu_inc->Sumw2();

  TH1F* h_met_ee_tar_njets0 = new TH1F("h_met_ee_tar_njets0","ee MET (Targeted, no jets)",350,0,350);
  h_met_ee_tar_njets0->SetDirectory(rootdir);
  h_met_ee_tar_njets0->Sumw2();

  TH1F* h_met_mumu_tar_njets0 = new TH1F("h_met_mumu_tar_njets0","mumu MET (Targeted, no jets)",350,0,350);
  h_met_mumu_tar_njets0->SetDirectory(rootdir);
  h_met_mumu_tar_njets0->Sumw2();

  TH2F* h_met_ll_tar_njets0 = new TH2F("h_met_ll_tar_njets0","ee+mumu MET (Targeted, no jets)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_tar_njets0->SetDirectory(rootdir);
  h_met_ll_tar_njets0->Sumw2();

  TH2F* h_met_emu2_tar_njets0 = new TH2F("h_met_emu2_tar_njets0","emu MET (Targeted, no jets)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_tar_njets0->SetDirectory(rootdir);
  h_met_emu2_tar_njets0->Sumw2();

  TH1F* h_met_emu_tar_njets0 = new TH1F("h_met_emu_tar_njets0","emu MET (Targeted, no jets)",350,0,350);
  h_met_emu_tar_njets0->SetDirectory(rootdir);
  h_met_emu_tar_njets0->Sumw2();

  TH1F* h_met_ee_tar_njets2 = new TH1F("h_met_ee_tar_njets2","ee MET (Targeted, njets >= 2)",350,0,350);
  h_met_ee_tar_njets2->SetDirectory(rootdir);
  h_met_ee_tar_njets2->Sumw2();

  TH1F* h_met_mumu_tar_njets2 = new TH1F("h_met_mumu_tar_njets2","mumu MET (Targeted, njets >= 2)",350,0,350);
  h_met_mumu_tar_njets2->SetDirectory(rootdir);
  h_met_mumu_tar_njets2->Sumw2();

  TH2F* h_met_ll_tar_njets2 = new TH2F("h_met_ll_tar_njets2","ee+mumu MET (Targeted, njets >= 2)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_ll_tar_njets2->SetDirectory(rootdir);
  h_met_ll_tar_njets2->Sumw2();

  TH2F* h_met_emu2_tar_njets2 = new TH2F("h_met_emu2_tar_njets2","emu MET (Targeted, njets >= 2)",700,-350,350,700,-350,350);//positive and negative met.  2D!
  h_met_emu2_tar_njets2->SetDirectory(rootdir);
  h_met_emu2_tar_njets2->Sumw2();

  TH1F* h_met_emu_tar_njets2 = new TH1F("h_met_emu_tar_njets2","emu MET (Targeted, njets >= 2)",350,0,350);
  h_met_emu_tar_njets2->SetDirectory(rootdir);
  h_met_emu_tar_njets2->Sumw2();

  TH1F* h_nvtx_scaled= new TH1F("h_nvtx_scaled","Number of Vertices (scaled)",35,0,35);
  h_nvtx_scaled->SetDirectory(rootdir);
  h_nvtx_scaled->Sumw2();

  TH1F* h_nvtx_unscaled= new TH1F("h_nvtx_unscaled","Number of Vertices (unscaled)",35,0,35);
  h_nvtx_unscaled->SetDirectory(rootdir);
  h_nvtx_unscaled->Sumw2();

  TH1F* h_phi= new TH1F("h_phi","phi distribution",40,-TMath::Pi(),TMath::Pi());
  h_phi->SetDirectory(rootdir);
  h_phi->Sumw2();
  //-------
  TFile *InputFile = new TFile("phiRatio.root","read");
  TH1F *h_phi_ratio = (TH1F*) InputFile->Get("h_phidata_clone_scaled")->Clone("h_phi_ratio");
  //-------
  TH1F* h_sumet_ee_inc = new TH1F("h_sumet_ee_inc","ee SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_ee_inc->SetDirectory(rootdir);
  h_sumet_ee_inc->Sumw2();

  TH1F* h_sumet_mumu_inc = new TH1F("h_sumet_mumu_inc","mumu SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_mumu_inc->SetDirectory(rootdir);
  h_sumet_mumu_inc->Sumw2();

  TH1F* h_sumet_emu_inc = new TH1F("h_sumet_emu_inc","emu SumET (Inclusive)",2500,0,2500);//350,0,350 for all met histos
  h_sumet_emu_inc->SetDirectory(rootdir);
  h_sumet_emu_inc->Sumw2();
  //-------
  TFile *InputFile_sumet = new TFile("sumet_Ratio.root","read");
  TH1F *h_sumet_ratio = (TH1F*) InputFile_sumet->Get("h_sumet_ee_inc_data_clone_scaled")->Clone("h_sumet_ratio");
  //-------

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("T1");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    zmet.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      zmet.GetEntry(event);
      ++nEventsTotal;
    
      // Progress
      ZMET::progress( nEventsTotal, nEventsChain );
	  
	  //------------------------- CUT --------------------------------------------
	 
	  //
	  if( (zmet.leptype() != 0) && (zmet.leptype() != 1) && (zmet.leptype() != 2) ){ continue;} // 0 -> e's,  1 -> Mu's, 2->emu


	  float ptcutoff=20.;
	  if( ( zmet.lep1().Pt() <= ptcutoff) || ( zmet.lep2().Pt() <= ptcutoff) ) {continue;}

	  float etacutoff=2.4;
	  if( ( abs( zmet.lep1().Eta()) >= etacutoff) || ( abs( zmet.lep2().Eta()) >= etacutoff) ) {continue;}
	  
	  //barrel/endcap eta cuts
	  if( ( abs( zmet.lep1().Eta()) > 1.4 && abs( zmet.lep1().Eta()) < 1.6) || ( abs( zmet.lep2().Eta()) > 1.4 && abs( zmet.lep2().Eta()) < 1.6) ) 
		{continue;}

	  double weight_mc=zmet.weight()*19.5*zmet.trgeff()*zmet.vtxweight()*( h_phi_ratio->GetBinContent(h_phi_ratio->FindBin(zmet.pfmetphi())) )*( h_sumet_ratio->GetBinContent(h_sumet_ratio->FindBin(zmet.pfsumet())) );
	  double weight_data=1.;
	  //cout<< h_phi_ratio->GetBinContent(h_phi_ratio->FindBin(zmet.pfmetphi()))<<endl;
	  
	  //---------------------------------------
	  if (zmet.lep3().Pt() > 10.){continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() > 7.) {continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() <= 7. || zmet.nvtx() >= 20.) {continue;}
	  //---------------------------------------
	  //if (zmet.nvtx() < 20.) {continue;}

	  //Data cuts
	  if(zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )
		{
		  if(!(zmet.csc()==0 && 
			   zmet.hbhe()==1 && 
			   zmet.hcallaser()==1 && 
			   //zmet.ecallaser()==1 && 
			   zmet.ecaltp()==1 && 
			   zmet.trkfail()==1 && 
			   zmet.eebadsc()==1 && 
			   zmet.hbhenew()==1))     
			continue;    //met filter variables and trigger variables
		}

	  if(zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )
		{
		  if( zmet.leptype()==0 )
			{
			  if( zmet.ee()==0 )  
				{continue;}
			}
		  else if( zmet.leptype()==1 )
			{
			  if( zmet.mm()==0 )              
				{continue;}
			}
		  else if( zmet.leptype()==2 )
			{
			  if( zmet.em()==0 && zmet.me()==0 )
				{continue;}
			}
		}

	  //Fill  histograms
	  if (zmet.isdata() && goodrun( zmet.run(), zmet.lumi() )  )  //If it is data from good run
		{
		  if (zmet.leptype()==0 || zmet.leptype()==1 || zmet.leptype()==2)
			{
			  h_nvtx_scaled->Fill(zmet.nvtx(),weight_data);
			  h_nvtx_unscaled->Fill(zmet.nvtx(),weight_data);
			  h_phi->Fill(zmet.pfmetphi(), weight_data);
			}
		  if (zmet.leptype() == 0)
			{
			  h_mll_ee_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/ )             //Check this.  Only apply to MET histos
				{
				  h_met_ee_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_ee_inc, zmet.pfsumet(),weight_data);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
				 
				  if(zmet.njets()==0)
					{
					  h_met_ee_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_ee_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				}

			  if ( zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
				 {h_mll_ee_tar->Fill(zmet.dilmass(),weight_data);}
			}
		  else if (zmet.leptype()==1)
			{
			  h_mll_mumu_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/)             //check this.
				{		  
				  h_met_mumu_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_mumu_inc, zmet.pfsumet(),weight_data);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
			
				  if(zmet.njets()==0)
					{
					  h_met_mumu_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);					
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_mumu_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);					
					}

				}

			  if ( zmet.lep3().Pt() <= 10.   &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )  
				 {h_mll_mumu_tar->Fill(zmet.dilmass(),weight_data);}
			}
		  else if (zmet.leptype()==2)
			{
			  //h_mll_mumu_inc->Fill(zmet.dilmass(),weight_data);
			 
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /*&& zmet.lep3().Pt() <= 10.*/)             //check this.
				{		  
				  h_met_emu_inc->Fill(zmet.pfmet(),weight_data);
				  fillHist(h_sumet_emu_inc, zmet.pfsumet(),weight_data);
				  h_met_emu2_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
			
				  if(zmet.njets()==0)
					{
					  h_met_emu_tar_njets0->Fill(zmet.pfmet(),weight_data);
					  h_met_emu2_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_emu_tar_njets2->Fill(zmet.pfmet(),weight_data);
					  h_met_emu2_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_data);
					}
				}

			  // if ( zmet.lep3().Pt() <= 10.   &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )  
			  // {h_mll_mumu_tar->Fill(zmet.dilmass(),weight_data);}
			}
		}


	  else if (!zmet.isdata())   //If it is MC
		{
		  if (zmet.leptype()==0 || zmet.leptype()==1 || zmet.leptype()==2)
			{
			  h_nvtx_scaled->Fill(zmet.nvtx(), zmet.weight()*19.5*zmet.trgeff()*zmet.vtxweight() );
			  h_nvtx_unscaled->Fill(zmet.nvtx(), zmet.weight()*19.5*zmet.trgeff() );
			  h_phi->Fill(zmet.pfmetphi(), weight_mc);			}

		  if (zmet.leptype() == 0)
			{
			  h_mll_ee_inc->Fill(zmet.dilmass(),weight_mc);
			  
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_ee_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_ee_inc, zmet.pfsumet(),weight_mc);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
				
				  if(zmet.njets()==0)
					{
					  h_met_ee_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_ee_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}
			  if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )        
   				{h_mll_ee_tar->Fill(zmet.dilmass(),weight_mc);}
			}
		  else if (zmet.leptype()==1)
			{
			  h_mll_mumu_inc->Fill(zmet.dilmass(),weight_mc);
			
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_mumu_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_mumu_inc, zmet.pfsumet(),weight_mc);
				  h_met_ll_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);

				  if(zmet.njets()==0)
					{
					  h_met_mumu_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_mumu_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_ll_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}

			  if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
   				{h_mll_mumu_tar->Fill(zmet.dilmass(),weight_mc);}
			}
 
		  else if (zmet.leptype()==2)
			{
			  // h_mll_mumu_inc->Fill(zmet.dilmass(),weight_mc);
			
			  if(zmet.dilmass() > 81. && zmet.dilmass() < 101. /* && zmet.lep3().Pt() <= 10.*/)
				{
				  h_met_emu_inc->Fill(zmet.pfmet(),weight_mc);
				  fillHist(h_sumet_emu_inc, zmet.pfsumet(),weight_mc);
				  h_met_emu2_inc->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);

				  if(zmet.njets()==0)
					{
					  h_met_emu_tar_njets0->Fill(zmet.pfmet(),weight_mc);
					  h_met_emu2_tar_njets0->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				  else if(zmet.njets()>=2)
					{
					  h_met_emu_tar_njets2->Fill(zmet.pfmet(),weight_mc);
					  h_met_emu2_tar_njets2->Fill(zmet.pfmet()*TMath::Cos( zmet.pfmetphi() ), zmet.pfmet()*TMath::Sin( zmet.pfmetphi() ), weight_mc);
					}
				}

			  // if (zmet.lep3().Pt() <= 10.  &&  zmet.njets()>=2  &&  zmet.nbcsvm()==0 && (zmet.mjj() > 70. && zmet.mjj() < 110.) )
			  //	{h_mll_mumu_tar->Fill(zmet.dilmass(),weight_mc);}
			}
	}

	
  

 //---------------------------------------------------------------------------------------------------------
    }    //end events loop.
 
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }


  //Write to file
  TFile *OutputFile = new TFile(Form("%s.root", skimFilePrefix.c_str()),"recreate");
  OutputFile->cd();
  h_mll_ee_inc->Write();
  h_mll_mumu_inc->Write();
  h_mll_ee_tar->Write();
  h_mll_mumu_tar->Write();
  h_met_ee_inc->Write();
  h_met_mumu_inc->Write();
  h_met_ll_inc->Write();
  h_met_emu_inc->Write();
  h_met_emu2_inc->Write();
  h_met_ee_tar_njets0->Write();
  h_met_mumu_tar_njets0->Write();
  h_met_ll_tar_njets0->Write();
  h_met_emu_tar_njets0->Write();
  h_met_emu2_tar_njets0->Write();
  h_met_ee_tar_njets2->Write();
  h_met_mumu_tar_njets2->Write();
  h_met_ll_tar_njets2->Write();
  h_met_emu_tar_njets2->Write();
  h_met_emu2_tar_njets2->Write();
  h_nvtx_scaled->Write();
  h_nvtx_unscaled->Write();
  h_phi->Write();
  h_sumet_ee_inc->Write();
  h_sumet_mumu_inc->Write();
  h_sumet_emu_inc->Write();

  OutputFile->Close();


  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;

  return 0;
}
int ScanChain( TChain* chain, bool fast = true, int nEvents = -1, string skimFilePrefix = "test") {
  int version = 4;
  // Benchmark
  TBenchmark *bmark = new TBenchmark();
  bmark->Start("benchmark");

  // Example Histograms
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");


  map<string, TH1F*> histos;
  vector<string> histonames; histonames.clear();

  int nbins = 9; float blow = 0.5; float bup = 9.5; bool storeh = true;
  if(version== 1){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 2){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 3){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 4){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 5){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version== 6){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 7){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version== 8){ nbins =  7; blow = 0.5; bup =  7.5; storeh = true; }
  if(version== 9){ nbins =  7; blow = 0.5; bup =  7.5; storeh = true; }
  if(version==10){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==11){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version==12){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==13){ nbins =  6; blow = 0.5; bup =  6.5; storeh = true; }
  if(version==14){ nbins =  8; blow = 0.5; bup =  8.5; storeh = true; }
  if(version==15){ nbins =  5; blow = 0.5; bup =  5.5; storeh = true; }
  if(version==16){ nbins =  9; blow = 0.5; bup =  9.5; storeh = true; }
  if(version==17){ nbins = 11; blow = 0.5; bup = 11.5; storeh = true; }

  //AllBGCorr
  //CorrName1Name2Name3 with NameX being sampleX
  //CorrAllBG CorrAll means correlated among all backgrounds, or everything (bg+sig)
  histonames.push_back("SRyield");
  histonames.push_back("CRyield");
  histonames.push_back("StatUnc");
  histonames.push_back("SystUnc");
 
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    //cout << helper << endl;
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    string mapname;
    for(unsigned int i = 0; i<histonames.size();++i){
      mapname = histonames[i] + "_" + samplename;
      //cout << mapname << " " << nbins << " " << blow << " " << bup << endl;
      if(histos.count(mapname) == 0 ) histos[mapname] = new TH1F(mapname.c_str(), "", nbins, blow, bup);
      histos[mapname]->Sumw2(); histos[mapname]->SetDirectory(rootdir);
      //cout << mapname << endl;
      //cout << mapname << endl;
    }
  }

  // Loop over events to Analyze
  unsigned int nEventsTotal = 0;
  unsigned int nEventsChain = chain->GetEntries();
  if( nEvents >= 0 ) nEventsChain = nEvents;
  TObjArray *listOfFiles = chain->GetListOfFiles();
  TIter fileIter(listOfFiles);
  TFile *currentFile = 0;

  // File Loop
  while ( (currentFile = (TFile*)fileIter.Next()) ) {

    // Get File Content
    TFile *file = new TFile( currentFile->GetTitle() );
    TTree *tree = (TTree*)file->Get("t");
    if(fast) TTreeCache::SetLearnEntries(10);
    if(fast) tree->SetCacheSize(128*1024*1024);
    cms3.Init(tree);
    
    // Loop over Events in current file
    if( nEventsTotal >= nEventsChain ) continue;
    unsigned int nEventsTree = tree->GetEntriesFast();
    for( unsigned int event = 0; event < nEventsTree; ++event) {
    
      // Get Event Content
      if( nEventsTotal >= nEventsChain ) continue;
      if(fast) tree->LoadTree(event);
      cms3.GetEntry(event);
      ++nEventsTotal;
      
      // Progress
      CMS3::progress( nEventsTotal, nEventsChain );
      
      string samplename = skimFilePrefix;
      if(skimFilePrefix=="TTbar"){
	if(genlepsfromtop() ==2) samplename = "TTbar2l";
	else if(genlepsfromtop() ==1) samplename = "TTbar1l";
	else { samplename = "TTbarH"; continue; }// cout << "no gen lep" << " " << genlepsfromtop() << endl; }
      }
      TString helper = TString(samplename);
      /*if(helper.Contains("Signal")){
	if(helper.Contains("T2tt")){
	  TString signalname = Form("%s_%d_%d",samplename.c_str(),(int)mass_stop(),(int)mass_lsp());
	  samplename = signalname.Data();
	}
      }*/
      
      // Analysis Code
      float weight = cms3.scale1fb()*3.;
      if(samplename == "Data") weight = 1.;
      if(is_data()) weight = 1.;
      if(event==0) cout << "weight " << weight << " nEvents " << cms3.nEvents() << " filename " << currentFile->GetTitle() << endl;
      //bool trackveto = cms3.PassTrackVeto();
      //bool tauveto = cms3.PassTauVeto();

      int NGLeps = 0;
      int NSLeps = 0;
      int NGJets = 0;
      int NGBJets = 0;

      if(lep1_is_mu()){
	if(lep1_pt()>30&&fabs(lep1_eta())<2.1&&lep1_passMediumID()&&fabs(lep1_d0())<0.02&&fabs(lep1_dz())<0.1&&lep1_MiniIso()<0.1) {++NSLeps; }
	//if(lep1_pt()>30&&fabs(lep1_eta())<2.4&&fabs(lep1_d0())<0.02&&fabs(lep1_dz())<0.1&&lep1_MiniIso()<0.1) {++NGLeps; }
      } else if (lep1_is_el()){
	if(lep1_pt()>40&&fabs(lep1_eta())<2.1&&lep1_passMediumID()&&lep1_MiniIso()<0.1) {++NSLeps; }
	//if(lep1_pt()>40&&fabs(lep1_eta())<2.5&&lep1_is_phys14_medium_noIso()&&lep1_MiniIso()<0.1) {++NGLeps; }
      }
      if(lep2_is_mu()){
       	if(lep2_pt()>30&&fabs(lep2_eta())<2.1&&lep2_passMediumID()&&fabs(lep2_d0())<0.02&&fabs(lep2_dz())<0.1&&lep2_MiniIso()<0.1) {++NSLeps; }
      	//if(lep2_pt()>30&&fabs(lep2_eta())<2.4&&fabs(lep2_d0())<0.02&&fabs(lep2_dz())<0.1&&lep2_MiniIso()<0.1) {++NGLeps; }
      } else if (lep2_is_el()){
	if(lep2_pt()>40&&fabs(lep2_eta())<2.1&&lep2_passMediumID()&&lep2_MiniIso()<0.1) {++NSLeps; }
	//if(lep2_pt()>40&&fabs(lep2_eta())<2.5&&lep2_is_phys14_medium_noIso()&&lep2_MiniIso()<0.1) {++NGLeps; }
      }
      NGLeps = nvetoleps();
      
      for(unsigned int nj = 0; nj<ak4pfjets_CSV().size(); ++nj){
	if(ak4pfjets_p4()[nj].Pt()<30) continue;
	if(fabs(ak4pfjets_p4()[nj].Eta())>2.4) continue;
	if(ak4pfjets_loose_pfid()[nj]==false) continue;
	++NGJets;

	if(ak4pfjets_CSV()[nj]>0.890) {++NGBJets; }
      }

      if(nvtxs()<0)        continue;
      if(nvetoleps()!=1)   continue;
      //if(NSLeps!=1)        continue;
      if(ngoodleps()!=1)   continue;
      if(!PassTrackVeto_v3()) continue;
      if(!PassTauVeto())   continue;
      if(NGJets<3)         continue;
      if(NGBJets<1)        continue;
      if(mindphi_met_j1_j2()<0.8) continue;
      //if(hadronic_top_chi2()>10) continue;
      if(pfmet()<250)       continue;
      if(mt_met_lep()<150)  continue;

      //cout << __LINE__ << " version " << version << endl;
      bool ge4j = NGJets>=4;
      float met = pfmet();
      bool m2w = MT2W()>200.;
      bool mlb = Mlb_lead_bdiscr()>175.;
      float bpt = ak4pfjets_leadMEDbjet_p4().Pt();

      //NOTE that we already have MET>=250!
      float mybin = -1;
      
      if(version==16){
	if(bpt<=100){
	  if(!m2w) mybin = 1; else if(!mlb) mybin = 2; else mybin = 3;
	}
	else if(!m2w) mybin = 4;
	else if(!mlb){
	  if(met>375) mybin = 6; else mybin = 5;
	}
	else if(met>400) mybin = 9; else if(met>325) mybin = 8; else mybin = 7;
      }
      if(version==17){
	if(!mlb){
	  if(!m2w){
	    if(bpt<=150){
	      if(met>325) mybin = 2; else mybin = 1;
	    } else mybin = 8;
	  } else if(bpt<=150){
	    if(met>375) mybin = 4; else mybin = 3;
	  } else mybin = 9;
	}
	else if(!m2w) mybin = 5;
	else if(bpt<=150){
	  if(met>350) mybin = 7; else mybin = 6;
	}
	else if(met>350) mybin = 11; else mybin = 10;
      }
      
      if(!ge4j) continue;
      
      if(version==1){
	if(bpt<=100){
	  if(mlb) mybin = 3; else if(m2w) mybin = 2; else mybin = 1;
	} else {
	  if(!m2w) mybin = 4; else if(!mlb) mybin = 5;
	  else if(met>400) mybin = 8; else if(met>325) mybin = 7; else mybin = 6;
	}
      }
      if(version==2){
	if(bpt<=100){
	  if(!m2w) mybin = 1; else if(met>350) mybin = 3; else mybin = 2;
	} else {
	  if(!m2w) mybin = 4;
	  else if(met>450) mybin = 8; else if(met>350) mybin = 7; else if(met>300) mybin = 6; else mybin = 5;
	}
      }
      if(version==3){
	if(bpt<=100){
	  if(mlb) mybin = 3; else if(met>350) mybin = 2; else mybin = 1;
	} else if(bpt>100){
	  if(mlb){
	    if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
	  } else if(met>350) mybin = 5; else mybin = 4;
	}
      }
      if(version==4){
	if(bpt<=100){
	  if(met>400) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else {
	  if(met>450) mybin = 8; else if(met>375) mybin = 7; else if(met>325) mybin = 6; else if(met>275) mybin = 5; else mybin = 4;
	}
      }
      if(version==5){
	if(!mlb){
	  if(bpt>150) mybin = 4; else if(m2w) mybin = 2; else mybin = 1;
	} else {
	  if(m2w){
	    if(met>350&&bpt>150) mybin = 6; else if(bpt>150) mybin = 5;
	  } else mybin = 3;
	}
      }
      if(version==6){
	if(bpt<=150){
	  if(!m2w) mybin = 1; else if(met>400) mybin = 4; else if(met>300) mybin = 3; else mybin = 2;
	} else {
	  if(!m2w) mybin = 5; else if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
	}
      }
      if(version==7){
	if(bpt<=150){
	  if(mlb){ if(met>300) mybin = 5; else mybin = 4; }
	  else if(met>400) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else {
	  if(!mlb) mybin = 6; else if(met>350) mybin = 8; else mybin = 7;
	}
      }
      if(version==8){
	if(bpt<=150){
	  if(met>425) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
	} else if(met>400) mybin = 7; else if(met>325) mybin = 6; else mybin = 5;
      }
      if(version==9){
	if(bpt>200){
	  if(met>350) mybin = 7; else mybin = 6;
	} else if(m2w) {
	  if(met>400) mybin = 5; else if(met>325) mybin = 4; else mybin = 3;
	} else {
	  if(met>325) mybin = 2; else mybin = 1;
	}
      }
      if(version==10){
	if(bpt>200){
	  if(met>350) mybin = 8; else mybin = 7;
	} else if(mlb){
	  if(met>375) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	} else {
	  if(met>400) mybin = 3; else if(met>325) mybin = 2; else mybin = 1;
	}
      }
      if(version==11){
	if(bpt>200){
	  if(met>350) mybin = 6; else mybin = 5;
	}
	else if(met>450) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      if(version==12){
	if(!mlb){
	  if(!m2w){
	    if(met>325) mybin = 2; else mybin = 1;
	  }
	  else if(met>375) mybin = 4; else mybin = 3;
	} else if(!m2w) mybin = 5; else if(met>400) mybin = 8; else if(met>300) mybin = 7; else mybin = 6;
      }
      if(version==13){
	if(mlb){
	  if(met>350) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	}
	else if(met>425) mybin = 3; else if(met>325) mybin = 2; else mybin = 1;
      }
      if(version==14){
	if(m2w){
	  if(met>500) mybin = 8; else if(met>400) mybin = 7; else if(met>350) mybin = 6; else if(met>300) mybin = 5; else mybin = 4;
	}
	else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      if(version==15){
	if(met>500) mybin = 5; else if(met>400) mybin = 4; else if(met>350) mybin = 3; else if(met>300) mybin = 2; else mybin = 1;
      }
      //cout << __LINE__ << " mybin " << mybin << " " << samplename << endl;
      //cout << "SRyield_" + samplename << endl;
      histos["SRyield_" + samplename]->Fill(mybin,weight);

    }
  
    // Clean Up
    delete tree;
    file->Close();
    delete file;
  }
  if ( nEventsChain != nEventsTotal ) {
    cout << Form( "ERROR: number of events from files (%d) is not equal to total number of events (%d)", nEventsChain, nEventsTotal ) << endl;
  }

  //do all postrunning modifications here - maybe need some additional code if running over additional types of babies
  //i.e.if we have additional babies, run extra, hadd files and do further modifications (note you might need to store additional histos)
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) samplename = "TTbarH";
    string mapname;
    for(int i = 1; i<=histos["SRyield_"+samplename]->GetNbinsX();++i){
      if(histos["SRyield_"+samplename]->Integral()>0) {
	if(histos["SRyield_"+samplename]->GetBinContent(i)>0){
	  histos["StatUnc_"+samplename]->SetBinContent(i, histos["SRyield_"+samplename]->GetBinError(i)/histos["SRyield_"+samplename]->GetBinContent(i));
	}
	else histos["StatUnc_"+samplename]->SetBinContent(i, -999);
	histos["SystUnc_"+samplename]->SetBinContent(i, 0.3);
      }
    }
  }  

  //save all relevant histograms into some rootfiles
  for(unsigned int b = 0; b<2; ++b){
    string samplename = skimFilePrefix;
    TString helper = TString(samplename);
    if(skimFilePrefix!="TTbar"&&b>0) continue;
    if(skimFilePrefix=="TTbar"&&b==0) samplename = "TTbar1l";
    if(skimFilePrefix=="TTbar"&&b==1) samplename = "TTbar2l";
    if(skimFilePrefix=="TTbar"&&b==2) continue;
    string filename = "inputfiles/"+samplename+".root";
    if(version== 1) filename = "inputfiles/v1/"+samplename+".root";
    if(version== 2) filename = "inputfiles/v2/"+samplename+".root";
    if(version== 3) filename = "inputfiles/v3/"+samplename+".root";
    if(version== 4) filename = "inputfiles/v4/"+samplename+".root";
    if(version== 5) filename = "inputfiles/v5/"+samplename+".root";
    if(version== 6) filename = "inputfiles/v6/"+samplename+".root";
    if(version== 7) filename = "inputfiles/v7/"+samplename+".root";
    if(version== 8) filename = "inputfiles/v8/"+samplename+".root";
    if(version== 9) filename = "inputfiles/v9/"+samplename+".root";
    if(version==10) filename = "inputfiles/v10/"+samplename+".root";
    if(version==11) filename = "inputfiles/v11/"+samplename+".root";
    if(version==12) filename = "inputfiles/v12/"+samplename+".root";
    if(version==13) filename = "inputfiles/v13/"+samplename+".root";
    if(version==14) filename = "inputfiles/v14/"+samplename+".root";
    if(version==15) filename = "inputfiles/v15/"+samplename+".root";
    if(version==16) filename = "inputfiles/v16/"+samplename+".root";
    if(version==17) filename = "inputfiles/v17/"+samplename+".root";
    TFile *f = new TFile(filename.c_str(),"RECREATE");
    f->cd();
    string mapname;
    for(unsigned int i = 0; i<histonames.size();++i){
      mapname = histonames[i] + "_" + samplename;
      if(storeh) histos[mapname]->Write();
    }
    f->Close();
    cout << "Saved histos in " << f->GetName() << endl;
  }

  // return
  bmark->Stop("benchmark");
  cout << endl;
  cout << nEventsTotal << " Events Processed" << endl;
  cout << "------------------------------" << endl;
  cout << "CPU  Time:	" << Form( "%.01f", bmark->GetCpuTime("benchmark")  ) << endl;
  cout << "Real Time:	" << Form( "%.01f", bmark->GetRealTime("benchmark") ) << endl;
  cout << endl;
  delete bmark;
  return 0;
}
void TMVAClassificationApplication_tW(TString sample = "TWChannel", TString syst = "",TString region = "1j1t", TString directory = "v4", TString chanName = "emu",   TString bdtTraining =  "AdaBoost500TreesMET50", int variableSet = -1)
{   
#ifdef __CINT__
  gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif

  cout << sample << "\t" << syst << "\t" << region << "\t" << directory << "\t" << chanName << "\t" << bdtTraining << endl;
  
  //---------------------------------------------------------------
  // This loads the library
  TMVA::Tools::Instance();
  // --------------------------------------------------------------------------------------------------
  
  // --- Create the Reader object
  
  TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    
  
  // Create a set of variables and declare them to the reader
  // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
  
  Float_t ptjet;
  Float_t ptsys;
  Float_t ht;
  Float_t NlooseJet20;
  Float_t NlooseJet20Central;
  Float_t NbtaggedlooseJet20;
  Float_t centralityJLL;
  Float_t loosejetPt;
  Float_t ptsys_ht;
  Float_t msys;
  Float_t htleps_ht;
  Float_t ptjll;
  Float_t met;

  if (variableSet == -1 || variableSet == 0){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("NlooseJet20", &NlooseJet20);
    reader->AddVariable ("NlooseJet20Central", &NlooseJet20Central);
    reader->AddVariable ("NbtaggedlooseJet20", &NbtaggedlooseJet20);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("loosejetPt", &loosejetPt);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
    reader->AddVariable ("met", &met);
  }
  if (variableSet == 1){ //NoMET
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("NlooseJet20", &NlooseJet20);
    reader->AddVariable ("NlooseJet20Central", &NlooseJet20Central);
    reader->AddVariable ("NbtaggedlooseJet20", &NbtaggedlooseJet20);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("loosejetPt", &loosejetPt);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
  }

  if (variableSet == 2){ //NoMET, jetpt, loosejetPt, or NlooseJetCentral
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("NlooseJet20", &NlooseJet20);
    reader->AddVariable ("NbtaggedlooseJet20", &NbtaggedlooseJet20);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
  }

  if (variableSet == 3){ //No MET or jet variables
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
  }

  if (variableSet == 4){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("NlooseJet20", &NlooseJet20);
    reader->AddVariable ("NlooseJet20Central", &NlooseJet20Central);
    reader->AddVariable ("NbtaggedlooseJet20", &NbtaggedlooseJet20);
    reader->AddVariable ("loosejetPt", &loosejetPt);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
    reader->AddVariable ("met", &met);
  }

  if (variableSet == 5){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
    reader->AddVariable ("met", &met);
  }

  if (variableSet == 6){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("NlooseJet20Central", &NlooseJet20Central);
    reader->AddVariable ("NbtaggedlooseJet20", &NbtaggedlooseJet20);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("loosejetPt", &loosejetPt);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
    reader->AddVariable ("met", &met);
  }

  if (variableSet == 7){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("ht",&ht);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("ptsys_ht",&ptsys_ht);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
    reader->AddVariable ("met", &met);
  }

  if (variableSet == 8){
    reader->AddVariable ("ptjet", &ptjet);
    reader->AddVariable ("ptsys",&ptsys);
    reader->AddVariable ("NlooseJet20", &NlooseJet20);
    reader->AddVariable ("centralityJLL", &centralityJLL);
    reader->AddVariable ("msys", &msys);
    reader->AddVariable ("htleps_ht", &htleps_ht);
    reader->AddVariable ("ptjll", &ptjll);
  }
  
  // *************************************************
  
  // --- Book the MVA methods
  
  TString dir    = "weights/";
  TString extra =  bdtTraining;
  TString prefix = "test_tw_00_";



  TString name = extra +"_"+ chanName + "_" + region;
  
  if (bdtTraining == "AdaBoost500Trees") prefix = "test_tw_00_AdaBoostTests_13Vars_NtreeTests";

  //
  // book the MVA methods
  //
  
  reader->BookMVA( "BDT method", dir + prefix + extra+".weights.xml" );   
  
  // book output histograms
  
  
  // Prepare input tree (this must be replaced by your data source)
  // in this example, there is a toy tree with signal and one with background events
  // we'll later on use only the "signal" events for the test in this example.
  //   
  TFile *input(0);
    
  TString folder = "tmvaFiles/"+directory+"/";

  TString systlabel = "";
  if (syst != ""){
    systlabel = "_"+syst;
  }

  //  TString fname = folder + "TWChannel.root";
  TString fname = folder + sample + systlabel + ".root";


  cout << fname << endl;

  //  input->SetCacheSize(20*1024*1024);
  
  input = TFile::Open( fname,"r");   
  
  if (!input) {
    cout << "ERROR: could not open data file: " << fname << endl;
    exit(1);
  }
  
  // --- Event loop
  
  // Prepare the event tree
  // - here the variable names have to corresponds to your tree
  // - you can use the same variables as above which is slightly faster,
  //   but of course you can use different ones and copy the values inside the event loop
  //
  
  TString treeName = chanName + "Channel/"+region;
  TTree* theTree = (TTree*)input->Get(treeName);

  cout << "--- Select signal sample" << endl;

  theTree->SetCacheSize(20*1024*1024);
  
  Double_t userptjet;
  Double_t userptsys;
  Double_t userht;
  Int_t userNlooseJet20;
  Int_t userNlooseJet20Central;
  Int_t userNbtaggedlooseJet20;
  Double_t usercentralityJLL;
  Double_t userloosejetPt;
  Double_t userptsys_ht;
  Double_t usermsys;
  Double_t userhtleps_ht;
  Double_t userptjll;
  Double_t usermet;
  Double_t userweightA;
  Double_t userweightB;
  Double_t userweightC;
  Double_t userweightD;
    
  theTree->SetBranchAddress ("ptjet", &userptjet);
  theTree->SetBranchAddress ("ptsys",&userptsys);
  theTree->SetBranchAddress ("ht",&userht);
  theTree->SetBranchAddress ("NlooseJet20", &userNlooseJet20);
  theTree->SetBranchAddress ("NlooseJet20Central", &userNlooseJet20Central);
  theTree->SetBranchAddress ("NbtaggedlooseJet20", &userNbtaggedlooseJet20);
  theTree->SetBranchAddress ("centralityJLL", &usercentralityJLL);
  theTree->SetBranchAddress ("loosejetPt", &userloosejetPt);
  theTree->SetBranchAddress ("ptsys_ht",&userptsys_ht);
  theTree->SetBranchAddress ("msys", &usermsys);
  theTree->SetBranchAddress ("htleps_ht", &userhtleps_ht);
  theTree->SetBranchAddress ("ptjll", &userptjll);
  theTree->SetBranchAddress ("met", &usermet);
  theTree->SetBranchAddress ("weightA", &userweightA);
  theTree->SetBranchAddress ("weightB", &userweightB);
  theTree->SetBranchAddress ("weightC", &userweightC);
  theTree->SetBranchAddress ("weightD", &userweightD);
  
  Double_t tBDT;    
  Double_t tweightA;
  Double_t tweightB;
  Double_t tweightC;
  Double_t tweightD;

  TFile *output(0);

  TString outName = folder +bdtTraining+"/"+ sample+systlabel+"_Output.root";

  cout << "Output root file: " << outName << endl;

  output = TFile::Open(outName,"UPDATE");

  TTree* BDTTree = new TTree(name,"");
  BDTTree->Branch("BDT",&tBDT,"BDT/D");
  BDTTree->Branch("weightA",&tweightA,"weightA/D");
  BDTTree->Branch("weightB",&tweightB,"weightB/D");
  BDTTree->Branch("weightC",&tweightC,"weightC/D");
  BDTTree->Branch("weightD",&tweightD,"weightD/D");
  
  std::cout<<" ... opening file : "<<fname<<std::endl;
  cout << "--- Processing: " << theTree->GetEntries() << " events" << endl;
  
  TStopwatch sw;
  sw.Start();
  for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
    
    if (ievt%1000 == 0)      cout << "--- ... Processing event: " << ievt << endl;
          
    theTree->GetEntry(ievt);

    ptjet              = userptjet;
    ptsys	       = userptsys;	      
    ht		       = userht;		      
    NlooseJet20	       = userNlooseJet20;	      
    NlooseJet20Central = userNlooseJet20Central;
    NbtaggedlooseJet20 = userNbtaggedlooseJet20;
    centralityJLL      = usercentralityJLL;     
    loosejetPt	       = userloosejetPt;	      
    ptsys_ht	       = userptsys_ht;	      
    msys	       = usermsys;	      
    htleps_ht	       = userhtleps_ht;	      
    ptjll	       = userptjll;	      
    met                = usermet;               

    //    sw.Print();
    double bdt         = reader->EvaluateMVA("BDT method");
    tBDT = bdt;

    tweightA = userweightA;
    tweightB = userweightB;
    tweightC = userweightC;
    tweightD = userweightD;

    BDTTree->Fill();

  }

  // Get elapsed time
  sw.Stop();
  std::cout << "--- End of event loop: "; sw.Print();
  
  input->Close();


  output->cd();

  BDTTree->Write();
  
  output->Close();
  
    // --- Write histograms
  
  delete reader;
  
  std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
}