Пример #1
0
TChain * GetAnalysisChain(const char * incollection){
  // Builds a chain of esd files
  // incollection can be
  // - a single root file
  // - an xml collection of files on alien
  // - a ASCII containing a list of local root files
  TChain* analysisChain = 0;
  // chain
  analysisChain = new TChain("esdTree");
  if (TString(incollection).Contains(".root")){
    analysisChain->Add(incollection);
  }
  else if (TString(incollection).Contains("xml")){
    TGrid::Connect("alien://");
    TAlienCollection * coll = TAlienCollection::Open (incollection);
    while(coll->Next()){
      analysisChain->Add(TString("alien://")+coll->GetLFN());
    }
  } else {
    ifstream file_collect(incollection);
    TString line;
    while (line.ReadLine(file_collect) ) {
      analysisChain->Add(line.Data());
    }
  }
  analysisChain->GetListOfFiles()->Print();

  return analysisChain;
}
Пример #2
0
void formChain300(){
  cout << "Begin loading..." << endl;
  const TString treedirectory = "demo/T_weights";
  TChain* InputChain = new TChain(treedirectory);

  InputChain->Add("rfio:/castor/cern.ch/user/k/kreis/CUSusy/QCD/T_weight_QCD_Pt300_*.root");
  
  InputChain->Merge("/cu1/kreis/QCD/T_weights_QCD_Pt300.root");

  cout << "Loaded " << InputChain->GetListOfFiles()->GetEntries() << " files" << endl;

 return;

}
Пример #3
0
//__________________________________________________________
TChain* CreateChainCAF(Int_t nFilesMax, TFileCollection* coll, char* treeName)
{
  TIter iter(coll->GetList());
  
  TChain* target = new TChain(treeName);
  
  Int_t nFiles = 0;
  
  TFileInfo* fileInfo = 0;
  while ((fileInfo = dynamic_cast<TFileInfo*> (iter())) && (nFiles<nFilesMax || nFilesMax == 0)){
    if (fileInfo->GetFirstUrl()) {
      target->Add(fileInfo->GetFirstUrl()->GetUrl());
      nFiles++;
    }
  }
  
  Printf("Added %d files to chain", target->GetListOfFiles()->GetEntries());
  
  return target;
}
Пример #4
0
void efficiency_hitrecovery(TString fileName){
	bool verbose(false);
	TString dirname(fileName);
	TChain* chain = new TChain("dummy");
	TString ext("out_ana_");

	///Get the sample mass
	TString str = fileName;
	TString str2 = "DarkSUSY_mH_125_mGammaD_";
	Ssiz_t first = str.Index(str2);
	Ssiz_t last = str.Index("_cT_");
	TSubString mass_string = (str(first+str2.Length(),4));
	///Get the sample cT
	TString str3 = "_cT_";
	TSubString cT_string = (str(last+str3.Length(),4));

	// add files to the chain
	addfiles(chain, dirname, ext);

	//Initialize Variables and counters
	//{{{

	Int_t event;
	Int_t run;
	Int_t lumi;

	Bool_t is4GenMu;
	Bool_t is1GenMu17;
	Bool_t is2GenMu8;
	Bool_t is3GenMu8;
	Bool_t is4GenMu8;

	Bool_t is1SelMu17;
	Bool_t is2SelMu8;
	Bool_t is3SelMu8;
	Bool_t is4SelMu8;

	Bool_t is2MuJets;
	Bool_t is2DiMuons;
	Bool_t is2DiMuonsFittedVtxOK;
	Bool_t is2DiMuonsDzOK_FittedVtx;
	Bool_t isDiMuonHLTFired;
	Bool_t is2DiMuonsMassOK_FittedVtx;
	Bool_t is2DiMuonsIsoTkOK_FittedVtx;
	Bool_t isVertexOK;

	Float_t genA0_Lxy;
	Float_t genA1_Lxy;
	Float_t genA0_Lz;
	Float_t genA1_Lz;


	Int_t diMuonC_m1_FittedVtx_hitpix;
	Int_t diMuonC_m2_FittedVtx_hitpix;
	Int_t diMuonF_m1_FittedVtx_hitpix;
	Int_t diMuonF_m2_FittedVtx_hitpix;

	Float_t genA0_eta;
	Float_t genA0_phi;
	Float_t genA1_eta;
	Float_t genA1_phi;

	Float_t selMu0_phi;
	Float_t selMu1_phi;
	Float_t selMu2_phi;
	Float_t selMu3_phi;

	Float_t selMu0_eta;
	Float_t selMu1_eta;
	Float_t selMu2_eta;
	Float_t selMu3_eta;

	Float_t genA0_m;
	Float_t genA0_px;
	Float_t genA0_py;
	Float_t genA0_pz;

	Float_t genA1_m;
	Float_t genA1_px;
	Float_t genA1_py;
	Float_t genA1_pz;

	Float_t diMuonC_FittedVtx_m;
	Float_t diMuonC_FittedVtx_px;
	Float_t diMuonC_FittedVtx_py;
	Float_t diMuonC_FittedVtx_pz;
	Float_t diMuonC_FittedVtx_eta;
	Float_t diMuonC_FittedVtx_phi;
	Float_t diMuonC_FittedVtx_Lxy;
	Float_t diMuonC_FittedVtx_L;

	Float_t diMuonF_FittedVtx_m;
	Float_t diMuonF_FittedVtx_px;
	Float_t diMuonF_FittedVtx_py;
	Float_t diMuonF_FittedVtx_pz;
	Float_t diMuonF_FittedVtx_eta;
	Float_t diMuonF_FittedVtx_phi;
	Float_t diMuonF_FittedVtx_Lxy;
	Float_t diMuonF_FittedVtx_L;

	Float_t genA0Mu0_eta;
	Float_t genA1Mu0_eta;
	Float_t genA0Mu1_eta;
	Float_t genA1Mu1_eta;


	Float_t genA0Mu0_phi;
	Float_t genA1Mu0_phi;
	Float_t genA0Mu1_phi;
	Float_t genA1Mu1_phi;


	Float_t genA0Mu0_px;
	Float_t genA1Mu0_px;
	Float_t genA0Mu1_px;
	Float_t genA1Mu1_px;

	Float_t genA0Mu0_py;
	Float_t genA1Mu0_py;
	Float_t genA0Mu1_py;
	Float_t genA1Mu1_py;

	//Vertex information
	Float_t genA0_vx;
	Float_t genA0_vy;
	Float_t genA0_vz;

	Float_t genA1_vx;
	Float_t genA1_vy;
	Float_t genA1_vz;

	Float_t genA0Mu0_vx;
	Float_t genA0Mu1_vx;
	Float_t genA1Mu0_vx;
	Float_t genA1Mu1_vx;

	Float_t genA0Mu0_vy;
	Float_t genA0Mu1_vy;
	Float_t genA1Mu0_vy;
	Float_t genA1Mu1_vy;

	Float_t genA0Mu0_vz;
	Float_t genA0Mu1_vz;
	Float_t genA1Mu0_vz;
	Float_t genA1Mu1_vz;

	Float_t diMuonC_FittedVtx_vx;
	Float_t diMuonC_FittedVtx_vy;
	Float_t diMuonC_FittedVtx_vz;

	Float_t diMuonF_FittedVtx_vx;
	Float_t diMuonF_FittedVtx_vy;
	Float_t diMuonF_FittedVtx_vz;

	//============= Counters ===========================//

	vector<double> FakesPerSample;

	Int_t ev_all = 0;
	Int_t ev_isVtxOK = 0;
	Int_t ev_is2MuJets = 0;
	Int_t ev_is2DiMuons = 0;
	Int_t ev_is2DiMuonsFittedVtxOK = 0;
	Int_t ev_isPixelHitOK = 0;
	Int_t ev_is2DiMuonsDzOK_FittedVtx = 0;
	Int_t ev_is2DiMuonsMassOK_FittedVtx = 0;
	Int_t ev_is2DiMuonsIsoTkOK_FittedVtx = 0;
	Int_t ev_isDiMuonHLTFired = 0;

	Int_t c1genm = 0;
	Int_t c2genm = 0;
	Int_t c3genm = 0;
	Int_t c4genm = 0;
	Int_t ev_4gmlxylzcut = 0;

	Int_t c1recm = 0;
	Int_t c2recm = 0;
	Int_t c3recm = 0;
	Int_t c4recm = 0;

	Int_t uncuttableFakeCounter = 0;
	//}}}

	TObjArray *fileElements=chain->GetListOfFiles();
	TIter next(fileElements);
	TChainElement *chEl=0;

	while ((chEl=(TChainElement*)next())) {
		if (verbose) std::cout << "running on file " << chEl->GetTitle() << std::endl;
		TFile* myfile = new TFile(dirname + chEl->GetTitle());
		if (!myfile) {
			if (verbose) std::cout << "File " << chEl->GetTitle() << " does not exist" << std::endl;
			continue;
		}

		if (verbose) std::cout << "Loading directory cutFlowAnalyzer" << std::endl;
		myfile->cd("cutFlowAnalyzer");

		TTree *t = (TTree*)myfile->Get("cutFlowAnalyzer/Events");
		if (!t) {
			if (verbose) std::cout << "Tree cutFlowAnalyzer/Events does not exist" << std::endl;
			continue;
		}

		if (verbose) cout<<"  Events  "<<t->GetEntries()<<endl;

		//Pull variables from nTuple
		//{{{
		// Event info
		t->SetBranchAddress("event", &event);
		t->SetBranchAddress("run",   &run);
		t->SetBranchAddress("lumi",  &lumi);

		// GEN Level Selectors
		t->SetBranchAddress("is4GenMu",    &is4GenMu);
		t->SetBranchAddress("is1GenMu17",  &is1GenMu17);
		t->SetBranchAddress("is2GenMu8",   &is2GenMu8);
		t->SetBranchAddress("is3GenMu8",   &is3GenMu8);
		t->SetBranchAddress("is4GenMu8",   &is4GenMu8);

		// RECO Level Selectors
		t->SetBranchAddress("is1SelMu17",                     &is1SelMu17);
		t->SetBranchAddress("is2SelMu8",                      &is2SelMu8);
		t->SetBranchAddress("is3SelMu8",                      &is3SelMu8);
		t->SetBranchAddress("is4SelMu8",                      &is4SelMu8);

		t->SetBranchAddress("is2MuJets",                      &is2MuJets);
		t->SetBranchAddress("is2DiMuons",                     &is2DiMuons);
		t->SetBranchAddress("is2DiMuonsFittedVtxOK",          &is2DiMuonsFittedVtxOK);
		t->SetBranchAddress("is2DiMuonsDzOK_FittedVtx",       &is2DiMuonsDzOK_FittedVtx);
		t->SetBranchAddress("isDiMuonHLTFired",               &isDiMuonHLTFired);
		t->SetBranchAddress("is2DiMuonsMassOK_FittedVtx",     &is2DiMuonsMassOK_FittedVtx);
		t->SetBranchAddress("is2DiMuonsIsoTkOK_FittedVtx",    &is2DiMuonsIsoTkOK_FittedVtx);
		t->SetBranchAddress("isVertexOK",                     &isVertexOK);
		t->SetBranchAddress("isDiMuonHLTFired",              &isDiMuonHLTFired);

		t->SetBranchAddress("genA0_Lxy", &genA0_Lxy);
		t->SetBranchAddress("genA0_Lz",  &genA0_Lz);
		t->SetBranchAddress("genA1_Lxy", &genA1_Lxy);
		t->SetBranchAddress("genA1_Lz",  &genA1_Lz);

		t->SetBranchAddress("diMuonC_m1_FittedVtx_hitpix", &diMuonC_m1_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonC_m2_FittedVtx_hitpix", &diMuonC_m2_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonF_m1_FittedVtx_hitpix", &diMuonF_m1_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonF_m2_FittedVtx_hitpix", &diMuonF_m2_FittedVtx_hitpix);

		t->SetBranchAddress("genA1_phi",&genA1_phi);
		t->SetBranchAddress("genA1_eta",&genA1_eta);

		t->SetBranchAddress("genA0_phi",&genA0_phi);
		t->SetBranchAddress("genA0_eta",&genA0_eta);

		t->SetBranchAddress("selMu0_phi",&selMu0_phi);
		t->SetBranchAddress("selMu1_phi",&selMu1_phi);
		t->SetBranchAddress("selMu2_phi",&selMu2_phi);
		t->SetBranchAddress("selMu3_phi",&selMu3_phi);

		t->SetBranchAddress("selMu0_eta",&selMu0_eta);
		t->SetBranchAddress("selMu1_eta",&selMu1_eta);
		t->SetBranchAddress("selMu2_eta",&selMu2_eta);
		t->SetBranchAddress("selMu3_eta",&selMu3_eta);

		t->SetBranchAddress("genA0_m" , &genA0_m);
		t->SetBranchAddress("genA0_px", &genA0_px);
		t->SetBranchAddress("genA0_py", &genA0_py);
		t->SetBranchAddress("genA0_pz", &genA0_pz);

		t->SetBranchAddress("genA1_m" , &genA1_m);
		t->SetBranchAddress("genA1_px", &genA1_px);
		t->SetBranchAddress("genA1_py", &genA1_py);
		t->SetBranchAddress("genA1_pz", &genA1_pz);

		t->SetBranchAddress("diMuonF_FittedVtx_m", &diMuonF_FittedVtx_m);
		t->SetBranchAddress("diMuonF_FittedVtx_px", &diMuonF_FittedVtx_px);
		t->SetBranchAddress("diMuonF_FittedVtx_py", &diMuonF_FittedVtx_py);
		t->SetBranchAddress("diMuonF_FittedVtx_pz", &diMuonF_FittedVtx_pz);
		t->SetBranchAddress("diMuonF_FittedVtx_eta",&diMuonF_FittedVtx_eta);
		t->SetBranchAddress("diMuonF_FittedVtx_phi",&diMuonF_FittedVtx_phi);
		t->SetBranchAddress("diMuonF_FittedVtx_Lxy",&diMuonF_FittedVtx_Lxy);
		t->SetBranchAddress("diMuonF_FittedVtx_L",&diMuonF_FittedVtx_L);

		t->SetBranchAddress("diMuonC_FittedVtx_m", &diMuonC_FittedVtx_m);
		t->SetBranchAddress("diMuonC_FittedVtx_px", &diMuonC_FittedVtx_px);
		t->SetBranchAddress("diMuonC_FittedVtx_py", &diMuonC_FittedVtx_py);
		t->SetBranchAddress("diMuonC_FittedVtx_pz", &diMuonC_FittedVtx_pz);
		t->SetBranchAddress("diMuonC_FittedVtx_eta",&diMuonC_FittedVtx_eta);
		t->SetBranchAddress("diMuonC_FittedVtx_phi",&diMuonC_FittedVtx_phi);
		t->SetBranchAddress("diMuonC_FittedVtx_Lxy",&diMuonC_FittedVtx_Lxy);
		t->SetBranchAddress("diMuonC_FittedVtx_L",&diMuonC_FittedVtx_L);

		t->SetBranchAddress("genA0Mu0_eta",&genA0Mu0_eta);
		t->SetBranchAddress("genA1Mu0_eta",&genA1Mu0_eta);
		t->SetBranchAddress("genA0Mu1_eta",&genA0Mu1_eta);
		t->SetBranchAddress("genA1Mu1_eta",&genA1Mu1_eta);

		t->SetBranchAddress("genA0Mu0_phi",&genA0Mu0_phi);
		t->SetBranchAddress("genA1Mu0_phi",&genA1Mu0_phi);
		t->SetBranchAddress("genA0Mu1_phi",&genA0Mu1_phi);
		t->SetBranchAddress("genA1Mu1_phi",&genA1Mu1_phi);

		t->SetBranchAddress("genA0Mu0_px",&genA0Mu0_px);
		t->SetBranchAddress("genA1Mu0_px",&genA1Mu0_px);
		t->SetBranchAddress("genA0Mu1_px",&genA0Mu1_px);
		t->SetBranchAddress("genA1Mu1_px",&genA1Mu1_px);

		t->SetBranchAddress("genA0Mu0_py",&genA0Mu0_py);
		t->SetBranchAddress("genA1Mu0_py",&genA1Mu0_py);
		t->SetBranchAddress("genA0Mu1_py",&genA0Mu1_py);
		t->SetBranchAddress("genA1Mu1_py",&genA1Mu1_py);

		t->SetBranchAddress("genA0_vx", &genA0_vx); 
		t->SetBranchAddress("genA0_vy", &genA0_vy);
		t->SetBranchAddress("genA0_vz", &genA0_vz);

		t->SetBranchAddress("genA1_vx", &genA1_vx);
		t->SetBranchAddress("genA1_vy", &genA1_vy);
		t->SetBranchAddress("genA1_vz", &genA1_vz);

		t->SetBranchAddress("genA0Mu0_vx", &genA0Mu0_vx);
		t->SetBranchAddress("genA0Mu1_vx", &genA0Mu1_vx);
		t->SetBranchAddress("genA1Mu0_vx", &genA1Mu0_vx);
		t->SetBranchAddress("genA1Mu1_vx", &genA1Mu1_vx);

		t->SetBranchAddress("genA0Mu0_vy", &genA0Mu0_vy);
		t->SetBranchAddress("genA0Mu1_vy", &genA0Mu1_vy);
		t->SetBranchAddress("genA1Mu0_vy", &genA1Mu0_vy);
		t->SetBranchAddress("genA1Mu1_vy", &genA1Mu1_vy);

		t->SetBranchAddress("genA0Mu0_vz", &genA0Mu0_vz);
		t->SetBranchAddress("genA0Mu1_vz", &genA0Mu1_vz);
		t->SetBranchAddress("genA1Mu0_vz", &genA1Mu0_vz);
		t->SetBranchAddress("genA1Mu1_vz", &genA1Mu1_vz);

		t->SetBranchAddress("diMuonC_FittedVtx_vx", &diMuonC_FittedVtx_vx);
		t->SetBranchAddress("diMuonC_FittedVtx_vy", &diMuonC_FittedVtx_vy);
		t->SetBranchAddress("diMuonC_FittedVtx_vz", &diMuonC_FittedVtx_vz);

		t->SetBranchAddress("diMuonF_FittedVtx_vx", &diMuonF_FittedVtx_vx);
		t->SetBranchAddress("diMuonF_FittedVtx_vy", &diMuonF_FittedVtx_vy);
		t->SetBranchAddress("diMuonF_FittedVtx_vz", &diMuonF_FittedVtx_vz);
		//}}}

		for(int k=0;k<t->GetEntries();k++){
			t->GetEntry(k);
 double pT_00 = sqrt(genA0Mu0_px*genA0Mu0_px + genA0Mu0_py*genA0Mu0_py);
 double pT_01 = sqrt(genA0Mu1_px*genA0Mu1_px + genA0Mu1_py*genA0Mu1_py);
 double pT_10 = sqrt(genA1Mu0_px*genA1Mu0_px + genA1Mu0_py*genA1Mu0_py);
 double pT_11 = sqrt(genA1Mu1_px*genA1Mu1_px + genA1Mu1_py*genA1Mu1_py);

double leadingPt = 0;
double leadingEta = 0;

if(pT_00 >= pT_01 && pT_00 >= pT_10 && pT_00 >= pT_11){ //00 is leading mu
leadingPt = pT_00;
leadingEta = genA0Mu0_eta;
}
if(pT_01 >= pT_00 && pT_01 >= pT_10 && pT_01 >= pT_11){ //01 is leading mu
leadingPt = pT_01;
leadingEta = genA0Mu1_eta;
}
if(pT_10 >= pT_00 && pT_10 >= pT_01 && pT_10 >= pT_11){ //10 is leading mu
leadingPt = pT_10;
leadingEta = genA1Mu0_eta;
}
if(pT_11 >= pT_00 && pT_11 >= pT_10 && pT_11 >= pT_01){ //11 is leading mu
leadingPt = pT_11;
leadingEta = genA1Mu1_eta;
}


			etaDen->Fill(leadingEta);
			pTDen->Fill(leadingPt);
			if(isDiMuonHLTFired == 1){ 
				etaNum->Fill(leadingEta);
				pTNum->Fill(leadingPt);
			}
		} // closing for loop
		myfile->Close();
	} // closing while loop
	//Print out cutflow table
	//Fill ratio reco/gen vectors to be plotted  
	//Prepare plots and plot variables.  Also Fill final information printout vectors
}
Пример #5
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;
}
Пример #6
0
Файл: scan.C Проект: aminnj/WZ
// float scan(unsigned int njetsCut=0, int btagCut=9999, TString tag="", float manualScale=-1.0){
int scan(unsigned int njetsLow=0, unsigned int njetsHigh=9999, int btagCut=9999, int metLow=0, int metHigh=9999, int htLow=0, int htHigh=9999, TString tag=""){
    //njetsLow, njetsHigh, btagCut, metLow, metHigh, htLow, htHigh, tag, manualScale
    //

    // TH1F* h1D_dummy_data = new TH1F("dummy", "dummyhisto", 10, 0, 10); 

    TH1F* h1D_njets_data = new TH1F("njets", "", 15, 0, 15); 
    TH1F* h1D_ht_data = new TH1F("ht", "", 20, 0, 600); 
    TH1F* h1D_met_data = new TH1F("met", "", 20, 0, 300); 
    TH1F* h1D_mt_data = new TH1F("mt", "", 20, 0, 400); 
    TH1F* h1D_mtW_data = new TH1F("mtW", "", 40, 0, 200); 
    TH1F* h1D_zmass_data = new TH1F("zmass", "", 42, 70, 112); 
    TH1F* h1D_lepeta_data = new TH1F("lepeta", "", 50, -3.0, 3.0); 
    TH1F* h1D_leppt_data = new TH1F("leppt", "", 50, 0, 150); 
    TH1F* h1D_Wleppt_data = new TH1F("Wleppt", "", 30, 0, 150); 

    TH1F* h1D_nbtags_data = new TH1F("nbtags", "", 15, 0, 15); 
    TH1F* h1D_btagval_data = new TH1F("btagval", "", 20, 0, 1); 
    TH1F* h1D_ptZ_data = new TH1F("ptZ", "", 25, 0, 400);
    TH1F* h1D_st_data = new TH1F("st", "", 25, 100, 800);
    TH1F* h1D_minRLeadingJet_data = new TH1F("minRLeadingJet", "",10,0,5);
    TH1F* h1D_ptj1_data = new TH1F("ptj1", "", 25, 0, 300);
    TH1F* h1D_ptj2_data = new TH1F("ptj2", "", 25, 0, 300);
    TH1F* h1D_massZj1_data = new TH1F("massZj1", "", 25, 100, 600);
    TH1F* h1D_massZj2_data = new TH1F("massZj2", "", 25, 100, 600);
    TH1F* h1D_ptjj_data = new TH1F("ptjj", "", 25, 0, 400);
    TH1F* h1D_massjj_data = new TH1F("massjj", "", 25, 0, 600);

    TH1F* h1D_mtWeemu_data = new TH1F("mtWeem", "", 40, 0, 200); 
    TH1F* h1D_mtWmumue_data = new TH1F("mtWmme", "", 40, 0, 200); 
    TH1F* h1D_mtWeee_data = new TH1F("mtWeee", "", 40, 0, 200); 
    TH1F* h1D_mtWmumumu_data = new TH1F("mtWmmm", "", 40, 0, 200); 
    TH1F* h1D_lepetae_data = new TH1F("lepetae", "", 50, -3.0, 3.0); 
    TH1F* h1D_lepetamu_data = new TH1F("lepetamu", "", 50, -3.0, 3.0); 

    float luminosity = 19.407;
    float ptCut = 20; // threshold for "high-pT" in AN
    float zmassCut = 15; // line 212 of AN
    float btagDiscriminant = 0.679; // line 230 of AN

    map<int, vector<int> > runLumi;
    cout << ">>> tag is " << tag << endl;
    cout << ">>> excluding events with #btaggedjets>= " << btagCut << endl;
    cout << ">>> considering events with njets in [" << njetsLow << "," << njetsHigh << "]" << endl;
    cout << ">>> considering events with met in [" << metLow << "," << metHigh << "]" << endl;
    cout << ">>> considering events with ht in [" << htLow << "," << htHigh << "]" << endl;
    // cout << ">>> manualScale is " << manualScale << endl;
    // DATADATA
    {
        initCounter();

        clear_seen();

        TChain *ch = new TChain("tree");

        ch->Add("/home/users/namin/sandbox/condorTest/output/baby_2012ABCD.root");

        int nEventsTotal = ch->GetEntries();
        int nEventsSoFar = 0;
        int nGoodEvents = 0;
        float scale = 1.0;

        TFile *currentFile = 0;
        TObjArray *listOfFiles = ch->GetListOfFiles();
        TIter fileIter(listOfFiles);

        // File Loop
        while ( (currentFile = (TFile*)fileIter.Next()) ) { 
            TFile *file = new TFile( currentFile->GetTitle() );
            TTree *tree = (TTree*)file->Get("tree");
            cms2.Init(tree);
            // Set Good Run List
            if(evt_isRealData()) set_goodrun_file("final_19p49fb_cms2.txt");

            TString filename(currentFile->GetTitle());

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

                // if(event > 30000) break;

                // Get Event Content
                cms2.GetEntry(event);
                nEventsSoFar++;

                // Progress
                CMS2::progress( nEventsSoFar, nEventsTotal );

                // Select Good Runs
                if( evt_isRealData() && !goodrun( evt_run(), evt_lumiBlock() ) ) continue;

                if(evt_isRealData()){
                    DorkyEventIdentifier id = { evt_run(), evt_event(), evt_lumiBlock() };
                    if ( is_duplicate(id) ){
                        continue;
                    }
                }

                std::vector<LorentzVector> goodEls;
                std::vector<LorentzVector> goodMus;
                std::vector<JetStruct> maybeGoodJets;
                std::vector<JetStruct> goodJets;
                std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
                std::map<int, int> goodToP4MapMu;

                pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
                float met = p.first;
                float metPhi = p.second;
                // float met = pfmet_type1cor();
                // float metPhi = metphi();


                if(met < metLow || met > metHigh) continue;

                // make electron quality cuts
                for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                    if(!looseEl().at(iEl)) continue;
                    if(els_p4().at(iEl).pt() < ptCut) continue;
                    if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                    goodToP4MapEl[goodEls.size()] = iEl;
                    goodEls.push_back(els_p4().at(iEl));


                }
                // mirror for muons
                for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                    if(!looseMu().at(iMu)) continue;
                    if(mus_p4().at(iMu).pt() < ptCut) continue;
                    if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                    goodToP4MapMu[goodMus.size()] = iMu;
                    goodMus.push_back(mus_p4().at(iMu));

                }

                // require that we have 3 good leptons
                if(goodMus.size() + goodEls.size() != 3) continue;

                // select good jets
                for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                    if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                    if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                    if (!passesLoosePFJetID().at(iJet)) continue;

                    JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                    myJet.jet = pfjets_p4().at(iJet);
                    myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                    myJet.idx = iJet;

                    maybeGoodJets.push_back(myJet);
                }

                vector<int> closestJetsMu; 
                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsMu.push_back(iClosestJet);
                    }
                }
                vector<int> closestJetsEl; 
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    double mindR = 999.0;
                    int iClosestJet = -1;
                    for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                        double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                        if( dR < min(mindR, 0.4) ) {
                            mindR = dR;
                            iClosestJet = iJet;
                        }
                    }
                    if(iClosestJet != -1) {
                        closestJetsEl.push_back(iClosestJet);
                    }
                }
                float ht = 0;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    bool tooClose = false;
                    for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                        if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                    }
                    for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                        if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                    }
                    if(tooClose) continue;

                    goodJets.push_back(maybeGoodJets.at(iJet));
                    ht += maybeGoodJets.at(iJet).pt;
                }


                if(ht < htLow || ht > htHigh) continue;



                vector<int> pair = findZPair(goodEls, goodMus);
                vector<LorentzVector> leps;
                float mtW = 0.0, mass = 0.0;
                if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                        pair[3] != -1 && pair[4] != -1 ) {
                    if(pair[0] == 0) { // el
                        mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                        leps.push_back(goodEls.at(pair[1]));
                        leps.push_back(goodEls.at(pair[2]));
                    } else { // mu
                        mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                        leps.push_back(goodMus.at(pair[1]));
                        leps.push_back(goodMus.at(pair[2]));
                    }

                    if(pair[3] == 0) { // W lep is el
                        if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                        leps.push_back(goodEls.at(pair[4]));

                        mtW = MT(goodEls.at(pair[4]), met, metPhi);

                    } else { // W lep is mu
                        if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                        leps.push_back(goodMus.at(pair[4]));

                        mtW = MT(goodMus.at(pair[4]), met, metPhi);

                    }
                } else {
                    cout << "shouldn't end up with pair[i] == -1" << endl;
                }


                // XXX
                if(abs(mass - 91.2) > zmassCut) continue;
                if(goodJets.size() < njetsLow ||
                        goodJets.size() > njetsHigh ) continue;


                int nbtags = 0;
                float minRLeadingJet = 9999.0;
                std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
                for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                    float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                    if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                    // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                    float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                    fill(h1D_btagval_data, btagval, scale);
                    // fill(h1D_btagval_data, btagval, scale);

                    if(btagval > btagDiscriminant) {
                        nbtags++;
                    }
                }

                if(nbtags >= btagCut) continue; // FIXME


                // fill(h1D_dummy_data, 5.0,scale);

                // We are now in the region of interest


                for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                    fill(h1D_leppt_data,goodMus.at(iMu).pt(), scale);
                    fill(h1D_lepeta_data, goodMus.at(iMu).eta(), scale);
                    fill(h1D_lepetamu_data, goodMus.at(iMu).eta(), scale);
                }
                for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                    fill(h1D_leppt_data,goodEls.at(iEl).pt(), scale);
                    fill(h1D_lepeta_data, goodEls.at(iEl).eta(), scale);
                    fill(h1D_lepetae_data, goodEls.at(iEl).eta(), scale);
                }




                // FIXME
                if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                    mtW = MT(goodEls[0], met, metPhi);
                    fill(h1D_mtWmumue_data, mtW, scale);


                } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                    mtW = MT(goodMus[0], met, metPhi);
                    fill(h1D_mtWeemu_data, mtW, scale);


                } else { 
                    if(goodMus.size() == 3) { //mumumu
                        fill(h1D_mtWmumumu_data, mtW, scale);
                    } else { // eee
                        fill(h1D_mtWeee_data, mtW, scale);
                    }
                }


                double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
                float ptZ = (leps[0]+leps[1]).pt();
                float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

                fill(h1D_ptZ_data, ptZ, scale);
                fill(h1D_Wleppt_data,leps[2].pt(), scale);
                if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_data, minRLeadingJet, scale);
                fill(h1D_st_data, st, scale);
                fill(h1D_mt_data,mt, scale);
                fill(h1D_mtW_data, mtW, scale);
                fill(h1D_zmass_data,mass, scale); 
                fill(h1D_njets_data,goodJets.size(), scale);
                fill(h1D_ht_data,ht, scale);
                fill(h1D_met_data,met, scale);
                fill(h1D_nbtags_data, nbtags, scale);

                nGoodEvents++;
                addToCounter(filename, scale);

                if(goodJets.size() < 1) continue;

                float ptj1 = goodJets[0].pt;
                float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptj1_data, ptj1, scale);
                fill(h1D_massZj1_data, massZj1, scale);

                if(goodJets.size() < 2) continue;

                float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
                float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
                float ptj2 = goodJets[1].pt;
                float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

                fill(h1D_ptjj_data, ptjj, scale);
                fill(h1D_massjj_data, massjj, scale);
                fill(h1D_ptj2_data, ptj2, scale);
                fill(h1D_massZj2_data, massZj2, scale);



            }//event loop

        }//file loop


        std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
        std::cout << "ASDF DATA " << tag << " " << nGoodEvents << std::endl;

        // std::cout << "This dataset (A+B+C+D) has 19.4 fb^-1 of data" << std::endl;
        // std::cout << " nGoodEvents scaled to 1/fb: " << nGoodEvents*(1.0/luminosity) << std::endl;
        // std::cout << " nGoodEvents scaled to 19.4/fb: " << nGoodEvents*(19.4/luminosity) << std::endl;

        printCounter();


    } // DATADATA

    // MCMC
    TChain *ch = new TChain("tree");

    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WZ.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_ZZJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_DYJetsToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TBZToLL.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTJets.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_TTW.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_VVV.root");
    ch->Add("/home/users/namin/sandbox/condorTest/output/baby_WJetsToLNu.root");

    int nEventsTotal = ch->GetEntries();
    int nEventsSoFar = 0;
    int nGoodEvents = 0;
    float nGoodEventsWeighted = 0;

    TFile *currentFile = 0;
    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);


    // vector<TH1F*> h1D_dummy_vec;

    vector<TH1F*> h1D_njets_vec;
    vector<TH1F*> h1D_ht_vec;
    vector<TH1F*> h1D_met_vec;
    vector<TH1F*> h1D_mt_vec;
    vector<TH1F*> h1D_mtW_vec;
    vector<TH1F*> h1D_zmass_vec;
    vector<TH1F*> h1D_lepeta_vec;
    vector<TH1F*> h1D_leppt_vec;
    vector<TH1F*> h1D_Wleppt_vec;

    // btag+jet stuff
    vector<TH1F*> h1D_nbtags_vec;
    vector<TH1F*> h1D_btagval_vec;
    vector<TH1F*> h1D_ptZ_vec;
    vector<TH1F*> h1D_st_vec;
    vector<TH1F*> h1D_minRLeadingJet_vec;
    vector<TH1F*> h1D_ptj1_vec;
    vector<TH1F*> h1D_ptj2_vec;
    vector<TH1F*> h1D_massZj1_vec;
    vector<TH1F*> h1D_massZj2_vec;
    vector<TH1F*> h1D_ptjj_vec;
    vector<TH1F*> h1D_massjj_vec;

    // w mt debugging
    vector<TH1F*> h1D_mtWeemu_vec;
    vector<TH1F*> h1D_mtWmumue_vec;
    vector<TH1F*> h1D_mtWeee_vec;
    vector<TH1F*> h1D_mtWmumumu_vec;
    vector<TH1F*> h1D_lepetae_vec;
    vector<TH1F*> h1D_lepetamu_vec;

    vector<TH1F*> h1D_test_mete_vec;
    vector<TH1F*> h1D_test_dphie_vec;
    vector<TH1F*> h1D_test_pte_vec;

    vector<TH1F*> h1D_test_metm_vec;
    vector<TH1F*> h1D_test_dphim_vec;
    vector<TH1F*> h1D_test_ptm_vec;

    vector<TH1F*> h1D_test_dphinu_vec;

    vector<TH1F*> h1D_gen_dR_vec;
    vector<TH1F*> h1D_gen_id_vec;

    vector<TH1F*> h1D_metphie_vec;
    vector<TH1F*> h1D_metphim_vec;


    initCounter();
    TH1D* error = new TH1D("error","",1,0,1);
    // error->Sumw2();

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

        // Get File Content
        TFile *file = new TFile( currentFile->GetTitle() );
        TTree *tree = (TTree*)file->Get("tree");
        cms2.Init(tree);

        iFile++; 
        TString filename(currentFile->GetTitle());


        // TH1F* h1D_dummy_file = new TH1F("dummy"+filename, "dummyhisto", 10, 0, 10); 

        TH1F* h1D_njets_file = new TH1F("njets"+filename, "Njets;;Entries", 15, 0, 15); 
        TH1F* h1D_ht_file = new TH1F("ht"+filename, "H_{T};GeV;Entries", 20, 0, 600); 
        TH1F* h1D_met_file = new TH1F("met"+filename, "#slash{E}_{T};GeV;Entries", 20, 0, 300); 
        TH1F* h1D_mt_file = new TH1F("mt"+filename, "M_{T};GeV;Entries", 20, 0, 400); 
        TH1F* h1D_mtW_file = new TH1F("mtW"+filename, "W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_zmass_file = new TH1F("zmass"+filename, "Z Mass;GeV;Entries", 42, 70, 112); 
        TH1F* h1D_lepeta_file = new TH1F("lepeta"+filename, "lepton #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_leppt_file = new TH1F("leppt"+filename, "lepton p_{T};p_{T} [GeV];Entries", 50, 0, 150); 
        TH1F* h1D_Wleppt_file = new TH1F("Wleppt"+filename, "W lepton p_{T};p_{T} [GeV];Entries", 30, 0, 150); 

        TH1F* h1D_nbtags_file = new TH1F("nbtags"+filename, "N btagged jets;;Entries", 15, 0, 15); 
        TH1F* h1D_btagval_file = new TH1F("btagval"+filename, "Value of csv bjet tag;;Entries", 20, 0, 1); 
        TH1F* h1D_ptZ_file = new TH1F("ptZ"+filename, "Z p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_st_file = new TH1F("st"+filename, "S_{T}=H_{T}+#Sigma p_{T,leps}+#slash{E}_{T};S_{T} [GeV];Entries", 25, 100, 800);
        TH1F* h1D_minRLeadingJet_file = new TH1F("minRLeadingJet"+filename, "Minimum dR between jet 1 and another jet",10,0,5);
        TH1F* h1D_ptj1_file = new TH1F("ptj1"+filename, "j1 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_ptj2_file = new TH1F("ptj2"+filename, "j2 p_{T};[GeV];Entries", 25, 0, 300);
        TH1F* h1D_massZj1_file = new TH1F("massZj1"+filename, "Zj1 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_massZj2_file = new TH1F("massZj2"+filename, "Zj2 mass;[GeV];Entries", 25, 100, 600);
        TH1F* h1D_ptjj_file = new TH1F("ptjj"+filename, "j1j2 p_{T};[GeV];Entries", 25, 0, 400);
        TH1F* h1D_massjj_file = new TH1F("massjj"+filename, "j1j2 mass;[GeV];Entries", 25, 0, 600);

        TH1F* h1D_mtWeemu_file = new TH1F("mtWeem"+filename, "ee#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumue_file = new TH1F("mtWmme"+filename, "#mu#mue W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWeee_file = new TH1F("mtWeee"+filename, "eee W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_mtWmumumu_file = new TH1F("mtWmmm"+filename, "#mu#mu#mu W lep M_{T};GeV;Entries", 40, 0, 200); 
        TH1F* h1D_lepetae_file = new TH1F("lepetae"+filename, "e #eta;#eta;Entries", 50, -3.0, 3.0); 
        TH1F* h1D_lepetamu_file = new TH1F("lepetamu"+filename, "#mu #eta;#eta;Entries", 50, -3.0, 3.0); 

        TH1F* h1D_test_mete_file = new TH1F("testmete"+filename, "met for e;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphie_file = new TH1F("testphie"+filename, "dphi(met,e);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_pte_file = new TH1F("testpte"+filename, "pt for e;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_metm_file = new TH1F("testmetm"+filename, "met for mu;GeV;Entries", 40, 0, 200); 
        TH1F* h1D_test_dphim_file = new TH1F("testphim"+filename, "dphi(met,mu);;Entries", 40, 0, M_PI+0.1); 
        TH1F* h1D_test_ptm_file = new TH1F("testptm"+filename, "pt for mu;GeV;Entries", 40, 0, 200); 

        TH1F* h1D_test_dphinu_file = new TH1F("testphinu"+filename, "dphi(W lep,gen nu);;Entries", 40, 0, M_PI+0.1); 

        TH1F* h1D_gen_dR_file = new TH1F("gendr"+filename, "#DeltaR between reco W lepton and closest gen lepton", 60, 0, 0.4); 
        TH1F* h1D_gen_id_file = new TH1F("genid"+filename, "abs(mother id) for gen particle matched to reco W lept;;Entries", 40, 0, 40); 

        TH1F* h1D_metphie_file = new TH1F("metphie"+filename, "metphi for e from W;;Entries", 30, -3.2, 3.2); 
        TH1F* h1D_metphim_file = new TH1F("metphim"+filename, "metphi for m from W;;Entries", 30, -3.2, 3.2); 

        h1D_njets_vec.push_back(h1D_njets_file); 
        h1D_ht_vec.push_back(h1D_ht_file); 
        h1D_met_vec.push_back(h1D_met_file); 
        h1D_mt_vec.push_back(h1D_mt_file); 
        h1D_mtW_vec.push_back(h1D_mtW_file); 
        h1D_zmass_vec.push_back(h1D_zmass_file); 
        h1D_lepeta_vec.push_back(h1D_lepeta_file);
        h1D_leppt_vec.push_back(h1D_leppt_file); 
        h1D_Wleppt_vec.push_back(h1D_Wleppt_file); 

        h1D_nbtags_vec.push_back(h1D_nbtags_file);
        h1D_btagval_vec.push_back(h1D_btagval_file);
        h1D_ptZ_vec.push_back(h1D_ptZ_file);
        h1D_st_vec.push_back(h1D_st_file);
        h1D_minRLeadingJet_vec.push_back(h1D_minRLeadingJet_file);
        h1D_ptj1_vec.push_back(h1D_ptj1_file);
        h1D_ptj2_vec.push_back(h1D_ptj2_file);
        h1D_massZj1_vec.push_back(h1D_massZj1_file);
        h1D_massZj2_vec.push_back(h1D_massZj2_file);
        h1D_ptjj_vec.push_back(h1D_ptjj_file);
        h1D_massjj_vec.push_back(h1D_massjj_file);

        h1D_mtWeemu_vec.push_back(h1D_mtWeemu_file);
        h1D_mtWmumue_vec.push_back(h1D_mtWmumue_file);
        h1D_mtWeee_vec.push_back(h1D_mtWeee_file);
        h1D_mtWmumumu_vec.push_back(h1D_mtWmumumu_file);
        h1D_lepetae_vec.push_back(h1D_lepetae_file);
        h1D_lepetamu_vec.push_back(h1D_lepetamu_file);

        h1D_test_mete_vec.push_back(h1D_test_mete_file);
        h1D_test_dphie_vec.push_back(h1D_test_dphie_file);
        h1D_test_pte_vec.push_back(h1D_test_pte_file);

        h1D_test_metm_vec.push_back(h1D_test_metm_file);
        h1D_test_dphim_vec.push_back(h1D_test_dphim_file);
        h1D_test_ptm_vec.push_back(h1D_test_ptm_file);

        h1D_test_dphinu_vec.push_back(h1D_test_dphinu_file);

        h1D_gen_dR_vec.push_back(h1D_gen_dR_file);
        h1D_gen_id_vec.push_back(h1D_gen_id_file);

        h1D_metphie_vec.push_back(h1D_metphie_file);
        h1D_metphim_vec.push_back(h1D_metphim_file);

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

            // if(event > 30000) break;

            // Get Event Content
            cms2.GetEntry(event);
            nEventsSoFar++;

            if(event == 0) {
                std::cout << " evt_scale1fb(): " << evt_scale1fb() << " filename: " << filename << std::endl;
            }
            // Progress
            CMS2::progress( nEventsSoFar, nEventsTotal );

            std::vector<LorentzVector> goodEls;
            std::vector<LorentzVector> goodMus;
            std::vector<JetStruct> maybeGoodJets;
            std::vector<JetStruct> goodJets;
            std::map<int, int> goodToP4MapEl; // map indices in good{Els,Mus} to {els,mus}_p4 indices
            std::map<int, int> goodToP4MapMu;

            float scale = evt_scale1fb()  * luminosity;

            pair<float,float> p = getPhiCorrMET(pfmet_type1cor(), metphi(), evt_nvtxs(), evt_isRealData());
            float met = p.first;
            float metPhi = p.second;


            if(met < metLow || met > metHigh) continue;

            // make electron quality cuts
            for(unsigned int iEl = 0; iEl < els_p4().size(); iEl++) {

                if(!looseEl().at(iEl)) continue;
                if(els_p4().at(iEl).pt() < ptCut) continue;
                if(fabs(els_p4().at(iEl).eta()) > 2.4) continue;

                goodToP4MapEl[goodEls.size()] = iEl;
                goodEls.push_back(els_p4().at(iEl));


            }
            // mirror for muons
            for(unsigned int iMu = 0; iMu < mus_p4().size(); iMu++) {

                if(!looseMu().at(iMu)) continue;
                if(mus_p4().at(iMu).pt() < ptCut) continue;
                if(fabs(mus_p4().at(iMu).eta()) > 2.4) continue;

                goodToP4MapMu[goodMus.size()] = iMu;
                goodMus.push_back(mus_p4().at(iMu));

            }

            // require that we have 3 good leptons
            if(goodMus.size() + goodEls.size() != 3) continue;

            // select good jets
            for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < 40) continue;
                if (fabs(pfjets_p4().at(iJet).eta()) > 2.4) continue;
                if (!passesLoosePFJetID().at(iJet)) continue;

                JetStruct myJet = {*(new LorentzVector()), 0.0, -1};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.pt = pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet);
                myJet.idx = iJet;

                maybeGoodJets.push_back(myJet);
            }

            vector<int> closestJetsMu; 
            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodMus.at(iMu),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsMu.push_back(iClosestJet);
                }
            }
            vector<int> closestJetsEl; 
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                double mindR = 999.0;
                int iClosestJet = -1;
                for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                    double dR = deltaR(goodEls.at(iEl),maybeGoodJets.at(iJet).jet);
                    if( dR < min(mindR, 0.4) ) {
                        mindR = dR;
                        iClosestJet = iJet;
                    }
                }
                if(iClosestJet != -1) {
                    closestJetsEl.push_back(iClosestJet);
                }
            }
            float ht = 0;
            for(unsigned int iJet = 0; iJet < maybeGoodJets.size(); iJet++) {
                bool tooClose = false;
                for(unsigned int iMu = 0; iMu < closestJetsMu.size(); iMu++) {
                    if(iJet == closestJetsMu.at(iMu)) tooClose = true;
                }
                for(unsigned int iEl = 0; iEl < closestJetsEl.size(); iEl++) {
                    if(iJet == closestJetsEl.at(iEl)) tooClose = true;
                }
                if(tooClose) continue;

                goodJets.push_back(maybeGoodJets.at(iJet));
                ht += maybeGoodJets.at(iJet).pt;
            }


            if(ht < htLow || ht > htHigh) continue;

            vector<int> pair = findZPair(goodEls, goodMus);
            vector<LorentzVector> leps;
            float mtW = 0.0, mass = 0.0;
            if( pair[0] != -1 && pair[1] != -1 && pair[2] != -1 && 
                    pair[3] != -1 && pair[4] != -1 ) {
                if(pair[0] == 0) { // el
                    mass += (goodEls.at(pair[1])+goodEls.at(pair[2])).mass();
                    leps.push_back(goodEls.at(pair[1]));
                    leps.push_back(goodEls.at(pair[2]));
                } else { // mu
                    mass += (goodMus.at(pair[1])+goodMus.at(pair[2])).mass();
                    leps.push_back(goodMus.at(pair[1]));
                    leps.push_back(goodMus.at(pair[2]));
                }

                if(pair[3] == 0) { // W lep is el
                    if( !tightEl().at(goodToP4MapEl[pair[4]]) ) continue;
                    leps.push_back(goodEls.at(pair[4]));

                    mtW = MT(goodEls.at(pair[4]), met, metPhi);

                } else { // W lep is mu
                    if( !tightMu().at(goodToP4MapMu[pair[4]]) ) continue;
                    leps.push_back(goodMus.at(pair[4]));

                    mtW = MT(goodMus.at(pair[4]), met, metPhi);

                }
            } else {
                cout << "shouldn't end up with pair[i] == -1" << endl;
            }


            // XXX
            if(abs(mass - 91.2) > zmassCut) continue;
            if(goodJets.size() < njetsLow ||
                    goodJets.size() > njetsHigh ) continue;


            int nbtags = 0;
            float minRLeadingJet = 9999.0;
            std::sort(goodJets.begin(), goodJets.end(), jetCompare); // sort jets in descending pt
            for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {

                float dR = deltaR(goodJets[iJet].jet, goodJets[0].jet);
                if(iJet != 0 && dR < minRLeadingJet) minRLeadingJet = dR;

                // float looseB = 0.244, mediumB = 0.679, tightB = 0.898;
                float btagval = pfjets_combinedSecondaryVertexBJetTag().at(goodJets[iJet].idx);
                fill(h1D_btagval_file, btagval, scale);
                // fill(h1D_btagval_file, btagval, scale);

                if(btagval > btagDiscriminant) {
                    nbtags++;
                }
            }

            if(nbtags >= btagCut) continue; // FIXME


            // We are now in the region of interest

            // try to match W lepton to genps
            float mindR = 9999.0;
            int brotherIdx = -1;
            for(unsigned int iLep = 0; iLep < genps_p4().size(); iLep++) {
                if( abs(genps_id().at(iLep)) != 11 && abs(genps_id().at(iLep)) != 13 ) continue;
                float dR = deltaR(genps_p4().at(iLep), leps[2]);
                if(dR <= mindR) {
                    mindR = dR;
                    brotherIdx = iLep;
                }

                // now try to find matching neutrino (id of same flavor neutrino = 1 + id of lepton)

                for(unsigned int iNu = 0; iNu < genps_p4().size(); iNu++) {
                    if( abs(genps_id().at(iNu)) == abs(genps_id().at(iLep)) + 1) {
                        // fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        fill(h1D_test_dphinu_file, deltaPhi(genps_p4().at(iNu).phi(), genps_p4().at(iLep).phi()), scale);
                        break;
                    }
                }

            }
            if(brotherIdx >= 0) {
                fill(h1D_gen_dR_file, mindR, scale);
                if(mindR < 0.15) {
                    fill(h1D_gen_id_file, abs(genps_id_mother().at(brotherIdx)), scale);
                }
            } else {
                // cout << "ERROR: " << mindR << " " << brotherIdx << " " << endl;
            }


            for(unsigned int iMu = 0; iMu < goodMus.size(); iMu++) {
                fill(h1D_leppt_file,goodMus.at(iMu).pt(), scale);
                fill(h1D_lepeta_file, goodMus.at(iMu).eta(), scale);
                fill(h1D_lepetamu_file, goodMus.at(iMu).eta(), scale);
            }
            for(unsigned int iEl = 0; iEl < goodEls.size(); iEl++) {
                fill(h1D_leppt_file,goodEls.at(iEl).pt(), scale);
                fill(h1D_lepeta_file, goodEls.at(iEl).eta(), scale);
                fill(h1D_lepetae_file, goodEls.at(iEl).eta(), scale);
            }




            // FIXME
            if(goodMus.size() == 2 && goodEls.size() == 1) { // mumue
                mtW = MT(goodEls[0], met, metPhi);
                fill(h1D_mtWmumue_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_mete_file, met);
                    float dphi = deltaPhi(metPhi,goodEls.at(0).phi());
                    // cout << "electron " << " metPhi: " << metPhi << " elphi: " << goodEls.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphie_file, dphi, scale);
                    fill(h1D_test_pte_file, goodEls.at(0).pt(), scale);
                    fill(h1D_metphie_file, metPhi, scale);
                }

            } else if(goodMus.size() == 1 && goodEls.size() == 2) { //eemu
                mtW = MT(goodMus[0], met, metPhi);
                fill(h1D_mtWeemu_file, mtW, scale);

                if(true || mtW < 40) { // XXX XXX XXX
                    fill(h1D_test_metm_file, met);
                    float dphi = deltaPhi(metPhi,goodMus.at(0).phi());
                    // cout << "muon     " << " metPhi: " << metPhi << " muphi: " << goodMus.at(0).phi() << " dphi: " << dphi << endl;
                    fill(h1D_test_dphim_file, dphi, scale);
                    fill(h1D_test_ptm_file, goodMus.at(0).pt(), scale);
                    fill(h1D_metphim_file, metPhi, scale);
                }

            } else { 
                if(goodMus.size() == 3) { //mumumu
                    fill(h1D_mtWmumumu_file, mtW, scale);
                } else { // eee
                    fill(h1D_mtWeee_file, mtW, scale);
                }
            }


            double mt = MT(leps[0]+leps[1]+leps[2], met, metPhi);
            float ptZ = (leps[0]+leps[1]).pt();
            float st = ht + leps[0].pt() + leps[1].pt() + leps[2].pt() + met;

            fill(h1D_ptZ_file, ptZ, scale);
            fill(h1D_Wleppt_file,leps[2].pt(), scale);
            if(minRLeadingJet < 9000) fill(h1D_minRLeadingJet_file, minRLeadingJet, scale);
            fill(h1D_st_file, st, scale);
            fill(h1D_mt_file,mt, scale);
            fill(h1D_mtW_file, mtW, scale);
            fill(h1D_zmass_file,mass, scale); 
            fill(h1D_njets_file,goodJets.size(), scale);
            fill(h1D_ht_file,ht, scale);
            fill(h1D_met_file,met, scale);
            fill(h1D_nbtags_file, nbtags, scale);

            error->Fill(0.5,scale);
            addToCounter(filename, scale);
            nGoodEvents++;
            nGoodEventsWeighted+=scale*1.0;

            if(goodJets.size() < 1) continue;

            float ptj1 = goodJets[0].pt;
            float massZj1 = (goodJets[0].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptj1_file, ptj1, scale);
            fill(h1D_massZj1_file, massZj1, scale);

            if(goodJets.size() < 2) continue;

            float ptjj = (goodJets[0].jet + goodJets[1].jet).pt();
            float massjj = (goodJets[0].jet + goodJets[1].jet).mass();
            float ptj2 = goodJets[1].pt;
            float massZj2 = (goodJets[1].jet + leps[0]+leps[1]).mass();

            fill(h1D_ptjj_file, ptjj, scale);
            fill(h1D_massjj_file, massjj, scale);
            fill(h1D_ptj2_file, ptj2, scale);
            fill(h1D_massZj2_file, massZj2, scale);


        }//event loop

    }//file loop MCMC

    std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;
    std::cout << " nGoodEventsWeighted to 19.4 1/fb: " << error->GetBinContent(1) << std::endl;

    // std::cout << " error->GetBinContent(1): " << error->GetBinContent(1) << " error->GetBinError(1): " << error->GetBinError(1) << std::endl;

    std::cout << "ASDF MC " << tag << " " << error->GetBinContent(1)  << " " << error->GetBinError(1) << std::endl;

    printCounter();

    TString prefix("plots");
    prefix += tag;
    prefix += "/";

    // stringstream ss; ss << njetsCut;
    // std::string common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq"+ss.str();
    // TString common = " --luminosity 19.4 --percentages --scaletodata --label njets#geq" + TString::Itoa(njetsCut,10);
    // TString common = " --luminosity 19.4 --percentages ";
    TString common = " --luminosity 19.4 --percentages --scaletodata";
    // std::string common = " --luminosity 19.4 --percentages --label njets>="+ss.str();

    // drawStacked(h1D_dummy_data, h1D_dummy_vec,prefix+"h1D_dummy.pdf",""+common);

    drawStacked(h1D_njets_data, h1D_njets_vec, prefix+"h1D_njets.pdf", "--centerlabel --printbins"+common);
    drawStacked(h1D_ht_data, h1D_ht_vec,prefix+"h1D_ht.pdf","--logscale --binsize --centerlabel"+common);
    drawStacked(h1D_leppt_data, h1D_leppt_vec,prefix+"h1D_leppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_Wleppt_data, h1D_Wleppt_vec,prefix+"h1D_Wleppt.pdf","--logscale --centerlabel"+common);
    drawStacked(h1D_met_data, h1D_met_vec,prefix+"h1D_met.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mt_data, h1D_mt_vec,prefix+"h1D_mt.pdf","--binsize --centerlabel"+common);
    drawStacked(h1D_mtW_data, h1D_mtW_vec,prefix+"h1D_mtW.pdf","--binsize "+common);
    drawStacked(h1D_lepeta_data, h1D_lepeta_vec,prefix+"h1D_lepeta.pdf",""+common);
    drawStacked(h1D_zmass_data, h1D_zmass_vec,prefix+"h1D_zmass.pdf","--binsize --reorderstack"+common);

    drawStacked(h1D_mtWeemu_data, h1D_mtWeemu_vec,prefix+"h1D_mtWeemu.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumue_data, h1D_mtWmumue_vec,prefix+"h1D_mtWmumue.pdf","--binsize "+common);
    drawStacked(h1D_mtWmumumu_data, h1D_mtWmumumu_vec,prefix+"h1D_mtWmumumu.pdf","--binsize "+common);
    drawStacked(h1D_mtWeee_data, h1D_mtWeee_vec,prefix+"h1D_mtWeee.pdf","--binsize "+common);
    drawStacked(h1D_lepetae_data, h1D_lepetae_vec,prefix+"h1D_lepetae.pdf",""+common);
    drawStacked(h1D_lepetamu_data, h1D_lepetamu_vec,prefix+"h1D_lepetamu.pdf",""+common);

    drawStacked(h1D_btagval_data, h1D_btagval_vec, prefix+"h1D_btagval.pdf", "--centerlabel "+common);
    drawStacked(h1D_nbtags_data, h1D_nbtags_vec, prefix+"h1D_nbtags.pdf", "--centerlabel --logscale"+common);

    drawStacked(h1D_ptZ_data, h1D_ptZ_vec, prefix+"h1D_ptZ.pdf","--centerlabel "+common);
    drawStacked(h1D_st_data, h1D_st_vec, prefix+"h1D_st.pdf","--centerlabel "+common);
    drawStacked(h1D_minRLeadingJet_data, h1D_minRLeadingJet_vec, prefix+"h1D_minRLeadingJet.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj1_data, h1D_ptj1_vec, prefix+"h1D_ptj1.pdf","--centerlabel "+common);
    drawStacked(h1D_ptj2_data, h1D_ptj2_vec, prefix+"h1D_ptj2.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj1_data, h1D_massZj1_vec, prefix+"h1D_massZj1.pdf","--centerlabel "+common);
    drawStacked(h1D_massZj2_data, h1D_massZj2_vec, prefix+"h1D_massZj2.pdf","--centerlabel "+common);
    drawStacked(h1D_ptjj_data, h1D_ptjj_vec, prefix+"h1D_ptjj.pdf","--centerlabel "+common);
    drawStacked(h1D_massjj_data, h1D_massjj_vec, prefix+"h1D_massjj.pdf","--centerlabel "+common);

    TH1F* dog = new TH1F("dog","",1,0,1);

    drawStacked(dog, h1D_test_metm_vec,prefix+"h1D_test_metm.pdf",""+common);
    drawStacked(dog, h1D_test_dphim_vec,prefix+"h1D_test_dphim.pdf",""+common);
    drawStacked(dog, h1D_test_ptm_vec,prefix+"h1D_test_ptm.pdf",""+common);

    drawStacked(dog, h1D_test_dphinu_vec,prefix+"h1D_test_dphinu.pdf",""+common);

    drawStacked(dog, h1D_test_mete_vec,prefix+"h1D_test_mete.pdf",""+common);
    drawStacked(dog, h1D_test_dphie_vec,prefix+"h1D_test_dphie.pdf",""+common);
    drawStacked(dog, h1D_test_pte_vec,prefix+"h1D_test_pte.pdf",""+common);

    drawStacked(dog, h1D_gen_dR_vec,prefix+"h1D_gen_dR.pdf","--logscale --centerlabel "+common);
    drawStacked(dog, h1D_gen_id_vec,prefix+"h1D_gen_id.pdf",""+common);

    drawStacked(dog, h1D_metphie_vec,prefix+"h1D_metphie.pdf",""+common);
    drawStacked(dog, h1D_metphim_vec,prefix+"h1D_metphim.pdf",""+common);

    return 0;
}
void ROC_Occupancy() {
  gStyle->SetPalette(1);

  TH2D* l1 = new TH2D("l1","Layer 1;Modules along Z;Ladders",72, -4.5, 4.5,  42, -10.5,  10.5);
  TH2D* l2 = new TH2D("l2","Layer 2;Modules along Z;Ladders",72, -4.5, 4.5,  66, -16.5,  16.5);
  TH2D* l3 = new TH2D("l3","Layer 3;Modules along Z;Ladders",72, -4.5, 4.5,  90, -22.5,  22.5);
  TH2D* fpixI = new TH2D("fpixI","FPix Inner Shells (+x);;Blades", 72, -4.5, 4.5, 144,   0.5,  12.5);
  TH2D* fpixO = new TH2D("fpixO","FPix Outer Shells (-X);;Blades", 72, -4.5, 4.5, 144, -12.5,  -0.5);
  fpixI->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixI->GetXaxis()->LabelsOption("d");
  fpixO->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixO->GetXaxis()->LabelsOption("d");

  TreeReader tr;
  TChain *filechain = new TChain("filechain");
  filechain->Add("Ntuple.root");

  
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  TCanvas c("c","c",1200,800);
  c.Divide(3,2);

  TObjArray* files=filechain->GetListOfFiles();
  for (int nf=0; nf<files->GetEntries(); ++nf) {
    TFile* file = TFile::Open(files->At(nf)->GetTitle());
    tr.readtrees(*file);
    
    for (Long64_t i=0; i<tr.nclu(); i++) {
      tr.clu_read(i);
      Cluster clu = tr.clu();
      EventData e = tr.clu_evt();
      
      int clu_sdpx = ((clu.mod_on.disk>0) ? 1 : -1) * (2 * (abs(clu.mod_on.disk) - 1) + clu.mod_on.panel);
      // Roc BinX number for ROC map plots (clust branch)
      int clu_roc_binx = NOVAL_I;
      if (clu.mod_on.det==0) {
	for (int j=1;j<=8;j++) if (clu.y>=((8-j)*52.0)&&clu.y<((9-j)*52.0))
          clu_roc_binx = (clu.mod_on.module+4)*8 + j;
      } else if (clu.mod_on.det==1) {
        // Roc is left (0) or right (1) on the ROC map plot (+Z side)
        int binselx = (clu.mod_on.panel==1&&(clu.mod_on.module==1||clu.mod_on.module==4)) ? (clu.mod_on.module==1)
          : ((clu.mod_on.panel==1&&clu.x<80.0)||(clu.mod_on.panel==2&&clu.x>=80.0));
        // Gives the Roc location inside a panel (0 to 5 on +Z side)
        int nperpan = 2 * clu.mod_on.module + clu.mod_on.panel - 1 + binselx;
        clu_roc_binx = ((clu.mod_on.disk>0) ? nperpan : 9 - nperpan) + (clu_sdpx + 4) * 8 
          - 2 * ((abs(clu.mod_on.disk)==1) ? clu.mod_on.disk : 0);
      }
      // Roc BinY number for ROC map plots (c branch)
      int clu_roc_biny = NOVAL_I; 
      if (clu.mod_on.det==0) {
        // Roc is in bottom (0) or top bin (1) inside a ladder on th ROC map plot
        int binsely = ((clu.mod_on.half==1&&((clu.mod_on.ladder<0&&clu.mod_on.ladder%2==0)||clu.mod_on.ladder%2==1))
        	       ||(clu.mod_on.half==0&&((clu.mod_on.ladder<0 &&((clu.mod_on.ladder%2==-1&&clu.x<80.0)
        								   ||(clu.mod_on.ladder%2==0&&clu.x>=80.0)))
        					 ||(clu.mod_on.ladder>0 &&((clu.mod_on.ladder%2==0&&clu.x<80.0)
        								     ||(clu.mod_on.ladder%2==1&&clu.x>=80.0))))));
        clu_roc_biny = (clu.mod_on.layer * 6 + clu.mod_on.ladder + 4) * 2 + 1 + binsely;
      } else if (clu.mod_on.det==1) {
        // Gives the number of ROCs along ly
        int nrocly = clu.mod_on.module + clu.mod_on.panel;
        for (int j=0; j<nrocly; j++) {
          // ROC number = nrocly - 1 - j for + LX and nrocly + j for -LX.
          int k = (clu.mod_on.disk<0) ? j : nrocly - 1 - j;
          if (clu.y>=(k*52.0)&&clu.y<((k+1)*52.0))
            clu_roc_biny = 6 - nrocly + 2 * j + ((clu.mod_on.blade>0) ? clu.mod_on.blade-1 : clu.mod_on.blade + 12)*12 + 1;
        }
      }
      
      if (clu.mod_on.layer==1) l1->SetBinContent(clu_roc_binx,clu_roc_biny, l1->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==2) l2->SetBinContent(clu_roc_binx,clu_roc_biny, l2->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==3) l3->SetBinContent(clu_roc_binx,clu_roc_biny, l3->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.blade>0) {
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      } else if (clu.mod_on.blade<0) {
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      }
	
      if (i%500000==0) {
	c.cd(1);
	l1->Draw("COLZ");
	c.cd(2);
	l2->Draw("COLZ");
	c.cd(3);
	l3->Draw("COLZ");
	c.cd(4);
	fpixI->Draw("COLZ");
	c.cd(5);
	fpixO->Draw("COLZ");
	gPad->Update();
      }
    }
	c.SaveAs("output.root");
  } std::cout<<"Done."<<std::endl;
}
void gep_trigger_analysis_elastic( const char *rootfilename, const char *logicfilename_ecal, const char *logicfilename_hcal, const char *thresholdfilename_ecal, const char *thresholdfilename_hcal, const char *outputfilename, double thetacaldeg=29.0, int pheflag=0, const char *assocfilename="ECAL_HCAL_correlations_nophe.txt", int Q2cut=0 ){

  double nominal_threshold_HCAL = 0.5;
  double nominal_threshold_ECAL = 0.9;
  
  double thetacal = thetacaldeg*PI/180.0;
  
  TFile *fout = new TFile(outputfilename,"RECREATE");
  TChain *C = new TChain("T");
  C->Add(rootfilename);

  gep_tree_elastic *T = new gep_tree_elastic( C );

  G4SBSRunData *rd;

  long ngen = 0;
  int nfiles = 0;
  
  TObjArray *FileList = C->GetListOfFiles();
  TIter next(FileList);

  TChainElement *chEl = 0;

  set<TString> bad_file_list;
  
  while( (chEl=(TChainElement*)next() )){
    TFile newfile(chEl->GetTitle());
    newfile.GetObject("run_data",rd);
    if( rd ){
      ngen += rd->fNtries;
      nfiles++;
    } else {
      bad_file_list.insert( chEl->GetTitle());
    }
  }

  cout << "number of generated events = " << ngen << endl;
  
  set<int> list_of_nodes_ecal;
  map<int, set<int> > cells_logic_sums_ecal; //mapping between node numbers and cell numbers
  map<int, double> logic_mean_ecal; //mean peak positions by node number
  map<int, double> logic_sigma_ecal; //peak width by node number
  map<int, double> threshold_ecal; //threshold by node number
  map<std::pair<int,int>, int > cell_rowcol_ecal; //cell numbers mapped by unique row and column pairs
  map<int,set<int> > nodes_cells_ecal; //mapping of nodes by cell number:
  map<int,int> rows_cells_ecal;
  map<int,int> cols_cells_ecal;
  map<int,double> xcells_ecal;
  map<int,double> ycells_ecal;
  
  //keep track of min and max x by row number:
  double ycellmin,ycellmax;
  map<int,double> ycell_rows;
  map<int,double> cellsize_rows;
  map<int,double> xcellmin_rows;
  map<int,double> xcellmax_rows;
  
  int minrow=1000,maxrow=-1;
  
  set<int> rows_ecal;
  map<int,set<int> > columns_rows_ecal;
  
  map<int,double> elastic_peak_new_ecal;
  map<int,double> sigma_new_ecal;
  map<int,double> threshold_new_ecal;
  
  ifstream logicfile_ecal(logicfilename_ecal);
  //ifstream thresholdfile(thresholdfilename);

  TString currentline;
  
  int current_node = 1;

  bool first_cell = true;
  
  while( currentline.ReadLine( logicfile_ecal ) ){
    if( !currentline.BeginsWith( "#" ) ){
      
      TObjArray *tokens = currentline.Tokenize(" ");
      int ntokens = tokens->GetEntries();
      if( ntokens >= 11 ){
	cout << currentline.Data() << ", ntokens = " << ntokens << endl;
	
	TString snode = ( (TObjString*) (*tokens)[0] )->GetString();
	int nodenumber = snode.Atoi();
	
	TString scell = ( (TObjString*) (*tokens)[1] )->GetString();
	int cellnumber = scell.Atoi();
	
	TString speakpos = ( (TObjString*) (*tokens)[8] )->GetString();
	double mean = speakpos.Atof();
	
	TString ssigma = ( (TObjString*) (*tokens)[9] )->GetString();
	double sigma = ssigma.Atof();

	TString sthreshold = ( (TObjString*) (*tokens)[10] )->GetString();
	double threshold = sthreshold.Atof();

	TString srow = ( (TObjString*) (*tokens)[2] )->GetString();
	TString scol = ( (TObjString*) (*tokens)[3] )->GetString();

	std::pair<int,int> rowcoltemp( srow.Atoi(), scol.Atoi() );

	cell_rowcol_ecal[rowcoltemp] = cellnumber;
	
	list_of_nodes_ecal.insert( nodenumber );

	cells_logic_sums_ecal[nodenumber].insert( cellnumber );

	logic_mean_ecal[nodenumber] = mean;
	logic_sigma_ecal[nodenumber] = sigma;
	threshold_ecal[nodenumber] = threshold;

	nodes_cells_ecal[ cellnumber ].insert(nodenumber);

	TString sxcell = ( (TObjString*) (*tokens)[4] )->GetString(); 
	TString sycell = ( (TObjString*) (*tokens)[5] )->GetString(); 

	cols_cells_ecal[cellnumber] = scol.Atoi(); 
	rows_cells_ecal[cellnumber] = srow.Atoi();

	xcells_ecal[cellnumber] = sxcell.Atof()/1000.0; //convert to m
	ycells_ecal[cellnumber] = sycell.Atof()/1000.0; //convert to m

	if( ycell_rows.empty() || sycell.Atof()/1000.0 < ycellmin ) ycellmin = sycell.Atof()/1000.0;
	if( ycell_rows.empty() || sycell.Atof()/1000.0 > ycellmax ) ycellmax = sycell.Atof()/1000.0;
	
	ycell_rows[srow.Atoi()] = sycell.Atof()/1000.0;
	TString ssize = ( (TObjString*) (*tokens)[6] )->GetString();
	double size = ssize.Atof();

	cellsize_rows[srow.Atoi()] = size/1000.0; 
	
	if( xcellmin_rows.empty() || sxcell.Atof()/1000.0 < xcellmin_rows[srow.Atoi()] ){
	  xcellmin_rows[srow.Atoi()] = sxcell.Atof()/1000.0;
	}
	if( xcellmax_rows.empty() || sxcell.Atof()/1000.0 > xcellmax_rows[srow.Atoi()] ){
	  xcellmax_rows[srow.Atoi()] = sxcell.Atof()/1000.0;
	}
	
      }
    }
  }

  set<int> list_of_nodes_hcal;
  map<int, set<int> > cells_logic_sums_hcal; //mapping between node numbers and cell numbers
  map<int, double> logic_mean_hcal; //mean peak positions by node number
  map<int, double> logic_sigma_hcal; //peak width by node number
  map<int, double> threshold_hcal; //threshold by node number
  map<std::pair<int,int>, int > cell_rowcol_hcal; //cell numbers mapped by unique row and column pairs
  map<int,set<int> > nodes_cells_hcal; //mapping of nodes by cell number:

  ifstream logicfile_hcal(logicfilename_hcal);

  current_node = 1;
  //  bool first_cell = true;

  while( currentline.ReadLine(logicfile_hcal) ){
    if( !currentline.BeginsWith("#") ){
      TObjArray *tokens = currentline.Tokenize(" ");
      int ntokens = tokens->GetEntries();
      if( ntokens >= 11 ){
	cout << currentline.Data() << ", ntokens = " << ntokens << endl;

	TString snode = ( (TObjString*) (*tokens)[0] )->GetString();
	int nodenumber = snode.Atoi();
	
	TString scell = ( (TObjString*) (*tokens)[1] )->GetString();
	int cellnumber = scell.Atoi();
	
	TString speakpos = ( (TObjString*) (*tokens)[8] )->GetString();
	double mean = speakpos.Atof();
	
	TString ssigma = ( (TObjString*) (*tokens)[9] )->GetString();
	double sigma = ssigma.Atof();

	TString sthreshold = ( (TObjString*) (*tokens)[10] )->GetString();
	double threshold = sthreshold.Atof();

	TString srow = ( (TObjString*) (*tokens)[2] )->GetString();
	TString scol = ( (TObjString*) (*tokens)[3] )->GetString();

	std::pair<int,int> rowcoltemp( srow.Atoi(), scol.Atoi() );

	cell_rowcol_hcal[rowcoltemp] = cellnumber;
	
	list_of_nodes_hcal.insert( nodenumber );

	cells_logic_sums_hcal[nodenumber].insert( cellnumber );

	logic_mean_hcal[nodenumber] = mean;
	logic_sigma_hcal[nodenumber] = sigma;
	threshold_hcal[nodenumber] = threshold;

	nodes_cells_hcal[ cellnumber ].insert(nodenumber);
	
      }
    }
  }
  
  TH1D::SetDefaultSumw2();

  //double PI = TMath::Pi();

  //Photoelectron statistics:
  double phe_per_GeV_ECAL = 1000.0/1.33; //~ 750 pe/GeV
  double phe_per_GeV_HCAL = 1000.0/0.30; //~ 3,333 pe/GeV (but sampling fraction is small)

  //read in alternate threshold:
  ifstream thresholdfile_ecal(thresholdfilename_ecal);
  if( thresholdfile_ecal ){
    int node;
    double mean,sigma;
    while( thresholdfile_ecal >> node >> mean >> sigma ){
      if( list_of_nodes_ecal.find( node ) != list_of_nodes_ecal.end() ){
	logic_mean_ecal[ node ] = mean;
	logic_sigma_ecal[ node ] = sigma;
      }
    }
  }

  //read in alternate threshold:
  ifstream thresholdfile_hcal(thresholdfilename_hcal);
  if( thresholdfile_hcal ){
    int node;
    double mean,sigma;
    while( thresholdfile_hcal >> node >> mean >> sigma ){
      if( list_of_nodes_hcal.find( node ) != list_of_nodes_hcal.end() ){
	logic_mean_hcal[ node ] = mean;
	logic_sigma_hcal[ node ] = sigma;
      }
    }
  }

  ifstream assocfile( assocfilename );

  bool use_ECAL_HCAL_associations=false;
  map<int, set<int> > ECAL_nodes_HCAL;
  if( assocfile ){
    while( !assocfile.eof() ){
      int hcalnode, N;
      assocfile >> hcalnode >> N;
      for( int i=0; i<N; i++ ){
	int ecalnode;
	assocfile >> ecalnode;

	ECAL_nodes_HCAL[hcalnode].insert(ecalnode);
      }
    }
  }
  
  fout->cd();

  // TH1D *hrate_vs_threshold_ECAL = new TH1D("hrate_vs_threshold_ECAL","",30,0.0,1.5);
  // //TH1D *hnum_logic_sums_fired_vs_threshold = new TH1D("hnum_logic_sums_fired_vs_threshold

  // TH1D *hrate_vs_threshold_HCAL = new TH1D("hrate_vs_threshold_HCAL","",40,0.0,2.0);

  //TH2D *htrue_coincidence_rate_vs_threshold_ECAL_HCAL = new TH2D("htrue_coincidence_rate_vs_threshold_ECAL_HCAL","",40,0,2.0,30,0,1.5);
  
  TH2D *hnphesum_vs_node_ECAL_all = new TH2D("hnphesum_vs_node_ECAL_all","",list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5,100,0.0,5000.0);
  TH2D *hnphesum_vs_node_HCAL_all = new TH2D("hnphesum_vs_node_HCAL_all","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);

  //TH2D *hnphesum_vs_node_ECAL_FTcut = new TH2D("hnphesum_vs_node_ECAL_FTcut","",list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5,100,0.0,5000.0);
  TH2D *hnphesum_vs_node_HCAL_FTcut = new TH2D("hnphesum_vs_node_HCAL_FTcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPP1cut = new TH2D("hnphesum_vs_node_HCAL_FPP1cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPP2cut = new TH2D("hnphesum_vs_node_HCAL_FPP2cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPPbothcut = new TH2D("hnphesum_vs_node_HCAL_FPPbothcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCAL_FPPeithercut = new TH2D("hnphesum_vs_node_HCAL_FPPeithercut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);

  TH2D *hnphesum_vs_node_HCALmax_all = new TH2D("hnphesum_vs_node_HCALmax_all","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FTcut = new TH2D("hnphesum_vs_node_HCALmax_FTcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPP1cut = new TH2D("hnphesum_vs_node_HCALmax_FPP1cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPP2cut = new TH2D("hnphesum_vs_node_HCALmax_FPP2cut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPPbothcut = new TH2D("hnphesum_vs_node_HCALmax_FPPbothcut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  TH2D *hnphesum_vs_node_HCALmax_FPPeithercut = new TH2D("hnphesum_vs_node_HCALmax_FPPeithercut","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,100,0.0,3500.0);
  
  
  TH2D *hmaxnode_ECAL_vs_HCAL = new TH2D("hmaxnode_ECAL_vs_HCAL","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5);
  TH2D *hallnodes_ECAL_vs_HCAL = new TH2D("hallnodes_ECAL_vs_HCAL","",list_of_nodes_hcal.size(),0.5,list_of_nodes_hcal.size()+0.5,list_of_nodes_ecal.size(),0.5,list_of_nodes_ecal.size()+0.5);

  TH1D *hshouldhit_vs_threshold_ECAL = new TH1D("hshouldhit_vs_threshold_ECAL","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_ECAL = new TH1D("hefficiency_vs_threshold_ECAL","",30,0.025,1.525);
  TH1D *hshouldhit_vs_threshold_ECAL_FTcut = new TH1D("hshouldhit_vs_threshold_ECAL_FTcut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_ECAL_FTcut = new TH1D("hefficiency_vs_threshold_ECAL_FTcut","",30,0.025,1.525);
  
  TH1D *hefficiency_vs_threshold_HCAL_FTcut = new TH1D("hefficiency_vs_threshold_HCAL_FTcut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_HCAL_FPP1cut = new TH1D("hefficiency_vs_threshold_HCAL_FPP1cut","",30,0.025,1.525);
  TH1D *hefficiency_vs_threshold_HCAL_FPP2cut = new TH1D("hefficiency_vs_threshold_HCAL_FPP2cut","",30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut","",30,0.025,1.525,30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut","",30,0.025,1.525,30,0.025,1.525);

  TH2D *hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut = new TH2D("hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut","",30,0.025,1.525,30,0.025,1.525);
  TH2D *hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut = new TH2D("hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut","",30,0.025,1.525,30,0.025,1.525);
  
  TH1D *hshouldhit_HCAL_FTcut = new TH1D("hshouldhit_HCAL_FTcut","",30,0.025,1.525);
  TH1D *hshouldhit_HCAL_FPP1cut = new TH1D("hshouldhit_HCAL_FPP1cut","",30,0.025,1.525);
  TH1D *hshouldhit_HCAL_FPP2cut = new TH1D("hshouldhit_HCAL_FPP2cut","",30,0.025,1.525);
  
  TH2D *hnphe_vs_sum_edep_ECAL = new TH2D("hnphe_vs_sum_edep_ECAL","",125,0.0,5.0,125,0.0,5000.0 );
  TH2D *hnphe_vs_sum_edep_HCAL = new TH2D("hnphe_vs_sum_edep_HCAL","",125,0.0,0.75,125,0.0,2500.0 );

  TH1D *hthetaFPP1 = new TH1D("hthetaFPP1","",120,0.0,12.0);
  TH1D *hthetaFPP2 = new TH1D("hthetaFPP2","",120,0.0,12.0);

  TH1D *hthetaFPP1_cointrig = new TH1D("hthetaFPP1_cointrig","",120,0.0,12.0);
  TH1D *hthetaFPP2_cointrig = new TH1D("hthetaFPP2_cointrig","",120,0.0,12.0);

  TH1D *hshouldhit_vs_Q2_ECAL_FTcut = new TH1D("hshouldhit_vs_Q2_ECAL_FTcut","",100,8.0,16.0);
  TH1D *hefficiency_vs_Q2_ECAL_FTcut = new TH1D("hefficiency_vs_Q2_ECAL_FTcut","",100,8.0,16.0);

  
  
  double Ibeam = 75.0e-6; //Amps
  double Ltarget = 40.0; //cm
  double e = 1.602e-19; //electron charge;
  double rho_target = 0.072; //g/cm^3
  double N_A = 6.022e23; //atoms/mol:
  double Mmol_H = 1.008; //g/mol
  double Lumi = rho_target * Ltarget * N_A / Mmol_H * Ibeam/e; //~ 8e38;
  
  TRandom3 num(0);

  cout << "Entering event loop " << endl;
  
  long nevent=0;
  for( nevent=0; nevent<C->GetEntries(); ++nevent ){
    T->GetEntry(nevent);

    double weight;
    //cross section is given in mb: 1 mb = 1e-3 * 1e-24 = 1e-27 cm^2
    // if (pythia6flag != 0 ){
    //   weight = Lumi * T->primaries_Sigma * 1.0e-27/ double(ngen); //luminosity times cross section / number of events generated.
    // } else {
    weight = T->ev_rate / double(nfiles);

    if( Q2cut == 0 || (T->ev_Q2 >= 10.5 && T->ev_Q2 <= 14.0) ){
    
      bool FTtrack = false;
      int itrack_FT=-1;
      for( int itrack=0; itrack<T->Harm_FT_Track_ntracks; itrack++ ){
	if( (*(T->Harm_FT_Track_MID))[itrack] == 0 &&
	    (*(T->Harm_FT_Track_PID))[itrack] == 2212 ){ //primary elastically scattered proton track in FT:
	  FTtrack = true;
	  itrack_FT = itrack;
	}
      }

      TVector3 nhat_FT, nhat_FPP1, nhat_FPP2;
      if( FTtrack ){
	nhat_FT.SetXYZ( (*(T->Harm_FT_Track_Xp))[itrack_FT],
			(*(T->Harm_FT_Track_Yp))[itrack_FT],
			1.0 );
	nhat_FT = nhat_FT.Unit();
      }

      double thetaFPP1, thetaFPP2, pFPP1, pFPP2;
      bool FPP1track = false, FPP2track = false;
      //    if( FTtrack )
      if( T->Harm_FPP1_Track_ntracks > 0 && FTtrack ){
	for( int itrack=0; itrack<T->Harm_FPP1_Track_ntracks; itrack++ ){
	  if( (*(T->Harm_FPP1_Track_MID))[itrack] == 0 ){
	    nhat_FPP1.SetXYZ( (*(T->Harm_FPP1_Track_Xp))[itrack],
			      (*(T->Harm_FPP1_Track_Yp))[itrack],
			      1.0 );
	    nhat_FPP1 = nhat_FPP1.Unit();
	    thetaFPP1 = acos( nhat_FPP1.Dot( nhat_FT ) );
	    pFPP1 = (*(T->Harm_FPP1_Track_P))[itrack];
	    FPP1track = thetaFPP1 < 12.0*PI/180.0 && pFPP1 >= 0.5*T->ev_np;
	    if( FPP1track ) hthetaFPP1->Fill(thetaFPP1*180.0/PI,weight);
	  }
	}
      }

      if( T->Harm_FPP2_Track_ntracks > 0 && FTtrack && FPP1track){
	for( int itrack=0; itrack<T->Harm_FPP2_Track_ntracks; itrack++ ){
	  if( (*(T->Harm_FPP2_Track_MID))[itrack] == 0 ){
	    nhat_FPP2.SetXYZ( (*(T->Harm_FPP2_Track_Xp))[itrack],
			      (*(T->Harm_FPP2_Track_Yp))[itrack],
			      1.0 );
	    nhat_FPP2 = nhat_FPP2.Unit();
	    thetaFPP2 = acos( nhat_FPP2.Dot( nhat_FPP1 ) );
	    pFPP2 = (*(T->Harm_FPP2_Track_P))[itrack];
	    //FPP2track = thetaFPP2 < 24.0*PI/180.0 && pFPP2/T->ev_np > 0.5;
	    FPP2track = thetaFPP2 < 12.0*PI/180.0 && pFPP2/T->ev_np > 0.5;
	    if( FPP2track ) hthetaFPP2->Fill(thetaFPP2*180.0/PI,weight);
	  }
	}
      }
      
      double nu = T->ev_Q2 / 2.0 / 0.938272;
      double pp_elastic = sqrt(pow(nu,2)+2.0*.938272*nu);
    
   
      //}

      double R = T->gen_dbb;
      double thetacal = T->gen_thbb;
    
      //ECAL is on beam left:
      TVector3 nhat_e( sin( T->ev_th )*cos( T->ev_ph ), sin(T->ev_th)*sin(T->ev_ph), cos(T->ev_th) );
      TVector3 vertex( T->ev_vx, T->ev_vy, T->ev_vz );
      TVector3 ecal_z( sin(thetacal), 0, cos(thetacal) );
      TVector3 ecal_y(0,1,0);
      TVector3 ecal_x = (ecal_y.Cross(ecal_z)).Unit();

      TVector3 Rcalo = R * ecal_z;
      //ecal_z dot (vertex + s * nhat_e - Rcalo ) = 0;
      double s = (Rcalo - vertex).Dot( ecal_z )/ ( nhat_e.Dot( ecal_z ) );

      TVector3 pos_calo = vertex + s * nhat_e;

      double xcalo = (pos_calo - Rcalo).Dot( ecal_x );
      double ycalo = (pos_calo - Rcalo).Dot( ecal_y ); //
    
      if( (nevent+1) % 1000 == 0 ){ cout << "Event number " << nevent+1 << ", event weight = " << weight << endl; }
    
      map<int,double> node_sums; //initialize all node sums to zero:
      for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
	node_sums[ *inode ] = 0.0;
      }

      bool should_hit_ECAL = false;

      if( ycalo >= ycellmin && ycalo <= ycellmax ){
	//make an initial guess at which row: (row runs from 1 to N):
	int closest_row = int( (ycalo - ycellmin)/4.0 ) + 1;

	map<int,double>::iterator rowguess = ycell_rows.find( closest_row );

	while( rowguess != ycell_rows.end() && ycalo > ycell_rows[rowguess->first] + 0.5*cellsize_rows[rowguess->first] ){ ++rowguess; }
	while( rowguess != ycell_rows.end() && ycalo < ycell_rows[rowguess->first] - 0.5*cellsize_rows[rowguess->first] ){ --rowguess; }

	if( rowguess != ycell_rows.end() ){
	  closest_row = rowguess->first;
	  if( xcalo >= xcellmin_rows[closest_row] + 0.5*cellsize_rows[closest_row] &&
	      xcalo <= xcellmax_rows[closest_row] - 0.5*cellsize_rows[closest_row] &&
	      ycalo >= ycellmin + 0.5*cellsize_rows[closest_row] && ycalo <= ycellmax - 0.5*cellsize_rows[closest_row] ){
	    should_hit_ECAL = true;
	  }
	}
      }

      int nphe = 0;
    
      if( pheflag == 0 ){
	for( int ihit = 0; ihit<T->Earm_ECalTF1_hit_nhits; ihit++ ){
	  int rowhit = ( *(T->Earm_ECalTF1_hit_row))[ihit]+1;
	  int colhit = ( *(T->Earm_ECalTF1_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit( rowhit,colhit );
	
	  int cellhit = cell_rowcol_ecal[rowcolhit];
	
	  //int trigger_group = nodes_cells_ecal[cellhit];
	
	  double edep = (*(T->Earm_ECalTF1_hit_sumedep))[ihit];

	  double mean = 752.2*edep;
	  double sigma = 52.0*sqrt(edep) + 20.76*edep;

	  nphe = TMath::Max(0,TMath::Nint(num.Gaus(mean,sigma)));
	
	  for( set<int>::iterator inode = nodes_cells_ecal[cellhit].begin(); inode != nodes_cells_ecal[cellhit].end(); ++inode ){
	    node_sums[ *inode ] += double(nphe);
	  }
	
	}
      } else {
	for( int ihit = 0; ihit<T->Earm_ECAL_hit_nhits; ihit++){
	  int rowhit = ( *(T->Earm_ECAL_hit_row))[ihit]+1;
	  int colhit = ( *(T->Earm_ECAL_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit( rowhit,colhit );
	
	  int cellhit = cell_rowcol_ecal[rowcolhit];
	
	  //int trigger_group = nodes_cells_ecal[cellhit];
	
	  //	double edep = (*(T->Earm_ECalTF1_hit_sumedep))[ihit];

	  int nphe = (*(T->Earm_ECAL_hit_NumPhotoelectrons))[ihit];
	
	  for( set<int>::iterator inode = nodes_cells_ecal[cellhit].begin(); inode != nodes_cells_ecal[cellhit].end(); ++inode ){
	    node_sums[ *inode ] += double(nphe);
	  }
	  for( int jhit=0; jhit<T->Earm_ECalTF1_hit_nhits; jhit++ ){
	    if( (*(T->Earm_ECalTF1_hit_row))[jhit]+1 == rowhit &&
		(*(T->Earm_ECalTF1_hit_col))[jhit]+1 == colhit &&
		fabs( (*(T->Earm_ECAL_hit_Time_avg))[ihit]-(*(T->Earm_ECalTF1_hit_tavg))[jhit]-2.5)<=10.0 ){
	      hnphe_vs_sum_edep_ECAL->Fill( (*(T->Earm_ECalTF1_hit_sumedep))[jhit], nphe );
	    }   
	  }
	}
      
	//node_sums[ trigger_group ] += double(nphe);
      }

      vector<int> trigger_nodes_fired(hefficiency_vs_threshold_ECAL->GetNbinsX());
      for( int ithr=0; ithr<hefficiency_vs_threshold_ECAL->GetNbinsX(); ithr++ ){
	trigger_nodes_fired[ithr] = 0;
      }

      int maxnode_ECAL=-1;
      int maxnode_HCAL=-1;
      double maxsum_ECAL = 0.0;
      double maxsum_HCAL = 0.0;

      bool ECALtrig_nominal = false;
    
      int nominal_threshold_bin_HCAL = hefficiency_vs_threshold_HCAL_FTcut->FindBin(nominal_threshold_HCAL);
      int nominal_threshold_bin_ECAL = hefficiency_vs_threshold_ECAL->FindBin(nominal_threshold_ECAL);
    
      for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
	for( int bin=1; bin<=hefficiency_vs_threshold_ECAL->GetNbinsX(); bin++ ){
	  if( node_sums[*inode]/logic_mean_ecal[*inode] > hefficiency_vs_threshold_ECAL->GetBinCenter(bin) ){
	    //cout << "node above threshold, nphe, peak position = " << node_sums[*inode] << ", " << logic_mean_ecal[*inode] << endl;
	    trigger_nodes_fired[bin-1]++;
	    if( bin == nominal_threshold_bin_ECAL ) ECALtrig_nominal = true;
	  }
	
	}
	if( node_sums[*inode] > maxsum_ECAL ) {
	  maxsum_ECAL = node_sums[*inode];
	  maxnode_ECAL = *inode;
	}
      
	if( node_sums[*inode] > 0.0 ) hnphesum_vs_node_ECAL_all->Fill( *inode, node_sums[*inode], weight );
      }

      if( should_hit_ECAL ){
	for( int ithr=0; ithr<hefficiency_vs_threshold_ECAL->GetNbinsX(); ithr++ ){
	  hshouldhit_vs_threshold_ECAL->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	  if( trigger_nodes_fired[ithr] > 0 ){
	    hefficiency_vs_threshold_ECAL->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	  }
	  if( FTtrack ){
	    hshouldhit_vs_threshold_ECAL_FTcut->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	    if( trigger_nodes_fired[ithr] > 0 ){
	      hefficiency_vs_threshold_ECAL_FTcut->Fill( hefficiency_vs_threshold_ECAL->GetBinCenter(ithr+1), weight );
	    }
	  }
	}
      }

      if( FTtrack ){
	hshouldhit_vs_Q2_ECAL_FTcut->Fill( T->ev_Q2, weight );
	if( ECALtrig_nominal ){
	  hefficiency_vs_Q2_ECAL_FTcut->Fill( T->ev_Q2, weight );
	}
      }
    
      map<int,double> node_sums_hcal;
      for( set<int>::iterator inode = list_of_nodes_hcal.begin(); inode != list_of_nodes_hcal.end(); ++inode ){
	node_sums_hcal[*inode] = 0.0;
      }

      //int nphe = 0;
    
      if( pheflag == 0 ){
	for( int ihit=0; ihit<T->Harm_HCalScint_hit_nhits; ihit++ ){
	  int rowhit = (*(T->Harm_HCalScint_hit_row))[ihit]+1;
	  int colhit = (*(T->Harm_HCalScint_hit_col))[ihit]+1;
	  std::pair<int,int> rowcolhit(rowhit,colhit);
	  int cellhit = cell_rowcol_hcal[rowcolhit];
	  //int trigger_group = nodes_cells_hcal[cellhit];
	  double edep = (*(T->Harm_HCalScint_hit_sumedep))[ihit];
	  //nphe = num.Poisson( phe_per_GeV_HCAL * edep );
	  double mean = 2981.0*edep;
	  double sigma = 69.54*sqrt(edep) + 155.3*edep;

	  nphe = TMath::Max(0,TMath::Nint(num.Gaus(mean,sigma)));
	
	  //cout << "HCAL hit " << ihit+1 << " node, edep, nphe = " << trigger_group << ", " << edep << ", " << nphe << endl;
	  //node_sums_hcal[trigger_group] += double(nphe);
	  for( set<int>::iterator inode = nodes_cells_hcal[cellhit].begin(); inode != nodes_cells_hcal[cellhit].end(); ++inode ){
	  
	    node_sums_hcal[*inode] += double(nphe);
	  
	  }
	}
      } else {
	for( int jhit=0; jhit<T->Harm_HCal_hit_nhits; jhit++ ){
	  int rowhit = (*(T->Harm_HCal_hit_row))[jhit]+1;
	  int colhit = (*(T->Harm_HCal_hit_col))[jhit]+1;
	  std::pair<int,int> rowcolhit(rowhit,colhit);
	  int cellhit = cell_rowcol_hcal[rowcolhit];
	  nphe = (*(T->Harm_HCal_hit_NumPhotoelectrons))[jhit];
	  for( set<int>::iterator inode = nodes_cells_hcal[cellhit].begin(); inode != nodes_cells_hcal[cellhit].end(); ++inode ){
	  
	    node_sums_hcal[*inode] += double(nphe);
	  
	  }

	  for( int khit=0; khit<T->Harm_HCalScint_hit_nhits; khit++ ){
	    if( (*(T->Harm_HCalScint_hit_row))[khit]+1 == rowhit &&
		(*(T->Harm_HCalScint_hit_col))[khit]+1 == colhit &&
		fabs( (*(T->Harm_HCal_hit_Time_avg))[jhit]-(*(T->Harm_HCalScint_hit_tavg))[khit] - 8.6 )<=15.0 ){
	      hnphe_vs_sum_edep_HCAL->Fill( (*(T->Harm_HCalScint_hit_sumedep))[khit], nphe );
	    }
	  }
	
	}
      }
    
      vector<int> trigger_nodes_fired_hcal(hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX());
      for( int ithr=0; ithr<hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); ithr++ ){
	trigger_nodes_fired_hcal[ithr] = 0;
      }

      vector<int> coin_trigger_fired( hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX()*hefficiency_vs_threshold_ECAL->GetNbinsX() );
      for( int ithr=0; ithr<coin_trigger_fired.size(); ithr++ ){
	coin_trigger_fired[ithr] = 0;
      }

    

      bool cointrig_nominal_threshold = false;
    
      for( set<int>::iterator inode = list_of_nodes_hcal.begin(); inode != list_of_nodes_hcal.end(); ++inode ){
	for( int bin=1; bin<=hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); bin++ ){
	  if( node_sums_hcal[*inode]/logic_mean_hcal[*inode] > hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin) ){ //this HCAL sum fired:
	    trigger_nodes_fired_hcal[bin-1]++;
	    for( set<int>::iterator enode = list_of_nodes_ecal.begin(); enode != list_of_nodes_ecal.end(); ++enode ){
	      if( ECAL_nodes_HCAL[*inode].find(*enode) != ECAL_nodes_HCAL[*inode].end() ){ //Check associated ECAL trigger sums:
		for( int ebin=1; ebin<=hefficiency_vs_threshold_ECAL->GetNbinsX(); ebin++ ){ //check ECAL sums:
		  if( node_sums[ *enode ]/logic_mean_ecal[*enode] > hefficiency_vs_threshold_ECAL->GetBinCenter(ebin) ){ //this ECAL sum fired:
		    coin_trigger_fired[ (ebin-1) + (bin-1)*hefficiency_vs_threshold_ECAL->GetNbinsX() ]++;
		    if( ebin == nominal_threshold_bin_ECAL && bin == nominal_threshold_bin_HCAL ){
		      cointrig_nominal_threshold = true;
		    }
		  }
		}
	      } 
	    }
	  }
	}
	if( node_sums_hcal[*inode] > maxsum_HCAL ) {
	  maxsum_HCAL = node_sums_hcal[*inode];
	  maxnode_HCAL = *inode;
	}

	hnphesum_vs_node_HCAL_all->Fill( *inode, node_sums_hcal[*inode], weight );
	if( FTtrack ){
	  hnphesum_vs_node_HCAL_FTcut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track ) hnphesum_vs_node_HCAL_FPP1cut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP2track ) hnphesum_vs_node_HCAL_FPP2cut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track && FPP2track ) hnphesum_vs_node_HCAL_FPPbothcut->Fill( *inode, node_sums_hcal[*inode], weight );
	  if( FPP1track || FPP2track ) hnphesum_vs_node_HCAL_FPPeithercut->Fill( *inode, node_sums_hcal[*inode], weight );
	}
      }

      if( cointrig_nominal_threshold ){
	if( FPP1track ) hthetaFPP1_cointrig->Fill(thetaFPP1*180.0/PI,weight);
	if( FPP2track ) hthetaFPP2_cointrig->Fill(thetaFPP2*180.0/PI,weight);
      }
    
      for( int bin=1; bin<=hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); bin++ ){
	if( FTtrack ) hshouldhit_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( FTtrack && FPP1track ) hshouldhit_HCAL_FPP1cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( FTtrack && FPP2track ) hshouldhit_HCAL_FPP2cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	if( trigger_nodes_fired_hcal[bin-1] > 0 ){
	  if( FTtrack ){
	    hefficiency_vs_threshold_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	    if( FPP1track ) hefficiency_vs_threshold_HCAL_FPP1cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	    if( FPP2track ) hefficiency_vs_threshold_HCAL_FPP2cut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(bin), weight );
	  }
	}
      }

      for( int ithr=0; ithr<coin_trigger_fired.size(); ithr++ ){
	int bin_e = ithr%(hefficiency_vs_threshold_ECAL->GetNbinsX())+1;
	int bin_h = ithr/(hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX())+1;
	double thr_e = hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->GetYaxis()->GetBinCenter(bin_e);
	double thr_h = hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->GetXaxis()->GetBinCenter(bin_h);
	if( FTtrack ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut->Fill( thr_h, thr_e, weight );
	if( FTtrack && FPP1track ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Fill( thr_h, thr_e, weight );
	if( FTtrack && FPP2track ) hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Fill( thr_h, thr_e, weight );
	if( coin_trigger_fired[ithr] > 0 ){
	  if( FTtrack ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->Fill( thr_h, thr_e, weight );
	  if( FTtrack && FPP1track ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Fill( thr_h, thr_e, weight );
	  if( FTtrack && FPP2track ) hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Fill( thr_h, thr_e, weight );
	}
      }
    
      hnphesum_vs_node_HCALmax_all->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
      if( FTtrack ){
	hnphesum_vs_node_HCALmax_FTcut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track ) hnphesum_vs_node_HCALmax_FPP1cut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP2track ) hnphesum_vs_node_HCALmax_FPP2cut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track && FPP2track ) hnphesum_vs_node_HCALmax_FPPbothcut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
	if( FPP1track || FPP2track ) hnphesum_vs_node_HCALmax_FPPeithercut->Fill( maxnode_HCAL, node_sums_hcal[maxnode_HCAL], weight );
      }
    
      // for( int ithr=0; ithr<hefficiency_vs_threshold_HCAL_FTcut->GetNbinsX(); ithr++ ){
      //   if( trigger_nodes_fired_hcal[ithr] > 0 ) hefficiency_vs_threshold_HCAL_FTcut->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(ithr+1),weight );
      //   for( int jthr=0; jthr<hefficiency_vs_threshold_ECAL->GetNbinsX(); jthr++ ){
      // 	if( trigger_nodes_fired[jthr] > 0 && trigger_nodes_fired_hcal[ithr] > 0 ){
      // 	  //htrue_coincidence_rate_vs_threshold_ECAL_HCAL->Fill( hefficiency_vs_threshold_HCAL_FTcut->GetBinCenter(ithr+1),hefficiency_vs_threshold_ECAL->GetBinCenter(jthr+1),weight );
      // 	}
      //   }
      // }

      // for( set<int>::iterator inode = list_of_nodes_ecal.begin(); inode != list_of_nodes_ecal.end(); ++inode ){
      //   for( set<int>::iterator jnode = list_of_nodes_hcal.begin(); jnode != list_of_nodes_hcal.end(); ++jnode ){
      // 	//Fill the correlation histogram for all true coincidence events for which ECAL and HCAL node are both above threshold:
      // 	if( node_sums[*inode] >= nominal_threshold_ECAL*logic_mean_ecal[*inode] && node_sums_hcal[*jnode] >= nominal_threshold_HCAL*logic_mean_hcal[*jnode] ){
      // 	  hallnodes_ECAL_vs_HCAL->Fill( *jnode, *inode, weight );
      // 	}
      //   }
      // }
      //if( maxsum_ECAL >= nominal_threshold_ECAL*logic_mean_ecal[maxnode_ECAL] && maxsum_HCAL >= nominal_threshold_HCAL*logic_mean_hcal[maxnode_HCAL] ){
      if( FTtrack && FPP2track) {
	hmaxnode_ECAL_vs_HCAL->Fill( maxnode_HCAL, maxnode_ECAL, weight );
      }
      //}
    }
  }

  hefficiency_vs_threshold_HCAL_FTcut->Divide( hshouldhit_HCAL_FTcut );
  hefficiency_vs_threshold_HCAL_FPP1cut->Divide( hshouldhit_HCAL_FPP1cut );
  hefficiency_vs_threshold_HCAL_FPP2cut->Divide( hshouldhit_HCAL_FPP2cut );

  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FTcut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FTcut );
  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP1cut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP1cut );
  hefficiency_vs_threshold_ECAL_HCAL_coincidence_FPP2cut->Divide( hshouldhit_vs_threshold_ECAL_HCAL_coincidence_FPP2cut );
  
  // TCanvas *c1 = new TCanvas("c1","c1",1200,900);
  
  // c1->Divide(2,1);

  // c1->cd(1)->SetLogy();
  // hefficiency_vs_threshold_ECAL->SetMarkerStyle(20);
  // hefficiency_vs_threshold_ECAL->Draw();
  
  // c1->cd(2)->SetLogy();
  // hefficiency_vs_threshold_HCAL_FTcut->SetMarkerStyle(20);
  // hefficiency_vs_threshold_HCAL_FTcut->Draw();

  hefficiency_vs_threshold_ECAL->Divide( hshouldhit_vs_threshold_ECAL );
  hefficiency_vs_threshold_ECAL_FTcut->Divide(hshouldhit_vs_threshold_ECAL_FTcut );
  
  hefficiency_vs_threshold_HCAL_FTcut->SetMarkerStyle(20);
  hefficiency_vs_threshold_ECAL->SetMarkerStyle(20);

  hefficiency_vs_Q2_ECAL_FTcut->Divide(hshouldhit_vs_Q2_ECAL_FTcut);
  
  fout->Write();
  fout->Close();
}
Пример #9
0
void background_rates_GMN( const char *setupfilename, const char *outfilename ){

  ifstream setupfile(setupfilename);

  TString filename;

  TChain *C = new TChain("T");
  
  while( setupfile >> filename ){
    C->Add(filename);
  }
  
  G4SBSRunData *rd;
  
  // C->Add(rootfilename);

  long ngen = 0;

  int nfiles = 0;

  TObjArray *FileList = C->GetListOfFiles();
  TIter next(FileList);
  
  TChainElement *chEl = 0;

  set<TString> bad_file_list;
  
  while( (chEl=(TChainElement*)next() )){
    TFile newfile(chEl->GetTitle());
    newfile.GetObject("run_data",rd);
    if( rd ){
      ngen += rd->fNtries;
      nfiles++;
    } else {
      bad_file_list.insert( chEl->GetTitle());
    }
    //cout << chEl->GetTitle() << endl;
  }

  cout << "Total number of generated events = " << ngen << endl;

  gmn_tree *T = new gmn_tree(C);

  TFile *fout = new TFile( outfilename, "RECREATE" );

  TH2D *hnphe_vs_edep_HCAL = new TH2D("hnphe_vs_edep_HCAL","",500,0.0,0.5,501,-0.5,500.5);
  TH2D *hrate_vs_nphe_HCAL = new TH2D("hrate_vs_nphe_HCAL","",288,-0.5,287.5,500,0.5,500.5);
  TH2D *hrate_vs_edep_HCALscint = new TH2D("hrate_vs_edep_HCALscint","",288,-0.5,287.5,500,0.0,1.0); //GeV

  TH2D *hnphe_vs_edep_CDET = new TH2D("hnphe_vs_edep_CDET","",500,0.0,0.25,501,-0.5,500.5);
  TH2D *hrate_vs_nphe_CDET = new TH2D("hrate_vs_nphe_CDET","",2352,-0.5,2351.5,500,0.5,500.5);
  TH2D *hrate_vs_edep_CDETscint = new TH2D("hrate_vs_edep_CDETscint","",2352,-0.5,2351.5,500,0.0,1.0); //GeV

  //TH2D *hnphe_vs_edep_BBhodo = new TH2D("hnphe_vs_edep_BBhodo","",500,0.0,0.25,501,-0.5,500.5);
  //TH2D *hrate_vs_nphe_BBhodo = new TH2D("hrate_vs_nphe_BBhodo","",2352,-0.5,2351.5,500,0.5,500.5);
  TH2D *hrate_vs_edep_BBHodoScint = new TH2D("hrate_vs_edep_BBHodoScint","",90,-0.5,89.5,500,0.0,0.15); //GeV

  TH2D *hnphe_vs_edep_BBPS = new TH2D("hnphe_vs_edep_BBPS","",500,0.0,0.25,501,-0.5,500.5);
  TH2D *hrate_vs_nphe_BBPS = new TH2D("hrate_vs_nphe_BBPS","",54,-0.5,53.5,501,-0.5,500.5);
  TH2D *hrate_vs_edep_BBPSTF1 = new TH2D("hrate_vs_edep_BBPSTF1","",54,-0.5,53.5,500,0.0,0.25); //GeV

  TH2D *hnphe_vs_edep_BBSH = new TH2D("hnphe_vs_edep_BBSH","",500,0.0,0.5,501,-0.5,500.5);
  TH2D *hrate_vs_nphe_BBSH = new TH2D("hrate_vs_nphe_BBSH","",189,-0.5,188.5,501,-0.5,500.5);
  TH2D *hrate_vs_edep_BBSHTF1 = new TH2D("hrate_vs_edep_BBSHTF1","",189,-0.5,188.5,500,0.0,0.5); //GeV
  
  double pmtnum[288];
  double sumedep_HCAL[288];
  // double sum2edep_HCAL[288];
  double sumnphe_HCAL[288];
  double hitrate_HCAL[288];
  
  for( int ipmt=0; ipmt<288; ipmt++ ){
    sumedep_HCAL[ipmt] = 0.0;
    pmtnum[ipmt] = ipmt;
    sumnphe_HCAL[ipmt] = 0.0;
    hitrate_HCAL[ipmt] = 0.0;
  }

  double pmt_CDET[2352];
  double sumedep_CDET[2352];
  double sumnphe_CDET[2352];
  double hitrate_CDET[2352];
  
  for( int ipmt=0; ipmt<2352; ipmt++ ){
    pmt_CDET[ipmt] = ipmt;
    sumedep_CDET[ipmt] = 0.0;
    sumnphe_CDET[ipmt] = 0.0;
    hitrate_CDET[ipmt] = 0.0;
  }

  double pmtBBHodo[90];
  double sumedep_BBHodo[90];
  double hitrate_BBHodo[90];
  
  for( int ipmt=0; ipmt<90; ipmt++ ){
    pmtBBHodo[ipmt] = ipmt;
    sumedep_BBHodo[ipmt] = 0.0;
    hitrate_BBHodo[ipmt] = 0.0;
  }

  double PMT_PS[2*27];
  double PMT_SH[189];

  double sumedep_PS[54];
  double sumedep_SH[189];
  double sumnphe_PS[54];
  double sumnphe_SH[189];
  double hitrate_PS[54];
  double hitrate_SH[189];
  
  for( int i=0; i<54; i++ ){
    PMT_PS[i] = i;
    sumedep_PS[i] = 0.0;
    sumnphe_PS[i] = 0.0;
    hitrate_PS[i] = 0.0;
  }

  for( int i=0; i<189; i++ ){
    PMT_SH[i] = i;
    sumedep_SH[i] = 0.0;
    sumnphe_SH[i] = 0.0;
    hitrate_SH[i] = 0.0;
  }

  
  double thresh_CDET = .0055; //5.5 MeV
  double thresh_BBhodo = 0.008; //3 MeV
  // double thresh_BBPS   = 0.02*0.751; //7.5 MeV
  // double thresh_BBSH   = 0.02*2.83; //28.3 MeV
  double thresh_BBPS   = 0.05;
  double thresh_BBSH   = 0.05;
  double thresh_HCAL   = 0.02*0.56; //~11 MeV
  
  long nevent=0;

  double Ibeam = 30e-6; //A
  double weight = Ibeam/double(ngen)/1.602e-19;

  
  
  while( T->GetEntry( nevent++ ) ){
    if( nevent % 1000 == 0 ) cout << nevent << endl;
    
    TFile *f = ( (TChain*) (T->fChain) )->GetFile();

    if( bad_file_list.find( f->GetName() ) == bad_file_list.end() ){
      for( int ihit=0; ihit<T->Harm_HCal_hit_nhits; ihit++ ){
	int PMT = (*(T->Harm_HCal_hit_PMT))[ihit];
	int nphe = (*(T->Harm_HCal_hit_NumPhotoelectrons))[ihit];

	double edep = 0.0;
	
	for( int jhit=0; jhit<T->Harm_HCalScint_hit_nhits; jhit++ ){
	  if( (*(T->Harm_HCalScint_hit_cell))[jhit] == PMT ){
	    edep = (*(T->Harm_HCalScint_hit_sumedep))[jhit];
	  }
	}
	hrate_vs_nphe_HCAL->Fill( PMT, nphe, weight );
	hrate_vs_edep_HCALscint->Fill( PMT, edep, weight );

	hnphe_vs_edep_HCAL->Fill( edep, nphe, weight );
	
	sumedep_HCAL[PMT] += edep * weight;
	sumnphe_HCAL[PMT] += nphe * weight;

	if( edep >= thresh_HCAL ) hitrate_HCAL[PMT] += weight;
      }

      for( int ihit=0; ihit<T->Harm_CDET_hit_nhits; ihit++ ){
	int PMT = (*(T->Harm_CDET_hit_PMT))[ihit];
	int nphe = (*(T->Harm_CDET_hit_NumPhotoelectrons))[ihit];

	double edep = 0.0;
	
	for( int jhit=0; jhit<T->Harm_CDET_Scint_hit_nhits; jhit++ ){
	  if( (*(T->Harm_CDET_Scint_hit_cell))[jhit] == PMT ){
	    edep = (*(T->Harm_CDET_Scint_hit_sumedep))[jhit];
	  }
	}
	hrate_vs_nphe_CDET->Fill( PMT, nphe, weight );
	hrate_vs_edep_CDETscint->Fill( PMT, edep, weight );

	hnphe_vs_edep_CDET->Fill( edep, nphe, weight );
	
	sumedep_CDET[PMT] += edep * weight;
	sumnphe_CDET[PMT] += nphe * weight;

	if( edep >= thresh_CDET ) hitrate_CDET[PMT] += weight;
      }

      for( int ihit=0; ihit<T->Earm_BBHodoScint_hit_nhits; ihit++ ){
	double edep = (*(T->Earm_BBHodoScint_hit_sumedep))[ihit];
	int PMT = (*(T->Earm_BBHodoScint_hit_cell))[ihit];
	hrate_vs_edep_BBHodoScint->Fill( PMT, edep, weight );

	sumedep_BBHodo[PMT] += edep * weight;

	if( edep >= thresh_BBhodo ) hitrate_BBHodo[PMT] += weight;
      }

      //BB PS:
      for( int ihit=0; ihit<T->Earm_BBPS_hit_nhits; ihit++ ){
	int PMT = (*(T->Earm_BBPS_hit_PMT))[ihit];
	int nphe = (*(T->Earm_BBPS_hit_NumPhotoelectrons))[ihit];
	double edep = 0.0;
	for( int jhit=0; jhit<T->Earm_BBPSTF1_hit_nhits; jhit++ ){
	  int cell = (*(T->Earm_BBPSTF1_hit_cell))[jhit];
	  if( cell == PMT ){
	    edep = (*(T->Earm_BBPSTF1_hit_sumedep))[jhit];
	  }
	}

	hrate_vs_nphe_BBPS->Fill( PMT, nphe, weight );
	hrate_vs_edep_BBPSTF1->Fill( PMT, edep, weight );

	hnphe_vs_edep_BBPS->Fill( edep, nphe, weight );

	sumnphe_PS[PMT] += nphe * weight;
	sumedep_PS[PMT] += edep * weight;

	if( edep >= thresh_BBPS ) hitrate_PS[PMT] += weight;
      }

      //BB SH:
      for( int ihit=0; ihit<T->Earm_BBSH_hit_nhits; ihit++ ){
	int PMT = (*(T->Earm_BBSH_hit_PMT))[ihit];
	int nphe = (*(T->Earm_BBSH_hit_NumPhotoelectrons))[ihit];
	double edep = 0.0;
	for( int jhit=0; jhit<T->Earm_BBSHTF1_hit_nhits; jhit++ ){
	  int cell = (*(T->Earm_BBSHTF1_hit_cell))[jhit];
	  if( cell == PMT ){
	    edep = (*(T->Earm_BBSHTF1_hit_sumedep))[jhit];
	  }
	}

	hrate_vs_nphe_BBSH->Fill( PMT, nphe, weight );
	hrate_vs_edep_BBSHTF1->Fill( PMT, edep, weight );

	hnphe_vs_edep_BBSH->Fill( edep, nphe, weight );
	
	sumnphe_SH[PMT] += nphe * weight;
	sumedep_SH[PMT] += edep * weight;

	if( edep >= thresh_BBSH ) hitrate_SH[PMT] += weight;
      }
      
    }
  }

  TGraph *edep_rate_HCAL = new TGraph( 288, pmtnum, sumedep_HCAL );
  TGraph *nphe_rate_HCAL = new TGraph( 288, pmtnum, sumnphe_HCAL );

  edep_rate_HCAL->SetMarkerStyle(20);
  edep_rate_HCAL->GetYaxis()->SetTitle("GeV/s (nphe >= 1)");
  edep_rate_HCAL->GetXaxis()->SetTitle("HCAL PMT number");
  nphe_rate_HCAL->SetMarkerStyle(20);
  nphe_rate_HCAL->GetYaxis()->SetTitle("phe/s");
  nphe_rate_HCAL->GetXaxis()->SetTitle("HCAL PMT number");
  
  edep_rate_HCAL->Write("edep_total_rate_vs_PMT_HCAL");
  nphe_rate_HCAL->Write("nphe_total_rate_vs_PMT_HCAL");

  TGraph *ghitrate_HCAL = new TGraph( 288, pmtnum, hitrate_HCAL );
  ghitrate_HCAL->SetMarkerStyle(20);
  ghitrate_HCAL->GetXaxis()->SetTitle("HCAL PMT number");
  ghitrate_HCAL->GetYaxis()->SetTitle("Hit rate (thresh. 11 MeV)");
  ghitrate_HCAL->Write("hitrate_HCAL");
  
  TGraph *edep_rate_CDET = new TGraph( 2352, pmt_CDET, sumedep_CDET );
  TGraph *nphe_rate_CDET = new TGraph( 2352, pmt_CDET, sumnphe_CDET );

  edep_rate_CDET->SetMarkerStyle(20);
  edep_rate_CDET->GetYaxis()->SetTitle("GeV/s (nphe >= 1)");
  edep_rate_CDET->GetXaxis()->SetTitle("CDET PMT number");
  nphe_rate_CDET->SetMarkerStyle(20);
  nphe_rate_CDET->GetYaxis()->SetTitle("phe/s");
  nphe_rate_CDET->GetXaxis()->SetTitle("CDET PMT number");

  
  edep_rate_CDET->Write("edep_total_rate_vs_PMT_CDET");
  nphe_rate_CDET->Write("nphe_total_rate_vs_PMT_CDET");

  TGraph *ghitrate_CDET = new TGraph( 2352, pmt_CDET, hitrate_CDET );
  ghitrate_CDET->SetMarkerStyle(20);
  ghitrate_CDET->GetXaxis()->SetTitle("CDET PMT number");
  ghitrate_CDET->GetYaxis()->SetTitle("Hit rate (thresh. 5.5 MeV)");
  ghitrate_CDET->Write("hitrate_CDET");
  
  TGraph *edep_rate_BBHodo = new TGraph( 90, pmtBBHodo, sumedep_BBHodo );
  edep_rate_BBHodo->SetMarkerStyle(20);
  edep_rate_BBHodo->GetYaxis()->SetTitle("GeV/s");
  edep_rate_BBHodo->GetXaxis()->SetTitle("BB hodo PMT number");

  edep_rate_BBHodo->Write("edep_rate_BBHodo");

  TGraph *ghitrate_BBHodo = new TGraph( 90, pmtBBHodo, hitrate_BBHodo );
  ghitrate_BBHodo->SetMarkerStyle(20);
  ghitrate_BBHodo->GetXaxis()->SetTitle("BBHodo PMT number");
  ghitrate_BBHodo->GetYaxis()->SetTitle("Hit rate (thresh. 3 MeV)");
  ghitrate_BBHodo->Write("hitrate_BBHodo");
  
  TGraph *edep_rate_PS = new TGraph( 54, PMT_PS, sumedep_PS );
  TGraph *nphe_rate_PS = new TGraph( 54, PMT_PS, sumnphe_PS );

  edep_rate_PS->SetMarkerStyle(20);
  edep_rate_PS->GetYaxis()->SetTitle( "GeV/s (nphe >= 1)" );
  edep_rate_PS->GetXaxis()->SetTitle( "PS PMT number" );
  edep_rate_PS->Write("edep_rate_PS");

  nphe_rate_PS->SetMarkerStyle(20);
  nphe_rate_PS->GetYaxis()->SetTitle( "nphe/s" );
  nphe_rate_PS->GetXaxis()->SetTitle( "PS PMT number" );
  nphe_rate_PS->Write("nphe_rate_PS");

  TGraph *ghitrate_PS = new TGraph( 54, PMT_PS, hitrate_PS );
  ghitrate_PS->SetMarkerStyle(20);
  ghitrate_PS->GetXaxis()->SetTitle("PS PMT number");
  ghitrate_PS->GetYaxis()->SetTitle("Hit rate (thresh. 7.5 MeV)");
  ghitrate_PS->Write("hitrate_PS");
  
  TGraph *edep_rate_SH = new TGraph( 189, PMT_SH, sumedep_SH );
  TGraph *nphe_rate_SH = new TGraph( 189, PMT_SH, sumnphe_SH );

  edep_rate_SH->SetMarkerStyle(20);
  edep_rate_SH->GetYaxis()->SetTitle( "GeV/s (nphe >= 1)" );
  edep_rate_SH->GetXaxis()->SetTitle( "SH PMT number" );
  edep_rate_SH->Write("edep_rate_SH");

  nphe_rate_SH->SetMarkerStyle(20);
  nphe_rate_SH->GetYaxis()->SetTitle( "nphe/s" );
  nphe_rate_SH->GetXaxis()->SetTitle( "SH PMT number" );
  nphe_rate_SH->Write("nphe_rate_SH");

  TGraph *ghitrate_SH = new TGraph( 189, PMT_SH, hitrate_SH );
  ghitrate_SH->SetMarkerStyle(20);
  ghitrate_SH->GetXaxis()->SetTitle("SH PMT number");
  ghitrate_SH->GetYaxis()->SetTitle("Hit rate (thresh. 28.3 MeV)");
  ghitrate_SH->Write("hitrate_SH");
  
  fout->Write();
  
}
Пример #10
0
// void scan(float jetPtCut=40.0, TString tag = "", bool requireLeptonic = false, float mtLow = -1.0, float mtHigh = -1.0) {
void scan(float jetPtCut=40.0, TString tag = "", bool requireLeptonic = false) {

    TChain *ch = new TChain("Events");

    // ch->Add("/hadoop/cms/store/user/namin/mStop500to800_mLSP1/ntuple_78_2_RJ3.root");

    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_309_4_16a.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_253_1_f2L.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_343_3_l8P.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_329_3_4dB.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_336_1_yfv.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_358_1_IPX.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_346_1_ptQ.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_281_1_Qqp.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_362_1_NNy.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_361_1_Yhs.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_359_1_YrF.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop825to900_mLSP1/ntuple_360_1_sfh.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop150to475_mLSP1/*.root");
    ch->Add("/hadoop/cms/store/user/namin/mStop500to800_mLSP1/*.root");

    int nEventsTotal = ch->GetEntries();
    int nEventsSoFar = 0;
    int nGoodEvents = 0;

    TFile *currentFile = 0;
    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);

    vector<TH1F*> h1D_mindR_vec;
    TH1F* h1D_mindR = new TH1F("", "min #DeltaR between reco jet and quark;;Entries", 100, 0.0, 2.0); h1D_mindR_vec.push_back(h1D_mindR);

    vector<TH1F*> h1D_stop_mass_vec;
    TH1F* h1D_stop_mass = new TH1F("", "Stop mass (events have 2 matched jets);;Entries", 100, 100, 900); h1D_stop_mass_vec.push_back(h1D_stop_mass); 

    vector<TH1F*> h1D_stop_mass_lt2match_vec;
    TH1F* h1D_stop_mass_lt2match = new TH1F("", "Stop mass (events have <2 matched jets);;Entries", 100, 100, 900); h1D_stop_mass_lt2match_vec.push_back(h1D_stop_mass_lt2match); 

    vector<TH1F*> h1D_stop_mass_all_vec;
    TH1F* h1D_stop_mass_all = new TH1F("", "Stop mass (events passing W daughter reqs);;Entries", 100, 100, 900); h1D_stop_mass_all_vec.push_back(h1D_stop_mass_all); 

    vector<TH1F*> h1D_lonelyjet_vec;
    TH1F* h1D_lonelyjet = new TH1F("", "Just 1 jet;;Entries", 100, 100, 900); h1D_lonelyjet_vec.push_back(h1D_lonelyjet); 

    vector<TH1F*> h1D_nonlonelyjet_vec;
    TH1F* h1D_nonlonelyjet = new TH1F("", "2 jets;;Entries", 100, 100, 900); h1D_nonlonelyjet_vec.push_back(h1D_nonlonelyjet); 

    TH2F* h2D_dRqq_Wpt = new TH2F("", "#DeltaR_{qq} (no matching);W_{p_{T}};#DeltaR_{qq}", 50,0.0,900, 50,0.0,5.0);

    vector<TH1F*> h1D_njets_gen_vec;
    vector<TH1F*> h1D_njets_reco_vec;
    vector<TH1F*> h1D_dRjj_masses_vec;
    vector<TH1F*> h1D_dRqq_nomatch_vec;
    vector<TH1F*> h1D_dRcone_nomatch_vec;
    vector<TH1F*> h1D_leadjmass_masses_vec;
    vector<TH1F*> h1D_mt_masses_vec;
    for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
        TH1F* h1D_njets_gen = new TH1F("", ";;Entries", 15, 0,15); h1D_njets_gen_vec.push_back(h1D_njets_gen);
        TH1F* h1D_njets_reco = new TH1F("", ";;Entries", 15, 0,15); h1D_njets_reco_vec.push_back(h1D_njets_reco);
        TH1F* h1D_dRjj_masses = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRjj_masses_vec.push_back(h1D_dRjj_masses);
        TH1F* h1D_dRqq_nomatch = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRqq_nomatch_vec.push_back(h1D_dRqq_nomatch);
        TH1F* h1D_dRcone_nomatch = new TH1F("", ";;Entries", 100, 0.0, 5.0); h1D_dRcone_nomatch_vec.push_back(h1D_dRcone_nomatch);
        TH1F* h1D_leadjmass_masses = new TH1F("", ";;Entries", 30, 0.0, 100.0); h1D_leadjmass_masses_vec.push_back(h1D_leadjmass_masses);
        TH1F* h1D_mt_masses = new TH1F("", ";;Entries", 45, 0.0, 900.0); h1D_mt_masses_vec.push_back(h1D_mt_masses);
    }

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

        // Get File Content
        TFile *file = new TFile( currentFile->GetTitle() );
        TTree *tree = (TTree*)file->Get("Events");
        cms2.Init(tree);

        TString filename(currentFile->GetTitle());

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


            // if(event > 300) break;

            addToCounter("total");

            // Get Event Content
            cms2.GetEntry(event);
            nEventsSoFar++;

            // each element of this vector is a pair of genps_ indices for the 2 quarks from a W
            vector<pair<int, int> > WtoqqIdxs; 
            // each element of this vector is a pair of goodJet indices for the 2 matched jets for the quarks
            vector<pair<int, int> > qqMatchedJets; 
            // indices of b quarks from same tops as Ws; this is in same order as WtoqqIdxs
            vector<int> bIdxs; 
            // indices of Ws
            vector<int> WIdxs;

            int stopMass = (int)sparm_values().at(0);
            int stopMassIdx = stopMassToIndex(stopMass);

            vector<int> WpDaughterIdxs, WmDaughterIdxs;
            for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {
                //store Ws
                // if(genps_id().at(iPart) == 24) WIdxs[0] = iPart;
                // else if(genps_id().at(iPart) == -24) WIdxs[1] = iPart;

                if(genps_status().at(iPart) != 3) continue; // only look at status=3

                // same requirements on quarks as jets
                if (genps_p4().at(iPart).pt() < jetPtCut) continue;
                if (fabs(genps_p4().at(iPart).eta()) > 2.5) continue;

                if(genps_id_mother().at(iPart) == 24) {
                    WpDaughterIdxs.push_back(iPart);
                }
                else if(genps_id_mother().at(iPart) == -24) {
                    WmDaughterIdxs.push_back(iPart);
                }
                else continue;
            }


            int nLeptonicDecay = 0;
            int leptonIdx = -1;
            if(WpDaughterIdxs.size() == 2) {
                if(abs(genps_id().at( WpDaughterIdxs[0] )) < 7 && abs(genps_id().at( WpDaughterIdxs[1] )) < 7) 
                    WtoqqIdxs.push_back( std::make_pair(WpDaughterIdxs[0], WpDaughterIdxs[1]) );
                else if(genps_id().at( WpDaughterIdxs[0] ) * genps_id().at( WpDaughterIdxs[1] ) < 0) {  // opposite signs for pdg ids
                    if( abs( abs(genps_id().at( WpDaughterIdxs[0] )) - abs(genps_id().at( WpDaughterIdxs[1] )) ) == 1 ) {  // lep + nu are same flavor
                        nLeptonicDecay++;
                        // lepton pdg codes are odd
                        if( abs( genps_id().at( WpDaughterIdxs[0] ) ) % 2 != 0) leptonIdx = WpDaughterIdxs[0];
                        else leptonIdx = WpDaughterIdxs[1];
                    }
                }
            }
            if(WmDaughterIdxs.size() == 2) {
                if(abs(genps_id().at( WmDaughterIdxs[0] )) < 7 && abs(genps_id().at( WmDaughterIdxs[1] )) < 7) 
                    WtoqqIdxs.push_back( std::make_pair(WmDaughterIdxs[0], WmDaughterIdxs[1]) );
                else if(genps_id().at( WmDaughterIdxs[0] ) * genps_id().at( WmDaughterIdxs[1] ) < 0) {  // opposite signs for pdg ids
                    if( abs( abs(genps_id().at( WmDaughterIdxs[0] )) - abs(genps_id().at( WmDaughterIdxs[1] )) ) == 1 ) {  // lep + nu are same flavor
                        nLeptonicDecay++;
                        // lepton pdg codes are odd
                        if( abs( genps_id().at( WmDaughterIdxs[0] ) ) % 2 != 0) leptonIdx = WmDaughterIdxs[0];
                        else leptonIdx = WmDaughterIdxs[1];
                    }
                }
            }

            if(requireLeptonic) {
                // want 1 W to go hadronically and 1 leptonically
                if(WtoqqIdxs.size() != 1) continue;
                if(nLeptonicDecay != 1) continue;

                if(leptonIdx == -1) cout << "woah dude, error, leptonIdx is -1" << endl;

            } else {

                if(WtoqqIdxs.size() < 1) continue; // we don't even have 1 W->qq :(
            }

            // cout << endl;
            // // cout << "_______________" << endl;

            // find bs (and Ws) from top that Ws came from. then we have the whole familia: b,q,q
            for(unsigned int iPair = 0; iPair < WtoqqIdxs.size(); iPair++) {

                // take first quark for example and get W id 
                int Wid = genps_id_mother().at( WtoqqIdxs[iPair].first );
                // std::cout << " Wid: " << Wid << std::endl;


                // std::cout << " genps_id().size(): " << genps_id().size() << std::endl;
                
                for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {

                    // iPart genps_id().at(iPart) Wid genps_id().at(iPart)==Wid
                    // std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << " Wid: " << Wid  << std::endl;
                    // std::cout << " genps_id().at(iPart)-Wid: " << genps_id().at(iPart) - Wid << std::endl;
                    // std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << " Wid: " << Wid << " genps_id().at(iPart)==Wid: " << genps_id().at(iPart)==Wid << std::endl;

                    if(genps_id().at(iPart) == Wid) WIdxs.push_back(iPart);
                    // std::cout << " iPart: " << iPart << std::endl;

                    // only consider b quarks
                    if(abs(genps_id().at(iPart)) != 5) continue;

                    int bid = genps_id().at(iPart);

                    // W+ goes with b; W- goes with bbar => product of W,b ID should be positive
                    if(Wid * bid > 0) {
                        bIdxs.push_back(iPart);
                        // break;
                    }
                }
                // if(WIdxs.size() < 1) { // XXX
                //     std::cout << " Wid: " << Wid << " WtoqqIdxs[iPair].first: " << WtoqqIdxs[iPair].first  << std::endl;
                //     for(unsigned int iPart = 0; iPart < genps_id().size(); iPart++) {
                //         std::cout << " iPart: " << iPart << " genps_id().at(iPart): " << genps_id().at(iPart) << std::endl;
                //     }
                // }
            }

            // if(WIdxs.size() < 1) { // XXX
            //     std::cout << " filename: " << filename << std::endl;
            //     dumpDocLines();
            // }
            // for(unsigned int iB = 0; iB < bIdxs.size(); iB++) {
            // std::cout << " genps_p4().at(bIxs[iB]).pt(): " << genps_p4().at(bIdxs[iB]).pt() << std::endl;
            // }
            if(bIdxs.size() != WtoqqIdxs.size() || WIdxs.size() < 1) {
                // t->qW, but q is mainly b. if it is not b, skip the event
                // also, for some reason, sometimes we can't find the W?! very rare, don't care to debug
                // dumpDocLines();
                continue;
            }

            // std::cout << " genps_p4().at(WIdxs[iPair]).pt(): " << genps_p4().at(WIdxs[0]).pt() << std::endl;


            // std::cout << " WIdxs.size(): " << WIdxs.size() << " bIdxs.size(): " << bIdxs.size() << " WtoqqIdxs.size(): " << WtoqqIdxs.size()  << std::endl;


            // mt stuff
            // sweet. gen met considers only lsps+neutrinos! 
            float mt = MT( genps_p4().at(leptonIdx), gen_met(), gen_metPhi() );
            fill(h1D_mt_masses_vec.at(stopMassIdx), mt);

            //             if(mtLow > 0 && mtHigh > 0) {
            //                 // std::cout << " mt: " << mt << " mtLow: " << mtLow << " mtHigh: " << mtHigh << std::endl;
            //                 if(mt > mtHigh || mt < mtLow) {
            //                     continue;
            //                 }
            //             }


            // end mt stuff

            fill(h1D_stop_mass_all, stopMass);

            std::vector<JetStruct> goodJets;
            std::vector<JetStruct> goodGenJets;
            for (unsigned int iJet = 0; iJet < pfjets_p4().size(); iJet++){
                if (pfjets_p4().at(iJet).pt()*pfjets_corL1FastL2L3().at(iJet) < jetPtCut) continue;
                if (fabs(pfjets_p4().at(iJet).eta()) > 2.5) continue;
                // if (!passesLoosePFJetID(iJet)) continue;


                ///// FIXME passesLoosePFJetID implementation
                float pfjet_chf_  = cms2.pfjets_chargedHadronE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_nhf_  = cms2.pfjets_neutralHadronE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_cef_  = cms2.pfjets_chargedEmE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                float pfjet_nef_  = cms2.pfjets_neutralEmE()[iJet] / cms2.pfjets_p4()[iJet].energy();
                int   pfjet_cm_   = cms2.pfjets_chargedMultiplicity()[iJet];
                if (cms2.pfjets_pfcandIndicies().size() < 2) continue;
                if (pfjet_nef_ >= 0.99) continue;
                if (pfjet_nhf_ >= 0.99) continue;
                if (pfjet_cm_ < 1) continue;
                if (pfjet_chf_ < 1e-6) continue;
                if (pfjet_cef_ >= 0.99) continue;
                //// end passesLoosePFJetID implementation


                JetStruct myJet = {*(new LorentzVector()), 0.0, 999};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.mindRToQuark = 9999;
                myJet.idx = iJet;

                goodJets.push_back(myJet);
            }
            for (unsigned int iJet = 0; iJet < genjets_p4().size(); iJet++) {
                if (genjets_p4().at(iJet).pt() < jetPtCut) continue;
                if (fabs(genjets_p4().at(iJet).eta()) > 2.5) continue;

                JetStruct myJet = {*(new LorentzVector()), 0.0, 999};
                myJet.jet = pfjets_p4().at(iJet);
                myJet.mindRToQuark = 9999;
                myJet.idx = iJet;

                goodGenJets.push_back(myJet);
            }

            fill(h1D_njets_gen_vec.at(stopMassIdx), goodGenJets.size());
            fill(h1D_njets_reco_vec.at(stopMassIdx), goodJets.size());

            for(unsigned int iPair = 0; iPair < WtoqqIdxs.size(); iPair++) {

                int q1idx = WtoqqIdxs[iPair].first;
                int q2idx = WtoqqIdxs[iPair].second;

                float mindR1 = 9999, mindR2 = 9999;
                int j1idx = -1, j2idx = -1;
                for(unsigned int iJet = 0; iJet < goodJets.size(); iJet++) {
                    float dR1 = deltaR( goodJets[iJet].jet, genps_p4().at(q1idx) );
                    float dR2 = deltaR( goodJets[iJet].jet, genps_p4().at(q2idx) );
                    if(dR1 < mindR1) {
                        mindR1 = dR1;
                        j1idx = iJet;
                    }
                    if(dR2 < mindR2) {
                        mindR2 = dR2;
                        j2idx = iJet;
                    }
                }

                float dRqq = deltaR( genps_p4().at(q1idx), genps_p4().at(q2idx) );
                fill(h1D_dRqq_nomatch_vec.at(stopMassIdx), dRqq);
                fill2D(h2D_dRqq_Wpt, genps_p4().at( WIdxs[iPair] ).pt(), dRqq);
                // cout << "before stuff" << endl; 
                // std::cout << " iPair: " << iPair << " WtoqqIdxs.size(): " << WtoqqIdxs.size() << std::endl;
                float dRq1b = deltaR( genps_p4().at( q1idx ), genps_p4().at( bIdxs[iPair] ) );
                float dRq2b = deltaR( genps_p4().at( q2idx ), genps_p4().at( bIdxs[iPair] ) );
                // cout << "after stuff" << endl; 
                float dRcone = max( max( dRq1b, dRq2b ), dRqq );
                fill(h1D_dRcone_nomatch_vec.at(stopMassIdx), dRcone);

                if(j1idx > -1 && j2idx > -1) {

                    if(j1idx != j2idx) {
                        goodJets[j1idx].mindRToQuark = mindR1;
                        goodJets[j2idx].mindRToQuark = mindR2;

                        qqMatchedJets.push_back( std::make_pair( j1idx, j2idx ) );

                        fill(h1D_nonlonelyjet, stopMass);
                    } else {
                        // cout << "just 1 jet that matches both quarks :(" << endl;
                        fill(h1D_lonelyjet, stopMass);

                    }
                } else {
                    // cout << "no good jets?!" << goodJets.size() << " " << pfjets_p4().size() <<  endl;
                }

                fill(h1D_mindR, mindR1);
                fill(h1D_mindR, mindR2);

            }

            for(unsigned int iPair = 0; iPair < qqMatchedJets.size(); iPair++) {
                int j1idx = qqMatchedJets[iPair].first;
                int j2idx = qqMatchedJets[iPair].second;

                int nMatchedJets = 0;
                if(goodJets[j1idx].mindRToQuark < 0.2) nMatchedJets++;
                if(goodJets[j2idx].mindRToQuark < 0.2) nMatchedJets++;

                if(nMatchedJets < 2) {
                    fill(h1D_stop_mass_lt2match, stopMass);
                    continue;
                }

                // at this point, both quarks for this pair have 2 matched jets

                float dRjj = deltaR( goodJets[j1idx].jet, goodJets[j2idx].jet );

                float leadingJetInvMass = goodJets[j1idx].jet.pt() > goodJets[j2idx].jet.pt() ? 
                    goodJets[j1idx].jet.mass() : goodJets[j2idx].jet.mass();

                fill(h1D_dRjj_masses_vec.at(stopMassIdx), dRjj);
                fill(h1D_leadjmass_masses_vec.at(stopMassIdx), leadingJetInvMass);
                // fill(h1D_njets_gen_vec.at(stopMassIdx), goodGenJets.size());
                // fill(h1D_njets_reco_vec.at(stopMassIdx), goodJets.size());

                fill(h1D_stop_mass, stopMass);
            } // outside of (beyond) this loop, only condition is that we have at least 1 W->qq

            CMS2::progress( nEventsSoFar, nEventsTotal );

            addToCounter("good events");

            // dumpDocLines();

            nGoodEvents++;

        }//event loop

    }//file loop MCMC

    printCounter();

    std::cout << " nGoodEvents: " << nGoodEvents << " nEventsTotal: " << nEventsTotal << std::endl;


    TString prefix("plots");
    prefix += tag;
    prefix += "/";

    TString common = "";
    // if(mtLow > 0 && mtHigh > 0) {
    //     common += " --label ";
    //     common += mtLow;
    //     common += " < M_{T} < ";
    //     common += mtHigh;
    // }

    TString massTitles = " --titles m_{#tilde{t}}=200| \
                          m_{#tilde{t}}=300| \
                          m_{#tilde{t}}=400| \
                          m_{#tilde{t}}=500| \
                          m_{#tilde{t}}=600| \
                          m_{#tilde{t}}=700| \
                          m_{#tilde{t}}=800| \
                          m_{#tilde{t}}=900| \
                          ";

    TH1F* dog = new TH1F("dog","",1,0,1);


    drawStacked(dog, h1D_lonelyjet_vec,prefix+"h1D_lonelyjet.pdf",""+common);
    h1D_lonelyjet->Divide(h1D_nonlonelyjet);
    drawStacked(dog, h1D_lonelyjet_vec,prefix+"h1D_lonelyjetfraction.pdf","--title lonely jet ratio (=1 jet/2 jets) (mindR, but no dR cut yet)"+common);

    drawStacked(dog, h1D_stop_mass_lt2match_vec,prefix+"h1D_stop_mass_lt2match.pdf",""+common);
    h1D_stop_mass_lt2match->Divide(h1D_stop_mass);
    drawStacked(dog, h1D_stop_mass_lt2match_vec,prefix+"h1D_jetmatchfraction.pdf","--title ratio of evts with <2 matched jets to 2 matched jets (after dR cut)"+common);

    drawStacked(dog, h1D_njets_gen_vec,prefix+"h1D_njets_gen.pdf","--keeporder --nostack --title Ngenjets --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_njets_reco_vec,prefix+"h1D_njets_reco.pdf","--keeporder --nostack --title Nrecojets --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_stop_mass_vec,prefix+"h1D_stop_mass.pdf",""+common);
    drawStacked(dog, h1D_stop_mass_all_vec,prefix+"h1D_stop_mass_all.pdf",""+common);
    drawStacked(dog, h1D_dRjj_masses_vec,prefix+"h1D_dRjj_masses.pdf","--keeporder --centerlabel --nostack --title dR between jj matched to qq --nofill "+massTitles+common);
    drawStacked(dog, h1D_dRqq_nomatch_vec,prefix+"h1D_dRqq_nomatch.pdf","--keeporder --centerlabel --nostack --title dR between qq (no matching at this point) --nofill "+massTitles+common);
    drawStacked(dog, h1D_dRcone_nomatch_vec,prefix+"h1D_dRcone_nomatch.pdf","--keeporder --centerlabel --nostack --title dR of cone with bqq (no matching at this point) --nofill "+massTitles+common);
    drawStacked(dog, h1D_leadjmass_masses_vec,prefix+"h1D_leadjmass_masses.pdf","--keeporder --centerlabel --nostack --title inv mass of leading j (of jj matched to qq) --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_mt_masses_vec,prefix+"h1D_mt_masses.pdf","--keeporder --centerlabel --nostack --title M_{T} --nofill --normalize --label normalized "+massTitles+common);
    drawStacked(dog, h1D_mindR_vec,prefix+"h1D_mindR.pdf","--centerlabel --title min #DeltaR between q-j --normalize --label normalized "+common);

    vector<float> thresholds;
    TString kTitles = " --titles ";
    thresholds.push_back(0.4); kTitles += "k = 0.4|";
    thresholds.push_back(0.5); kTitles += "k = 0.5|";
    thresholds.push_back(0.6); kTitles += "k = 0.6|";
    thresholds.push_back(0.7); kTitles += "k = 0.7|";
    thresholds.push_back(0.8); kTitles += "k = 0.8|";
    thresholds.push_back(0.9); kTitles += "k = 0.9|";
    thresholds.push_back(1.0); kTitles += "k = 1.0|";

    vector<float> masses;
    for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
        masses.push_back(iStop*100+200);
    }

    vector<vector<float> > xvals;
    vector<vector<float> > yvals_jj, yvals_qq, yvals_bqq;
    for(unsigned int i = 0; i < thresholds.size(); i++) {
        vector<float> fatfractions, qqfractions, bqqfractions;

        for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
            fatfractions.push_back( getFractionBetween(h1D_dRjj_masses_vec.at(iStop), 0.0, thresholds.at(i)) );
            qqfractions.push_back( getFractionBetween(h1D_dRqq_nomatch_vec.at(iStop), 0.0, thresholds.at(i)) );
            bqqfractions.push_back( getFractionBetween(h1D_dRcone_nomatch_vec.at(iStop), 0.0, thresholds.at(i)) );
        }

        xvals.push_back(masses);
        yvals_jj.push_back(fatfractions);
        yvals_qq.push_back(qqfractions);
        yvals_bqq.push_back(bqqfractions);
    }


    drawGraph(xvals, yvals_jj, prefix+"g1D_fatfraction.pdf", "--title Fraction of jj with #DeltaR_{jj}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fat fraction --legendposition bottom "+kTitles+common);
    drawGraph(xvals, yvals_qq, prefix+"g1D_qqfraction.pdf", "--title Fraction of qq (no match) with #DeltaR_{qq}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom "+kTitles+common);
    drawGraph(xvals, yvals_bqq, prefix+"g1D_bqqfraction.pdf", "--title Fraction of bqq cones (no match) with #DeltaR_{bqqcone}<k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom "+kTitles+common);

    vector<vector<float> > xval_masses;
    vector<vector<float> > yval_genjets, yval_recojets;
    for(int njets = 3; njets <= 4; njets++) {
        vector<float> genjetfractions, recojetfractions;

        for(int iStop = 0; iStop <= NSTOPMASSES; iStop++) {
            genjetfractions.push_back( getFractionBetween(h1D_njets_gen_vec.at(iStop), njets, 100) );
            recojetfractions.push_back( getFractionBetween(h1D_njets_reco_vec.at(iStop), njets, 100) );
        }

        yval_genjets.push_back(genjetfractions); 
        yval_recojets.push_back(recojetfractions); 
        xval_masses.push_back(masses); 
    }

    drawGraph(xval_masses, yval_genjets, prefix+"g1D_genjetfraction.pdf", "--title Fraction of ngenjets #geq k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --legendposition bottom --titles k=3|k=4 "+common);
    drawGraph(xval_masses, yval_recojets, prefix+"g1D_recojetfraction.pdf", "--title Fraction of nrecojets #geq k --xlabel m_{#tilde{t}}-m_{LSP} --ylabel fraction --lerecodposition bottom --titles k=3|k=4 "+common);

    // 2D hists
    drawHist2D(h2D_dRqq_Wpt, prefix+"h2D_dRqq_Wpt.pdf");

    // return 0;
}
Пример #11
0
void Skim(TString fname="ZnnH125", TString outputname = "")
{
    gROOT->LoadMacro("HelperFunctions.h" );  // make functions visible to TTreeFormula
    gROOT->SetBatch(1);

    TChain * chain  = new TChain("tree");
    TString dijet   = "";
    TString outdir  = "/afs/cern.ch/work/d/degrutto/public/MiniAOD/ZnnHbb_Phys14_PU20bx25/skimV11_v2/";
    TString prefix  = "skim_";
    TString suffix  = "tree*.root";
    


    TCut selection = baseline.c_str();
    // Different baseline for dimuons
    // MET filters
    selection += metfilter.c_str();

    // JSON & trigger
    if (fname.Contains("Data")) {
        TCut trigger = mettrigger.c_str();
        selection += trigger;
        //selection.Print();
      }
      /*
    } else if (process == "Data_METBTag_R" || process == "Data_METBTag_P") {
        TCut trigger = metbtagtrigger.c_str();
        selection += trigger;
        //selection.Print();
    } else if (process == "Data_SingleMu_R" || process == "Data_SingleMu_P") {
        TCut trigger = singlemutrigger.c_str();
        selection += trigger;
        //selection.Print();
    } else if (process == "Data_SingleEl_R" || process == "Data_SingleEl_P") {
        TCut trigger = singleeltrigger.c_str();
        selection += trigger;
        //selection.Print();
    }
      */


    chain->Add(fname);

    // Sum Count, CountWithPU, CountWithPUP, CountWithPUM
    TObjArray * files = chain->GetListOfFiles();
    TIter next(files);
    TChainElement * chainElem = 0;
    TFile * f2 = 0;
    TH1D * h1 = new TH1D("Count", ";Counts", 16, 0, 16);
    TH1F * htemp = 0;

    while ((chainElem = (TChainElement*) next())) {
      //#ifndef XROOTD
      //      f2 = TFile::Open("dcache:" + TString(chainElem->GetTitle()));
      //#else
      std::cout << "chainElem->GetTitle() " << chainElem->GetTitle() << std::endl; 
        f2 = TFile::Open( TString(chainElem->GetTitle()));
	//#endif
        htemp = (TH1F*) f2->Get("Count");
        h1->SetBinContent(1, h1->GetBinContent(1)+htemp->GetBinContent(1));
	/*
        htemp = (TH1F*) f2->Get("CountWithPU");
        h1->SetBinContent(2, h1->GetBinContent(2)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUP");
        h1->SetBinContent(3, h1->GetBinContent(3)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUM");
        h1->SetBinContent(4, h1->GetBinContent(4)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithMCProd");
        h1->SetBinContent(5, h1->GetBinContent(5)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("CountWithPUMCProd");
        h1->SetBinContent(6, h1->GetBinContent(6)+htemp->GetBinContent(1));
        htemp = (TH1F*) f2->Get("countWithSignalQCDcorrections");
        h1->SetBinContent(7, h1->GetBinContent(7)+htemp->GetBinContent(1));
        */
        std::clog << fname << ": skimmed from " << chainElem->GetTitle() << std::endl;
    }
    
    // LHE Count
    
    TH1D * h2 = new TH1D("LHECount", ";LHE Counts", 16, 0, 16);
    TString process_lhe = fname;
    if (process_lhe.BeginsWith("WJets"))
        process_lhe = "WJets";
    else if (process_lhe.BeginsWith("ZJets"))
        process_lhe = "ZJets";
    else 
        process_lhe = "";
    const std::vector<std::string>& lhecuts = GetLHECuts(process_lhe.Data());
    for (unsigned int i=0; i < lhecuts.size(); i++) {
        TCut cut2 = lhecuts.at(i).c_str();
        h2->SetBinContent(i+1, chain->GetEntries(cut2));
    }
    
    

    // Make output directory if it doesn't exist
    if (gSystem->AccessPathName(outdir))
        gSystem->mkdir(outdir);
    TString outname = outdir + prefix + Form("%s.root", outputname.Data());
    std::cout << "outname is " << outname << std::endl;

    TFile* f1 = TFile::Open(outname, "RECREATE");
    TTree* t1 = (TTree*) chain->CopyTree(selection);
    std::clog << fname << ": skimmed from " << chain->GetEntriesFast() << " to " << t1->GetEntriesFast() << " entries." << std::endl;
    
    t1->Write();
    h1->Write();
     h2->Write();
    f1->Close();

    return;
}
Пример #12
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;

}
Пример #14
0
void flux(const char *rootfilename, const char *outputfilename){

  gStyle->SetMarkerStyle(20);
  
  TH1::SetDefaultSumw2();
  
  TChain *C = new TChain("T");
  C->Add(rootfilename);

  G4SBSRunData *rd;

  long ngen = 0;
  int nfiles = 0;
  
  TObjArray *FileList = C->GetListOfFiles();
  TIter next(FileList);

  TChainElement *chEl = 0;

  set<TString> bad_file_list;
  
  while( (chEl=(TChainElement*)next() )){
    TFile newfile(chEl->GetTitle());
    newfile.GetObject("run_data",rd);
    if( rd ){
      ngen += rd->fNtries;
      nfiles++;
    } else {
      bad_file_list.insert( chEl->GetTitle());
    }
    //cout << chEl->GetTitle() << endl;
  }

  cout << "number of generated events = " << ngen << endl;

  C16_tree_with_flux *T = new C16_tree_with_flux(C);
  
  TFile *fout = new TFile(outputfilename,"RECREATE");

  long nevent=0;

  double cutgamma = 0.05*1.e-3; //energy cutoff in GeV for photons
  double cutelectron = 5.e-3; //range cutoff in GeV for electrons:
  
  TH1D *hphoton_rate_vs_theta = new TH1D("hphoton_rate_vs_theta","",80,0.0,40.0);
  TH1D *helectron_rate_vs_theta = new TH1D("helectron_rate_vs_theta","",80,0.0,40.0);
  TH1D *hphoton_rate_vs_theta_Edep = new TH1D("hphoton_rate_vs_theta_Edep","",80,0.0,40.0);
  TH1D *helectron_rate_vs_theta_Edep = new TH1D("helectron_rate_vs_theta_Edep","",80,0.0,40.0);
  TH1D *hother_rate_vs_theta = new TH1D("hother_rate_vs_theta","",80,0.0,40.0);
  TH1D *hother_rate_vs_theta_Edep = new TH1D("hother_rate_vs_theta_Edep","",80,0.0,40.0);

  TH1D *htotal_rate_vs_theta = new TH1D("htotal_rate_vs_theta","",80,0.0,40.0);
  TH1D *htotal_rate_vs_theta_Edep = new TH1D("htotal_rate_vs_theta_Edep","",80,0.0,40.0);

  double PI = TMath::Pi();

  double binwidth_theta = 40.0/80.0*PI/180.0;

  double Ibeam = 20e-6;
  double e = 1.602e-19;
  
  while( T->GetEntry( nevent++ ) ){
    TFile *f = ( (TChain*) (T->fChain) )->GetFile();

    TString fname = f->GetName();
    
    if( bad_file_list.find( fname ) == bad_file_list.end() ){ 
    
      if( nevent%1000 == 0 ) {
	cout << nevent << endl;
	cout << "Current file = " << f->GetName() << endl;
      }
      
      for( int part=0; part<T->FLUX_npart_CAL; part++ ){
	double E = (*(T->FLUX_E))[part];
	double px = (*(T->FLUX_px))[part];
	double py = (*(T->FLUX_py))[part];
	double pz = (*(T->FLUX_pz))[part];
	double p = (*(T->FLUX_p))[part];
	double theta = acos( pz/p );
	double phi = atan2( py, px );

	int bintheta = hphoton_rate_vs_theta->FindBin( theta * 180.0/PI );

	double dcostheta = cos( PI/180.0*hphoton_rate_vs_theta->GetBinLowEdge(bintheta) ) -
	  cos( PI/180.0*hphoton_rate_vs_theta->GetBinLowEdge(bintheta+1) );
	double dOmega = 2.0*PI *dcostheta;

	double weight = Ibeam/e/double(ngen)/dOmega;
	
	int pid = (*(T->FLUX_pid))[part];

	htotal_rate_vs_theta->Fill( theta*180.0/PI, weight );
	htotal_rate_vs_theta_Edep->Fill( theta*180.0/PI, weight*E );
	
	if( pid == 22 && E >= cutgamma ){//photon
	  hphoton_rate_vs_theta->Fill( theta*180.0/PI, weight );
	  hphoton_rate_vs_theta_Edep->Fill( theta*180.0/PI, weight*E );
	} else if( fabs(pid) == 11 && E >= cutelectron ){ //e+/e-
	  helectron_rate_vs_theta->Fill( theta*180.0/PI, weight );
	  helectron_rate_vs_theta_Edep->Fill( theta*180.0/PI, weight*E );
	} else { //other
	  hother_rate_vs_theta->Fill( theta*180.0/PI, weight );
	  hother_rate_vs_theta_Edep->Fill( theta*180.0/PI, weight*E );
	}
      }

    }
  }

  hphoton_rate_vs_theta->GetXaxis()->SetTitle("#theta (#circ)");
  hphoton_rate_vs_theta->GetYaxis()->SetTitle("#frac{dN_{#gamma}}{dt d#Omega} (Photons/s/sr)");

  helectron_rate_vs_theta->GetXaxis()->SetTitle("#theta (#circ)");
  helectron_rate_vs_theta->GetYaxis()->SetTitle("#frac{dN_{e}}{dt d#Omega} (Electrons/s/sr)");

  hother_rate_vs_theta->GetXaxis()->SetTitle("#theta (#circ)");
  hother_rate_vs_theta->GetYaxis()->SetTitle("#frac{dN_{other}}{dt d#Omega} (Particles/s/sr)");

  htotal_rate_vs_theta->GetXaxis()->SetTitle("#theta (#circ)");
  htotal_rate_vs_theta->GetYaxis()->SetTitle("#frac{dN_{total}}{dt d#Omega} (Particles/s/sr)");

  hphoton_rate_vs_theta_Edep->GetXaxis()->SetTitle("#theta (#circ)");
  hphoton_rate_vs_theta_Edep->GetYaxis()->SetTitle("#frac{dE}{dt d#Omega} (GeV/s/sr)");

  helectron_rate_vs_theta_Edep->GetXaxis()->SetTitle("#theta (#circ)");
  helectron_rate_vs_theta_Edep->GetYaxis()->SetTitle("#frac{dE}{dt d#Omega} (GeV/s/sr)");

  hother_rate_vs_theta_Edep->GetXaxis()->SetTitle("#theta (#circ)");
  hother_rate_vs_theta_Edep->GetYaxis()->SetTitle("#frac{dE}{dt d#Omega} (GeV/s/sr)");

  htotal_rate_vs_theta_Edep->GetXaxis()->SetTitle("#theta (#circ)");
  htotal_rate_vs_theta_Edep->GetYaxis()->SetTitle("#frac{dE}{dt d#Omega} (GeV/s/sr)");
  
  fout->Write();
}
Пример #15
0
void Classify_HWW( TString myMethodList = "" ) 
{   
#ifdef __CINT__
  gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif

  //--------------------------------------------------------------------
  // path to weights dir (this is where MVA training info is stored)
  // output root file will be stored at [path]/output
  //--------------------------------------------------------------------

  TString path   = "Trainings/v5/H160_WW_10vars_dphi10/";
  //TString path   = "./";

  //-----------------------------------
  // select samples to run over
  //-----------------------------------

  char* babyPath = "/tas/cerati/HtoWWmvaBabies/latest";
  int mH         = 160;  // choose Higgs mass

  vector<char*> samples;
  samples.push_back("WWTo2L2Nu");
  samples.push_back("GluGluToWWTo4L");
  samples.push_back("WZ");
  samples.push_back("ZZ");
  samples.push_back("TTJets");
  samples.push_back("tW");
  samples.push_back("WJetsToLNu");
  samples.push_back("DY");
  //samples.push_back("WJetsFO3");

  if     ( mH == 130 ) samples.push_back("Higgs130");
  else if( mH == 160 ) samples.push_back("Higgs160");
  else if( mH == 200 ) samples.push_back("Higgs200");
  else{
    cout << "Error, unrecognized Higgs mass " << mH << " GeV, quitting" << endl;
    exit(0);
  }

  //--------------------------------------------------------------------------------
  // IMPORTANT: set the following variables to the same set used for MVA training!!!
  //--------------------------------------------------------------------------------
  
  std::map<std::string,int> mvaVar;
  mvaVar[ "lephard_pt" ]        = 1;
  mvaVar[ "lepsoft_pt" ]        = 1;
  mvaVar[ "dil_dphi" ]          = 1;
  mvaVar[ "dil_mass" ]          = 1;
  mvaVar[ "event_type" ]        = 0;
  mvaVar[ "met_projpt" ]        = 1;
  mvaVar[ "met_pt" ]            = 0;
  mvaVar[ "mt_lephardmet" ]     = 1;
  mvaVar[ "mt_lepsoftmet" ]     = 1;
  mvaVar[ "mthiggs" ]           = 1;
  mvaVar[ "dphi_lephardmet" ]   = 1;
  mvaVar[ "dphi_lepsoftmet" ]   = 1;
  mvaVar[ "lepsoft_fbrem" ]     = 0;
  mvaVar[ "lepsoft_eOverPIn" ]  = 0;
  mvaVar[ "lepsoft_qdphi" ]     = 0;

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

  // This loads the library
  TMVA::Tools::Instance();

  // Default MVA methods to be trained + tested
  std::map<std::string,int> Use;

  // --- Cut optimisation
  Use["Cuts"]            = 1;
  Use["CutsD"]           = 1;
  Use["CutsPCA"]         = 0;
  Use["CutsGA"]          = 0;
  Use["CutsSA"]          = 0;
  // 
  // --- 1-dimensional likelihood ("naive Bayes estimator")
  Use["Likelihood"]      = 1;
  Use["LikelihoodD"]     = 0; // the "D" extension indicates decorrelated input variables (see option strings)
  Use["LikelihoodPCA"]   = 1; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
  Use["LikelihoodKDE"]   = 0;
  Use["LikelihoodMIX"]   = 0;
  //
  // --- Mutidimensional likelihood and Nearest-Neighbour methods
  Use["PDERS"]           = 1;
  Use["PDERSD"]          = 0;
  Use["PDERSPCA"]        = 0;
  Use["PDEFoam"]         = 1;
  Use["PDEFoamBoost"]    = 0; // uses generalised MVA method boosting
  Use["KNN"]             = 1; // k-nearest neighbour method
  //
  // --- Linear Discriminant Analysis
  Use["LD"]              = 1; // Linear Discriminant identical to Fisher
  Use["Fisher"]          = 0;
  Use["FisherG"]         = 0;
  Use["BoostedFisher"]   = 0; // uses generalised MVA method boosting
  Use["HMatrix"]         = 0;
  //
  // --- Function Discriminant analysis
  Use["FDA_GA"]          = 1; // minimisation of user-defined function using Genetics Algorithm
  Use["FDA_SA"]          = 0;
  Use["FDA_MC"]          = 0;
  Use["FDA_MT"]          = 0;
  Use["FDA_GAMT"]        = 0;
  Use["FDA_MCMT"]        = 0;
  //
  // --- Neural Networks (all are feed-forward Multilayer Perceptrons)
  Use["MLP"]             = 0; // Recommended ANN
  Use["MLPBFGS"]         = 0; // Recommended ANN with optional training method
  Use["MLPBNN"]          = 1; // Recommended ANN with BFGS training method and bayesian regulator
  Use["CFMlpANN"]        = 0; // Depreciated ANN from ALEPH
  Use["TMlpANN"]         = 0; // ROOT's own ANN
  //
  // --- Support Vector Machine 
  Use["SVM"]             = 1;
  // 
  // --- Boosted Decision Trees
  Use["BDT"]             = 1; // uses Adaptive Boost
  Use["BDTG"]            = 0; // uses Gradient Boost
  Use["BDTB"]            = 0; // uses Bagging
  Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
  // 
  // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
  Use["RuleFit"]         = 1;
  // ---------------------------------------------------------------
  Use["Plugin"]          = 0;
  Use["Category"]        = 0;
  Use["SVM_Gauss"]       = 0;
  Use["SVM_Poly"]        = 0;
  Use["SVM_Lin"]         = 0;

  std::cout << std::endl;
  std::cout << "==> Start TMVAClassificationApplication" << std::endl;

  // Select methods (don't look at this code - not of interest)
  if (myMethodList != "") {
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

    std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
    for (UInt_t i=0; i<mlist.size(); i++) {
      std::string regMethod(mlist[i]);

      if (Use.find(regMethod) == Use.end()) {
        std::cout << "Method \"" << regMethod 
                  << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
        for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
          std::cout << it->first << " ";
        }
        std::cout << std::endl;
        return;
      }
      Use[regMethod] = 1;
    }
  }

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

  const unsigned int nsamples = samples.size();
  
  for( unsigned int i = 0 ; i < nsamples ; ++i ){

    // --- 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 var1, var2;
    //    Float_t var3, var4;
    //    reader->AddVariable( "myvar1 := var1+var2", &var1 );
    //    reader->AddVariable( "myvar2 := var1-var2", &var2 );
    //    reader->AddVariable( "var3",                &var3 );
    //    reader->AddVariable( "var4",                &var4 );

    Float_t lephard_pt;
    Float_t lepsoft_pt;
    Float_t dil_dphi;
    Float_t dil_mass;
    Float_t event_type;
    Float_t met_projpt;
    Float_t met_pt;
    Float_t mt_lephardmet;
    Float_t mt_lepsoftmet;
    Float_t mthiggs;
    Float_t dphi_lephardmet;
    Float_t dphi_lepsoftmet;
    Float_t lepsoft_fbrem;
    Float_t lepsoft_eOverPIn;
    Float_t lepsoft_qdphi;

    if( mvaVar["lephard_pt"])       reader->AddVariable( "lephard_pt"                  ,   &lephard_pt        ); 
    if( mvaVar["lepsoft_pt"])       reader->AddVariable( "lepsoft_pt"                  ,   &lepsoft_pt        ); 
    if( mvaVar["dil_dphi"])         reader->AddVariable( "dil_dphi"                    ,   &dil_dphi          ); 
    if( mvaVar["dil_mass"])         reader->AddVariable( "dil_mass"                    ,   &dil_mass          ); 
    if( mvaVar["event_type"])       reader->AddVariable( "event_type"                  ,   &event_type        );
    if( mvaVar["met_projpt"])       reader->AddVariable( "met_projpt"                  ,   &met_pt            );
    if( mvaVar["met_pt"])           reader->AddVariable( "met_pt"                      ,   &met_pt            );
    if( mvaVar["mt_lephardmet"])    reader->AddVariable( "mt_lephardmet"               ,   &mt_lephardmet     );
    if( mvaVar["mt_lepsoftmet"])    reader->AddVariable( "mt_lepsoftmet"               ,   &mt_lepsoftmet     );
    if( mvaVar["mthiggs"])          reader->AddVariable( "mthiggs"                     ,   &mthiggs           );  
    if( mvaVar["dphi_lephardmet"])  reader->AddVariable( "dphi_lephardmet"             ,   &dphi_lephardmet   );
    if( mvaVar["dphi_lepsoftmet"])  reader->AddVariable( "dphi_lepsoftmet"             ,   &dphi_lepsoftmet   );
    if( mvaVar["lepsoft_fbrem"])    reader->AddVariable( "lepsoft_fbrem"               ,   &lepsoft_fbrem     );
    if( mvaVar["lepsoft_eOverPIn"]) reader->AddVariable( "lepsoft_eOverPIn"            ,   &lepsoft_eOverPIn  );
    if( mvaVar["lepsoft_qdphi"])    reader->AddVariable( "lepsoft_q * lepsoft_dPhiIn"  ,   &lepsoft_qdphi     );
 

    // Spectator variables declared in the training have to be added to the reader, too
    //    Float_t spec1,spec2;
    //    reader->AddSpectator( "spec1 := var1*2",   &spec1 );
    //    reader->AddSpectator( "spec2 := var1*3",   &spec2 );

    Float_t Category_cat1, Category_cat2, Category_cat3;
    if (Use["Category"]){
      // Add artificial spectators for distinguishing categories
      //       reader->AddSpectator( "Category_cat1 := var3<=0",             &Category_cat1 );
      //       reader->AddSpectator( "Category_cat2 := (var3>0)&&(var4<0)",  &Category_cat2 );
      //       reader->AddSpectator( "Category_cat3 := (var3>0)&&(var4>=0)", &Category_cat3 );
    }

    // --- Book the MVA methods

    //--------------------------------------------------------------------------------------
    // tell Classify_HWW where to find the weights dir, which contains the trained MVA's. 
    // In this example, the weights dir is located at [path]/[dir]
    // and the output root file is written to [path]/[output]
    //--------------------------------------------------------------------------------------

    TString dir    = path + "weights/";
    TString outdir = path + "output/";
    TString prefix = "TMVAClassification";

    // Book method(s)
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
        TString methodName = TString(it->first) + TString(" method");
        TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml");
        reader->BookMVA( methodName, weightfile ); 
      }
    }
   
    // Book output histograms
    UInt_t nbin = 1000;
    TH1F   *histLk(0), *histLkD(0), *histLkPCA(0), *histLkKDE(0), *histLkMIX(0), *histPD(0), *histPDD(0);
    TH1F   *histPDPCA(0), *histPDEFoam(0), *histPDEFoamErr(0), *histPDEFoamSig(0), *histKNN(0), *histHm(0);
    TH1F   *histFi(0), *histFiG(0), *histFiB(0), *histLD(0), *histNn(0),*histNnbfgs(0),*histNnbnn(0);
    TH1F   *histNnC(0), *histNnT(0), *histBdt(0), *histBdtG(0), *histBdtD(0), *histRf(0), *histSVMG(0);
    TH1F   *histSVMP(0), *histSVML(0), *histFDAMT(0), *histFDAGA(0), *histCat(0), *histPBdt(0);

    if (Use["Likelihood"])    histLk      = new TH1F( "MVA_Likelihood",    "MVA_Likelihood",    nbin, -1, 1 );               
    if (Use["LikelihoodD"])   histLkD     = new TH1F( "MVA_LikelihoodD",   "MVA_LikelihoodD",   nbin, -1, 0.9999 );
    if (Use["LikelihoodPCA"]) histLkPCA   = new TH1F( "MVA_LikelihoodPCA", "MVA_LikelihoodPCA", nbin, -1, 1 );
    if (Use["LikelihoodKDE"]) histLkKDE   = new TH1F( "MVA_LikelihoodKDE", "MVA_LikelihoodKDE", nbin,  -0.00001, 0.99999 );
    if (Use["LikelihoodMIX"]) histLkMIX   = new TH1F( "MVA_LikelihoodMIX", "MVA_LikelihoodMIX", nbin,  0, 1 );
    if (Use["PDERS"])         histPD      = new TH1F( "MVA_PDERS",         "MVA_PDERS",         nbin,  0, 1 );
    if (Use["PDERSD"])        histPDD     = new TH1F( "MVA_PDERSD",        "MVA_PDERSD",        nbin,  0, 1 );
    if (Use["PDERSPCA"])      histPDPCA   = new TH1F( "MVA_PDERSPCA",      "MVA_PDERSPCA",      nbin,  0, 1 );
    if (Use["KNN"])           histKNN     = new TH1F( "MVA_KNN",           "MVA_KNN",           nbin,  0, 1 );
    if (Use["HMatrix"])       histHm      = new TH1F( "MVA_HMatrix",       "MVA_HMatrix",       nbin, -0.95, 1.55 );
    if (Use["Fisher"])        histFi      = new TH1F( "MVA_Fisher",        "MVA_Fisher",        nbin, -4, 4 );
    if (Use["FisherG"])       histFiG     = new TH1F( "MVA_FisherG",       "MVA_FisherG",       nbin, -1, 1 );
    if (Use["BoostedFisher"]) histFiB     = new TH1F( "MVA_BoostedFisher", "MVA_BoostedFisher", nbin, -2, 2 );
    if (Use["LD"])            histLD      = new TH1F( "MVA_LD",            "MVA_LD",            nbin, -2, 2 );
    if (Use["MLP"])           histNn      = new TH1F( "MVA_MLP",           "MVA_MLP",           nbin, -1.25, 1.5 );
    if (Use["MLPBFGS"])       histNnbfgs  = new TH1F( "MVA_MLPBFGS",       "MVA_MLPBFGS",       nbin, -1.25, 1.5 );
    if (Use["MLPBNN"])        histNnbnn   = new TH1F( "MVA_MLPBNN",        "MVA_MLPBNN",        nbin, -1.25, 1.5 );
    if (Use["CFMlpANN"])      histNnC     = new TH1F( "MVA_CFMlpANN",      "MVA_CFMlpANN",      nbin,  0, 1 );
    if (Use["TMlpANN"])       histNnT     = new TH1F( "MVA_TMlpANN",       "MVA_TMlpANN",       nbin, -1.3, 1.3 );
    if (Use["BDT"])           histBdt     = new TH1F( "MVA_BDT",           "MVA_BDT",           nbin, -1. , 1. );
    if (Use["BDTD"])          histBdtD    = new TH1F( "MVA_BDTD",          "MVA_BDTD",          nbin, -0.8, 0.8 );
    if (Use["BDTG"])          histBdtG    = new TH1F( "MVA_BDTG",          "MVA_BDTG",          nbin, -1.0, 1.0 );
    if (Use["RuleFit"])       histRf      = new TH1F( "MVA_RuleFit",       "MVA_RuleFit",       nbin, -2.0, 2.0 );
    if (Use["SVM_Gauss"])     histSVMG    = new TH1F( "MVA_SVM_Gauss",     "MVA_SVM_Gauss",     nbin,  0.0, 1.0 );
    if (Use["SVM_Poly"])      histSVMP    = new TH1F( "MVA_SVM_Poly",      "MVA_SVM_Poly",      nbin,  0.0, 1.0 );
    if (Use["SVM_Lin"])       histSVML    = new TH1F( "MVA_SVM_Lin",       "MVA_SVM_Lin",       nbin,  0.0, 1.0 );
    if (Use["FDA_MT"])        histFDAMT   = new TH1F( "MVA_FDA_MT",        "MVA_FDA_MT",        nbin, -2.0, 3.0 );
    if (Use["FDA_GA"])        histFDAGA   = new TH1F( "MVA_FDA_GA",        "MVA_FDA_GA",        nbin, -2.0, 3.0 );
    if (Use["Category"])      histCat     = new TH1F( "MVA_Category",      "MVA_Category",      nbin, -2., 2. );
    if (Use["Plugin"])        histPBdt    = new TH1F( "MVA_PBDT",          "MVA_BDT",           nbin, -0.8, 0.8 );

    if (Use["Likelihood"])    histLk      ->Sumw2();
    if (Use["LikelihoodD"])   histLkD     ->Sumw2();
    if (Use["LikelihoodPCA"]) histLkPCA   ->Sumw2();
    if (Use["LikelihoodKDE"]) histLkKDE   ->Sumw2();
    if (Use["LikelihoodMIX"]) histLkMIX   ->Sumw2();
    if (Use["PDERS"])         histPD      ->Sumw2();
    if (Use["PDERSD"])        histPDD     ->Sumw2();
    if (Use["PDERSPCA"])      histPDPCA   ->Sumw2();
    if (Use["KNN"])           histKNN     ->Sumw2();
    if (Use["HMatrix"])       histHm      ->Sumw2();
    if (Use["Fisher"])        histFi      ->Sumw2();
    if (Use["FisherG"])       histFiG     ->Sumw2();
    if (Use["BoostedFisher"]) histFiB     ->Sumw2();
    if (Use["LD"])            histLD      ->Sumw2();
    if (Use["MLP"])           histNn      ->Sumw2();
    if (Use["MLPBFGS"])       histNnbfgs  ->Sumw2();
    if (Use["MLPBNN"])        histNnbnn   ->Sumw2();
    if (Use["CFMlpANN"])      histNnC     ->Sumw2();
    if (Use["TMlpANN"])       histNnT     ->Sumw2();
    if (Use["BDT"])           histBdt     ->Sumw2();
    if (Use["BDTD"])          histBdtD    ->Sumw2();
    if (Use["BDTG"])          histBdtG    ->Sumw2();
    if (Use["RuleFit"])       histRf      ->Sumw2();
    if (Use["SVM_Gauss"])     histSVMG    ->Sumw2();
    if (Use["SVM_Poly"])      histSVMP    ->Sumw2();
    if (Use["SVM_Lin"])       histSVML    ->Sumw2();
    if (Use["FDA_MT"])        histFDAMT   ->Sumw2();
    if (Use["FDA_GA"])        histFDAGA   ->Sumw2();
    if (Use["Category"])      histCat     ->Sumw2();
    if (Use["Plugin"])        histPBdt    ->Sumw2();

    // PDEFoam also returns per-event error, fill in histogram, and also fill significance
    if (Use["PDEFoam"]) {
      histPDEFoam    = new TH1F( "MVA_PDEFoam",       "MVA_PDEFoam",              nbin,  0, 1 );
      histPDEFoamErr = new TH1F( "MVA_PDEFoamErr",    "MVA_PDEFoam error",        nbin,  0, 1 );
      histPDEFoamSig = new TH1F( "MVA_PDEFoamSig",    "MVA_PDEFoam significance", nbin,  0, 10 );
    }

    // Book example histogram for probability (the other methods are done similarly)
    TH1F *probHistFi(0), *rarityHistFi(0);
    if (Use["Fisher"]) {
      probHistFi   = new TH1F( "MVA_Fisher_Proba",  "MVA_Fisher_Proba",  nbin, 0, 1 );
      rarityHistFi = new TH1F( "MVA_Fisher_Rarity", "MVA_Fisher_Rarity", nbin, 0, 1 );
    }

    // 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.
    //   

 
    TChain *ch = new TChain("Events");

    if( strcmp( samples.at(i) , "DY" ) == 0 ){
      ch -> Add( Form("%s/DYToMuMuM20_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/DYToMuMuM10To20_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/DYToEEM20_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/DYToEEM10To20_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/DYToTauTauM20_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/DYToTauTauM10To20_PU_testFinal_baby.root",babyPath) );
    }
    if( strcmp( samples.at(i) , "WJetsFO3" ) == 0 ){
      ch -> Add( Form("%s/WJetsToLNu_FOv3_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/WToLNu_FOv3_testFinal_baby.root",babyPath) );
    }
    else if( strcmp( samples.at(i) , "Higgs130" ) == 0 ){
      ch -> Add( Form("%s/HToWWTo2L2NuM130_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWToLNuTauNuM130_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWTo2Tau2NuM130_PU_testFinal_baby.root",babyPath) );
    }
    else if( strcmp( samples.at(i) , "Higgs160" ) == 0 ){
      ch -> Add( Form("%s/HToWWTo2L2NuM160_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWToLNuTauNuM160_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWTo2Tau2NuM160_PU_testFinal_baby.root",babyPath) );
    }
    else if( strcmp( samples.at(i) , "Higgs200" ) == 0 ){
      ch -> Add( Form("%s/HToWWTo2L2NuM200_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWToLNuTauNuM200_PU_testFinal_baby.root",babyPath) );
      ch -> Add( Form("%s/HToWWTo2Tau2NuM200_PU_testFinal_baby.root",babyPath) );
    }
    else{
      ch -> Add( Form("%s/%s_PU_testFinal_baby.root",babyPath,samples.at(i)) );
    }

    // --- 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
    //
  
    TTree *theTree     = (TTree*) ch;

    std::cout << "--- Using input files: -------------------" <<  std::endl;

    TObjArray *listOfFiles = ch->GetListOfFiles();
    TIter fileIter(listOfFiles);
    TChainElement* currentFile = 0;
    
    while((currentFile = (TChainElement*)fileIter.Next())) {
      std::cout << currentFile->GetTitle() << std::endl;
    }

    Float_t lephard_pt_;
    Float_t lepsoft_pt_;
    Float_t lepsoft_fr_;
    Float_t dil_dphi_;
    Float_t dil_mass_;
    Float_t event_type_;
    Float_t met_projpt_;
    Int_t   jets_num_;
    Int_t   extralep_num_;
    Int_t   lowptbtags_num_;
    Int_t   softmu_num_;
    Float_t event_scale1fb_;
    Float_t met_pt_;
    Int_t   lepsoft_passTighterId_;
    Float_t mt_lephardmet_;
    Float_t mt_lepsoftmet_;
    Float_t mthiggs_;
    Float_t dphi_lephardmet_;
    Float_t dphi_lepsoftmet_;
    Float_t lepsoft_fbrem_;
    Float_t lepsoft_eOverPIn_;
    Float_t lepsoft_q_;
    Float_t lepsoft_dPhiIn_;

    theTree->SetBranchAddress( "lephard_pt_"             ,   &lephard_pt_              ); 
    theTree->SetBranchAddress( "lepsoft_pt_"             ,   &lepsoft_pt_              ); 
    theTree->SetBranchAddress( "lepsoft_fr_"             ,   &lepsoft_fr_              ); 
    theTree->SetBranchAddress( "dil_dphi_"               ,   &dil_dphi_                ); 
    theTree->SetBranchAddress( "dil_mass_"               ,   &dil_mass_                ); 
    theTree->SetBranchAddress( "event_type_"             ,   &event_type_              ); 
    theTree->SetBranchAddress( "met_projpt_"             ,   &met_projpt_              ); 
    theTree->SetBranchAddress( "jets_num_"               ,   &jets_num_                ); 
    theTree->SetBranchAddress( "extralep_num_"           ,   &extralep_num_            ); 
    theTree->SetBranchAddress( "lowptbtags_num_"         ,   &lowptbtags_num_          ); 
    theTree->SetBranchAddress( "softmu_num_"             ,   &softmu_num_              ); 
    theTree->SetBranchAddress( "event_scale1fb_"         ,   &event_scale1fb_          ); 
    theTree->SetBranchAddress( "lepsoft_passTighterId_"  ,   &lepsoft_passTighterId_   );
    theTree->SetBranchAddress( "met_pt_"                 ,   &met_pt_                  );
    theTree->SetBranchAddress( "mt_lephardmet_"          ,   &mt_lephardmet_           );
    theTree->SetBranchAddress( "mt_lepsoftmet_"          ,   &mt_lepsoftmet_           );
    theTree->SetBranchAddress( "mthiggs_"                ,   &mthiggs_                 );
    theTree->SetBranchAddress( "dphi_lephardmet_"        ,   &dphi_lephardmet_         );
    theTree->SetBranchAddress( "dphi_lepsoftmet_"        ,   &dphi_lepsoftmet_         );
    theTree->SetBranchAddress( "lepsoft_fbrem_"          ,   &lepsoft_fbrem_           );
    theTree->SetBranchAddress( "lepsoft_eOverPIn_"       ,   &lepsoft_eOverPIn_        );
    theTree->SetBranchAddress( "lepsoft_q_"              ,   &lepsoft_q_               );
    theTree->SetBranchAddress( "lepsoft_dPhiIn_"         ,   &lepsoft_dPhiIn_          );

    // Efficiency calculator for cut method
    Int_t    nSelCutsGA = 0;
    Double_t effS       = 0.7;

    std::vector<Float_t> vecVar(4); // vector for EvaluateMVA tests

    std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
    TStopwatch sw;
    sw.Start();

    int npass   = 0;
    float yield = 0.;
    
    for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {

      if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      theTree->GetEntry(ievt);

      //-------------------------------------------------------
      // event selection
      //-------------------------------------------------------

      if( dil_dphi_ > 1. ) continue;

      //em
      if( event_type_ > 0.5 && event_type_ < 2.5 ){
        if( met_projpt_ < 20. )   continue;
      }
      //ee/mm
      if( event_type_ < 0.5 || event_type_ > 2.5 ){
        if( met_projpt_ < 35. )   continue;
      }
      if( lephard_pt_ < 20.           )             continue;
      if( jets_num_ > 0               )             continue;
      if( extralep_num_ > 0           )             continue;
      if( lowptbtags_num_ > 0         )             continue;
      if( softmu_num_ > 0             )             continue;
      if( dil_mass_ < 12.             )             continue;
      if( lepsoft_passTighterId_ == 0 )             continue;
      //if( event_type_ < 1.5    )                    continue;
      //if( event_type > 1.5 && lepsoft_pt_ < 15. )   continue;

      //mH-dependent selection
      if( mH == 130 ){
        if( lepsoft_pt_ < 10.    )                  continue;      
        if( dil_mass_   > 90.    )                  continue;     
      }
      else if( mH == 160 ){
        if( lepsoft_pt_ < 20.    )                  continue;      
        if( dil_mass_   > 100.   )                  continue;     
      }
      else if( mH == 200 ){
        if( lepsoft_pt_ < 20.    )                  continue;      
        if( dil_mass_   > 130.   )                  continue;     
      }

      float weight = event_scale1fb_ * lepsoft_fr_ * 0.5;

      //--------------------------------------------------------
      // important: here we associate branches to MVA variables
      //--------------------------------------------------------

      lephard_pt        = lephard_pt_;
      lepsoft_pt        = lepsoft_pt_;
      dil_mass          = dil_mass_;
      dil_dphi          = dil_dphi_;
      event_type        = event_type_;
      met_pt            = met_pt_;
      met_projpt        = met_projpt_;
      mt_lephardmet     = mt_lephardmet_;
      mt_lepsoftmet     = mt_lepsoftmet_;
      mthiggs           = mthiggs_;
      dphi_lephardmet   = dphi_lephardmet_;
      dphi_lepsoftmet   = dphi_lepsoftmet_;
      lepsoft_fbrem     = lepsoft_fbrem_;
      lepsoft_eOverPIn  = lepsoft_eOverPIn_;
      lepsoft_qdphi     = lepsoft_q_ * lepsoft_dPhiIn_;

      npass++;
      yield+=weight;

      //       var1 = userVar1 + userVar2;
      //       var2 = userVar1 - userVar2;

      // --- Return the MVA outputs and fill into histograms

      if (Use["CutsGA"]) {
        // Cuts is a special case: give the desired signal efficienciy
        Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS );
        if (passed) nSelCutsGA++;
      }

      if (Use["Likelihood"   ])   histLk     ->Fill( reader->EvaluateMVA( "Likelihood method"    ) , weight);
      if (Use["LikelihoodD"  ])   histLkD    ->Fill( reader->EvaluateMVA( "LikelihoodD method"   ) , weight);
      if (Use["LikelihoodPCA"])   histLkPCA  ->Fill( reader->EvaluateMVA( "LikelihoodPCA method" ) , weight);
      if (Use["LikelihoodKDE"])   histLkKDE  ->Fill( reader->EvaluateMVA( "LikelihoodKDE method" ) , weight);
      if (Use["LikelihoodMIX"])   histLkMIX  ->Fill( reader->EvaluateMVA( "LikelihoodMIX method" ) , weight);
      if (Use["PDERS"        ])   histPD     ->Fill( reader->EvaluateMVA( "PDERS method"         ) , weight);
      if (Use["PDERSD"       ])   histPDD    ->Fill( reader->EvaluateMVA( "PDERSD method"        ) , weight);
      if (Use["PDERSPCA"     ])   histPDPCA  ->Fill( reader->EvaluateMVA( "PDERSPCA method"      ) , weight);
      if (Use["KNN"          ])   histKNN    ->Fill( reader->EvaluateMVA( "KNN method"           ) , weight);
      if (Use["HMatrix"      ])   histHm     ->Fill( reader->EvaluateMVA( "HMatrix method"       ) , weight);
      if (Use["Fisher"       ])   histFi     ->Fill( reader->EvaluateMVA( "Fisher method"        ) , weight);
      if (Use["FisherG"      ])   histFiG    ->Fill( reader->EvaluateMVA( "FisherG method"       ) , weight);
      if (Use["BoostedFisher"])   histFiB    ->Fill( reader->EvaluateMVA( "BoostedFisher method" ) , weight);
      if (Use["LD"           ])   histLD     ->Fill( reader->EvaluateMVA( "LD method"            ) , weight);
      if (Use["MLP"          ])   histNn     ->Fill( reader->EvaluateMVA( "MLP method"           ) , weight);
      if (Use["MLPBFGS"      ])   histNnbfgs ->Fill( reader->EvaluateMVA( "MLPBFGS method"       ) , weight);
      if (Use["MLPBNN"       ])   histNnbnn  ->Fill( reader->EvaluateMVA( "MLPBNN method"        ) , weight);
      if (Use["CFMlpANN"     ])   histNnC    ->Fill( reader->EvaluateMVA( "CFMlpANN method"      ) , weight);
      if (Use["TMlpANN"      ])   histNnT    ->Fill( reader->EvaluateMVA( "TMlpANN method"       ) , weight);
      if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           ) , weight);
      if (Use["BDTD"         ])   histBdtD   ->Fill( reader->EvaluateMVA( "BDTD method"          ) , weight);
      if (Use["BDTG"         ])   histBdtG   ->Fill( reader->EvaluateMVA( "BDTG method"          ) , weight);
      if (Use["RuleFit"      ])   histRf     ->Fill( reader->EvaluateMVA( "RuleFit method"       ) , weight);
      if (Use["SVM_Gauss"    ])   histSVMG   ->Fill( reader->EvaluateMVA( "SVM_Gauss method"     ) , weight);
      if (Use["SVM_Poly"     ])   histSVMP   ->Fill( reader->EvaluateMVA( "SVM_Poly method"      ) , weight);
      if (Use["SVM_Lin"      ])   histSVML   ->Fill( reader->EvaluateMVA( "SVM_Lin method"       ) , weight);
      if (Use["FDA_MT"       ])   histFDAMT  ->Fill( reader->EvaluateMVA( "FDA_MT method"        ) , weight);
      if (Use["FDA_GA"       ])   histFDAGA  ->Fill( reader->EvaluateMVA( "FDA_GA method"        ) , weight);
      if (Use["Category"     ])   histCat    ->Fill( reader->EvaluateMVA( "Category method"      ) , weight);
      if (Use["Plugin"       ])   histPBdt   ->Fill( reader->EvaluateMVA( "P_BDT method"         ) , weight);

      // Retrieve also per-event error
      if (Use["PDEFoam"]) {
        Double_t val = reader->EvaluateMVA( "PDEFoam method" );
        Double_t err = reader->GetMVAError();
        histPDEFoam   ->Fill( val );
        histPDEFoamErr->Fill( err );         
        if (err>1.e-50) histPDEFoamSig->Fill( val/err , weight);
      }         

      // Retrieve probability instead of MVA output
      if (Use["Fisher"])   {
        probHistFi  ->Fill( reader->GetProba ( "Fisher method" ) , weight);
        rarityHistFi->Fill( reader->GetRarity( "Fisher method" ) , weight);
      }
    }

    std::cout << npass << " events passing selection, yield " << yield << std::endl;
 
    // Get elapsed time
    sw.Stop();
    std::cout << "--- End of event loop: "; sw.Print();

    // Get efficiency for cuts classifier
    if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries()
                                 << " (for a required signal efficiency of " << effS << ")" << std::endl;

    if (Use["CutsGA"]) {

      // test: retrieve cuts for particular signal efficiency
      // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer  
      TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ;

      if (mcuts) {      
        std::vector<Double_t> cutsMin;
        std::vector<Double_t> cutsMax;
        mcuts->GetCuts( 0.7, cutsMin, cutsMax );
        std::cout << "--- -------------------------------------------------------------" << std::endl;
        std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl;
        for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) {
          std::cout << "... Cut: " 
                    << cutsMin[ivar] 
                    << " < \"" 
                    << mcuts->GetInputVar(ivar)
                    << "\" <= " 
                    << cutsMax[ivar] << std::endl;
        }
        std::cout << "--- -------------------------------------------------------------" << std::endl;
      }
    }

    // --- Write histograms
    cout << "dir " << dir << endl;
    char* mydir = outdir;
    TFile *target  = new TFile( Form("%s/%s.root",mydir,samples.at(i) ) ,"RECREATE" );
    cout << "Writing to file " << Form("%s/%s.root",mydir,samples.at(i) ) << endl;

    if (Use["Likelihood"   ])   histLk     ->Write();
    if (Use["LikelihoodD"  ])   histLkD    ->Write();
    if (Use["LikelihoodPCA"])   histLkPCA  ->Write();
    if (Use["LikelihoodKDE"])   histLkKDE  ->Write();
    if (Use["LikelihoodMIX"])   histLkMIX  ->Write();
    if (Use["PDERS"        ])   histPD     ->Write();
    if (Use["PDERSD"       ])   histPDD    ->Write();
    if (Use["PDERSPCA"     ])   histPDPCA  ->Write();
    if (Use["KNN"          ])   histKNN    ->Write();
    if (Use["HMatrix"      ])   histHm     ->Write();
    if (Use["Fisher"       ])   histFi     ->Write();
    if (Use["FisherG"      ])   histFiG    ->Write();
    if (Use["BoostedFisher"])   histFiB    ->Write();
    if (Use["LD"           ])   histLD     ->Write();
    if (Use["MLP"          ])   histNn     ->Write();
    if (Use["MLPBFGS"      ])   histNnbfgs ->Write();
    if (Use["MLPBNN"       ])   histNnbnn  ->Write();
    if (Use["CFMlpANN"     ])   histNnC    ->Write();
    if (Use["TMlpANN"      ])   histNnT    ->Write();
    if (Use["BDT"          ])   histBdt    ->Write();
    if (Use["BDTD"         ])   histBdtD   ->Write();
    if (Use["BDTG"         ])   histBdtG   ->Write(); 
    if (Use["RuleFit"      ])   histRf     ->Write();
    if (Use["SVM_Gauss"    ])   histSVMG   ->Write();
    if (Use["SVM_Poly"     ])   histSVMP   ->Write();
    if (Use["SVM_Lin"      ])   histSVML   ->Write();
    if (Use["FDA_MT"       ])   histFDAMT  ->Write();
    if (Use["FDA_GA"       ])   histFDAGA  ->Write();
    if (Use["Category"     ])   histCat    ->Write();
    if (Use["Plugin"       ])   histPBdt   ->Write();

    // Write also error and significance histos
    if (Use["PDEFoam"]) { histPDEFoam->Write(); histPDEFoamErr->Write(); histPDEFoamSig->Write(); }

    // Write also probability hists
    if (Use["Fisher"]) { if (probHistFi != 0) probHistFi->Write(); if (rarityHistFi != 0) rarityHistFi->Write(); }
    target->Close();

    delete reader;
    
    std::cout << "==> TMVAClassificationApplication is done with sample " << samples.at(i) << endl << std::endl;
  } 
}
Пример #16
0
void efficiency_hitrecovery(const std::vector<std::string>& dirNames){
	bool verbose(false);
//	TString dirname(fileName);
	TChain* chain = new TChain("dummy");
	TString ext("out_ana_");

decodeFileNameMany(dirNames, mass_string, cT_string);
    fileName = "DarkSUSY_mH_125_mGammaD_" + mass_string + "_cT_" + cT_string;

	// add files to the chain
addfilesMany(chain, dirNames, ext);

	//Initialize Variables and counters
	//{{{

	Int_t event;
	Int_t run;
	Int_t lumi;

	Bool_t is4GenMu;
	Bool_t is1GenMu17;
	Bool_t is2GenMu8;
	Bool_t is3GenMu8;
	Bool_t is4GenMu8;

	Bool_t is1SelMu17;
	Bool_t is2SelMu8;
	Bool_t is3SelMu8;
	Bool_t is4SelMu8;

	Bool_t is2MuJets;
	Bool_t is2DiMuons;
	Bool_t is2DiMuonsFittedVtxOK;
	//Bool_t is2DiMuonsDzOK_FittedVtx;
	Float_t diMuons_dz_FittedVtx;
	Bool_t isDiMuonHLTFired;
	Bool_t is2DiMuonsMassOK_FittedVtx;
	//Bool_t is2DiMuonsIsoTkOK_FittedVtx;
	Float_t diMuonF_IsoTk_FittedVtx;
	Float_t diMuonC_IsoTk_FittedVtx;
	Bool_t isVertexOK;

	Float_t genA0_Lxy;
	Float_t genA1_Lxy;
	Float_t genA0_Lz;
	Float_t genA1_Lz;


	Int_t diMuonC_m1_FittedVtx_hitpix;
	Int_t diMuonC_m2_FittedVtx_hitpix;
	Int_t diMuonF_m1_FittedVtx_hitpix;
	Int_t diMuonF_m2_FittedVtx_hitpix;

	Int_t diMuonC_m1_FittedVtx_hitpix_l3inc;
	Int_t diMuonC_m2_FittedVtx_hitpix_l3inc;
	Int_t diMuonF_m1_FittedVtx_hitpix_l3inc;
	Int_t diMuonF_m2_FittedVtx_hitpix_l3inc;

	Float_t genA0_eta;
	Float_t genA0_phi;
	Float_t genA1_eta;
	Float_t genA1_phi;

	Float_t selMu0_phi;
	Float_t selMu1_phi;
	Float_t selMu2_phi;
	Float_t selMu3_phi;

	Float_t selMu0_eta;
	Float_t selMu1_eta;
	Float_t selMu2_eta;
	Float_t selMu3_eta;

	Float_t genA0_m;
	Float_t genA0_px;
	Float_t genA0_py;
	Float_t genA0_pz;

	Float_t genA1_m;
	Float_t genA1_px;
	Float_t genA1_py;
	Float_t genA1_pz;

	Float_t diMuonC_FittedVtx_m;
	Float_t diMuonC_FittedVtx_px;
	Float_t diMuonC_FittedVtx_py;
	Float_t diMuonC_FittedVtx_pz;
	Float_t diMuonC_FittedVtx_eta;
	Float_t diMuonC_FittedVtx_phi;
	Float_t diMuonC_FittedVtx_Lxy;
	Float_t diMuonC_FittedVtx_L;

	Float_t diMuonF_FittedVtx_m;
	Float_t diMuonF_FittedVtx_px;
	Float_t diMuonF_FittedVtx_py;
	Float_t diMuonF_FittedVtx_pz;
	Float_t diMuonF_FittedVtx_eta;
	Float_t diMuonF_FittedVtx_phi;
	Float_t diMuonF_FittedVtx_Lxy;
	Float_t diMuonF_FittedVtx_L;

	Float_t genA0Mu0_eta;
	Float_t genA1Mu0_eta;
	Float_t genA0Mu1_eta;
	Float_t genA1Mu1_eta;


	Float_t genA0Mu0_phi;
	Float_t genA1Mu0_phi;
	Float_t genA0Mu1_phi;
	Float_t genA1Mu1_phi;

	//Vertex information
	Float_t genA0_vx;
	Float_t genA0_vy;
	Float_t genA0_vz;

	Float_t genA1_vx;
	Float_t genA1_vy;
	Float_t genA1_vz;

	Float_t genA0Mu0_vx;
	Float_t genA0Mu1_vx;
	Float_t genA1Mu0_vx;
	Float_t genA1Mu1_vx;

	Float_t genA0Mu0_vy;
	Float_t genA0Mu1_vy;
	Float_t genA1Mu0_vy;
	Float_t genA1Mu1_vy;

	Float_t genA0Mu0_vz;
	Float_t genA0Mu1_vz;
	Float_t genA1Mu0_vz;
	Float_t genA1Mu1_vz;

	Float_t diMuonC_FittedVtx_vx;
	Float_t diMuonC_FittedVtx_vy;
	Float_t diMuonC_FittedVtx_vz;

	Float_t diMuonF_FittedVtx_vx;
	Float_t diMuonF_FittedVtx_vy;
	Float_t diMuonF_FittedVtx_vz;

	//============= Counters ===========================//

	vector<double> FakesPerSample;

	Int_t ev_all = 0;
	Int_t ev_isVtxOK = 0;
	Int_t ev_is2MuJets = 0;
	Int_t ev_is2DiMuons = 0;
	Int_t ev_is2DiMuonsFittedVtxOK = 0;
	Int_t ev_isPixelHitOK = 0;
	Int_t ev_is2DiMuonsDzOK_FittedVtx = 0;
	Int_t ev_is2DiMuonsMassOK_FittedVtx = 0;
	Int_t ev_is2DiMuonsIsoTkOK_FittedVtx = 0;
	Int_t ev_isDiMuonHLTFired = 0;

	Int_t c1genm = 0;
	Int_t c2genm = 0;
	Int_t c3genm = 0;
	Int_t c4genm = 0;
	Int_t ev_4gmlxylzcut = 0;

	Int_t c1recm = 0;
	Int_t c2recm = 0;
	Int_t c3recm = 0;
	Int_t c4recm = 0;

	Int_t uncuttableFakeCounter = 0;
	//}}}

	TObjArray *fileElements=chain->GetListOfFiles();
	TIter next(fileElements);
	TChainElement *chEl=0;

	while ((chEl=(TChainElement*)next())) {
		if (verbose) std::cout << "running on file " << chEl->GetTitle() << std::endl;
		TFile* myfile = new TFile(chEl->GetTitle());
		if (!myfile) {
			if (verbose) std::cout << "File " << chEl->GetTitle() << " does not exist" << std::endl;
			continue;
		}

		if (verbose) std::cout << "Loading directory cutFlowAnalyzerPXBL3PXFL2" << std::endl;
		myfile->cd("cutFlowAnalyzerPXBL3PXFL2");

		TTree *t = (TTree*)myfile->Get("cutFlowAnalyzerPXBL3PXFL2/Events");
		if (!t) {
			if (verbose) std::cout << "Tree cutFlowAnalyzerPXBL3PXFL2/Events does not exist" << std::endl;
			continue;
		}

		if (verbose) cout<<"  Events  "<<t->GetEntries()<<endl;

		//Pull variables from nTuple
		//{{{
		// Event info
		t->SetBranchAddress("event", &event);
		t->SetBranchAddress("run",   &run);
		t->SetBranchAddress("lumi",  &lumi);

		// GEN Level Selectors
		t->SetBranchAddress("is4GenMu",    &is4GenMu);
		t->SetBranchAddress("is1GenMu17",  &is1GenMu17);
		t->SetBranchAddress("is2GenMu8",   &is2GenMu8);
		t->SetBranchAddress("is3GenMu8",   &is3GenMu8);
		t->SetBranchAddress("is4GenMu8",   &is4GenMu8);

		// RECO Level Selectors
		t->SetBranchAddress("is1SelMu17",                     &is1SelMu17);
		t->SetBranchAddress("is2SelMu8",                      &is2SelMu8);
		t->SetBranchAddress("is3SelMu8",                      &is3SelMu8);
		t->SetBranchAddress("is4SelMu8",                      &is4SelMu8);

		t->SetBranchAddress("is2MuJets",                      &is2MuJets);
		t->SetBranchAddress("is2DiMuons",                     &is2DiMuons);
		t->SetBranchAddress("is2DiMuonsFittedVtxOK",          &is2DiMuonsFittedVtxOK);
		t->SetBranchAddress("diMuons_dz_FittedVtx",       &diMuons_dz_FittedVtx);
		t->SetBranchAddress("isDiMuonHLTFired",               &isDiMuonHLTFired);
		t->SetBranchAddress("is2DiMuonsMassOK_FittedVtx",     &is2DiMuonsMassOK_FittedVtx);
		t->SetBranchAddress("diMuonF_IsoTk_FittedVtx",    &diMuonF_IsoTk_FittedVtx);
		t->SetBranchAddress("diMuonC_IsoTk_FittedVtx",    &diMuonC_IsoTk_FittedVtx);
		t->SetBranchAddress("isVertexOK",                     &isVertexOK);
		t->SetBranchAddress("isDiMuonHLTFired",              &isDiMuonHLTFired);

		t->SetBranchAddress("genA0_Lxy", &genA0_Lxy);
		t->SetBranchAddress("genA0_Lz",  &genA0_Lz);
		t->SetBranchAddress("genA1_Lxy", &genA1_Lxy);
		t->SetBranchAddress("genA1_Lz",  &genA1_Lz);

		t->SetBranchAddress("diMuonC_m1_FittedVtx_hitpix", &diMuonC_m1_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonC_m2_FittedVtx_hitpix", &diMuonC_m2_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonF_m1_FittedVtx_hitpix", &diMuonF_m1_FittedVtx_hitpix);
		t->SetBranchAddress("diMuonF_m2_FittedVtx_hitpix", &diMuonF_m2_FittedVtx_hitpix);

		t->SetBranchAddress("diMuonC_m1_FittedVtx_hitpix_l3inc", &diMuonC_m1_FittedVtx_hitpix_l3inc);
		t->SetBranchAddress("diMuonC_m2_FittedVtx_hitpix_l3inc", &diMuonC_m2_FittedVtx_hitpix_l3inc);
		t->SetBranchAddress("diMuonF_m1_FittedVtx_hitpix_l3inc", &diMuonF_m1_FittedVtx_hitpix_l3inc);
		t->SetBranchAddress("diMuonF_m2_FittedVtx_hitpix_l3inc", &diMuonF_m2_FittedVtx_hitpix_l3inc);

		t->SetBranchAddress("genA1_phi",&genA1_phi);
		t->SetBranchAddress("genA1_eta",&genA1_eta);

		t->SetBranchAddress("genA0_phi",&genA0_phi);
		t->SetBranchAddress("genA0_eta",&genA0_eta);

		t->SetBranchAddress("selMu0_phi",&selMu0_phi);
		t->SetBranchAddress("selMu1_phi",&selMu1_phi);
		t->SetBranchAddress("selMu2_phi",&selMu2_phi);
		t->SetBranchAddress("selMu3_phi",&selMu3_phi);

		t->SetBranchAddress("selMu0_eta",&selMu0_eta);
		t->SetBranchAddress("selMu1_eta",&selMu1_eta);
		t->SetBranchAddress("selMu2_eta",&selMu2_eta);
		t->SetBranchAddress("selMu3_eta",&selMu3_eta);

		t->SetBranchAddress("genA0_m" , &genA0_m);
		t->SetBranchAddress("genA0_px", &genA0_px);
		t->SetBranchAddress("genA0_py", &genA0_py);
		t->SetBranchAddress("genA0_pz", &genA0_pz);

		t->SetBranchAddress("genA1_m" , &genA1_m);
		t->SetBranchAddress("genA1_px", &genA1_px);
		t->SetBranchAddress("genA1_py", &genA1_py);
		t->SetBranchAddress("genA1_pz", &genA1_pz);

		t->SetBranchAddress("diMuonF_FittedVtx_m", &diMuonF_FittedVtx_m);
		t->SetBranchAddress("diMuonF_FittedVtx_px", &diMuonF_FittedVtx_px);
		t->SetBranchAddress("diMuonF_FittedVtx_py", &diMuonF_FittedVtx_py);
		t->SetBranchAddress("diMuonF_FittedVtx_pz", &diMuonF_FittedVtx_pz);
		t->SetBranchAddress("diMuonF_FittedVtx_eta",&diMuonF_FittedVtx_eta);
		t->SetBranchAddress("diMuonF_FittedVtx_phi",&diMuonF_FittedVtx_phi);
		t->SetBranchAddress("diMuonF_FittedVtx_Lxy",&diMuonF_FittedVtx_Lxy);
		t->SetBranchAddress("diMuonF_FittedVtx_L",&diMuonF_FittedVtx_L);

		t->SetBranchAddress("diMuonC_FittedVtx_m", &diMuonC_FittedVtx_m);
		t->SetBranchAddress("diMuonC_FittedVtx_px", &diMuonC_FittedVtx_px);
		t->SetBranchAddress("diMuonC_FittedVtx_py", &diMuonC_FittedVtx_py);
		t->SetBranchAddress("diMuonC_FittedVtx_pz", &diMuonC_FittedVtx_pz);
		t->SetBranchAddress("diMuonC_FittedVtx_eta",&diMuonC_FittedVtx_eta);
		t->SetBranchAddress("diMuonC_FittedVtx_phi",&diMuonC_FittedVtx_phi);
		t->SetBranchAddress("diMuonC_FittedVtx_Lxy",&diMuonC_FittedVtx_Lxy);
		t->SetBranchAddress("diMuonC_FittedVtx_L",&diMuonC_FittedVtx_L);

		t->SetBranchAddress("genA0Mu0_eta",&genA0Mu0_eta);
		t->SetBranchAddress("genA1Mu0_eta",&genA1Mu0_eta);
		t->SetBranchAddress("genA0Mu1_eta",&genA0Mu1_eta);
		t->SetBranchAddress("genA1Mu1_eta",&genA1Mu1_eta);

		t->SetBranchAddress("genA0Mu0_phi",&genA0Mu0_phi);
		t->SetBranchAddress("genA1Mu0_phi",&genA1Mu0_phi);
		t->SetBranchAddress("genA0Mu1_phi",&genA0Mu1_phi);
		t->SetBranchAddress("genA1Mu1_phi",&genA1Mu1_phi);

		t->SetBranchAddress("genA0_vx", &genA0_vx); 
		t->SetBranchAddress("genA0_vy", &genA0_vy);
		t->SetBranchAddress("genA0_vz", &genA0_vz);

		t->SetBranchAddress("genA1_vx", &genA1_vx);
		t->SetBranchAddress("genA1_vy", &genA1_vy);
		t->SetBranchAddress("genA1_vz", &genA1_vz);

		t->SetBranchAddress("genA0Mu0_vx", &genA0Mu0_vx);
		t->SetBranchAddress("genA0Mu1_vx", &genA0Mu1_vx);
		t->SetBranchAddress("genA1Mu0_vx", &genA1Mu0_vx);
		t->SetBranchAddress("genA1Mu1_vx", &genA1Mu1_vx);

		t->SetBranchAddress("genA0Mu0_vy", &genA0Mu0_vy);
		t->SetBranchAddress("genA0Mu1_vy", &genA0Mu1_vy);
		t->SetBranchAddress("genA1Mu0_vy", &genA1Mu0_vy);
		t->SetBranchAddress("genA1Mu1_vy", &genA1Mu1_vy);

		t->SetBranchAddress("genA0Mu0_vz", &genA0Mu0_vz);
		t->SetBranchAddress("genA0Mu1_vz", &genA0Mu1_vz);
		t->SetBranchAddress("genA1Mu0_vz", &genA1Mu0_vz);
		t->SetBranchAddress("genA1Mu1_vz", &genA1Mu1_vz);

		t->SetBranchAddress("diMuonC_FittedVtx_vx", &diMuonC_FittedVtx_vx);
		t->SetBranchAddress("diMuonC_FittedVtx_vy", &diMuonC_FittedVtx_vy);
		t->SetBranchAddress("diMuonC_FittedVtx_vz", &diMuonC_FittedVtx_vz);

		t->SetBranchAddress("diMuonF_FittedVtx_vx", &diMuonF_FittedVtx_vx);
		t->SetBranchAddress("diMuonF_FittedVtx_vy", &diMuonF_FittedVtx_vy);
		t->SetBranchAddress("diMuonF_FittedVtx_vz", &diMuonF_FittedVtx_vz);
		//}}}

		for(int k=0;k<t->GetEntries();k++){
			t->GetEntry(k);

			ev_all++;

			if(is1GenMu17) c1genm++;
			if(is2GenMu8)  c2genm++;
			if(is3GenMu8)  c3genm++;
			if(is4GenMu8)  c4genm++;

			if(is1SelMu17) c1recm++;
			if(is2SelMu8)  c2recm++;
			if(is3SelMu8)  c3recm++;
			if(is4SelMu8)  c4recm++;

			int triggerFlag_std = 0;
			int triggerFlag_lxy = 0;
			int fakeFlag = 0;
			int realFlag = 0;
			int fakeDimuon1 = 0;
			int fakeDimuon2 = 0;

			int brokenCounter = 0;
			int fakeCounter_dimuon1 = 0;
			int fakeCounter_dimuon2 = 0;
			int fakeCounter_both = 0;

			//  ===========   GEN LEVEL information  ==============//

			//{{{
			if(is4GenMu8){
				Float_t dphi_gD = My_dPhi(genA1_phi,genA0_phi);
				//if(fabs(dphi_gD)>=2.5){
				if(fabs(genA0_Lxy)<9.8 && fabs(genA1_Lxy)<9.8 && fabs(genA0_Lz)<48.5 && fabs(genA1_Lz)<48.5){
					ev_4gmlxylzcut++;
				}
				//}
			}

			//}}}
			//  =============  Reco information ====================//

			//Numerator of ratio
			//{{{
			//if(is4GenMu8)
			//if(fabs(genA0_Lxy)<9.8 && fabs(genA1_Lxy)<9.8 && fabs(genA0_Lz)<48.5 && fabs(genA1_Lz)<48.5){
			Float_t dphi_gD = My_dPhi(genA1_phi,genA0_phi);
			//if(fabs(dphi_gD)>=2.5){
			if(is4SelMu8){
				brokenCounter++;
				if(isVertexOK){
					ev_isVtxOK++;
					brokenCounter++;
					if(is2MuJets){
						ev_is2MuJets++;
						brokenCounter++;
						if(is2DiMuons){
							ev_is2DiMuons++;
							brokenCounter++;
							if(is2DiMuonsFittedVtxOK){
								ev_is2DiMuonsFittedVtxOK++;
								brokenCounter++;
								//if( (diMuonC_m1_FittedVtx_hitpix==1||diMuonC_m2_FittedVtx_hitpix==1)&&(diMuonF_m1_FittedVtx_hitpix==1||diMuonF_m2_FittedVtx_hitpix==1) ) //First pixel layers
								if( (diMuonC_m1_FittedVtx_hitpix_l3inc==1||diMuonC_m2_FittedVtx_hitpix_l3inc==1)&&(diMuonF_m1_FittedVtx_hitpix_l3inc==1||diMuonF_m2_FittedVtx_hitpix_l3inc==1) ){
									ev_isPixelHitOK++;
									if(diMuons_dz_FittedVtx <= 0.1 && diMuons_dz_FittedVtx >= -10){
										ev_is2DiMuonsDzOK_FittedVtx++;
										brokenCounter++;
										if(is2DiMuonsMassOK_FittedVtx){
											ev_is2DiMuonsMassOK_FittedVtx++;
											brokenCounter++;
											if(diMuonF_IsoTk_FittedVtx <= 2 && diMuonF_IsoTk_FittedVtx >= -10){
											if(diMuonC_IsoTk_FittedVtx <= 2 && diMuonC_IsoTk_FittedVtx >= -10){
												ev_is2DiMuonsIsoTkOK_FittedVtx++;
												brokenCounter++;
												if(isDiMuonHLTFired){
													ev_isDiMuonHLTFired++;
													brokenCounter++;
													triggerFlag_std++;
												}
											}
											}
										}
									}
								}
							}
						}
					}
				}
			}
			//}//opening angle cut
			//}// fiducial cut in numerator
			//}}}

		} // closing for loop
		myfile->Close();
	} // closing while loop
	//Print out cutflow table
	//{{{
	std::cout << "" << std::endl;
	std::cout<<" Sample: " << fileName << endl;
	std::cout<<" Events          "<<ev_all<<std::endl;
	std::cout<<" ================ GEN MUONS ========================================= "<<std::endl;
	std::cout<<" 1GenMu17                       "<<c1genm<<"   reff "<<c1genm/(ev_all*1.0)<<std::endl;
	std::cout<<" 2GenMu8                        "<<c2genm<<"   reff  "<<c2genm/(c1genm*1.0)<<std::endl;
	std::cout<<" 3GenMu8                        "<<c3genm<<"   reff  "<<c3genm/(c2genm*1.0)<<std::endl;
	std::cout<<" 4GenMu8                        "<<c4genm<<"   reff  "<<c4genm/(c3genm*1.0)<<std::endl;
	std::cout<<" 4GenMu8 Lxy/Lz                 "<<ev_4gmlxylzcut<<"   reff   "<<ev_4gmlxylzcut/c4genm<<std::endl;
	std::cout<<" ================ RECO MUONS ========================================= "<<std::endl;
	std::cout<<" 1RecMu17                       "<<c1recm<<"  reff  "<<c1recm/(ev_all*1.0)<<std::endl;
	std::cout<<" 2RecMu8                        "<<c2recm<<"  reff  "<<c2recm/(c1recm*1.0)<<std::endl;
	std::cout<<" 3RecMu8                        "<<c3recm<<"  reff  "<<c3recm/(c2recm*1.0)<<std::endl;
	std::cout<<" 4RecMu8                        "<<c4recm<<"  reff  "<<c4recm/(c3recm*1.0)<<std::endl;
	std::cout<<" ================ EVENT variables ================= "<<std::endl;
	std::cout<<" Events with VtxOK              "<<ev_isVtxOK<<"    reff  "<<ev_isVtxOK/(1.0*c4recm)<<std::endl;
	std::cout<<" Events with 2 muonjets         "<<ev_is2MuJets<<"     reff  "<<ev_is2MuJets/(1.0*ev_isVtxOK)<<std::endl;
	std::cout<<" Events with 2 Dimuons          "<<ev_is2DiMuons<<"    reff  "<<ev_is2DiMuons/(1.0*ev_is2MuJets)<<std::endl;
	std::cout<<" Events with 2DimVtxOK          "<<ev_is2DiMuonsFittedVtxOK<<"    reff  "<<ev_is2DiMuonsFittedVtxOK/(1.0*ev_is2DiMuons)<<std::endl;
	std::cout<<" Events with 2DimHitPix         "<<ev_isPixelHitOK<<"     reff  "<<ev_isPixelHitOK/(1.0*ev_is2DiMuonsFittedVtxOK)<<std::endl;
	std::cout<<" Events with 2DimDzOK           "<<ev_is2DiMuonsDzOK_FittedVtx<<"   reff   "<<ev_is2DiMuonsDzOK_FittedVtx/(1.0*ev_isPixelHitOK)<<std::endl;
	std::cout<<" Events with 2DimMassOK         "<<ev_is2DiMuonsMassOK_FittedVtx<<"  reff   "<<ev_is2DiMuonsMassOK_FittedVtx/(1.0*ev_is2DiMuonsDzOK_FittedVtx)<<endl;
	std::cout<<" Events with 2DimIsoOK          "<<ev_is2DiMuonsIsoTkOK_FittedVtx<<"   reff   "<<ev_is2DiMuonsIsoTkOK_FittedVtx/(1.0*ev_is2DiMuonsMassOK_FittedVtx)<<endl;
	std::cout<<" Events with 2DimHLT            "<<ev_isDiMuonHLTFired<<"   reff   "<<ev_isDiMuonHLTFired/(1.0*ev_is2DiMuonsIsoTkOK_FittedVtx)<<endl;
	std::cout<<" ratio reco/gen                 "<<ev_isDiMuonHLTFired/(1.0*ev_4gmlxylzcut)<<" +/-  "<<sqrt( ((ev_isDiMuonHLTFired/(1.0*ev_4gmlxylzcut))*(1- (ev_isDiMuonHLTFired/(1.0*ev_4gmlxylzcut)) ))/(1.0*ev_4gmlxylzcut))<<std::endl;
	//}}}
}
Пример #17
0
void run(const Char_t *files=NULL, Bool_t mc=kFALSE, Bool_t tpid=kTRUE,  Bool_t tchg=kFALSE,  Bool_t tpp=kTRUE, Long64_t nev=1234567890, Long64_t first = 0)
{
  TStopwatch timer;
  timer.Start();

  // VERY GENERAL SETTINGS
  //AliLog::SetGlobalLogLevel(AliLog::kError);
  if(gSystem->Load("libANALYSIS.so")<0) return;
  if(gSystem->Load("libANALYSISalice.so")<0) return;
  if(gSystem->Load("libTender.so")<0) return;
  if(gSystem->Load("libTenderSupplies.so")<0) return;
//   if(gSystem->Load("libMES.so")<0) return;
    if(gSystem->Load("libPWGLFspectra.so")<0) return;

  // DEFINE DATA CHAIN
  TChain *chain = NULL;
  if(!files) chain = MakeChainLST();
  else chain = MakeChainLST(files);

  if(!chain) return;
  chain->Lookup();
  chain->GetListOfFiles()->Print();
  Long64_t nfound=chain->GetEntries();
  printf("\tENTRIES FOUND [%lli] REQUESTED [%lli]\n", nfound, nev>nfound?nfound:nev);

  // BUILD ANALYSIS MANAGER
  AliAnalysisManager *mgr = new AliAnalysisManager("Multiplicity and Event Shape");
  AliESDInputHandler *esdH = new AliESDInputHandler();
  AliMCEventHandler *mcH(NULL);
  mgr->SetInputEventHandler(esdH);
  if(mc) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler());
  //mgr->SetDebugLevel(10);
  mgr->SetSkipTerminate(kTRUE);

  // LOAD tasks
  // *******************  PID response  ******************
  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskPIDResponse.C");
  if(!mc) AddTaskPIDResponse();
  else AddTaskPIDResponse(kTRUE,kTRUE,kTRUE,2);

  // *******************  Tenders  ***********************
  AliTender *aliTender(NULL);
  gROOT->LoadMacro("$ALICE_PHYSICS/TENDER/TenderSupplies/AddTaskTender.C");
  if(!mc){    // for DATA
    aliTender = (AliTender*)AddTaskTender(!mc, kTRUE, kTRUE, kTRUE, kTRUE, kFALSE, kTRUE, kFALSE, kFALSE);
       // (useV0, useTPC,  !!! useTOF=kFALSE for MC !!!, useTRD, usePID, useVTX, useT0, useEmc, usePtFix)
  } else {  // for MC
    aliTender = (AliTender*)AddTaskTender(!mc, kTRUE, kFALSE, kTRUE, kTRUE, kTRUE, kTRUE, kFALSE, kFALSE);  // (useV0, useTPC,  !!! useTOF=kFALSE for MC !!!, useTRD, usePID, useVTX, useT0, useEmc, usePtFix)
  }
  aliTender->SetHandleOCDB(kTRUE);
  //aliTender->SetDefaultCDBStorage(Form("alien://folder=/alice/data/2010/OCDB?cacheFolder=%s/local", gSystem->ExpandPathName("$HOME")));
  // aliTender->SetDefaultCDBStorage(Form("local://%s/local/alice/data/2010/OCDB", gSystem->ExpandPathName("$HOME")));

// *******************  Physics Selection  *************
  gROOT->LoadMacro("$ALICE_PHYSICS/OADB/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask *physSelTask = AddTaskPhysicsSelection(mc); // 0 = real data; 1 = MC

  // *******************  MES Tender  ******************
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/MultEvShape/AddMEStender.C");
  AddMEStender(mc);

  // *******************  MES PID task  ******************
  if(tpid){
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/MultEvShape/AddMESpidTask.C");
	AddMESpidTask(mc);
  }
//

//   // *******************  MES CHG task  ******************
  if(tchg){
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/MultEvShape/AddMESchgTask.C");
    AddMESchgTask(mc);
  }
//
//   // *******************  MES ppCol task  ******************
  if(tpp){
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/MultEvShape/AddMESppColTask.C");
    AddMESppColTask(mc);
  }


  if (!mgr->InitAnalysis()) return;
  mgr->PrintStatus();
  mgr->StartAnalysis("local", chain, nev, first);
  timer.Stop();
  timer.Print();
  // verbosity
  printf("\tCLEANING TASK LIST:\n");
  mgr->GetTasks()->Delete();

  if(mcH) delete mcH;
  delete esdH;
  delete chain;
}
Пример #18
0
void runTask(Float_t etamax=0.5,const char * incollection = 0, const char * outfile = "dndeta.root", Bool_t skipNorm = kFALSE)
{
  // for running with root only
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libESD");
  gSystem->Load("libAOD");

  // load analysis framework
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");


  TChain * chain = new TChain ("TE");
  if (incollection == 0) {
    chain->Add("galice.root");
  }
  else if (TString(incollection).Contains("xml")){
    TGrid::Connect("alien://");
    TAlienCollection * coll = TAlienCollection::Open (incollection);
    while(coll->Next()){
      chain->Add(TString("alien://")+coll->GetLFN());
    }
  } else {
    ifstream file_collect(incollection);
    TString line;
    while (line.ReadLine(file_collect) ) {
      chain->Add(line.Data());
    }
  }
  chain->GetListOfFiles()->Print();

  // for includes use either global setting in $HOME/.rootrc
  // ACLiC.IncludePaths: -I$(ALICE_ROOT)/include
  // or in each macro
  gSystem->AddIncludePath("-I$ALICE_ROOT/include");

  // Create the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("dNdeta");

  AliVEventHandler* esdH = new AliESDInputHandler;
  ((AliESDInputHandler*)esdH)->SetReadFriends(kFALSE);
  mgr->SetInputEventHandler(esdH);

  // Create tasks
  gROOT->LoadMacro("AliAnalysisTaskdNdetaMC.cxx++g");

  AliAnalysisTask *task1 = new AliAnalysisTaskdNdetaMC("TaskdNdeta");
  ((AliAnalysisTaskdNdetaMC*)task1)->SetEtaMax(etamax);
  if (skipNorm) ((AliAnalysisTaskdNdetaMC*)task1)->SkipNormalization();
  // Enable MC event handler

  AliMCEventHandler* handler = new AliMCEventHandler;
  handler->SetReadTR(kFALSE);
  mgr->SetMCtruthEventHandler(handler);

  // Add tasks
  mgr->AddTask(task1);

  // Create containers for input/output
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("coutput", TList::Class(),    AliAnalysisManager::kOutputContainer, outfile);

  // Connect input/output
  mgr->ConnectInput(task1, 0, cinput);
  mgr->ConnectOutput(task1, 1, coutput1);

  // Enable debug printouts
  mgr->SetDebugLevel(0);

  if (!mgr->InitAnalysis()) return;

  mgr->PrintStatus();

  mgr->StartAnalysis("local", chain);
}