예제 #1
0
파일: GrowTree.C 프로젝트: swang373/VHbbUF
TLorentzVector makePtEtaPhiE(double ptCor, double pt, double eta, double phi, double e, 
                             bool rescaleEnergy=true)
{
    TLorentzVector j;
    j.SetPtEtaPhiE(ptCor, eta, phi, (rescaleEnergy ? (e * ptCor / pt) : e));
    return j;
}
예제 #2
0
void SingleTopTree::FillJets(){
  Jets.clear();
  bJets.clear();

  TLorentzVector muon;
  int tightMuIndex;
  bool mu = TightIso06Muons.size() > 0;
  
  if( mu )
    tightMuIndex = TightIso06Muons[0] ;
  if(!mu){
    mu = Tight12IsoMuons.size() > 0 ;
    if( mu )
      tightMuIndex = Tight12IsoMuons[0] ;
  }
  muon.SetPtEtaPhiE( muons_Pt[tightMuIndex] , muons_Eta[tightMuIndex] , muons_Phi[tightMuIndex] , muons_E[tightMuIndex] );

  for( int jid = 0 ; jid < jetsAK4_size ; jid++ ){

    //if( Event_EventNumber == 672782113 ) cout << (jetsAK4_CorrPt[jid] > 40) << " " <<  (fabs( jetsAK4_Eta[jid] ) < 4.7) << " " << jetsAK4_PassesID[jid];

    if( jetsAK4_CorrPt[jid] > 40 &&
	fabs( jetsAK4_Eta[jid] ) < 4.7 &&
	jetsAK4_PassesID[jid]
	){

      double DR = 1.0 ; 
      if( mu ){
	TLorentzVector jet;
	jet.SetPtEtaPhiE( jetsAK4_CorrPt[jid] , jetsAK4_Eta[jid] , jetsAK4_Phi[jid] , jetsAK4_CorrE[jid] );
	DR = muon.DeltaR( jet );
      }

      // if( Event_EventNumber == 672782113 )
      // 	cout << DR << endl;

      if ( DR > 0.3 ){
	Jets.push_back( jid );
	if( jetsAK4_IsCSVT[jid]  && fabs( jetsAK4_Eta[jid] ) <= 2.4 ){
	  bJets.push_back(jid);
	}
      }
    }
      //if( Event_EventNumber == 672782113 )
      //cout << endl;
  }
}
예제 #3
0
//Getting FourVectors
TLorentzVector D3PDSelector::GetFourVecByType(std::string ObjectType, unsigned int index)
{
	TLorentzVector par;
	float E = GetValByType<float>(ObjectType, "_E", index);
	float eta = GetValByType<float>(ObjectType, "_eta", index);
	float phi = GetValByType<float>(ObjectType, "_phi", index);
	float pt = GetValByType<float>(ObjectType, "_pt", index);
	par.SetPtEtaPhiE(pt,eta,phi,E);
	
	return par;
}
예제 #4
0
float BDTOhio_v2::Evaluate(std::string categoryLabel, const std::vector<pat::Muon>& selectedMuons, const std::vector<pat::Electron>& selectedElectrons, const std::vector<pat::Jet>& selectedJets, const std::vector<pat::Jet>& selectedJetsLoose, const pat::MET& pfMET){

  if(selectedMuons.size()+selectedElectrons.size()!=1){
    //    cerr << "BDTOhio_v2: not a SL event" << endl;
    return -2;
  }
  // ==================================================
  // construct object vectors etc
  TLorentzVector lepton_vec;
  TLorentzVector met_vec;
  vector<TLorentzVector> jet_vecs;
  vector<double> jetCSV;
  vector< vector<double> > jets_vvdouble;
  vector<TLorentzVector> jet_loose_vecs;
  vector<TLorentzVector> tagged_jet_vecs;
  vector<double> jetCSV_loose;
  vector<double> sortedCSV;
  if(selectedMuons.size()>0) lepton_vec.SetPtEtaPhiE(selectedMuons[0].pt(),selectedMuons[0].eta(),selectedMuons[0].phi(),selectedMuons[0].energy());
  if(selectedElectrons.size()>0) lepton_vec.SetPtEtaPhiE(selectedElectrons[0].pt(),selectedElectrons[0].eta(),selectedElectrons[0].phi(),selectedElectrons[0].energy());
  met_vec.SetPtEtaPhiE(pfMET.pt(),0,pfMET.phi(),pfMET.pt());
  for(auto jet=selectedJets.begin();jet!=selectedJets.end(); jet++){
    TLorentzVector jetvec;
    jetvec.SetPtEtaPhiE(jet->pt(),jet->eta(),jet->phi(),jet->energy());
    jet_vecs.push_back(jetvec);
    if(MiniAODHelper::GetJetCSV(*jet)>btagMcut){
      tagged_jet_vecs.push_back(jetvec);
    }
    vector<double> pxpypzE;
    pxpypzE.push_back(jet->px());
    pxpypzE.push_back(jet->py());
    pxpypzE.push_back(jet->pz());
    pxpypzE.push_back(jet->energy());
    jets_vvdouble.push_back(pxpypzE);
    jetCSV.push_back(MiniAODHelper::GetJetCSV(*jet));
  }
  sortedCSV=jetCSV;
  std::sort(sortedCSV.begin(),sortedCSV.end(),std::greater<float>());
  for(auto jet=selectedJetsLoose.begin();jet!=selectedJetsLoose.end(); jet++){
    TLorentzVector jetvec;
    jetvec.SetPtEtaPhiE(jet->pt(),jet->eta(),jet->phi(),jet->energy());
    jet_loose_vecs.push_back(jetvec);
    jetCSV_loose.push_back(MiniAODHelper::GetJetCSV(*jet));
  }

  // TODO loose jet and csv defintion

  // ==================================================
  // calculate variables
  // aplanarity and sphericity
  float aplanarity,sphericity;
  bdtvar.getSp(lepton_vec,met_vec,jet_vecs,aplanarity,sphericity);

  // Fox Wolfram
  float h0,h1,h2,h3,h4;
  bdtvar.getFox(jet_vecs,h0,h1,h2,h3,h4);

  // best higgs mass 1
  double minChi,dRbb;
  TLorentzVector bjet1,bjet2;
  float bestHiggsMass = bdtvar.getBestHiggsMass(lepton_vec,met_vec,jet_vecs,jetCSV,minChi,dRbb,bjet1,bjet2, jet_loose_vecs,jetCSV_loose);
  
  // study top bb system
  TLorentzVector dummy_metv;
  double minChiStudy, chi2lepW, chi2leptop, chi2hadW, chi2hadtop, mass_lepW, mass_leptop, mass_hadW, mass_hadtop, dRbbStudy, testquant1, testquant2, testquant3, testquant4, testquant5, testquant6, testquant7; 
  TLorentzVector b1,b2;
  bdtvar.study_tops_bb_syst (pfMET.pt(), pfMET.phi(), dummy_metv, lepton_vec, jets_vvdouble, jetCSV, minChiStudy, chi2lepW, chi2leptop, chi2hadW, chi2hadtop, mass_lepW, mass_leptop, mass_hadW, mass_hadtop, dRbbStudy, testquant1, testquant2, testquant3, testquant4, testquant5, testquant6, testquant7, b1, b2);
  float dEta_fn=testquant6;
  // ptE ratio
  float pt_E_ratio = bdtvar.pt_E_ratio_jets(jets_vvdouble);
  
  // etamax
  float jet_jet_etamax = bdtvar.get_jet_jet_etamax (jets_vvdouble);
  float jet_tag_etamax = bdtvar.get_jet_tag_etamax (jets_vvdouble,jetCSV);
  float tag_tag_etamax = bdtvar.get_tag_tag_etamax (jets_vvdouble,jetCSV);

  // jet variables
  float sum_pt_jets=0;
  float dr_between_lep_and_closest_jet=99;
  float mht_px=0;
  float mht_py=0;
  TLorentzVector p4_of_everything=lepton_vec;
  p4_of_everything+=met_vec;
  for(auto jetvec = jet_vecs.begin() ; jetvec != jet_vecs.end(); ++jetvec){
    dr_between_lep_and_closest_jet=fmin(dr_between_lep_and_closest_jet,lepton_vec.DeltaR(*jetvec));
    sum_pt_jets += jetvec->Pt();
    mht_px += jetvec->Px();
    mht_py += jetvec->Py();
    p4_of_everything += *jetvec;
  }
  mht_px+=lepton_vec.Px();
  mht_py+=lepton_vec.Py();
  float mass_of_everything=p4_of_everything.M();
  float sum_pt_wo_met=sum_pt_jets+lepton_vec.Pt();
  float sum_pt_with_met=pfMET.pt()+sum_pt_wo_met;
  float MHT=sqrt( mht_px*mht_px + mht_py*mht_py );

  float Mlb=0;   // mass of lepton and closest bt-tagged jet
  float minDr_for_Mlb=999.;
  for(auto tagged_jet=tagged_jet_vecs.begin();tagged_jet!=tagged_jet_vecs.end();tagged_jet++){
    float drLep=lepton_vec.DeltaR(*tagged_jet);
    if(drLep<minDr_for_Mlb){
      minDr_for_Mlb=drLep;
      Mlb=(lepton_vec+*tagged_jet).M();
    }
  }
  float closest_tagged_dijet_mass=-99;
  float minDrTagged=99;
  float sumDrTagged=0;
  int npairs=0;
  float tagged_dijet_mass_closest_to_125=-99;
  for(auto tagged_jet1=tagged_jet_vecs.begin();tagged_jet1!=tagged_jet_vecs.end();tagged_jet1++){
    for(auto tagged_jet2=tagged_jet1+1;tagged_jet2!=tagged_jet_vecs.end();tagged_jet2++){
      float dr=tagged_jet1->DeltaR(*tagged_jet2);
      float m = (*tagged_jet1+*tagged_jet2).M();
      sumDrTagged+=dr;
      npairs++;
      if(dr<minDrTagged){
	minDrTagged=dr;
	closest_tagged_dijet_mass=m;
      }
      if(fabs(tagged_dijet_mass_closest_to_125-125)>fabs(m-125)){
	tagged_dijet_mass_closest_to_125=m;
      }

    }
  }
  float avgDrTagged=-1;
  if(npairs!=0) avgDrTagged=sumDrTagged/npairs;
  // M3
  float m3 = -1.;
  float maxpt_for_m3=-1;
  for(auto itJetVec1 = jet_vecs.begin() ; itJetVec1 != jet_vecs.end(); ++itJetVec1){
    for(auto itJetVec2 = itJetVec1+1 ; itJetVec2 != jet_vecs.end(); ++itJetVec2){
      for(auto itJetVec3 = itJetVec2+1 ; itJetVec3 != jet_vecs.end(); ++itJetVec3){
    
        TLorentzVector m3vec = *itJetVec1 + *itJetVec2 + *itJetVec3;
        
	if(m3vec.Pt() > maxpt_for_m3){
	  maxpt_for_m3 = m3vec.Pt();
	  m3 = m3vec.M();
	}
      } 
    }
  }
  // btag variables
  float averageCSV = 0;
  float lowest_btag=99;
  int njets=selectedJets.size();
  int ntags=0;
  for(auto itCSV = jetCSV.begin() ; itCSV != jetCSV.end(); ++itCSV){
    if(*itCSV<btagMcut) continue;
    lowest_btag=fmin(*itCSV,lowest_btag);
    averageCSV += fmax(*itCSV,0);
    ntags++;
  }
  if(ntags>0)
    averageCSV /= ntags;
  else
    averageCSV=1;
  if(lowest_btag>90) lowest_btag=-1;

  float csvDev = 0;
  for(auto itCSV = jetCSV.begin() ; itCSV != jetCSV.end(); ++itCSV){
    if(*itCSV<btagMcut) continue;
    csvDev += pow(*itCSV - averageCSV,2);
  }
  if(ntags>0)
    csvDev /= ntags;
  else
    csvDev=-1.;


  // ==================================================
  // Fill variable map
  variableMap["all_sum_pt_with_met"]=sum_pt_with_met;
  variableMap["aplanarity"]=aplanarity;
  variableMap["avg_btag_disc_btags"]=averageCSV;
  variableMap["avg_dr_tagged_jets"]=avgDrTagged;
  variableMap["best_higgs_mass"]=bestHiggsMass;
  variableMap["closest_tagged_dijet_mass"]=closest_tagged_dijet_mass;
  variableMap["dEta_fn"]=dEta_fn;
  variableMap["dev_from_avg_disc_btags"]=csvDev;
  variableMap["dr_between_lep_and_closest_jet"]=dr_between_lep_and_closest_jet;
  variableMap["fifth_highest_CSV"]=njets>4?sortedCSV[4]:-1.;
  variableMap["first_jet_pt"]=jet_vecs.size()>0?jet_vecs[0].Pt():-99;
  variableMap["fourth_highest_btag"]=njets>3?sortedCSV[3]:-1.;
  variableMap["fourth_jet_pt"]=jet_vecs.size()>3?jet_vecs[3].Pt():-99;
  variableMap["h0"]=h0;
  variableMap["h1"]=h1;
  variableMap["h2"]=h2;
  variableMap["h3"]=h3;
  variableMap["HT"]=sum_pt_jets;
  variableMap["invariant_mass_of_everything"]=mass_of_everything;
  variableMap["lowest_btag"]=lowest_btag;
  variableMap["M3"]=m3;
  variableMap["maxeta_jet_jet"]=jet_jet_etamax;
  variableMap["maxeta_jet_tag"]=jet_tag_etamax;
  variableMap["maxeta_tag_tag"]=tag_tag_etamax;
  variableMap["min_dr_tagged_jets"]=minDrTagged;
  variableMap["MET"]=pfMET.pt();
  variableMap["MHT"]=MHT;
  variableMap["Mlb"]=Mlb;
  variableMap["pt_all_jets_over_E_all_jets"]=pt_E_ratio;
  variableMap["second_highest_btag"]=njets>1?sortedCSV[1]:-1.;
  variableMap["second_jet_pt"]=jet_vecs.size()>1?jet_vecs[1].Pt():-99;
  variableMap["sphericity"]=sphericity;
  variableMap["tagged_dijet_mass_closest_to_125"]=tagged_dijet_mass_closest_to_125;
  variableMap["third_highest_btag"]=njets>2?sortedCSV[2]:-1.;
  variableMap["third_jet_pt"]=jet_vecs.size()>2?jet_vecs[2].Pt():-99;

  // ==================================================
  // evaluate BDT of current category
  return readerMap[categoryLabel]->EvaluateMVA("BDT");
}
예제 #5
0
void pgsAnalysis::Loop()
{

double tHrec, tZ1m, tZ2m, tcosthetaStar, tPhi, tPhi1, tcostheta1, tcostheta2,tHrec_constr,tZ1m_constr, tZ2m_constr;
string ttype;
hists->Branch("Hrec", &tHrec);
hists->Branch("Z1m", &tZ1m);
hists->Branch("Z2m", &tZ2m);
hists->Branch("costhetaStar", &tcosthetaStar);
hists->Branch("Phi", &tPhi);
hists->Branch("Phi1", &tPhi1);
hists->Branch("costheta1", &tcostheta1);
hists->Branch("costheta2", &tcostheta2);
hists->Branch("type", &ttype);

//event type!!
int eeee, xxxx, eexx, xxee;

double Zmass = 91.19;
double vZmass;
if (pairing == 0){
	vZmass = 91.19;
}
else{
	vZmass = 45.;
}
		TVectorT<double> elSum(4);
		TVectorT<double> muSum(4);


	//electrons array
	vector<int> el; int elC = 0;
	//muons array
	vector<int> mu;	int muC = 0;
	//antielectrons array
	vector<int> antiel;	int antielC = 0;
	//antimuons array
	vector<int> antimu;	int antimuC = 0;

	vector<TVector3> leptons;

	TVector3 lep1,lep2,lep3,lep4;
	TVector3 Za, Zb, Zc, Zd, H;


	int lCounter = 0;
	int totaLlCounter = 0;
	int goodEventCounter = 0;
	int histCounter = 0;

	if (fChain == 0) return;
	

	int nentries = n;

// 	cout << " nentries are "<<nentries<<endl;


	Long64_t nbytes = 0, nb = 0;
	for (Long64_t jentry=0; jentry<nentries;jentry++) {
	Long64_t ientry = LoadTree(jentry);
	if (ientry < 0) break;
	nb = fChain->GetEntry(jentry);   nbytes += nb;
	// if (Cut(ientry) < 0) continue;

		el.clear();
		antiel.clear();
		mu.clear();
		antimu.clear();
		lCounter = 0;
		eeee = 0;
		xxxx = 0;
		eexx = 0;
		xxee = 0;

		//particles identified by type, ntrk
		for (int inst = 0; inst < npart; inst++){	// inst from "instance" on the scan tree
			
// 			cout<< " instance "<< inst <<endl;
// 			cout<< pT[inst]<< endl;
	
			//fill el mu vectors
			if ( typ[inst] == 1 && ntrk[inst] == -1){
				el.push_back(inst);
				elC++;
				lCounter++;
				totaLlCounter++;
			}
			if ( typ[inst] == 1 && ntrk[inst] == 1){
				antiel.push_back(inst);
				antielC++;
				lCounter++;
				totaLlCounter++;
			}
			if ( typ[inst] == 2 && ntrk[inst] == -1){
				mu.push_back(inst);
				muC++;
				lCounter++;
				totaLlCounter++;
			}
			if ( typ[inst] == 2 && ntrk[inst] == 1){
				antimu.push_back(inst);
				antimuC++;
				lCounter++;
				totaLlCounter++;
			}
			if ( (typ[inst] == 4 && jmas[inst] > 10. )|| (typ[inst] == 6 && pT[inst] > 10. )){
				lCounter = 0; //dont count the event
			}

		
		}//end instance loop (particles in an event

// 		cout<< "leptons in the event are "<< lCounter<<endl;
// 		if (lCounter == 4) { 

		fillFlag = false;

		// If else if loops reconstructing the particles according to the type 4e,4mu, 2e2mu
		
		if (el.size() == 1 && mu.size() == 1 && antiel.size() == 1 && antimu.size() == 1){ //2e2m
			goodEventCounter++;


			lep1.SetPtEtaPhi( pT[el[0]], eta[el[0]]	, phi[el[0]]);			//set up of lepton four-vectors
			lep2.SetPtEtaPhi( pT[antiel[0]], eta[antiel[0]]	, phi[antiel[0]]);
			lep3.SetPtEtaPhi( pT[mu[0]], eta[mu[0]]	, phi[mu[0]]);
			lep4.SetPtEtaPhi( pT[antimu[0]], eta[antimu[0]]	, phi[antimu[0]]);

			Za = lep1 + lep2;
			Zb = lep3 + lep4;

			mZ1 = sqrt(pow(lep1.Mag()+lep2.Mag(),2)-Za.Mag2());	// reconstruct z masses 
			mZ2 = sqrt(pow(lep3.Mag()+lep4.Mag(),2)-Zb.Mag2());


			//select leading Z
			if(mZ1 > mZ2) { Z1.SetVectM( Za, mZ1); Z2.SetVectM(Zb,mZ2); lep_min1.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus1.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min2.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus2.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());eexx++;}	//to set the highest mass the z
			else { Z2.SetVectM( Za, mZ1); Z1.SetVectM(Zb,mZ2); lep_min2.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus2.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min1.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus1.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());xxee++;}


			

		fillFlag = true;
		}



		else if (el.size() == 2 && mu.size() == 0  && antiel.size() == 2 && antimu.size() == 0){ //4e
			goodEventCounter++;

			lep1.SetPtEtaPhi( pT[el[0]], eta[el[0]]	, phi[el[0]]);	
			lep2.SetPtEtaPhi( pT[antiel[0]], eta[antiel[0]]	, phi[antiel[0]]);
			lep3.SetPtEtaPhi( pT[el[1]], eta[el[1]]	, phi[el[1]]);	
			lep4.SetPtEtaPhi( pT[antiel[1]], eta[antiel[1]]	, phi[antiel[1]]);

			Za = lep1 + lep2;
			Zb = lep3 + lep4;
			Zc = lep1 + lep4;
			Zd = lep3 + lep2;

			double mZa = sqrt(pow(lep1.Mag()+lep2.Mag(),2)-Za.Mag2());
			double mZb = sqrt(pow(lep3.Mag()+lep4.Mag(),2)-Zb.Mag2());
			double mZc = sqrt(pow(lep1.Mag()+lep4.Mag(),2)-Zc.Mag2());
			double mZd = sqrt(pow(lep2.Mag()+lep3.Mag(),2)-Zd.Mag2());

			double s1a;
			double s1b;
			double s2a;
			double s2b;
			if ( pairing == 0){
			s1a = pow(mZa-vZmass,2) + pow(mZb-Zmass,2);
			s1b = pow(mZa-Zmass,2) + pow(mZb-vZmass,2);
			s2a = pow(mZc-vZmass,2) + pow(mZd-Zmass,2);
			s2b = pow(mZc-Zmass,2) + pow(mZd-vZmass,2);
			}
			else{
			s1a = fabs(mZb-Zmass);
			s1b = fabs(mZa-Zmass);
			s2a = fabs(mZd-Zmass);
			s2b = fabs(mZc-Zmass);
			}

			elSum[0] = s1a;
			elSum[1] = s1b;
			elSum[2] = s2a;
			elSum[3] = s2b;

			int min = TMath::LocMin(4, &elSum[0]);

			if( (min == 0 || min == 1) ){
				if(mZa > mZb) { Z1.SetVectM( Za, mZa); Z2.SetVectM(Zb,mZb); lep_min1.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus1.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min2.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus2.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());}	//to set the highest mass the z
				else { Z2.SetVectM( Za, mZa); Z1.SetVectM(Zb,mZb); lep_min2.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus2.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min1.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus1.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());}
				
			}
			else if( (min == 2 || min == 3) ){
				if(mZc > mZd) { Z1.SetVectM( Zc, mZc); Z2.SetVectM(Zd,mZd); lep_min1.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus1.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag()); lep_min2.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus2.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag());}	//to set the highest mass the z
				else { Z2.SetVectM( Zc, mZc); Z1.SetVectM(Zd,mZd); lep_min2.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus2.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag()); lep_min1.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus1.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag());}


			}
			eeee++;
		fillFlag = true;
		} 


		else if(el.size() == 0 && mu.size() == 2  && antiel.size() == 0 && antimu.size() == 2 )  { //4m
			goodEventCounter++;

			lep1.SetPtEtaPhi( pT[mu[0]], eta[mu[0]]	, phi[mu[0]]);	
			lep2.SetPtEtaPhi( pT[antimu[0]], eta[antimu[0]]	, phi[antimu[0]]);
			lep3.SetPtEtaPhi( pT[mu[1]], eta[mu[1]]	, phi[mu[1]]);	
			lep4.SetPtEtaPhi( pT[antimu[1]], eta[antimu[1]]	, phi[antimu[1]]);

			Za = lep1 + lep2;
			Zb = lep3 + lep4;
			Zc = lep1 + lep4;
			Zd = lep3 + lep2;

			double mZa = sqrt(pow(lep1.Mag()+lep2.Mag(),2)-Za.Mag2());
			double mZb = sqrt(pow(lep3.Mag()+lep4.Mag(),2)-Zb.Mag2());
			double mZc = sqrt(pow(lep1.Mag()+lep4.Mag(),2)-Zc.Mag2());
			double mZd = sqrt(pow(lep2.Mag()+lep3.Mag(),2)-Zd.Mag2());

			double s1a;
			double s1b;
			double s2a;
			double s2b;
			if ( pairing == 0){
			s1a = pow(mZa-vZmass,2) + pow(mZb-Zmass,2);
			s1b = pow(mZa-Zmass,2) + pow(mZb-vZmass,2);
			s2a = pow(mZc-vZmass,2) + pow(mZd-Zmass,2);
			s2b = pow(mZc-Zmass,2) + pow(mZd-vZmass,2);
			}
			else{
			s1a = fabs(mZb-Zmass);
			s1b = fabs(mZa-Zmass);
			s2a = fabs(mZd-Zmass);
			s2b = fabs(mZc-Zmass);
			}


			muSum[0] = s1a;
			muSum[1] = s1b;
			muSum[2] = s2a;
			muSum[3] = s2b;

			int min = TMath::LocMin(4, &muSum[0]);

			if( (min == 0 || min == 1) ){
				if(mZa > mZb) { Z1.SetVectM( Za, mZa); Z2.SetVectM(Zb,mZb); lep_min1.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus1.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min2.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus2.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());}	//to set the highest mass the z
				else { Z2.SetVectM( Za, mZa); Z1.SetVectM(Zb,mZb); lep_min2.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus2.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag()); lep_min1.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus1.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag());}
				
			}
			else if( (min == 2 || min == 3) ){
				if(mZc > mZd) { Z1.SetVectM( Zc, mZc); Z2.SetVectM(Zd,mZd); lep_min1.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus1.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag()); lep_min2.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus2.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag());}	//to set the highest mass the z
				else { Z2.SetVectM( Zc, mZc); Z1.SetVectM(Zd,mZd); lep_min2.SetPtEtaPhiE(lep1.Pt(),lep1.Eta(), lep1.Phi(),lep1.Mag()); lep_plus2.SetPtEtaPhiE(lep4.Pt(),lep4.Eta(), lep4.Phi(),lep4.Mag()); lep_min1.SetPtEtaPhiE(lep3.Pt(),lep3.Eta(), lep3.Phi(),lep3.Mag()); lep_plus1.SetPtEtaPhiE(lep2.Pt(),lep2.Eta(), lep2.Phi(),lep2.Mag());}


			}
		xxxx++;
		fillFlag = true;
		}


		if ( fillFlag == true && goodEventCounter < 25001) {	//if it fullfills the specs then fill and find angles

			rec_H = Z1 + Z2;
			double Hmass = rec_H.M();
			tHrec = Hmass;
// 			cout<<tHrec<<endl;

			double Z1mass = Z1.M();
			tZ1m = Z1mass;
			double Z2mass = Z2.M();
			tZ2m = Z2mass;
			double ptlepp1 = lep_plus1.Pt();
			double ptlepm1 = lep_min1.Pt();
			double ptlepp2 = lep_plus2.Pt();
			double ptlepm2 = lep_min2.Pt();
			double dR1 = sqrt(pow(fabs(lep_min1.Eta() - lep_plus1.Eta()),2)+pow(fabs(lep_min1.DeltaPhi(lep_plus1)),2));
			double dR2 = sqrt(pow(fabs(lep_min2.Eta() - lep_plus2.Eta()),2)+pow(fabs(lep_min2.DeltaPhi(lep_plus2)),2));

// 			if ( /*Hmass<120 || Hmass>130 || */Z1mass < 49 || Z1mass>107 || Z2mass < 12 || Z2mass> 115 ){continue;}	//constrains		
	
			//filling the simple histogram values
			h_Z1_m -> Fill(Z1.M());
			h_Z1_E -> Fill(Z1.E());
			h_Z1_Pt -> Fill(Z1.Pt());
			h_Z1_eta -> Fill(Z1.Eta());
			h_Z1_phi -> Fill(Z1.Phi());
	
			h_Z2_m -> Fill(Z2.M());
			h_Z2_E -> Fill(Z2.E());
			h_Z2_Pt -> Fill(Z2.Pt());
			h_Z2_eta -> Fill(Z2.Eta());
			h_Z2_phi -> Fill(Z2.Phi());
	
	
			h_rec_H_m	-> Fill(Hmass);
			h_rec_H_E	-> Fill(rec_H.E());
			h_rec_H_Pt	-> Fill(rec_H.Pt());
			h_rec_H_eta	-> Fill(rec_H.Eta());
			h_rec_H_phi	-> Fill(rec_H.Phi());	

			h_lep_plus1_E	-> Fill(lep_plus1.E());
			h_lep_plus1_Pt	-> Fill(ptlepp1);
			h_lep_plus1_eta	-> Fill(lep_plus1.Eta());
			h_lep_plus1_phi	-> Fill(lep_plus1.Phi());

			h_lep_min1_E	-> Fill(lep_min1.E());
			h_lep_min1_Pt	-> Fill(ptlepm1);
			h_lep_min1_eta	-> Fill(lep_min1.Eta());
			h_lep_min1_phi	-> Fill(lep_min1.Phi());

			h_lep_plus2_E	-> Fill(lep_plus2.E());
			h_lep_plus2_Pt	-> Fill(ptlepp2);
			h_lep_plus2_eta	-> Fill(lep_plus2.Eta());
			h_lep_plus2_phi	-> Fill(lep_plus2.Phi());

			h_lep_min2_E	-> Fill(lep_min2.E());
			h_lep_min2_Pt	-> Fill(ptlepm2);
			h_lep_min2_eta	-> Fill(lep_min2.Eta());
			h_lep_min2_phi	-> Fill(lep_min2.Phi());	

		//reconstructing the two lepton pairs Lorentz vectors
		lpair1 = lep_plus1 + lep_min1;
		lpair2 = lep_plus2 + lep_min2;

		//constructing 3-vectors in the lab frame
		lep_plus1_lab 	= lep_plus1.Vect();
		lep_plus2_lab 	= lep_plus2.Vect();	//.Vect() gives 3 vector from 4vector
		lep_min1_lab 	= lep_min1.Vect();	
		lep_min2_lab 	= lep_min2.Vect();
		lpair1_lab 	= lep_plus1_lab.Cross(lep_min1_lab);	
		lpair2_lab 	= lep_plus2_lab.Cross(lep_min2_lab);

// 		cout << " pt of lepton pair1 on rest frame is: "<< lpair1.Perp()<<endl;


	   	//Filling up Histograms with angles defined in the lab frame
		h_angle_lab_pair1 -> Fill(lep_plus1_lab.Angle(lep_min1_lab));
		h_angle_lab_pair2 -> Fill(lep_plus2_lab.Angle(lep_min2_lab));


       		//Filling up histograms with variables from articles
       		h_angle_lab_deleta1	-> Fill(fabs(lep_min1.Eta() - lep_plus1.Eta()));
       		h_angle_lab_delphi1	-> Fill(fabs(lep_min1.DeltaPhi(lep_plus1)));
       		h_angle_lab_deleta2	-> Fill(fabs(lep_min2.Eta() - lep_plus2.Eta()));
       		h_angle_lab_delphi2	-> Fill(fabs(lep_min2.DeltaPhi(lep_plus2)));


	   	//Looking at the Higgs rest frame
	   	TVector3 boost_rH 	= -rec_H.BoostVector(); //NOTE the minus sign! WHY - sign???
	   	TVector3 boost_rZ1	= -Z1.BoostVector();
	   	TVector3 boost_rZ2	= -Z2.BoostVector();	
	   	Higgs_rest	= rec_H;
	   	Z1_rH		= Z1;
	   	Z2_rH		= Z2;
	   	lep_p1_rH	= lep_plus1;	//
	   	lep_m1_rH	= lep_min1;
	   	lep_p2_rH	= lep_plus2;
	   	lep_m2_rH	= lep_min2;
	   	lep_p1_rZ1	= lep_plus1;
	   	lep_m2_rZ2	= lep_min2;
	   	lep_p2_rZ2	= lep_plus2;
	   	lep_m1_rZ1	= lep_min1;

	   	//Boosting vectors to the Higgs rest frame
	   	Higgs_rest.Boost(boost_rH);
	   	Z1_rH.Boost(boost_rH);
	   	Z2_rH.Boost(boost_rH);
	   	lep_p1_rH.Boost(boost_rH);
	   	lep_m1_rH.Boost(boost_rH);
	   	lep_p2_rH.Boost(boost_rH);
	   	lep_m2_rH.Boost(boost_rH);

	   	//Boosting leptons to Z rest frames
	   	lep_p1_rZ1.Boost(boost_rZ1);
	   	lep_m1_rZ1.Boost(boost_rZ1);
	   	lep_p2_rZ2.Boost(boost_rZ2);
	   	lep_m2_rZ2.Boost(boost_rZ2);

	   	//Setting 3Vectors in Higgs rest frame
	   	Z3_1_rH		= Z1_rH.Vect();
	   	Z3_2_rH		= Z2_rH.Vect();
	   	lep3_plus1_rH 	= lep_p1_rH.Vect();
	   	lep3_min1_rH	= lep_m1_rH.Vect();
	   	lep3_plus2_rH 	= lep_p2_rH.Vect();
	   	lep3_min2_rH	= lep_m2_rH.Vect();
		TVector3 Z3_1plane_rH 	= lep3_plus1_rH.Cross(lep3_min1_rH);	//wrong?
	   	TVector3 Z3_2plane_rH 	= lep3_plus2_rH.Cross(lep3_min2_rH);

	   	//Setting 3Vectors in Z1/Z2 rest frame
	   	lep3_plus1_rZ1	= lep_p1_rZ1.Vect();
	   	lep3_plus2_rZ2	= lep_p2_rZ2.Vect();
	   	lep3_min1_rZ1	= lep_m1_rZ1.Vect();
	   	lep3_min2_rZ2	= lep_m2_rZ2.Vect();

	   	//Filling up histogram for the phi angle distribution

		//pairnoume ta monadiaia dianysmata twn kathetwn pediwn, prwta ypologizoume to metro tous, meta eswteriko ginomeno, meta tokso tou costheta tous
		double metro1 = sqrt((pow(Z3_1plane_rH.X(),2))+(pow(Z3_1plane_rH.Y(),2))+(pow(Z3_1plane_rH.Z(),2)));
		double metro2 = sqrt((pow(Z3_2plane_rH.X(),2))+(pow(Z3_2plane_rH.Y(),2))+(pow(Z3_2plane_rH.Z(),2)));
		TVector3 Z3_1plane_rH_un = Z3_1plane_rH.Unit();
		TVector3 Z3_2plane_rH_un = Z3_2plane_rH.Unit();

		TVector3 drtPlane = Z3_1plane_rH_un.Cross(Z3_2plane_rH_un);
		double phi = acos(-Z3_1plane_rH_un.Dot(Z3_2plane_rH_un))*(Z3_1_rH.Dot(skata))/fabs(Z3_1_rH.Dot(skata));

		h_angle_rH_phi	-> Fill( phi );
		tPhi = phi;		



		//****Phi one angle , same procedure as before. Now the plane is the first Z boson vector with beam axis, so they form a plane, phi1 is angle between this plane and the Z1 plane (apo to decay twn 2 leptoniwn)
		TVector3 niScatter_un = (beamAxis.Cross(Z3_1_rH)).Unit();
		TVector3 drtPlane2 = Z3_1plane_rH_un.Cross(niScatter_un);
		double phiOne = acos(Z3_1plane_rH_un.Dot(niScatter_un))*(Z3_1_rH.Dot(skata2))/fabs(Z3_1_rH.Dot(skata2));
		h_angle_rH_phiOne	-> Fill( phiOne );
		tPhi1 = phiOne;


	   	//Filling up histogram for theta* angle: Z1/Z2 with Higgs boost vector
	   	h_angle_rH_thetaZ2	-> Fill(Z3_2_rH.CosTheta());
		
		double cosThetaStar = Z3_1_rH.CosTheta();
		h_angle_rH_thetaZ1	-> Fill(cosThetaStar);
		tcosthetaStar = cosThetaStar;

		//  boosting the z to the other z frame
		TLorentzVector Z_1_rZ2 = Z1;
		Z_1_rZ2.Boost(boost_rZ2);
		TVector3 Z3_1_rZ2 = Z_1_rZ2.Vect();
		TLorentzVector Z_2_rZ1 = Z2;
		Z_2_rZ1.Boost(boost_rZ1);
		TVector3 Z3_2_rZ1 = Z_2_rZ1.Vect();
		double cosTheta1 = cos(lep3_min1_rZ1.Angle(-Z3_2_rZ1));
		double cosTheta2 = cos(lep3_min2_rZ2.Angle(-Z3_1_rZ2));
	   	h_angle_rZ1_lp1Z1	-> Fill(cos(lep3_plus1_rZ1.Angle(-Z3_2_rZ1)));	
	   	h_angle_rZ1_lm1Z1	-> Fill(cosTheta1);	// theta1
	   	h_angle_rZ2_lp2Z2	-> Fill(cos(lep3_plus2_rZ2.Angle(-Z3_1_rZ2)));	
	   	h_angle_rZ2_lm2Z2	-> Fill(cosTheta2);	// theta2
		tcostheta1 = cosTheta1;
		tcostheta2 = cosTheta2;	

       		h_angle_rH_delphi1	-> Fill(fabs(lep_p1_rH.DeltaPhi(lep_m1_rH)));
		h_angle_rH_delphi2	-> Fill(fabs(lep_p2_rH.DeltaPhi(lep_m2_rH)));

		h_mZ1mZ2		-> Fill(Z1.M(),Z2.M());
		h_mVsPtZ1		-> Fill(Z1.M(),Z1.Pt());

		h_delphi1VsPtZ1_lab	-> Fill(Z1.Pt(),fabs(lep_min1.DeltaPhi(lep_plus1)));
		h_delphi2VsPtZ2_lab	-> Fill(Z2.Pt(),fabs(lep_min2.DeltaPhi(lep_plus2)));

		if (eexx ==1){ttype = "eexx";}
		else if(xxee ==1){ttype = "xxee";}
		else if(eeee ==1){ttype = "eeee";}
		else if(xxxx ==1){ttype = "xxxx";}
		hists->Fill();
		histCounter++;
		
		hists->Close();
		}	//end if fill

		////////////// fill out the decay type

		
		
	// filling the TTree


	}//end entries loop (events)

	//some regular reports
	cout<<endl;
	cout<<" good events are "<<goodEventCounter<<endl;
	cout<<" we see % "<< (double) goodEventCounter/n <<endl;

	cout<<endl;
	cout<<" histogram fills are "<<histCounter<<endl;
// 	cout<<" we see % "<< (double) goodEventCounter/n <<endl;




}//end loop void
예제 #6
0
void TreeFinalizerC_ZJet::finalize() {



    TString dataset_tstr(dataset_);

    gROOT->cd();

    std::string outfileName;

    if( DEBUG_ ) outfileName = "provaZJet_"+dataset_;
    else {
        if(dataset_!="") outfileName = "ZJet_"+dataset_;
        else outfileName = "ZJet";
    }

    outfileName = outfileName;


    if( nBlocks_ >1 ) {
        char blockText[100];
        sprintf( blockText, "_%d", iBlock_ );
        std::string iBlockString(blockText);
        outfileName = outfileName + iBlockString;
    }
    outfileName += ".root";


    TFile* outFile = new TFile(outfileName.c_str(), "RECREATE");
    outFile->cd();

    TTree* tree_passedEvents = new TTree("tree_passedEvents", "Unbinned data for statistical treatment");



    TH1D* h1_cutflow_50100 = new TH1D("cutflow_50100", "", 6, 0, 6);
    h1_cutflow_50100->Sumw2();


    TH1F* h1_nvertex = new TH1F("nvertex", "", 21, -0.5, 20.5);
    h1_nvertex->Sumw2();
    TH1F* h1_nvertex_PUW = new TH1F("nvertex_PUW", "", 21, -0.5, 20.5);
    h1_nvertex_PUW->Sumw2();

    TH1D* h1_quarkFraction_3050 = new TH1D("quarkFraction_3050", "", 1, 0., 1.);
    h1_quarkFraction_3050->Sumw2();
    TH1D* h1_quarkFraction_5080 = new TH1D("quarkFraction_5080", "", 1, 0., 1.);
    h1_quarkFraction_5080->Sumw2();
    TH1D* h1_quarkFraction_80120 = new TH1D("quarkFraction_80120", "", 1, 0., 1.);
    h1_quarkFraction_80120->Sumw2();

    TH1D* h1_quarkFraction_antibtag_3050 = new TH1D("quarkFraction_antibtag_3050", "", 1, 0., 1.);
    h1_quarkFraction_antibtag_3050->Sumw2();
    TH1D* h1_quarkFraction_antibtag_5080 = new TH1D("quarkFraction_antibtag_5080", "", 1, 0., 1.);
    h1_quarkFraction_antibtag_5080->Sumw2();
    TH1D* h1_quarkFraction_antibtag_80120 = new TH1D("quarkFraction_antibtag_80120", "", 1, 0., 1.);
    h1_quarkFraction_antibtag_80120->Sumw2();

    TH1D* h1_ptJetReco = new TH1D("ptJetReco", "", 100, 0., 300);
    h1_ptJetReco->Sumw2();
    TH1D* h1_pt2ndJetReco = new TH1D("pt2ndJetReco", "", 100, 5., 400);
    h1_pt2ndJetReco->Sumw2();

    TH1D* h1_ptDJetReco_3050 = new TH1D("ptDJetReco_3050", "", 50, 0., 1.0001);
    h1_ptDJetReco_3050->Sumw2();
    TH1D* h1_nChargedJetReco_3050 = new TH1D("nChargedJetReco_3050", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_3050->Sumw2();
    TH1D* h1_nNeutralJetReco_3050 = new TH1D("nNeutralJetReco_3050", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_3050->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_3050 = new TH1D("QGLikelihoodJetReco_3050", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_3050->Sumw2();

    TH1D* h1_ptDJetReco_antibtag_3050 = new TH1D("ptDJetReco_antibtag_3050", "", 50, 0., 1.0001);
    h1_ptDJetReco_antibtag_3050->Sumw2();
    TH1D* h1_nChargedJetReco_antibtag_3050 = new TH1D("nChargedJetReco_antibtag_3050", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_antibtag_3050->Sumw2();
    TH1D* h1_nNeutralJetReco_antibtag_3050 = new TH1D("nNeutralJetReco_antibtag_3050", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_antibtag_3050->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_3050 = new TH1D("QGLikelihoodJetReco_antibtag_3050", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_3050->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_gluon_3050 = new TH1D("QGLikelihoodJetReco_antibtag_gluon_3050", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_gluon_3050->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_quark_3050 = new TH1D("QGLikelihoodJetReco_antibtag_quark_3050", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_quark_3050->Sumw2();

    TH1D* h1_ptDJetReco_5080 = new TH1D("ptDJetReco_5080", "", 50, 0., 1.0001);
    h1_ptDJetReco_5080->Sumw2();
    TH1D* h1_nChargedJetReco_5080 = new TH1D("nChargedJetReco_5080", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_5080->Sumw2();
    TH1D* h1_nNeutralJetReco_5080 = new TH1D("nNeutralJetReco_5080", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_5080->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_5080 = new TH1D("QGLikelihoodJetReco_5080", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_5080->Sumw2();

    TH1D* h1_ptDJetReco_antibtag_5080 = new TH1D("ptDJetReco_antibtag_5080", "", 50, 0., 1.0001);
    h1_ptDJetReco_antibtag_5080->Sumw2();
    TH1D* h1_nChargedJetReco_antibtag_5080 = new TH1D("nChargedJetReco_antibtag_5080", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_antibtag_5080->Sumw2();
    TH1D* h1_nNeutralJetReco_antibtag_5080 = new TH1D("nNeutralJetReco_antibtag_5080", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_antibtag_5080->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_5080 = new TH1D("QGLikelihoodJetReco_antibtag_5080", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_5080->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_gluon_5080 = new TH1D("QGLikelihoodJetReco_antibtag_gluon_5080", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_gluon_5080->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_quark_5080 = new TH1D("QGLikelihoodJetReco_antibtag_quark_5080", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_quark_5080->Sumw2();

    TH1D* h1_ptDJetReco_80120 = new TH1D("ptDJetReco_80120", "", 50, 0., 1.0001);
    h1_ptDJetReco_80120->Sumw2();
    TH1D* h1_nChargedJetReco_80120 = new TH1D("nChargedJetReco_80120", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_80120->Sumw2();
    TH1D* h1_nNeutralJetReco_80120 = new TH1D("nNeutralJetReco_80120", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_80120->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_80120 = new TH1D("QGLikelihoodJetReco_80120", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_80120->Sumw2();

    TH1D* h1_ptDJetReco_antibtag_80120 = new TH1D("ptDJetReco_antibtag_80120", "", 50, 0., 1.0001);
    h1_ptDJetReco_antibtag_80120->Sumw2();
    TH1D* h1_nChargedJetReco_antibtag_80120 = new TH1D("nChargedJetReco_antibtag_80120", "", 51, -0.5, 50.5);
    h1_nChargedJetReco_antibtag_80120->Sumw2();
    TH1D* h1_nNeutralJetReco_antibtag_80120 = new TH1D("nNeutralJetReco_antibtag_80120", "", 51, -0.5, 50.5);
    h1_nNeutralJetReco_antibtag_80120->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_80120 = new TH1D("QGLikelihoodJetReco_antibtag_80120", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_80120->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_gluon_80120 = new TH1D("QGLikelihoodJetReco_antibtag_gluon_80120", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_gluon_80120->Sumw2();
    TH1D* h1_QGLikelihoodJetReco_antibtag_quark_80120 = new TH1D("QGLikelihoodJetReco_antibtag_quark_80120", "", 50, 0., 1.0001);
    h1_QGLikelihoodJetReco_antibtag_quark_80120->Sumw2();


    Double_t ptBinning[4];
    ptBinning[0] = 30.;
    ptBinning[1] = 50.;
    ptBinning[2] = 80.;
    ptBinning[3] = 120.;

    TH1D* h1_nEvents_passed = new TH1D("nEvents_passed", "", 3, ptBinning);
    h1_nEvents_passed->Sumw2();
    TH1D* h1_nEvents_passed_quark = new TH1D("nEvents_passed_quark", "", 3, ptBinning);
    h1_nEvents_passed_quark->Sumw2();


    TH1D* h1_ptZ = new TH1D("ptZ", "", 500, 0., 500.);
    h1_ptZ->Sumw2();
    TH1D* h1_mZ = new TH1D("mZ", "", 100, 50., 150.);
    h1_mZ->Sumw2();
    TH1D* h1_etaZ = new TH1D("etaZ", "", 15, -1.3, 1.3);
    h1_etaZ->Sumw2();
    TH1D* h1_phiZ = new TH1D("phiZ", "", 15, -3.1416, 3.1416);
    h1_phiZ->Sumw2();





    Int_t run;
    tree_->SetBranchAddress("run", &run);
    Int_t LS;
    tree_->SetBranchAddress("LS", &LS);
    Int_t event;
    tree_->SetBranchAddress("event", &event);
    Int_t nvertex;
    tree_->SetBranchAddress("nvertex", &nvertex);
    Float_t eventWeight;
    tree_->SetBranchAddress("eventWeight", &eventWeight);
    Float_t eventWeight_genjets;

    Float_t eMet;
    Float_t phiMet;
    tree_->SetBranchAddress("epfMet", &eMet);
    tree_->SetBranchAddress("phipfMet", &phiMet);


    Float_t ptHat;
    tree_->SetBranchAddress("ptHat", &ptHat);

    Int_t nPU;
    tree_->SetBranchAddress("nPU", &nPU);
    Int_t PUReWeight;
    tree_->SetBranchAddress("PUReWeight", &PUReWeight);
    Float_t rhoPF;
    tree_->SetBranchAddress("rhoPF", &rhoPF);
    Float_t rhoJetPF;
    tree_->SetBranchAddress("rhoJetPF", &rhoJetPF);

    Float_t eLeptZ1;
    tree_->SetBranchAddress("eLeptZ1", &eLeptZ1);
    Float_t ptLeptZ1;
    tree_->SetBranchAddress("ptLeptZ1", &ptLeptZ1);
    Float_t etaLeptZ1;
    tree_->SetBranchAddress("etaLeptZ1", &etaLeptZ1);
    Float_t phiLeptZ1;
    tree_->SetBranchAddress("phiLeptZ1", &phiLeptZ1);

    Float_t eLeptZ2;
    tree_->SetBranchAddress("eLeptZ2", &eLeptZ2);
    Float_t ptLeptZ2;
    tree_->SetBranchAddress("ptLeptZ2", &ptLeptZ2);
    Float_t etaLeptZ2;
    tree_->SetBranchAddress("etaLeptZ2", &etaLeptZ2);
    Float_t phiLeptZ2;
    tree_->SetBranchAddress("phiLeptZ2", &phiLeptZ2);



    Bool_t matchedToMC;
    tree_->SetBranchAddress("matchedToMC", &matchedToMC);

    Int_t nJets;
    tree_->SetBranchAddress("nJets", &nJets);
    Float_t eJet[50];
    tree_->SetBranchAddress("eJet", eJet);
    Float_t ptJet[50];
    tree_->SetBranchAddress("ptJet", ptJet);
    Float_t etaJet[50];
    tree_->SetBranchAddress("etaJet", etaJet);
    Float_t phiJet[50];
    tree_->SetBranchAddress("phiJet", phiJet);
    Int_t nChargedJet[50];
    tree_->SetBranchAddress("nChargedJet", nChargedJet);
    Int_t nNeutralJet[50];
    tree_->SetBranchAddress("nNeutralJet", nNeutralJet);
    Float_t eChargedHadronsJet[50];
    tree_->SetBranchAddress("eChargedHadronsJet", eChargedHadronsJet);
    Float_t eNeutralHadronsJet[50];
    tree_->SetBranchAddress("eNeutralHadronsJet", eNeutralHadronsJet);
    Float_t ePhotonsJet[50];
    tree_->SetBranchAddress("ePhotonsJet", ePhotonsJet);
    Float_t eHFHadronsJet[50];
    tree_->SetBranchAddress("eHFHadronsJet", eHFHadronsJet);
    Float_t eHFEMJet[50];
    tree_->SetBranchAddress("eHFEMJet", eHFEMJet);
    Float_t ptDJet[50];
    tree_->SetBranchAddress("ptDJet", ptDJet);
    Float_t rmsCandJet[50];
    tree_->SetBranchAddress("rmsCandJet", rmsCandJet);
    Float_t betaStarJet[50];
    tree_->SetBranchAddress("betaStarJet", betaStarJet);
    Float_t QGLikelihoodJet[50];
    tree_->SetBranchAddress("QGLikelihoodJet", QGLikelihoodJet);
    Float_t trackCountingHighEffBJetTagsJet[50];
    tree_->SetBranchAddress("trackCountingHighEffBJetTagsJet", trackCountingHighEffBJetTagsJet);
    Float_t combinedSecondaryVertexBJetTagJet[50];
    tree_->SetBranchAddress("combinedSecondaryVertexBJetTagJet", combinedSecondaryVertexBJetTagJet);
    Int_t pdgIdPartJet[50];
    tree_->SetBranchAddress("pdgIdPartJet", pdgIdPartJet);
    Float_t ptPartJet[50];
    tree_->SetBranchAddress("ptPartJet", ptPartJet);
    Float_t etaPartJet[50];
    tree_->SetBranchAddress("etaPartJet", etaPartJet);
    Float_t phiPartJet[50];
    tree_->SetBranchAddress("phiPartJet", phiPartJet);
    Float_t ptGenJet[50];
    tree_->SetBranchAddress("ptGenJet", ptGenJet);
    Float_t etaGenJet[50];
    tree_->SetBranchAddress("etaGenJet", etaGenJet);
    Float_t phiGenJet[50];
    tree_->SetBranchAddress("phiGenJet", phiGenJet);


    Float_t axis1Jet[50];
    tree_->SetBranchAddress("axis1Jet",axis1Jet);
    Float_t axis2Jet[50];
    tree_->SetBranchAddress("axis2Jet",axis2Jet);
    Float_t pullJet[50];
    tree_->SetBranchAddress("pullJet",pullJet);
    Float_t tanaJet[50];
    tree_->SetBranchAddress("tanaJet",tanaJet);
    Float_t ptD_QCJet[50];
    tree_->SetBranchAddress("ptD_QCJet",ptD_QCJet);
    Float_t rmsCand_QCJet[50];
    tree_->SetBranchAddress("rmsCand_QCJet",rmsCand_QCJet);
    Float_t axis1_QCJet[50];
    tree_->SetBranchAddress("axis1_QCJet",axis1_QCJet);
    Float_t axis2_QCJet[50];
    tree_->SetBranchAddress("axis2_QCJet",axis2_QCJet);
    Float_t pull_QCJet[50];
    tree_->SetBranchAddress("pull_QCJet",pull_QCJet);
    Float_t tana_QCJet[50];
    tree_->SetBranchAddress("tana_QCJet",tana_QCJet);
    Int_t   nPFCand_QC_ptCutJet[50];
    tree_->SetBranchAddress("nPFCand_QC_ptCutJet",nPFCand_QC_ptCutJet);
    //Float_t nChg_ptCutJet[50];	tree_->SetBranchAddress("nChg_ptCutJet",nChg_ptCutJet);
    //Float_t nChg_QCJet[50];		tree_->SetBranchAddress("nChg_QCJet",nChg_QCJet);
    //Float_t nChg_ptCut_QCJet[50];	tree_->SetBranchAddress("nChg_ptCut_QCJet",nChg_ptCut_QCJet);
    //Float_t nNeutral_ptCutJet[50];	tree_->SetBranchAddress("nNeutral_ptCutJet",nNeutral_ptCutJet);
    Float_t RchgJet[50];
    tree_->SetBranchAddress("RchgJet",RchgJet);
    Float_t RneutralJet[50];
    tree_->SetBranchAddress("RneutralJet",RneutralJet);
    Float_t RJet[50];
    tree_->SetBranchAddress("RJet",RJet);
    Float_t Rchg_QCJet[50];
    tree_->SetBranchAddress("Rchg_QCJet",Rchg_QCJet);







    Bool_t secondJetOK;
    Bool_t btagged;
    Bool_t matchedToGenJet;
    Float_t deltaPhi_jet;
    Float_t eventWeight_noPU;
    Float_t ptZ, etaZ, mZ;
    Float_t QGlikelihood, QGlikelihood2012;

    Float_t ptJet0_t;
    Float_t etaJet0_t;
    Int_t nChargedJet0_t;
    Int_t nNeutralJet0_t;
    Float_t ptDJet0_t;
    Float_t ptD_QCJet0_t;
    Float_t axis1_QCJet0_t;
    Float_t axis2_QCJet0_t;
    Int_t nPFCand_QC_ptCutJet0_t;
    Int_t pdgIdPartJet_t;
    Float_t betaStarJet0_t;

    Float_t ptJet1_t;
    Float_t etaJet1_t;



    tree_passedEvents->Branch( "run", &run, "run/I" );
    tree_passedEvents->Branch( "LS", &LS, "LS/I" );
    tree_passedEvents->Branch( "nPU", &nPU, "nPU/I" );
    tree_passedEvents->Branch( "PUReWeight", &PUReWeight, "PUReWeight/F" );
    tree_passedEvents->Branch( "event", &event, "event/I" );
    tree_passedEvents->Branch( "eventWeight", &eventWeight, "eventWeight/F");
    tree_passedEvents->Branch( "eventWeight_noPU", &eventWeight_noPU, "eventWeight_noPU/F");
    tree_passedEvents->Branch( "nvertex", &nvertex, "nvertex/I");
    tree_passedEvents->Branch( "rhoPF", &rhoPF, "rhoPF/F");
    tree_passedEvents->Branch( "rhoJetPF", &rhoJetPF, "rhoJetPF/F");
    tree_passedEvents->Branch( "secondJetOK", &secondJetOK, "secondJetOK/O");
    tree_passedEvents->Branch( "btagged", &btagged, "btagged/O");
    tree_passedEvents->Branch( "mZ", &mZ, "mZ/F");
    tree_passedEvents->Branch( "ptZ", &ptZ, "ptZ/F");
    tree_passedEvents->Branch( "etaZ", &etaZ, "etaZ/F");
    tree_passedEvents->Branch( "ptJet0", &ptJet0_t, "ptJet0_t/F");
    tree_passedEvents->Branch( "etaJet0", &etaJet0_t, "etaJet0_t/F");
    tree_passedEvents->Branch( "ptJet1", &ptJet1_t, "ptJet1_t/F");
    tree_passedEvents->Branch( "etaJet1", &etaJet1_t, "etaJet1_t/F");
    tree_passedEvents->Branch( "nChargedJet0", &nChargedJet0_t, "nChargedJet0_t/I");
    tree_passedEvents->Branch( "nNeutralJet0", &nNeutralJet0_t, "nNeutralJet0_t/I");
    tree_passedEvents->Branch( "ptDJet0", &ptDJet0_t, "ptDJet0_t/F");
    //tree_passedEvents->Branch( "rmsCandJet0", &rmsCandJet0_t, "rmsCandJet[0]/F");
    //tree_passedEvents->Branch( "betaStarJet0", &betaStarJet0_t, "betaStarJet[0]/F");
    tree_passedEvents->Branch( "QGLikelihoodJet0", &QGlikelihood, "QGlikelihood/F");
    tree_passedEvents->Branch( "QGLikelihood2012Jet0", &QGlikelihood2012, "QGlikelihood2012/F");
    tree_passedEvents->Branch( "pdgIdPartJet0", &pdgIdPartJet_t, "pdgIdPart_t/I");
    tree_passedEvents->Branch( "deltaPhi_jet", &deltaPhi_jet, "deltaPhi_jet/F");

    //tree_passedEvents->Branch( "axis1Jet0"		, &axis1Jet[0]			, "axis1Jet[0]/F");
    //tree_passedEvents->Branch( "axis2Jet0"		, &axis2Jet[0]			, "axis2Jet[0]/F");
    //tree_passedEvents->Branch( "pullJet0"			, &pullJet[0]			, "pullJet[0]/F");
    //tree_passedEvents->Branch( "tanaJet0"			, &tanaJet[0]			, "tanaJet[0]/F");

    tree_passedEvents->Branch( "ptD_QCJet0"		, &ptD_QCJet0_t		, "ptD_QCJet0_t/F");
    //tree_passedEvents->Branch( "rmsCand_QCJet0"		, &rmsCand_QCJet[0]		, "rmsCand_QCJet[0]/F");
    tree_passedEvents->Branch( "axis1_QCJet0"		, &axis1_QCJet0_t		, "axis1_QCJet0_t/F");
    tree_passedEvents->Branch( "axis2_QCJet0"		, &axis2_QCJet0_t		, "axis2_QCJet0_t/F");
    //tree_passedEvents->Branch( "pull_QCJet0"		, &pull_QCJet[0]		, "pull_QCJet[0]/F");
    //tree_passedEvents->Branch( "tana_QCJet0"		, &tana_QCJet[0]		, "tana_QCJet[0]/F");

    tree_passedEvents->Branch( "nPFCand_QC_ptCutJet"		, &nPFCand_QC_ptCutJet0_t		, "nPFCand_QC_ptCutJet0_t/I");
    //tree_passedEvents->Branch( "nChg_ptCutJet0"		, &nChg_ptCutJet[0]		, "nChg_ptCutJet[0]/I");
    //tree_passedEvents->Branch( "nChg_QCJet0"		, &nChg_QCJet[0]		, "nChg_QCJet[0]/I");
    //tree_passedEvents->Branch( "nChg_ptCut_QCJet0"	, &nChg_ptCut_QCJet[0]	 	, "nChg_ptCut_QCJet[0]/I");
    //tree_passedEvents->Branch( "nNeutral_ptCutJet0"	, &nNeutral_ptCutJet[0]	, "nNeutral_ptCutJet[0]/I");

    //tree_passedEvents->Branch( "RchgJet0"			, &RchgJet[0]			, "RchgJet[0]/F");
    //tree_passedEvents->Branch( "RneutralJet0"		, &RneutralJet[0]		, "RneutralJet[0]/F");
    //tree_passedEvents->Branch( "RJet0"			, &RJet[0]			, "RJet[0]/F");
    //tree_passedEvents->Branch( "Rchg_QCJet0"		, &Rchg_QCJet[0]		, "Rchg_QCJet[0]/F");

    tree_passedEvents->Branch( "betaStarJet0"		, &betaStarJet0_t		, "betaStarJet0_t/F");



    QGLikelihoodCalculator* qglikeli = new QGLikelihoodCalculator("/afs/cern.ch/work/p/pandolf/public/QG/QG_QCD_Pt-15to3000_TuneZ2_Flat_8TeV_pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1.root");






    TRandom3* rand = new TRandom3(13);



    int nEntries = tree_->GetEntries();
//nEntries = 100000;

    std::map< int, std::map<int, std::vector<int> > > run_lumi_ev_map;


    int blockSize = TMath::Floor( (float)nEntries/nBlocks_ );
    int iEventMin = iBlock_*blockSize;
    int iEventMax = (iBlock_+1)*blockSize;
    if( iEventMax>nEntries ) iEventMax = nEntries;

    std::cout << "-> Running on events: " << iEventMin << " - " << iEventMax << std::endl;

    for(int iEntry=iEventMin; iEntry<iEventMax; ++iEntry) {

        if( ((iEntry-iEventMin) % 100000)==0 ) std::cout << "Entry: " << (iEntry-iEventMin) << " /" << blockSize << std::endl;

        tree_->GetEntry(iEntry);


        if( eventWeight <= 0. ) eventWeight = 1.;

        int icut = 0;
        h1_cutflow_50100->Fill( icut++, eventWeight );
        h1_nvertex->Fill( nvertex, eventWeight);

        bool isMC = run<5;

        if( isMC ) {

            // PU reweighting:
            eventWeight_noPU = eventWeight;

        } else { //it's data: remove duplicate events (if any):

            std::map<int, std::map<int, std::vector<int> > >::iterator it;

            it = run_lumi_ev_map.find(run);


            if( it==run_lumi_ev_map.end() ) {

                std::vector<int> events;
                events.push_back(event);
                std::map<int, std::vector<int> > lumi_ev_map;
                lumi_ev_map.insert( std::pair<int,std::vector<int> >(LS, events));
                run_lumi_ev_map.insert( std::pair<int, std::map<int, std::vector<int> > > (run, lumi_ev_map) );

            } else { //run exists, look for LS


                std::map<int, std::vector<int> >::iterator it_LS;
                it_LS = it->second.find( LS );

                if( it_LS==(it->second.end())  ) {

                    std::vector<int> events;
                    events.push_back(event);
                    it->second.insert( std::pair<int, std::vector<int> > (LS, events) );

                } else { //LS exists, look for event

                    std::vector<int>::iterator ev;
                    for( ev=it_LS->second.begin(); ev!=it_LS->second.end(); ++ev )
                        if( *ev==event ) break;


                    if( ev==it_LS->second.end() ) {

                        it_LS->second.push_back(event);

                    } else {

                        std::cout << "DISCARDING DUPLICATE EVENT!! Run: " << run << " LS: " << LS << " event: " << event << std::endl;

                        continue;

                    }
                }
            }

        } //if is mc




        h1_nvertex_PUW->Fill( nvertex, eventWeight);


        TLorentzVector lept1, lept2;
        lept1.SetPtEtaPhiE( ptLeptZ1, etaLeptZ1, phiLeptZ1, eLeptZ1 );
        lept2.SetPtEtaPhiE( ptLeptZ2, etaLeptZ2, phiLeptZ2, eLeptZ2 );

        TLorentzVector Z = lept1 + lept2;

        ptZ = Z.Pt();
        mZ = Z.M();
        etaZ = Z.Eta();

        h1_mZ->Fill( Z.M(), eventWeight );

        if( Z.M()<70. || Z.M()>110. ) continue;

        if( nJets==0 ) continue;
        if( ptJet[0] < 20. ) continue;


        // jet id:
        TLorentzVector jet;
        jet.SetPtEtaPhiE( ptJet[0], etaJet[0], phiJet[0], eJet[0] );

        if( fabs(jet.Eta())<2.4 && nChargedJet[0]==0 ) continue;
        if( (nNeutralJet[0]+nChargedJet[0])==1 ) continue;
        if( (ePhotonsJet[0]+eHFEMJet[0])/jet.E()>0.99 ) continue;
        if( (eNeutralHadronsJet[0])/jet.E()>0.99 ) continue;


        pdgIdPartJet_t = 0;

        if( isMC ) {

            // check if matched to parton/genjet
            TLorentzVector part;
            part.SetPtEtaPhiE( ptPartJet[0], etaPartJet[0], phiPartJet[0], ptPartJet[0] );

            TLorentzVector genJet;
            genJet.SetPtEtaPhiE( ptGenJet[0], etaGenJet[0], phiGenJet[0], ptGenJet[0] );

            float deltaR_jet_part = jet.DeltaR(part);

            if( deltaR_jet_part<0.3 ) {

                pdgIdPartJet_t = pdgIdPartJet[0];

            } else {

                float deltaR_jet_genjet = jet.DeltaR(genJet);

                if( deltaR_jet_genjet < 0.3 ) { //undefined
                    pdgIdPartJet_t = -999;
                } else {
                    pdgIdPartJet_t = 0;  //PU
                }

            } // else (if not matched to parton)

        } // if is MC



        //leading jet and Z back2back in transverse plane
        bool back2back = true;
        deltaPhi_jet = fabs(delta_phi(Z.Phi(), phiJet[0]));
        Float_t pi = TMath::Pi();
        float deltaPhiThreshold = 1.;
        if( fabs(deltaPhi_jet) < (pi - deltaPhiThreshold) ) back2back = false; //loose back to back for now


        // cut away b-jets:
        //if( trackCountingHighEffBJetTagsJetReco>1.7 ) continue;
        btagged = combinedSecondaryVertexBJetTagJet[0]>0.244;
        if( btagged ) continue;

        if( nJets>1 )
            secondJetOK = ( ptJet[1] < secondJetThreshold_*Z.Pt() || ptJet[1] < 10. );
        else
            secondJetOK = true;


        ptJet0_t = jet.Pt();
        etaJet0_t = jet.Eta();
        nChargedJet0_t = nChargedJet[0];
        nNeutralJet0_t = nNeutralJet[0];
        ptDJet0_t = ptDJet[0];
        ptD_QCJet0_t = ptD_QCJet[0];
        axis1_QCJet0_t = axis1_QCJet[0];
        axis2_QCJet0_t = axis2_QCJet[0];
        betaStarJet0_t= betaStarJet[0];
        nPFCand_QC_ptCutJet0_t = nPFCand_QC_ptCutJet[0];

        ptJet1_t  = (nJets>0) ? ptJet[1] : 0.;
        etaJet1_t = (nJets>0) ? etaJet[1] : 10.;




        QGlikelihood = qglikeli->computeQGLikelihoodPU( ptJet[0], rhoPF, nChargedJet[0], nNeutralJet[0], ptDJet[0], -1. );
        QGlikelihood2012 = qglikeli->computeQGLikelihood2012( ptJet[0], etaJet[0], rhoPF, nPFCand_QC_ptCutJet[0], ptD_QCJet[0], axis2_QCJet[0] );


        tree_passedEvents->Fill();

    }


    outFile->cd();

    tree_passedEvents->Write();

    h1_cutflow_50100->Write();

    h1_nvertex->Write();
    h1_nvertex_PUW->Write();

    h1_ptZ->Write();
    h1_mZ->Write();
    h1_phiZ->Write();
    h1_etaZ->Write();
    h1_ptJetReco->Write();
    h1_pt2ndJetReco->Write();

    h1_nEvents_passed_quark->Write();
    h1_nEvents_passed->Write();




    outFile->Close();


}
void analysisClass::Loop()
{
  //STDOUT("analysisClass::Loop() begins");

  if (fChain == 0) return;

  /*//------------------------------------------------------------------
   *
   *
   *      
   *      Get all Pre-cut values!
   *
   *
   *
   *///-----------------------------------------------------------------
  
   //--------------------------------------------------------------------------
   // Decide which plots to save (default is to save everything)
   //--------------------------------------------------------------------------
   
   fillSkim                         ( !true  ) ;
   fillAllPreviousCuts              ( !true  ) ;
   fillAllOtherCuts                 ( !true  ) ;
   fillAllSameLevelAndLowerLevelCuts( !true  ) ;
   fillAllCuts                      ( !true  ) ;


  //-----------------------------------------------------------------
  // Electron cut values
  //-----------------------------------------------------------------
  
  double ele_PtCut_STORE = getPreCutValue2("ele_PtCut");
  double ele_PtCut_ANA   = getPreCutValue1("ele_PtCut");
  
  double eleEta_bar      = getPreCutValue1("eleEta_bar");
  double eleEta_end_min  = getPreCutValue1("eleEta_end");
  double eleEta_end_max  = getPreCutValue2("eleEta_end");
  
  if ( ele_PtCut_STORE > ele_PtCut_ANA ) {
    STDOUT("ERROR in Electron cut values: all storage cuts must be looser or equal to analysis cuts.");
    exit(0) ;
  }

  // For WP80

  double eleMissingHitsWP             = getPreCutValue1("eleMissingHitsWP"        );
  double eleDistWP                    = getPreCutValue1("eleDistWP"               );
  double eleDCotThetaWP               = getPreCutValue1("eleDCotThetaWP"          );
  double eleCombRelIsoWP_bar          = getPreCutValue1("eleCombRelIsoWP"         );
  double eleCombRelIsoWP_end          = getPreCutValue2("eleCombRelIsoWP"         );
  double eleSigmaIetaIetaWP_bar       = getPreCutValue1("eleSigmaIetaIetaWP"      );
  double eleSigmaIetaIetaWP_end       = getPreCutValue2("eleSigmaIetaIetaWP"      );
  double eleDeltaPhiTrkSCWP_bar       = getPreCutValue1("eleDeltaPhiTrkSCWP"      );
  double eleDeltaPhiTrkSCWP_end       = getPreCutValue2("eleDeltaPhiTrkSCWP"      );
  double eleDeltaEtaTrkSCWP_bar       = getPreCutValue1("eleDeltaEtaTrkSCWP"      );
  double eleDeltaEtaTrkSCWP_end       = getPreCutValue2("eleDeltaEtaTrkSCWP"      );
  double eleUseEcalDrivenWP           = getPreCutValue1("eleUseEcalDrivenWP"      );
  double eleUseHasMatchConvWP         = getPreCutValue1("eleUseHasMatchConvWP"    );

  // For HEEP 3.1

  double eleDeltaEtaTrkSCHeep_bar     = getPreCutValue1("eleDeltaEtaTrkSCHeep"    );
  double eleDeltaEtaTrkSCHeep_end     = getPreCutValue2("eleDeltaEtaTrkSCHeep"    );
  double eleDeltaPhiTrkSCHeep_bar     = getPreCutValue1("eleDeltaPhiTrkSCHeep"    );
  double eleDeltaPhiTrkSCHeep_end     = getPreCutValue2("eleDeltaPhiTrkSCHeep"    );
  double eleHoEHeep_bar               = getPreCutValue1("eleHoEHeep"              );
  double eleHoEHeep_end               = getPreCutValue2("eleHoEHeep"              );
  double eleE2x5OverE5x5Heep_bar      = getPreCutValue1("eleE2x5OverE5x5Heep"     );
  double eleE1x5OverE5x5Heep_bar      = getPreCutValue1("eleE1x5OverE5x5Heep"     );
  double eleSigmaIetaIetaHeep_end     = getPreCutValue2("eleSigmaIetaIetaHeep"    );
  double eleEcalHcalIsoHeep_1_bar     = getPreCutValue1("eleEcalHcalIsoHeep"      );
  double eleEcalHcalIsoHeep_2_bar     = getPreCutValue2("eleEcalHcalIsoHeep"      );
  double eleEcalHcalIsoHeep_1_end     = getPreCutValue3("eleEcalHcalIsoHeep"      );
  double eleEcalHcalIsoHeep_2_end     = getPreCutValue4("eleEcalHcalIsoHeep"      );
  double eleEcalHcalIsoHeep_PTthr_end = getPreCutValue2("eleEcalHcalIsoHeep_PTthr");
  double eleHcalIsoD2Heep_end         = getPreCutValue2("eleHcalIsoD2Heep"        );
  double eleTrkIsoHeep_bar            = getPreCutValue1("eleTrkIsoHeep"           );
  double eleTrkIsoHeep_end            = getPreCutValue2("eleTrkIsoHeep"           );
  double eleMissingHitsHeep           = getPreCutValue1("eleMissingHitsHeep"      );
  double eleUseEcalDrivenHeep         = getPreCutValue1("eleUseEcalDrivenHeep"    );

  // For HEEP 3.2

  double eleDeltaEtaTrkSCHeep32_bar     = getPreCutValue1("eleDeltaEtaTrkSCHeep32"    );
  double eleDeltaEtaTrkSCHeep32_end     = getPreCutValue2("eleDeltaEtaTrkSCHeep32"    );
  double eleDeltaPhiTrkSCHeep32_bar     = getPreCutValue1("eleDeltaPhiTrkSCHeep32"    );
  double eleDeltaPhiTrkSCHeep32_end     = getPreCutValue2("eleDeltaPhiTrkSCHeep32"    );
  double eleHoEHeep32_bar               = getPreCutValue1("eleHoEHeep32"              );
  double eleHoEHeep32_end               = getPreCutValue2("eleHoEHeep32"              );
  double eleE2x5OverE5x5Heep32_bar      = getPreCutValue1("eleE2x5OverE5x5Heep32"     );
  double eleE1x5OverE5x5Heep32_bar      = getPreCutValue1("eleE1x5OverE5x5Heep32"     );
  double eleSigmaIetaIetaHeep32_end     = getPreCutValue2("eleSigmaIetaIetaHeep32"    );
  double eleEcalHcalIsoHeep32_1_bar     = getPreCutValue1("eleEcalHcalIsoHeep32"      );
  double eleEcalHcalIsoHeep32_2_bar     = getPreCutValue2("eleEcalHcalIsoHeep32"      );
  double eleEcalHcalIsoHeep32_1_end     = getPreCutValue3("eleEcalHcalIsoHeep32"      );
  double eleEcalHcalIsoHeep32_2_end     = getPreCutValue4("eleEcalHcalIsoHeep32"      );
  double eleEcalHcalIsoHeep32_PTthr_end = getPreCutValue2("eleEcalHcalIsoHeep32_PTthr");
  //double eleHcalIsoD2Heep32_end         = getPreCutValue2("eleHcalIsoD2Heep32"        );
  double eleTrkIsoHeep32_bar            = getPreCutValue1("eleTrkIsoHeep32"           );
  double eleTrkIsoHeep32_end            = getPreCutValue2("eleTrkIsoHeep32"           );
  double eleMissingHitsHeep32           = getPreCutValue1("eleMissingHitsHeep32"      );
  double eleUseEcalDrivenHeep32         = getPreCutValue1("eleUseEcalDrivenHeep32"    );

  //-----------------------------------------------------------------
  // Vertex cut values
  //-----------------------------------------------------------------

  double vertexMinimumNDOF = getPreCutValue1("vertexMinimumNDOF");
  double vertexMaxAbsZ     = getPreCutValue1("vertexMaxAbsZ");
  double vertexMaxd0       = getPreCutValue1("vertexMaxd0");

  //-----------------------------------------------------------------
  // Which algorithms to use?
  //-----------------------------------------------------------------

  int    eleAlgorithm = (int) getPreCutValue1("eleAlgorithm");

  //-----------------------------------------------------------------
  // Counters
  //-----------------------------------------------------------------
  int    N_probe_PassEleOffline = 0;
  int    N_probe_PassEleOfflineAndWP80 = 0;
  int    N_probe_PassEleOfflineAndTag = 0;  

  int    N_probe_PassEleOffline_bar = 0;
  int    N_probe_PassEleOfflineAndWP80_bar = 0;
  int    N_probe_PassEleOfflineAndTag_bar = 0;  

  int    N_probe_PassEleOffline_end = 0;
  int    N_probe_PassEleOfflineAndWP80_end = 0;
  int    N_probe_PassEleOfflineAndTag_end = 0;  

  //Histograms
  CreateUserTH1D("eta_recoEleMatchProbe_PassEleOffline", 50, -5, 5);
  CreateUserTH1D("pt_recoEleMatchProbe_PassEleOffline", 40, 0, 200);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOffline", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOffline_bar", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOffline_end", 50, 0, 50);			

  CreateUserTH1D("eta_recoEleMatchProbe_PassEleOfflineAndWP80", 50, -5, 5);
  CreateUserTH1D("pt_recoEleMatchProbe_PassEleOfflineAndWP80", 40, 0, 200);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80_bar", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80_end", 50, 0, 50);			

  CreateUserTH1D("eta_recoEleMatchProbe_PassEleOfflineAndTag", 50, -5, 5);
  CreateUserTH1D("pt_recoEleMatchProbe_PassEleOfflineAndTag", 40, 0, 200);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag_bar", 50, 0, 50);			
  CreateUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag_end", 50, 0, 50);			

  /*//------------------------------------------------------------------
   *
   *
   *      
   *      Start analysis loop!
   *
   *
   *
   *///-----------------------------------------------------------------


  Long64_t nentries = fChain->GetEntries();
  //Long64_t nentries = 100000;
  STDOUT("analysisClass::Loop(): nentries = " << nentries);

  Long64_t nbytes = 0, nb = 0;
  for (Long64_t jentry=0; jentry<nentries;jentry++) { // Begin of loop over events
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(jentry < 10 || jentry%1000 == 0) STDOUT("analysisClass::Loop(): jentry = " << jentry << "/" << nentries );
    
    //-----------------------------------------------------------------
    // Do pileup re-weighting, if necessary
    //  --> To be done after the skim, so commented out for now
    //-----------------------------------------------------------------
    
    // double event_weight = getPileupWeight ( PileUpInteractions, isData ) ;
    
    //-----------------------------------------------------------------
    // Get trigger information, if necessary
    //-----------------------------------------------------------------

    if ( isData ) { 
      getTriggers ( HLTKey, HLTInsideDatasetTriggerNames, HLTInsideDatasetTriggerDecisions,  HLTInsideDatasetTriggerPrescales ) ;
    }
    
    //-----------------------------------------------------------------
    // Selection: Electrons
    //-----------------------------------------------------------------    

    vector<int> v_idx_ele_PtCut_IDISO_STORE;
    vector<int> v_idx_ele_PtCut_IDISO_ANA;
    vector<int> v_idx_ele_IDISO;

    //Loop over electrons
    for(int iele=0; iele<ElectronPt->size(); iele++){
      
      int passEleSel = 0;
      int isBarrel = 0;
      int isEndcap = 0;
      
      if( fabs( ElectronSCEta->at(iele) ) < eleEta_bar )       isBarrel = 1;
      if( fabs( ElectronSCEta->at(iele) ) > eleEta_end_min &&
	  fabs( ElectronSCEta->at(iele) ) < eleEta_end_max )   isEndcap = 1;

      //-----------------------------------------------------------------    
      // HEEP ID application 3.1
      //-----------------------------------------------------------------    

      if ( eleAlgorithm == 1 ) { 
	
	if(isBarrel) {		

	  if(   fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCHeep_bar 
		&& fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCHeep_bar 
		&& ElectronHoE->at(iele) < eleHoEHeep_bar 
		&& (ElectronE2x5OverE5x5->at(iele) >eleE2x5OverE5x5Heep_bar || ElectronE1x5OverE5x5->at(iele) > eleE1x5OverE5x5Heep_bar ) 
		&& ( ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele) ) < eleEcalHcalIsoHeep_1_bar + eleEcalHcalIsoHeep_2_bar*ElectronPt->at(iele)
		&& ElectronTrkIsoDR03->at(iele) <eleTrkIsoHeep_bar 
		&& ElectronMissingHits->at(iele) == 0 
		&& ElectronHasEcalDrivenSeed->at(iele)
	     )
	    passEleSel = 1;		

	}//end barrel
	
	if(isEndcap) {		
	  
	  int passEcalHcalIsoCut=0;
	  if(ElectronPt->at(iele) < eleEcalHcalIsoHeep_PTthr_end && 
	     (ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele)) < eleEcalHcalIsoHeep_1_end) 
	    passEcalHcalIsoCut=1;
	  if(ElectronPt->at(iele) > eleEcalHcalIsoHeep_PTthr_end && 
	     (ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele)) < eleEcalHcalIsoHeep_1_end+eleEcalHcalIsoHeep_2_end*(ElectronPt->at(iele)-eleEcalHcalIsoHeep_PTthr_end) ) 
	    passEcalHcalIsoCut=1;
	  
	  if(fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCHeep_end 
	     && fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCHeep_end 
	     && ElectronHoE->at(iele) < eleHoEHeep_end 
	     && ElectronSigmaIEtaIEta->at(iele) < eleSigmaIetaIetaHeep_end 
	     && passEcalHcalIsoCut == 1
	     && ElectronHcalIsoD2DR03->at(iele) < eleHcalIsoD2Heep_end 
	     && ElectronTrkIsoDR03->at(iele) < eleTrkIsoHeep_end 
	     && ElectronMissingHits->at(iele) == 0 
	     && ElectronHasEcalDrivenSeed->at(iele)
	     )
	    passEleSel = 1;
	  
	}//end endcap
      }

      //-----------------------------------------------------------------    
      // WP80 ID application
      //-----------------------------------------------------------------    

      else if ( eleAlgorithm == 2 ) { 
	// ecal driven	    
	if( eleUseEcalDrivenWP && !ElectronHasEcalDrivenSeed->at(iele) ) continue;
	
	// isolation
	double ElectronCombRelIsoWP_bar  =  ( ElectronTrkIsoDR03->at(iele) 
					    + max( 0., ElectronEcalIsoDR03->at(iele) - 1. ) 
					    + ElectronHcalIsoDR03FullCone->at(iele) 
					    - rhoIso*TMath::Pi()*0.3*0.3 
					    ) / ElectronPt->at(iele) ;
	
	double ElectronCombRelIsoWP_end  =  ( ElectronTrkIsoDR03->at(iele) 
					      + ElectronEcalIsoDR03->at(iele) 
					      + ElectronHcalIsoDR03FullCone->at(iele) 
					      - rhoIso*TMath::Pi()*0.3*0.3 
					      ) / ElectronPt->at(iele) ;
	
	// conversions
	int isPhotConv = 0;
	if(eleUseHasMatchConvWP) {
	  if( ElectronHasMatchedConvPhot->at(iele) ) 
	    isPhotConv = 1;
	}
	else {
	  if( ElectronDist->at(iele) < eleDistWP && ElectronDCotTheta->at(iele) < eleDCotThetaWP )	
	    isPhotConv = 1;
	}

	if(isBarrel) {
	  
	  if( ElectronMissingHits->at(iele) <= eleMissingHitsWP              && 
	      isPhotConv == 0					             && 
	      ElectronCombRelIsoWP_bar < eleCombRelIsoWP_bar		     && 
	      ElectronSigmaIEtaIEta->at(iele) < eleSigmaIetaIetaWP_bar       && 
	      fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCWP_bar && 
	      fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCWP_bar  )
	    passEleSel = 1;		
	  
	}//end barrel
	
	if(isEndcap) {		
	    
	  if( ElectronMissingHits->at(iele) == eleMissingHitsWP              && 
	      isPhotConv == 0						     && 
	      ElectronCombRelIsoWP_end < eleCombRelIsoWP_end		     && 
	      ElectronSigmaIEtaIEta->at(iele) < eleSigmaIetaIetaWP_end 	     && 
	      fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCWP_end && 
	      fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCWP_end  )
	    passEleSel = 1;		
	  
	}//end endcap	
      }

      //-----------------------------------------------------------------    
      // HEEP ID application 3.2
      //-----------------------------------------------------------------    

      else if ( eleAlgorithm == 3 ) { 
	
	if(isBarrel) {
		
	  if(   fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCHeep32_bar 
		&& fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCHeep32_bar 
		&& ElectronHoE->at(iele) < eleHoEHeep32_bar 
		&& (ElectronE2x5OverE5x5->at(iele) >eleE2x5OverE5x5Heep32_bar || ElectronE1x5OverE5x5->at(iele) > eleE1x5OverE5x5Heep32_bar ) 
		&& ( ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele) ) < eleEcalHcalIsoHeep32_1_bar + eleEcalHcalIsoHeep32_2_bar*ElectronPt->at(iele)
		&& ElectronTrkIsoDR03->at(iele) <eleTrkIsoHeep32_bar 
		&& ElectronMissingHits->at(iele) == 0 
		&& ElectronHasEcalDrivenSeed->at(iele)
	     )
	    passEleSel = 1;		

	}//end barrel
	
	if(isEndcap) {		
	  
	  int passEcalHcalIsoCut=0;
	  if(ElectronPt->at(iele) < eleEcalHcalIsoHeep32_PTthr_end && 
	     (ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele)) < eleEcalHcalIsoHeep32_1_end) 
	    passEcalHcalIsoCut=1;
	  if(ElectronPt->at(iele) > eleEcalHcalIsoHeep32_PTthr_end && 
	     (ElectronEcalIsoDR03->at(iele)+ElectronHcalIsoD1DR03->at(iele)) < eleEcalHcalIsoHeep32_1_end+eleEcalHcalIsoHeep32_2_end*(ElectronPt->at(iele)-eleEcalHcalIsoHeep32_PTthr_end) ) 
	    passEcalHcalIsoCut=1;
	  
	  if(fabs(ElectronDeltaEtaTrkSC->at(iele)) < eleDeltaEtaTrkSCHeep32_end 
	     && fabs(ElectronDeltaPhiTrkSC->at(iele)) < eleDeltaPhiTrkSCHeep32_end 
	     && ElectronHoE->at(iele) < eleHoEHeep32_end 
	     && ElectronSigmaIEtaIEta->at(iele) < eleSigmaIetaIetaHeep32_end 
	     && passEcalHcalIsoCut == 1
	     //&& ElectronHcalIsoD2DR03->at(iele) < eleHcalIsoD2Heep32_end 
	     && ElectronTrkIsoDR03->at(iele) < eleTrkIsoHeep32_end 
	     && ElectronMissingHits->at(iele) == 0 
	     && ElectronHasEcalDrivenSeed->at(iele)
	     )
	    passEleSel = 1;
	  
	}//end endcap
      }
      
      if ( passEleSel ) { 
	v_idx_ele_IDISO.push_back ( iele ) ;
	if ( ElectronPt -> at (iele) >= ele_PtCut_STORE ) v_idx_ele_PtCut_IDISO_STORE.push_back ( iele ) ;
	if ( ElectronPt -> at (iele) >= ele_PtCut_ANA   ) v_idx_ele_PtCut_IDISO_ANA  .push_back ( iele ) ;
      }

    }
    

    //-----------------------------------------------------------------
    // Selection: vertices
    //-----------------------------------------------------------------

    vector<int> v_idx_vertex_good;
    // loop over vertices
    for(int ivertex = 0; ivertex<VertexChi2->size(); ivertex++){
      if ( !(VertexIsFake->at(ivertex))
    	   && VertexNDF->at(ivertex) > vertexMinimumNDOF
    	   && fabs( VertexZ->at(ivertex) ) <= vertexMaxAbsZ
    	   && fabs( VertexRho->at(ivertex) ) <= vertexMaxd0 )
    	{
    	  v_idx_vertex_good.push_back(ivertex);
    	  //STDOUT("v_idx_vertex_good.size = "<< v_idx_vertex_good.size() );
    	}
    }

    //-----------------------------------------------------------------
    // Fill your single-object variables with values
    //-----------------------------------------------------------------

    // Set the evaluation of the cuts to false and clear the variable values and filled status
    resetCuts();
    
    fillVariableWithValue( "PassJSON", passJSON(run, ls, isData) );    
    // Set the value of the variableNames listed in the cutFile to their current value

    //event info
    fillVariableWithValue( "isData"   , isData     ) ;
    fillVariableWithValue( "bunch"    , bunch      ) ;
    fillVariableWithValue( "event"    , event      ) ;
    fillVariableWithValue( "ls"       , ls         ) ;
    fillVariableWithValue( "orbit"    , orbit      ) ;
    fillVariableWithValue( "run"      , run        ) ;

    // nVertex and pile-up
    fillVariableWithValue( "nVertex", VertexChi2->size() ) ;
    fillVariableWithValue( "nVertex_good", v_idx_vertex_good.size() ) ;

    // Trigger (L1 and HLT)
    if(isData==true)
      {
	fillVariableWithValue( "PassBPTX0", isBPTX0 ) ;
	fillVariableWithValue( "PassPhysDecl", isPhysDeclared ) ;

	bool PassHLT = false;
	if( triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v1") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v2") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v3") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v4") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v5") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v6") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v7") 
	    || triggerFired ("HLT_Ele32_CaloIdT_CaloIsoT_TrkIdT_TrkIsoT_SC17_v8") 
	    )
	  {
	    PassHLT = true;
	  }
	fillVariableWithValue( "PassHLT", PassHLT ) ;
      }
    else
      {
	fillVariableWithValue( "PassBPTX0", true ) ;
	fillVariableWithValue( "PassPhysDecl", true ) ;
	fillVariableWithValue( "PassHLT", true ) ;
      }


    //Event filters at RECO level
    fillVariableWithValue( "PassBeamScraping", !isBeamScraping ) ;
    fillVariableWithValue( "PassPrimaryVertex", isPrimaryVertex ) ;
    fillVariableWithValue( "PassHBHENoiseFilter", passHBHENoiseFilter ) ;
    fillVariableWithValue( "PassBeamHaloFilterLoose", passBeamHaloFilterLoose ) ;
    fillVariableWithValue( "PassBeamHaloFilterTight", passBeamHaloFilterTight ) ;
    fillVariableWithValue( "PassTrackingFailure", !isTrackingFailure ) ;
    fillVariableWithValue( "PassCaloBoundaryDRFilter", passCaloBoundaryDRFilter ) ;
    fillVariableWithValue( "PassEcalMaskedCellDRFilter", passEcalMaskedCellDRFilter ) ;
    
    // Evaluate cuts (but do not apply them)
    evaluateCuts();


    //Basic Event Selection
    if( passedCut("PassJSON") 
	&& passedCut("run")
	&& passedCut("PassBPTX0") 
	&& passedCut("PassBeamScraping") 
	&& passedCut("PassPrimaryVertex")
	&& passedCut("PassHBHENoiseFilter")
	&& passedCut("PassBeamHaloFilterTight") 
	&& passedCut("PassHLT")
	)
      {      
	//Loop over probes
	for(int iprobe=0; iprobe<HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTSC17HEDoubleFilterPt->size(); iprobe++)
	  {

	    TLorentzVector probe;
	    probe.SetPtEtaPhiE(HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTSC17HEDoubleFilterPt->at(iprobe),
			       HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTSC17HEDoubleFilterEta->at(iprobe),
			       HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTSC17HEDoubleFilterPhi->at(iprobe),
			       HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTSC17HEDoubleFilterEnergy->at(iprobe)
			       );

	    int isProbeBarrel = 0;
	    int isProbeEndcap = 0;
	    
	    if( fabs( probe.Eta() ) < eleEta_bar )       isProbeBarrel = 1;
	    if( fabs( probe.Eta() ) > eleEta_end_min &&
		fabs( probe.Eta() ) < eleEta_end_max )   isProbeEndcap = 1;


	    CreateAndFillUserTH1D("Pt_Probe", 200, 0, 200, probe.Pt() );

	    //Loop over tags
 	    for(int itag=0; itag<HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPt->size(); itag++)
	      {

		TLorentzVector tag;
		tag.SetPtEtaPhiE(HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPt->at(itag),
				 HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterEta->at(itag),
				 HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPhi->at(itag),
				 HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterEnergy->at(itag)
				 );	    

		CreateAndFillUserTH1D("DR_ProbeVsTag", 100, 0, 10, probe.DeltaR(tag) );

		//-----------------
		//if the tag matches in DR with the probe --> move to the next tag candidate
		if( probe.DeltaR(tag) < 0.5) 
		  continue;
		//-----------------


		//Now we should have a good (tag-probe) pair

		bool IsProbeMatchedWithOfflineEle = false;
		bool IsProbeMatchedWithTriggerWP80 = false;
		bool IsProbeMatchedWithTriggerTag = false;
		bool IsTagMatchedWithOfflineEle = false;

		//Loop over offline electrons
		TLorentzVector RecoEleMatchedWithProbe;
		TLorentzVector RecoEleMatchedWithTag;
		for(int iele=0; iele<v_idx_ele_PtCut_IDISO_ANA.size(); iele++)
		  {
		    TLorentzVector ele;
		    ele.SetPtEtaPhiE( ElectronPt->at(v_idx_ele_PtCut_IDISO_ANA[iele]),
				      ElectronEta->at(v_idx_ele_PtCut_IDISO_ANA[iele]),
				      ElectronPhi->at(v_idx_ele_PtCut_IDISO_ANA[iele]),
				      ElectronEnergy->at(v_idx_ele_PtCut_IDISO_ANA[iele])
				      );	    
		    
		    CreateAndFillUserTH1D("DR_ProbeVsEle", 100, 0, 10, probe.DeltaR(ele) );
		    CreateAndFillUserTH1D("DR_TagVsEle", 100, 0, 10, tag.DeltaR(ele) );

		    if( probe.DeltaR(ele) < 0.2 )
		      {
			IsProbeMatchedWithOfflineEle = true;
			RecoEleMatchedWithProbe = ele;
		      }

		    if( tag.DeltaR(ele) < 0.2 ) 
		      {
			IsTagMatchedWithOfflineEle = true;		    
			RecoEleMatchedWithTag = ele;
		      }

		  }

		//Loop over trigger WP80 electrons
		for(int iwp80=0; iwp80<HLTEle27WP80TrackIsoFilterPt->size(); iwp80++)
		  {
		    TLorentzVector wp80;
		    wp80.SetPtEtaPhiE(HLTEle27WP80TrackIsoFilterPt->at(iwp80),
				      HLTEle27WP80TrackIsoFilterEta->at(iwp80),
				      HLTEle27WP80TrackIsoFilterPhi->at(iwp80),
				      HLTEle27WP80TrackIsoFilterEnergy->at(iwp80)
				      );	    
		    
		    CreateAndFillUserTH1D("DR_ProbeVsWP80", 100, 0, 10, probe.DeltaR(wp80) );

		    if( probe.DeltaR(wp80) < 0.2 ) 
		      IsProbeMatchedWithTriggerWP80 = true;
		  }

		//Loop over trigger tag
		for(int itag2=0; itag2<HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPt->size(); itag2++)
		  {
		    TLorentzVector tag2;
		    tag2.SetPtEtaPhiE(HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPt->at(itag2),
				      HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterEta->at(itag2),
				      HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterPhi->at(itag2),
				      HLTEle32CaloIdTCaloIsoTTrkIdTTrkIsoTEle17TrackIsolFilterEnergy->at(itag2)
				      );	    

		    CreateAndFillUserTH1D("DR_ProbeVsTag2", 100, 0, 10, probe.DeltaR(tag2) );

		    if( probe.DeltaR(tag2) < 0.2 ) 
		      IsProbeMatchedWithTriggerTag = true;
		  }				

		TLorentzVector tag_probe_system;
		tag_probe_system = tag + probe;
		double mass = tag_probe_system.M();

		CreateAndFillUserTH1D("Mass_TagProbeSystem_NoCutOnProbe", 200, 0, 200, mass );

		if( IsProbeMatchedWithOfflineEle && IsTagMatchedWithOfflineEle )
		  {
		    CreateAndFillUserTH1D("Mass_TagProbeSystem_ProbeMatchedOfflineEle", 200, 0, 200, mass );

		    if( mass > 75 && mass < 95)
		      {
			CreateAndFillUserTH1D("Mass_TagProbeSystem_ForEfficiencyCalculation", 200, 0, 200, mass );

			FillUserTH1D("eta_recoEleMatchProbe_PassEleOffline", RecoEleMatchedWithProbe.Eta() );
			FillUserTH1D("pt_recoEleMatchProbe_PassEleOffline", RecoEleMatchedWithProbe.Pt() );			
			FillUserTH1D("NPV_recoEleMatchProbe_PassEleOffline", getVariableValue("nVertex") );			

			N_probe_PassEleOffline++;
			if( isProbeBarrel )
			  {
			    N_probe_PassEleOffline_bar++;
			    FillUserTH1D("NPV_recoEleMatchProbe_PassEleOffline_bar", getVariableValue("nVertex") );			
			  }
			if( isProbeEndcap )
			  {
			    N_probe_PassEleOffline_end++;
			    FillUserTH1D("NPV_recoEleMatchProbe_PassEleOffline_end", getVariableValue("nVertex") );			
			  }			

			if(IsProbeMatchedWithTriggerWP80)
			  {
			    FillUserTH1D("eta_recoEleMatchProbe_PassEleOfflineAndWP80", RecoEleMatchedWithProbe.Eta() );
			    FillUserTH1D("pt_recoEleMatchProbe_PassEleOfflineAndWP80", RecoEleMatchedWithProbe.Pt() );			
			    FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80", getVariableValue("nVertex") );			

			    N_probe_PassEleOfflineAndWP80++;
			    if( isProbeBarrel )
			      {
				N_probe_PassEleOfflineAndWP80_bar++;
				FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80_bar", getVariableValue("nVertex") );			
			      }
			    if( isProbeEndcap )
			      {
				N_probe_PassEleOfflineAndWP80_end++;
				FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndWP80_end", getVariableValue("nVertex") );			
			      }
			  }
			
			if(IsProbeMatchedWithTriggerTag)
			  {
			    FillUserTH1D("eta_recoEleMatchProbe_PassEleOfflineAndTag", RecoEleMatchedWithProbe.Eta() );
			    FillUserTH1D("pt_recoEleMatchProbe_PassEleOfflineAndTag", RecoEleMatchedWithProbe.Pt() );			
			    FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag", getVariableValue("nVertex") );			

			    N_probe_PassEleOfflineAndTag++;
			    if( isProbeBarrel )
			      {
				N_probe_PassEleOfflineAndTag_bar++;
				FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag_bar", getVariableValue("nVertex") );			
			      }
			    if( isProbeEndcap )
			      {
				N_probe_PassEleOfflineAndTag_end++;
				FillUserTH1D("NPV_recoEleMatchProbe_PassEleOfflineAndTag_end", getVariableValue("nVertex") );			
			      }
			  }
			
		      }//mass cut

		  }//IsProbeMatchedWithOfflineEle
		
	      }//end loop over tag


	  }//end loop over probe
	  


	//	fillVariableWithValue( "PassEcalMaskedCellDRFilter", passEcalMaskedCellDRFilter ) ;

	//triggerFired ("HLT_Photon30_CaloIdVL_v1") 


	//v_idx_ele_PtCut_IDISO_ANA.size()

	//CreateAndFillUserTH1D("ElePt_AfterPhoton30", 100, 0, 1000, ElectronPt -> at (v_idx_ele_PtCut_IDISO_ANA[0]) );

      }//end Basic Event Selection


  } // End of loop over events

  //##################################################

  /*//------------------------------------------------------------------
   *
   *
   *      
   *      End analysis loop!
   *
   *
   *
   *///-----------------------------------------------------------------

  //Printout
  double eff_WP80 = double(N_probe_PassEleOfflineAndWP80)/double(N_probe_PassEleOffline);
  double eff_Tag = double(N_probe_PassEleOfflineAndTag)/double(N_probe_PassEleOffline);

  cout << "*** ALL ***" << endl;
  cout << "N_probe_PassEleOffline: " << N_probe_PassEleOffline << endl;
  cout << "N_probe_PassEleOfflineAndWP80: " << N_probe_PassEleOfflineAndWP80 << endl;
  cout << "N_probe_PassEleOfflineAndTag: " << N_probe_PassEleOfflineAndTag << endl;
  cout << endl;
  cout << "eff_WP80: " << eff_WP80 << " +/- " << sqrt(eff_WP80 * (1- eff_WP80) / N_probe_PassEleOffline ) << endl;  
  cout << "eff_Tag: " << eff_Tag << " +/- " << sqrt(eff_Tag * (1- eff_Tag) / N_probe_PassEleOffline ) << endl;  
  cout << endl;

  double eff_WP80_bar = double(N_probe_PassEleOfflineAndWP80_bar)/double(N_probe_PassEleOffline_bar);
  double eff_Tag_bar = double(N_probe_PassEleOfflineAndTag_bar)/double(N_probe_PassEleOffline_bar);

  cout << "*** BARREL ***" << endl;
  cout << "N_probe_PassEleOffline_bar: " << N_probe_PassEleOffline_bar << endl;
  cout << "N_probe_PassEleOfflineAndWP80_bar: " << N_probe_PassEleOfflineAndWP80_bar << endl;
  cout << "N_probe_PassEleOfflineAndTag_bar: " << N_probe_PassEleOfflineAndTag_bar << endl;
  cout << endl;
  cout << "eff_WP80_bar: " << eff_WP80_bar << " +/- " << sqrt(eff_WP80_bar * (1- eff_WP80_bar) / N_probe_PassEleOffline_bar ) << endl;  
  cout << "eff_Tag_bar: " << eff_Tag_bar << " +/- " << sqrt(eff_Tag_bar * (1- eff_Tag_bar) / N_probe_PassEleOffline_bar ) << endl;  
  cout << endl;

  double eff_WP80_end = double(N_probe_PassEleOfflineAndWP80_end)/double(N_probe_PassEleOffline_end);
  double eff_Tag_end = double(N_probe_PassEleOfflineAndTag_end)/double(N_probe_PassEleOffline_end);

  cout << "*** ENDCAP ***" << endl;
  cout << "N_probe_PassEleOffline_end: " << N_probe_PassEleOffline_end << endl;
  cout << "N_probe_PassEleOfflineAndWP80_end: " << N_probe_PassEleOfflineAndWP80_end << endl;
  cout << "N_probe_PassEleOfflineAndTag_end: " << N_probe_PassEleOfflineAndTag_end << endl;
  cout << endl;
  cout << "eff_WP80_end: " << eff_WP80_end << " +/- " << sqrt(eff_WP80_end * (1- eff_WP80_end) / N_probe_PassEleOffline_end ) << endl;  
  cout << "eff_Tag_end: " << eff_Tag_end << " +/- " << sqrt(eff_Tag_end * (1- eff_Tag_end) / N_probe_PassEleOffline_end ) << endl;  
  cout << endl;


  STDOUT("analysisClass::Loop() ends");
}
예제 #8
0
int PhotonJet::process_event(PHCompositeNode *topnode)
{
 
  cout<<"at event number "<<nevents<<endl;


  //get the nodes from the NodeTree
  JetMap* truth_jets = findNode::getClass<JetMap>(topnode,"AntiKt_Truth_r04");
  JetMap *reco_jets = findNode::getClass<JetMap>(topnode,"AntiKt_Tower_r04");
  PHG4TruthInfoContainer* truthinfo = findNode::getClass<PHG4TruthInfoContainer>(topnode,"G4TruthInfo");
  RawClusterContainer *clusters = findNode::getClass<RawClusterContainer>(topnode,"CLUSTER_CEMC");
  SvtxTrackMap *trackmap = findNode::getClass<SvtxTrackMap>(topnode,"SvtxTrackMap");
  JetEvalStack* _jetevalstack = new JetEvalStack(topnode,"AntiKt_Tower_r04","AntiKt_Truth_r04");
  PHG4TruthInfoContainer::Range range = truthinfo->GetPrimaryParticleRange();

  if(!truth_jets){
      cout<<"no truth jets"<<endl;
      return 0;
    }
  if(!reco_jets){
      cout<<"no reco jets"<<endl;
      return 0;
    }
  if(!truthinfo){
      cout<<"no truth track info"<<endl;
      return 0;
    }
  if(!clusters){
    cout<<"no cluster info"<<endl;
    return 0;
  }
  if(!trackmap){
    cout<<"no track map"<<endl;
    return 0;
  }
  if(!_jetevalstack){
    cout<<"no good truth jets"<<endl;
    return 0;
  }


  JetRecoEval* recoeval = _jetevalstack->get_reco_eval();


 /***********************************************

  GET THE TRUTH PARTICLES

  ************************************************/



  for( PHG4TruthInfoContainer::ConstIterator iter = range.first; iter!=range.second; ++iter){

    PHG4Particle *truth = iter->second;
    
    truthpx = truth->get_px();
    truthpy = truth->get_py();
    truthpz = truth->get_pz();
    truthp = sqrt(truthpx*truthpx+truthpy*truthpy+truthpz*truthpz);
    truthenergy = truth->get_e();
    
    TLorentzVector vec;
    vec.SetPxPyPzE(truthpx,truthpy,truthpz,truthenergy);
    
    truthpt = sqrt(truthpx*truthpx+truthpy*truthpy);
    if(truthpt<0.5)
      continue;
    
    truthphi = vec.Phi();
    trutheta = vec.Eta();
    truthpid = truth->get_pid();
    
    truth_g4particles->Fill();

  }


  /***********************************************

  GET THE EMCAL CLUSTERS

  ************************************************/


  RawClusterContainer::ConstRange begin_end = clusters->getClusters();
  RawClusterContainer::ConstIterator clusiter;
  
  for(clusiter = begin_end.first; clusiter!=begin_end.second; ++clusiter){

    RawCluster *cluster = clusiter->second;

    clus_energy = cluster->get_energy();
    clus_eta = cluster->get_eta();
    clus_theta = 2.*TMath::ATan((TMath::Exp(-1.*clus_eta)));
    clus_pt = clus_energy*TMath::Sin(clus_theta);
    clus_phi = cluster->get_phi();
    
    if(clus_pt<0.5)
      continue;

   
    
    TLorentzVector *clus = new TLorentzVector();
    clus->SetPtEtaPhiE(clus_pt,clus_eta,clus_phi,clus_energy);
    
    float dumarray[4];
    clus->GetXYZT(dumarray);
    clus_x = dumarray[0];
    clus_y = dumarray[1];
    clus_z = dumarray[2];
    clus_t = dumarray[3];

    clus_px = clus_pt*TMath::Cos(clus_phi);
    clus_py = clus_pt*TMath::Sin(clus_phi);
    clus_pz = sqrt(clus_energy*clus_energy-clus_px*clus_px-clus_py*clus_py);

    cluster_tree->Fill();

    //only interested in high pt photons to be isolated
    if(clus_pt<mincluspt)
      continue;
    if(fabs(clus_eta)>(1.0-isoconeradius))
      continue;

    float energysum = ConeSum(cluster,clusters,trackmap,isoconeradius);
    bool conecut = energysum > 0.1*clus_energy;
    if(conecut)
      continue;
   
    isolated_clusters->Fill();
    
    GetRecoHadronsAndJets(cluster, trackmap, reco_jets,recoeval);

  }



  /***********************************************

  GET THE SVTX TRACKS

  ************************************************/
  
  SvtxEvalStack *svtxevalstack = new SvtxEvalStack(topnode);
  svtxevalstack->next_event(topnode);

  SvtxTrackEval *trackeval = svtxevalstack->get_track_eval();

  for(SvtxTrackMap::Iter iter = trackmap->begin(); iter!=trackmap->end(); ++iter){

    SvtxTrack *track = iter->second;

    //get reco info
    tr_px = track->get_px();
    tr_py = track->get_py();
    tr_pz = track->get_pz();
    tr_p = sqrt(tr_px*tr_px+tr_py*tr_py+tr_pz*tr_pz);
    
    tr_pt = sqrt(tr_px*tr_px+tr_py*tr_py);
    
    if(tr_pt<0.5)
      continue;
  
    tr_phi = track->get_phi();
    tr_eta = track->get_eta();

    if(fabs(tr_eta)>1)
      continue;

    charge = track->get_charge();
    chisq = track->get_chisq();
    ndf = track->get_ndf();
    dca = track->get_dca();
    tr_x = track->get_x();
    tr_y = track->get_y();
    tr_z = track->get_z();
    
   
    //get truth info
    PHG4Particle *truthtrack = trackeval->max_truth_particle_by_nclusters(track);
    truth_is_primary = truthinfo->is_primary(truthtrack);
    
    truthtrackpx = truthtrack->get_px();
    truthtrackpy = truthtrack->get_py();
    truthtrackpz = truthtrack->get_pz();
    truthtrackp = sqrt(truthtrackpx*truthtrackpx+truthtrackpy*truthtrackpy+truthtrackpz*truthtrackpz);
    
    truthtracke = truthtrack->get_e();
    TLorentzVector *Truthtrack = new TLorentzVector();
    Truthtrack->SetPxPyPzE(truthtrackpx,truthtrackpy,truthtrackpz,truthtracke);
    truthtrackpt = Truthtrack->Pt();
    truthtrackphi = Truthtrack->Phi();
    truthtracketa = Truthtrack->Eta();
    truthtrackpid = truthtrack->get_pid();


    tracktree->Fill();

  }







  /***************************************

   TRUTH JETS

   ***************************************/


  for(JetMap::Iter iter = truth_jets->begin(); iter!=truth_jets->end(); ++iter){
    Jet *jet = iter->second;
    
    truthjetpt = jet->get_pt();
    if(truthjetpt<10.)
      continue;
    
    truthjeteta = jet->get_eta();
    if(fabs(truthjeteta)>2.)
      continue;

    truthjetpx = jet->get_px();
    truthjetpy = jet->get_py();
    truthjetpz = jet->get_pz();
    truthjetphi = jet->get_phi();
    truthjetmass = jet->get_mass();
    truthjetp = jet->get_p();
    truthjetenergy = jet->get_e();
    
    truthjettree->Fill();
    


  }



/***************************************

   RECONSTRUCTED JETS

   ***************************************/



  for(JetMap::Iter iter = reco_jets->begin(); iter!=reco_jets->end(); ++iter){
    Jet *jet = iter->second;
    Jet *truthjet = recoeval->max_truth_jet_by_energy(jet);
    recojetpt = jet->get_pt();
    if(recojetpt<4.)
      continue;
    
    recojeteta = jet->get_eta();
    if(fabs(recojeteta)>2.)
      continue;
    recojetid = jet->get_id();
    recojetpx = jet->get_px();
    recojetpy = jet->get_py();
    recojetpz = jet->get_pz();
    recojetphi = jet->get_phi();
    recojetmass = jet->get_mass();
    recojetp = jet->get_p();
    recojetenergy = jet->get_e();

    if(truthjet){
      truthjetid = truthjet->get_id();
      truthjetp = truthjet->get_p();
      truthjetphi = truthjet->get_phi();
      truthjeteta = truthjet->get_eta();
      truthjetpt = truthjet->get_pt();
      truthjetenergy = truthjet->get_e();
      truthjetpx = truthjet->get_px();
      truthjetpy = truthjet->get_py();
      truthjetpz = truthjet->get_pz();
    }
    else{
      truthjetid = 0;
      truthjetp = 0;
      truthjetphi = 0;
      truthjeteta = 0;
      truthjetpt = 0;
      truthjetenergy = 0;
      truthjetpx = 0;
      truthjetpy = 0;
      truthjetpz = 0;
      
    }
    recojettree->Fill();

  }

  


  nevents++;
  tree->Fill();
  return 0;

}
예제 #9
0
void Ntp1Analyzer_HWWlvjj::Loop(){

   DEBUG_VERBOSE_ = false;

   if (fChain == 0) return;

   Long64_t nentries;

   if( DEBUG_ ) nentries = 100000;
   else nentries = fChain->GetEntries();

   Long64_t nbytes = 0, nb = 0;

   TRandom3 rand;
   float Cont_inclusive=0., Cont_PV=0., Cont_MU=0., Cont_ELE=0., Cont_VetoMU=0., Cont_VetoELE=0., Cont_JetsELE=0., Cont_JetsMU=0.;
   Long64_t Jentry;

requiredTriggerElectron.push_back("1-164237:HLT_Ele27_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v");
requiredTriggerElectron.push_back("165085-166967:HLT_Ele32_CaloIdVT_CaloIsoT_TrkIdT_TrkIsoT_v");
requiredTriggerElectron.push_back("166968-999999:HLT_Ele52_CaloIdVT_TrkIdT_v");
requiredTriggerMuon.push_back("1-163261:HLT_Mu15_v");
requiredTriggerMuon.push_back("163262-164237:HLT_Mu24_v");
requiredTriggerMuon.push_back("165085-166967:HLT_Mu30_v");
requiredTriggerMuon.push_back("163262-166967:HLT_IsoMu17_v");
requiredTriggerMuon.push_back("167039-999999:HLT_IsoMu20_eta2p1_v");
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;

     Jentry=jentry;

     if( DEBUG_VERBOSE_ ) std::cout << "entry n." << jentry << std::endl;
     

     if( (jentry%100000) == 0 ) std::cout << "Event #" << jentry  << " of " << nentries << std::endl;
  
   //HLT_Mu11_ = this->PassedHLT("HLT_Mu11");
   //HLT_Ele17_SW_EleId_L1R_ = this->PassedHLT("HLT_Ele17_SW_EleId_L1R");
   //HLT_DoubleMu3_ = this->PassedHLT("HLT_DoubleMu3");

     run_ = runNumber;
     LS_ = lumiBlock;
     event_ = eventNumber;
     eventWeight_ = -1.; //default

     Cont_inclusive++;//Other;

     if( !isGoodEvent( jentry ) ) continue; //this takes care also of integrated luminosity and trigger

       if( nPV==0 ) continue;
     bool goodVertex = (ndofPV[0] >= 4.0 && sqrt(PVxPV[0]*PVxPV[0]+PVyPV[0]*PVyPV[0]) < 2. && fabs(PVzPV[0]) < 24. );
     if( !goodVertex ) continue;
     nvertex_ = nPV;
     rhoPF_ = rhoFastjet;

     Cont_PV++; //Other

     //trigger:
     // not yet

     if( !isMC_ ){
     reloadTriggerMask(runNumber);
     bool passedElectronTrigger=true, passedMuonTrigger=true;
     std::string SingEle("SingleElectron_6july");//WW
     std::string SingMuo("SingleMu_6july");
     int elect=dataset_.compare(SingEle), muo=dataset_.compare(SingMuo);
     if( elect==0 ){ passedElectronTrigger = hasPassedHLT(0); }
     if( muo==0 ){ passedMuonTrigger = hasPassedHLT(1); }
     if( elect!=0 && muo!=0  ){ std::cout<<"Trigger doesn't works; dataset wrong"<<std::endl; }
     if( !passedElectronTrigger && elect==0 ){ continue;}
     if( !passedMuonTrigger && muo==0 ){ continue;}
     }
         ptHat_ = (isMC_) ? genPtHat : ptHat_;

     //if( isMC_ ) 
     //  if( (ptHat_ > ptHatMax_) || (ptHat_ < ptHatMin_) ) continue;

     bool noLeptons = false;
     TLorentzVector lept1MC, lept2MC;
     int wIndexqq=-1;
     int wIndexll=-1;
   
     if( isMC_ ) {
       
       // first look for W->qq'
       std::vector<TLorentzVector> quarksMC;

       for( unsigned iMc=0; iMc<nMc && quarksMC.size()<2; ++iMc ) {

         // quarks have status 3
         if( statusMc[iMc] != 3 ) continue;

         TLorentzVector* thisParticle = new TLorentzVector();
         thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

         if( fabs(idMc[iMc])<7 && fabs(idMc[mothMc[iMc]])==24 ) {
           wIndexqq = mothMc[iMc];
           quarksMC.push_back( *thisParticle );
         }
       }

       // (checked that always 2 quarks are found)
       if( quarksMC.size()==2 && wIndexqq!=-1 ) {
	   eQuark1_=quarksMC[0].E();
	   ptQuark1_=quarksMC[0].Pt();
	   etaQuark1_=quarksMC[0].Eta();
	   phiQuark1_=quarksMC[0].Phi();
	   eQuark2_=quarksMC[1].E();
	   ptQuark2_=quarksMC[1].Pt();
	   etaQuark2_=quarksMC[1].Eta();
	   phiQuark2_=quarksMC[1].Phi();
 
         TLorentzVector WqqMC;
         WqqMC.SetPtEtaPhiE( pMc[wIndexqq]*sin(thetaMc[wIndexqq]), etaMc[wIndexqq], phiMc[wIndexqq], energyMc[wIndexqq] );
         ptWqqMC_  = WqqMC.Pt();
         eWqqMC_   = WqqMC.Energy();
         etaWqqMC_ = WqqMC.Eta();
         phiWqqMC_ = WqqMC.Phi();
	 //float deltaRqq = quarksMC[0].DeltaR(quarksMC[1]);
	 // h1_deltaRqq->Fill(deltaRqq);
       }
       
       // now look for W->lv

       std::vector<TLorentzVector> electronMC;
       std::vector<TLorentzVector> muonMC;
       std::vector<TLorentzVector> neutrinoMC;

       for( unsigned iMc=0; iMc<nMc; ++iMc ) {
	 
	 if( statusMc[iMc] != 3 ) continue;
	 
         TLorentzVector* thisParticle = new TLorentzVector();
         thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( fabs(idMc[iMc])==11 && fabs(idMc[mothMc[iMc]])==24 ) {electronMC.push_back( *thisParticle ); wIndexll = mothMc[iMc]; }
	   if( fabs(idMc[iMc])==13 && fabs(idMc[mothMc[iMc]])==24 ) {muonMC.push_back( *thisParticle ); wIndexll = mothMc[iMc]; }
	   if( (fabs(idMc[iMc])==12 || fabs(idMc[iMc])==14 ) && fabs(idMc[mothMc[iMc]])==24 ) {
	     neutrinoMC.push_back( *thisParticle );  wIndexll = mothMc[iMc];
	       }//for comparison with fit
 
         delete thisParticle;
         thisParticle = 0;
       }
       
       if( electronMC.size()==1 && neutrinoMC.size()==1 ) {
	 lept1MC = electronMC[0];
	 lept2MC = neutrinoMC[0];
	
       	 if( (fabs(lept1MC.Eta()) < 2.5) && ( fabs(lept1MC.Eta())<1.4442 || fabs(lept1MC.Eta())>1.566) ){
       	 h1_nEvents_vs_ptEle->Fill( lept1MC.Pt() );}
       	 h1_nEvents_vs_ptEle->Fill( lept2MC.Pt() );
       	 }
       else if( muonMC.size()==1 && neutrinoMC.size()==1 ) {
	 lept1MC = muonMC[0];
	 lept2MC = neutrinoMC[0];

	 if( fabs(lept1MC.Eta()) < 2.4 ){ 
         h1_nEvents_vs_ptMuon->Fill( lept1MC.Pt() );} h1_nEvents_vs_ptMuon->Fill( lept2MC.Pt() );
       }
       else {
	 //taus
	 noLeptons=true;
       }

       if( !noLeptons ) {
       eLeptMC_=lept1MC.E();
       ptLeptMC_=lept1MC.Pt();
       etaLeptMC_=lept1MC.Eta();
       phiLeptMC_=lept1MC.Phi();       
       eNeuMC_=lept2MC.E();
       ptNeuMC_=lept2MC.Pt();
       etaNeuMC_=lept2MC.Eta();
       phiNeuMC_=lept2MC.Phi();
       }
       //if is a tau or a not recognized e/mu default values are setted
       if( noLeptons ) {
       eLeptMC_=1.;
       ptLeptMC_=1.;
       etaLeptMC_=10.;
       phiLeptMC_=1.;       
       eNeuMC_=1.;
       ptNeuMC_=1.;
       etaNeuMC_=10.;
       phiNeuMC_=1.;    
       }

       if( !noLeptons ) {
       TLorentzVector WllMC;
       WllMC.SetPtEtaPhiE( pMc[wIndexll]*sin(thetaMc[wIndexll]), etaMc[wIndexll], phiMc[wIndexll], energyMc[wIndexll] );
       
       ptWllMC_  = WllMC.Pt();
       eWllMC_   = WllMC.Energy();
       etaWllMC_ = WllMC.Eta();
       phiWllMC_ = WllMC.Phi();
       }
       
       // now look for the higgs:
       if( wIndexll!=-1 && wIndexqq!=-1 ) {
	 
         int higgsIndex = mothMc[wIndexll];
         if( idMc[higgsIndex] == 25 ) {
           TLorentzVector HiggsMC;
           HiggsMC.SetPtEtaPhiE( pMc[higgsIndex]*sin(thetaMc[higgsIndex]), etaMc[higgsIndex], phiMc[higgsIndex], energyMc[higgsIndex] );

           eHiggsMC_   = HiggsMC.Energy(); 
           ptHiggsMC_  = HiggsMC.Pt(); 
           etaHiggsMC_ = HiggsMC.Eta(); 
           phiHiggsMC_ = HiggsMC.Phi(); 
         } // if higgs

       } //if found two W's
     
     } //if isMC
    
     // -----------------------------
     //      FROM NOW ON RECO
     // -----------------------------

     energyPFMet_ = energyPFMet[0];
     phiPFMet_ = phiPFMet[0];
     pxPFMet_ = pxPFMet[0];
     pyPFMet_ = pyPFMet[0];     
     
     // -----------------------------
     //###      uncorrEnergyJet (to use in Neutrino's fit if you don't have SumEt)
     // -----------------------------
     
       for( int i=0;i<nAK5Jet;i++ ){
       uncorrEnergyAK5Jet_ += uncorrEnergyAK5Jet[i];
       }

     // -----------------------------
     //###      SumEt
     // -----------------------------
       
     SumEt_ = sumEtPFMet[0]; 
 
     // ------------------
     // MUON
     // ------------------

     std::vector<AnalysisMuon> muon;
     bool looseMuon=false;

     for( unsigned int iMuon=0; iMuon<nMuon; ++iMuon ) {

         AnalysisMuon thisMuon( pxMuon[iMuon], pyMuon[iMuon], pzMuon[iMuon], energyMuon[iMuon] );

       // --------------
       // kinematics:
       // --------------

       if( thisMuon.Pt() < 10. ) continue;
       if( fabs(thisMuon.Eta()) > 2.4 ) continue; //2.4 OtherMine

	 thisMuon.isGlobalMuonPromptTight = (muonIdMuon[iMuon]>>8)&1;
	 thisMuon.isAllTrackerMuon = (muonIdMuon[iMuon]>>11)&1;

       //     // --------------
       //     // ID:
       //     // --------------
       //     if( !( (muonIdMuon[iMuon]>>8)&1 ) ) continue; //GlobalMuonPromptTight
       //     if( !( (muonIdMuon[iMuon]>>11)&1 ) ) continue; //AllTrackerMuon
       //if( numberOfValidPixelBarrelHitsTrack[trackIndexMuon[iMuon]]==0 && numberOfValidPixelEndcapHitsTrack[trackIndexMuon[iMuon]]==0 ) continue;      
         
	thisMuon.pixelHits = numberOfValidPixelBarrelHitsTrack[trackIndexMuon[iMuon]]+numberOfValidPixelEndcapHitsTrack[trackIndexMuon[iMuon]];
        thisMuon.trackerHits = trackValidHitsTrack[trackIndexMuon[iMuon]];
        thisMuon.nMatchedStations = numberOfMatchesMuon[iMuon]; // This branch not exists yet in WW500

       // to compute dxy, look for leading primary vertex:
       int hardestPV = -1;
       float sumPtMax = 0.0;
       for(int v=0; v<nPV; v++) {
         if(SumPtPV[v] > sumPtMax) {
           sumPtMax = SumPtPV[v];
           hardestPV = v;
         }
       }  
      
       float dxy;
       if( hardestPV==-1 ) {
         dxy = 0.;
       } else {
         dxy = fabs(this->trackDxyPV(PVxPV[hardestPV], PVyPV[hardestPV], PVzPV[hardestPV],
                              trackVxTrack[trackIndexMuon[iMuon]], trackVyTrack[trackIndexMuon[iMuon]], trackVzTrack[trackIndexMuon[iMuon]],
				     pxTrack[trackIndexMuon[iMuon]], pyTrack[trackIndexMuon[iMuon]], pzTrack[trackIndexMuon[iMuon]]));
       }
 
       float dz = fabs(trackVzTrack[trackIndexMuon[iMuon]]-PVzPV[hardestPV]);
      
       thisMuon.dxy = dxy;
       thisMuon.dz = dz;
       
       thisMuon.sumPt03 = sumPt03Muon[iMuon];
       thisMuon.emEt03  = emEt03Muon[iMuon];
       thisMuon.hadEt03 = hadEt03Muon[iMuon];

       if( !thisMuon.passedVBTF() ) continue;
     
       // --------------
       // isolation:
       // --------------
       // (this is sum pt tracks)
       //if( sumPt03Muon[iMuon] >= 3. ) continue;
       // combined isolation < 15%:
       //if( (sumPt03Muon[iMuon] + emEt03Muon[iMuon] + hadEt03Muon[iMuon]) >= 0.15*thisMuon.Pt() ) continue;

       // looking at loose muon
       looseMuon=true;
       if( thisMuon.Pt()<20. ) continue;

       // for now simple selection, will have to optimize this (T&P?)
       chargeLept_=chargeMuon[iMuon];
     muon.push_back( thisMuon );
       looseMuon=false;

   } //for muon

     // ------------------
     // ELECTRON
     // ------------------

     std::vector<AnalysisElectron> electron;    
     bool looseEle = false; //Other
     
     for( unsigned int iEle=0; iEle<nEle ; ++iEle ) {

       AnalysisElectron thisEle( pxEle[iEle], pyEle[iEle], pzEle[iEle], energyEle[iEle] );

       // --------------
       // kinematics:
       // --------------
       if( thisEle.Pt() < 15. ) continue;
       if( (fabs(thisEle.Eta()) > 2.5) || ( fabs(thisEle.Eta())>1.4442 && fabs(thisEle.Eta())<1.566) ) continue;

       // isolation
       thisEle.dr03TkSumPt = dr03TkSumPtEle[iEle];
       thisEle.dr03EcalRecHitSumEt = dr03EcalRecHitSumEtEle[iEle];
       thisEle.dr03HcalTowerSumEt = dr03HcalTowerSumEtEle[iEle];

       // electron ID
       thisEle.sigmaIetaIeta = (superClusterIndexEle[iEle]>=0) ? covIEtaIEtaSC[superClusterIndexEle[iEle]] : covIEtaIEtaSC[PFsuperClusterIndexEle[iEle]];
       thisEle.deltaPhiAtVtx = deltaPhiAtVtxEle[iEle];
       thisEle.deltaEtaAtVtx = deltaEtaAtVtxEle[iEle];
       thisEle.hOverE = hOverEEle[iEle];

       // conversion rejection
       thisEle.expInnerLayersGsfTrack = expInnerLayersGsfTrack[gsfTrackIndexEle[iEle]];
       thisEle.convDist = convDistEle[iEle];
       thisEle.convDcot = convDcotEle[iEle];

       bool passed_VBTF95 = thisEle.passedVBTF95();
       bool passed_VBTF80 = thisEle.passedTrigger80();//thisEle.passedVBTF80();

       if( !passed_VBTF80 && passed_VBTF95 ) looseEle=true; //Other
       if( !passed_VBTF80 ) continue; 
       if( thisEle.Pt() < 20. ) continue; // if is not a loose ele I require a higher Pt     

       // check that not matched to muon (clean electron faked by muon MIP):
       bool matchedtomuon=false;
       for( std::vector<AnalysisMuon>::iterator iMu=muon.begin(); iMu!=muon.end(); ++iMu )
         if( iMu->DeltaR(thisEle)<0.1 ) matchedtomuon=true;

       if( matchedtomuon ) continue;

       // for now simple selection, will have to optimize this (T&P?)
       // one electron required to pass VBTF80, the other VBTF95
       chargeLept_=chargeEle[iEle];
       electron.push_back( thisEle );
     } //for electron 
                                         //  FILL LEPTONS
// Fill Efficiency for Others

bool findJetELE=false;
bool findJetMU=false;

if( electron.size() >= 1 ) { Cont_ELE++;
  if( electron.size() == 1 && muon.size()==0 && !looseEle && !looseMuon ) { Cont_VetoELE++; findJetELE=true; }
  }

if( muon.size() >= 1 ) { Cont_MU++;
  if( muon.size() == 1 && electron.size()==0 && !looseEle && !looseMuon ) { Cont_VetoMU++; findJetMU=true; }
  }
// Fill lepton
    if( electron.size() > 1 || muon.size() > 1 ) continue;

     if( electron.size() < 1 &&  muon.size() < 1 ) continue;
     
     //   // clean electron faked by muon MIP in ECAL
     //   for( std::vector<TLorentzVector>::iterator iEle=electron.begin(); iEle!=electron.end(); ++iEle ) {
     //     for( std::vector<TLorentzVector>::iterator iMu=muon.begin(); iMu!=muon.end(); ++iMu ) {
     //       if( iMu->DeltaR(*iEle)<0.1 ) {
     //         std::cout << "lll" << std::endl;
     //         electron.erase(iEle);
     //       }
     //     } //for ele
     //   } //for mu
     
     //   if( electron.size() < 2 && muon.size() < 1 ) continue;
    
     std::vector< AnalysisLepton > leptons;

     if( electron.size() == 1 && muon.size() == 1 ) continue;
     if( electron.size() == 1 && (looseEle || looseMuon) ) continue;
     if( muon.size() == 1 && (looseEle || looseMuon) ) continue;

     if( electron.size() == 1 && (!looseEle || !looseMuon) ) { //Other 
       leptType_ = 1;
       leptons.push_back( electron[0] );

     } else if( muon.size() == 1 && (!looseEle || !looseMuon) ) {
       leptType_ = 0;
       leptons.push_back( muon[0] );

     } else {
       std::cout << "There must be an error this is not possible." << std::endl;
       exit(9101);
     }

     eLept_ = leptons[0].Energy();
     ptLept_ = leptons[0].Pt();
     etaLept_ = leptons[0].Eta();
     phiLept_ = leptons[0].Phi(); //chargeLept_ filled before
    
     // --------------------
     // match leptons to MC:
     // --------------------
     int correctIdMc = (leptType_==0 ) ? 13 : 11;

	float deltaRmin = 100.;
	TLorentzVector matchedLeptonMC;
	for( unsigned iMc=0; iMc<nMc; ++iMc ){
	   if( statusMc[iMc]==1 && fabs(idMc[iMc])==correctIdMc && idMc[mothMc[mothMc[iMc]]]==24 ) {
	     
	     TLorentzVector* thisParticle = new TLorentzVector();
	     thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );
	     float thisDeltaR = leptons[0].DeltaR( *thisParticle );
	     if( thisDeltaR < deltaRmin ) {
	       deltaRmin = thisDeltaR;
	       matchedLeptonMC = *thisParticle;
	     }
	     
	     delete thisParticle;
	     thisParticle = 0; 
	   } //if correct id mc
	   
	  } // for i mc

	  if( !noLeptons ) {
	    if( leptType_==0 ) {
	      h1_deltaRmatching_muons->Fill( deltaRmin );
	      if( deltaRmin<0.1 ) {
		h1_passed_vs_ptMuon->Fill( matchedLeptonMC.Pt() );
	      }
	    } else if( leptType_==1 ) { 
	      h1_deltaRmatching_electrons->Fill( deltaRmin );
	      if( deltaRmin<0.1 ) {
		h1_passed_vs_ptEle->Fill( matchedLeptonMC.Pt() );
	      }
	    }  //if lept type
	  } //if yes leptons
   
      // ------------------
      // JETS
      // ------------------
	     
	float jetPt_thresh = 20.;
	bool matched=false;      
	
	// first save leading jets in event:
	std::vector<AnalysisJet> leadJets;
	std::vector<int> leadJetsIndex; //index in the event collection (needed afterwards for PFCandidates)
	int nJets30=0;
	
	//QGLikelihoodCalculator qglc;
     for( unsigned int iJet=0; iJet<nAK5PFPUcorrJet; ++iJet ) {
       
       AnalysisJet thisJet( pxAK5PFPUcorrJet[iJet], pyAK5PFPUcorrJet[iJet], pzAK5PFPUcorrJet[iJet], energyAK5PFPUcorrJet[iJet] );
       
       thisJet.eChargedHadrons = chargedHadronEnergyAK5PFPUcorrJet[iJet];
       thisJet.ePhotons        = photonEnergyAK5PFPUcorrJet[iJet];
       thisJet.eNeutralEm      = neutralEmEnergyAK5PFPUcorrJet[iJet];
       thisJet.eNeutralHadrons = neutralHadronEnergyAK5PFPUcorrJet[iJet];
       thisJet.eElectrons      = electronEnergyAK5PFPUcorrJet[iJet];
       thisJet.eMuons          = muonEnergyAK5PFPUcorrJet[iJet];

       thisJet.nChargedHadrons = chargedHadronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nPhotons        = photonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nNeutralHadrons = neutralHadronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nElectrons      = electronMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nMuons          = muonMultiplicityAK5PFPUcorrJet[iJet];

       thisJet.nCharged = chargedHadronMultiplicityAK5PFPUcorrJet[iJet]+electronMultiplicityAK5PFPUcorrJet[iJet]+muonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.nNeutral = neutralHadronMultiplicityAK5PFPUcorrJet[iJet]+photonMultiplicityAK5PFPUcorrJet[iJet];
       thisJet.rmsCand =  rmsCandAK5PFPUcorrJet[iJet];
       thisJet.ptD =  ptDAK5PFPUcorrJet[iJet];

       thisJet.trackCountingHighEffBJetTag = trackCountingHighEffBJetTagsAK5PFPUcorrJet[iJet];

       if( thisJet.Pt()>jetPt_thresh ) nJets30++;

       // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
       if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

       // far away from leptons:
      if( leptType_==0){ if(thisJet.DeltaR( leptons[0] ) < 0.5 ) continue;}    
      if( leptType_==1){ if(thisJet.DeltaR( leptons[0] ) < 0.5 ) continue;} 

       // jet ID:
       int multiplicity = thisJet.nCharged +  thisJet.nNeutral + HFEMMultiplicityAK5PFPUcorrJet[iJet] + HFHadronMultiplicityAK5PFPUcorrJet[iJet];
       if( multiplicity < 2 ) continue;
       if( fabs(thisJet.Eta())<2.4 && thisJet.nChargedHadrons == 0 ) continue;
       if( thisJet.eNeutralHadrons >= 0.99*thisJet.Energy() ) continue;
       if( thisJet.ePhotons >= 0.99*thisJet.Energy() ) continue;
       // match to genjet:

       float bestDeltaR=999.;
       TLorentzVector matchedGenJet;
       bool matched=false;
       for( unsigned iGenJet=0; iGenJet<nAK5GenJet; ++iGenJet ) {
         TLorentzVector thisGenJet(pxAK5GenJet[iGenJet], pyAK5GenJet[iGenJet], pzAK5GenJet[iGenJet], energyAK5GenJet[iGenJet]);
         if( thisGenJet.DeltaR(thisJet) < bestDeltaR ) {
           bestDeltaR=thisGenJet.DeltaR(thisJet);
           matchedGenJet=thisGenJet; matched==true;
         }
       }
       if(matched){
       thisJet.ptGen  = (isMC_) ? matchedGenJet.Pt() : 0.;
       thisJet.etaGen = (isMC_) ? matchedGenJet.Eta() : 20.;
       thisJet.phiGen = (isMC_) ? matchedGenJet.Phi() : 0.;
       thisJet.eGen   = (isMC_) ? matchedGenJet.Energy() : 0.;}
       else{
       thisJet.ptGen  = 0.;
       thisJet.etaGen = 20.;
       thisJet.phiGen = 0.;
       thisJet.eGen   = 0.;}
       // match to parton:
       float bestDeltaR_part=999.;
       TLorentzVector matchedPart;
       int pdgIdPart=0;
       for( unsigned iPart=0; iPart<nMc; ++iPart ) {
         if( statusMc[iPart]!=3 ) continue; //partons
         if( idMc[iPart]!=21 && abs(idMc[iPart])>6 ) continue; //quarks or gluons
         TLorentzVector thisPart;
         thisPart.SetPtEtaPhiE(pMc[iPart]*sin(thetaMc[iPart]), etaMc[iPart], phiMc[iPart], energyMc[iPart]);
         if( thisPart.DeltaR(thisJet) < bestDeltaR_part ) {
           bestDeltaR_part=thisPart.DeltaR(thisJet);
           matchedPart=thisPart;
           pdgIdPart=idMc[iPart];
         }
       }

       leadJets.push_back(thisJet);
       leadJetsIndex.push_back(iJet); 
     }//iJet

     h1_nJets30->Fill(nJets30);

     if( leadJets.size()<2 ) continue;
     if( leadJets[1].Pt()<jetPt_thresh ) continue; //at least 2 jets over thresh
   
     // now look for best invariant mass jet pair 
     float Wmass = 80.399;
     float bestMass = 0.;
     int best_i=-1;
     int best_j=-1;
     int best_i_eventIndex=-1;
     int best_j_eventIndex=-1;

     nPairs_ = 0;
     nPart_ = 0;
    
     for( unsigned iJet=0; iJet<leadJets.size(); ++iJet ) {
   
       AnalysisJet thisJet = leadJets[iJet];

       // --------------
       // kinematics:
       // --------------
       if( thisJet.Pt() < jetPt_thresh ) continue;
       if( fabs(thisJet.Eta()) > 2.4 ) continue;

       for( unsigned int jJet=iJet+1; jJet<leadJets.size(); ++jJet ) {

         AnalysisJet otherJet = leadJets[jJet];

         // --------------
         // kinematics:
         // --------------
         if( otherJet.Pt() < jetPt_thresh ) continue;
         if( fabs(otherJet.Eta()) > 2.4 ) continue;

         if( nPairs_>=50 ) {
        
           std::cout << "MORE than 50 jet pairs found. SKIPPING!!" << std::endl;

         } else {

           eJet1_[nPairs_] = leadJets[iJet].Energy();
           ptJet1_[nPairs_] = leadJets[iJet].Pt();
           etaJet1_[nPairs_] = leadJets[iJet].Eta();
           phiJet1_[nPairs_] = leadJets[iJet].Phi();
           eChargedHadronsJet1_[nPairs_] = leadJets[iJet].eChargedHadrons;
           ePhotonsJet1_[nPairs_]        = leadJets[iJet].ePhotons;
           eNeutralEmJet1_[nPairs_]      = leadJets[iJet].eNeutralEm;
           eNeutralHadronsJet1_[nPairs_] = leadJets[iJet].eNeutralHadrons;
           eElectronsJet1_[nPairs_]      = leadJets[iJet].eElectrons;
           eMuonsJet1_[nPairs_]          = leadJets[iJet].eMuons;
           nChargedHadronsJet1_[nPairs_] = leadJets[iJet].nChargedHadrons;
           nPhotonsJet1_[nPairs_]        = leadJets[iJet].nPhotons;
           nNeutralHadronsJet1_[nPairs_] = leadJets[iJet].nNeutralHadrons;
           nElectronsJet1_[nPairs_]      = leadJets[iJet].nElectrons;
           nMuonsJet1_[nPairs_]          = leadJets[iJet].nMuons;

           trackCountingHighEffBJetTagJet1_[nPairs_] = leadJets[iJet].trackCountingHighEffBJetTag;
           trackCountingHighEffBJetTagJet2_[nPairs_] = leadJets[jJet].trackCountingHighEffBJetTag;

           ptDJet1_[nPairs_] = leadJets[iJet].ptD;
           rmsCandJet1_[nPairs_] = leadJets[iJet].rmsCand;
           nChargedJet1_[nPairs_] = leadJets[iJet].nCharged;
           nNeutralJet1_[nPairs_] = leadJets[iJet].nNeutral;
           QGlikelihoodJet1_[nPairs_] = leadJets[iJet].QGlikelihood;

           eJet1Gen_[nPairs_] = leadJets[iJet].eGen;
           ptJet1Gen_[nPairs_] = leadJets[iJet].ptGen;
           etaJet1Gen_[nPairs_] = leadJets[iJet].etaGen;
           phiJet1Gen_[nPairs_] = leadJets[iJet].phiGen;
            
           eJet2_[nPairs_] = leadJets[jJet].Energy();
           ptJet2_[nPairs_] = leadJets[jJet].Pt();
           etaJet2_[nPairs_] = leadJets[jJet].Eta();
           phiJet2_[nPairs_] = leadJets[jJet].Phi();
           eChargedHadronsJet2_[nPairs_] = leadJets[jJet].eChargedHadrons;
           ePhotonsJet2_[nPairs_]        = leadJets[jJet].ePhotons;
           eNeutralEmJet2_[nPairs_]      = leadJets[jJet].eNeutralEm;
           eNeutralHadronsJet2_[nPairs_] = leadJets[jJet].eNeutralHadrons;
           eElectronsJet2_[nPairs_]      = leadJets[jJet].eElectrons;
           eMuonsJet2_[nPairs_]          = leadJets[jJet].eMuons;
           nChargedHadronsJet2_[nPairs_] = leadJets[jJet].nChargedHadrons;
           nPhotonsJet2_[nPairs_]        = leadJets[jJet].nPhotons;
           nNeutralHadronsJet2_[nPairs_] = leadJets[jJet].nNeutralHadrons;
           nElectronsJet2_[nPairs_]      = leadJets[jJet].nElectrons;
           nMuonsJet2_[nPairs_]          = leadJets[jJet].nMuons;

           ptDJet2_[nPairs_] = leadJets[jJet].ptD;
           rmsCandJet2_[nPairs_] = leadJets[jJet].rmsCand;
           nChargedJet2_[nPairs_] = leadJets[jJet].nCharged;
           nNeutralJet2_[nPairs_] = leadJets[jJet].nNeutral;
           QGlikelihoodJet2_[nPairs_] = leadJets[jJet].QGlikelihood;

           eJet2Gen_[nPairs_] = leadJets[jJet].eGen;
           ptJet2Gen_[nPairs_] = leadJets[jJet].ptGen;
           etaJet2Gen_[nPairs_] = leadJets[jJet].etaGen;
           phiJet2Gen_[nPairs_] = leadJets[jJet].phiGen;
            

           nPairs_++;
          
         }
	
       } //for j
     } //for i
   if( findJetELE && nPairs_>=1 ) {Cont_JetsELE++;} //Other 
   if( findJetMU && nPairs_>=1 ) {Cont_JetsMU++;} //Other 

 
     if( isMC_ ) {

       // store event partons in tree:
       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         //if( statusMc[iMc]==3 && (fabs(idMc[iMc])<=6 || idMc[iMc]==21) ) {
         if( statusMc[iMc]==3 && pMc[iMc]*sin(thetaMc[iMc])>0.1 ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( nPart_<20 ) {

             ptPart_[nPart_] = thisParticle->Pt();
             etaPart_[nPart_] = thisParticle->Eta();
             phiPart_[nPart_] = thisParticle->Phi();
             ePart_[nPart_] = thisParticle->Energy();
             pdgIdPart_[nPart_] = idMc[iMc];
             motherPart_[nPart_] = idMc[mothMc[iMc]];

             nPart_++;

           } else {
      
             std::cout << "Found more than 20 partons, skipping." << std::endl;

           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc

     } // if is mc

     reducedTree_->Fill(); 

   } //for entries
                       // Other
float proportion = 2061760. /*109989.*/ /Cont_inclusive;
	if( Jentry == (nentries-1) ){
//  std::cout << std::fixed << std::setprecision(6) << "Inclusive: " << Cont_inclusive*proportion << " PV: " << Cont_PV*proportion << " MU: " << Cont_MU*proportion << " ELE: " << Cont_ELE*proportion << " VetoMU: " << Cont_VetoMU*proportion 
  //<< " VetoELE: " << Cont_VetoELE*proportion << " JetsELE: " << Cont_JetsELE*proportion << " JetsMU: " << Cont_JetsMU*proportion << std::endl;

h1_Cont_inclusive->SetBinContent(1,Cont_inclusive*proportion);
h1_Cont_PV->SetBinContent(1,Cont_PV*proportion);
h1_Cont_TightMu->SetBinContent(1,Cont_MU*proportion);
h1_Cont_TightEle->SetBinContent(1,Cont_ELE*proportion);
h1_Cont_VetoMU->SetBinContent(1,Cont_VetoMU*proportion);
h1_Cont_VetoELE->SetBinContent(1,Cont_VetoELE*proportion);
h1_Cont_JetsELE->SetBinContent(1,Cont_JetsELE*proportion);
h1_Cont_JetsMU->SetBinContent(1,Cont_JetsMU*proportion);
}

} //loop
예제 #10
0
Bool_t Analysis::Process(Long64_t entry)
{

  jpt  ->clear();    
  jeta ->clear(); 
  jphi ->clear(); 
  jmass->clear();
  jconst->clear();
  toppt->clear();
  jhasb->clear();
  jhasq->clear();
  
  if (entry%1==0) cout << "\r Events  " << entry << "\r" << flush;
  this->GetEntry(entry);
    
  double rho = 2*173.5;
  double min_r = 0.4;
  double max_r = 1.5;
  double ptmin = 200.;

  // fill jets
  //-----------------------------------------------
  vector<fastjet::PseudoJet> pseudojets; pseudojets.clear();
  for (int ijet=0;ijet<jets_n;++ijet){
    if(jets_isBad->at(ijet)!=0) return kFALSE;
    if(jets_pt->at(ijet)<20.) continue;
    if(fabs(jets_eta->at(ijet))>2.8) continue;
    TLorentzVector tvit = TLorentzVector();
    tvit.SetPtEtaPhiE(jets_pt->at(ijet),
		      jets_eta->at(ijet),
		      jets_phi->at(ijet),
		      jets_e->at(ijet));
    pseudojets.push_back( fastjet::PseudoJet(tvit.Px(), tvit.Py(), 
					     tvit.Pz(), tvit.E()) );
  }

  // fill truth
  //----------------------------------------------
  vector<int> tops;
  vector<int> Wq1s;
  vector<int> Wq2s;
  vector<int> bs;
  for (int imc=0;imc<mc_n;++imc)
    if (fabs(mc_pdgId->at(imc))==6){
      int windex = mc_children_index->at(imc)[0];
      int bindex = mc_children_index->at(imc)[1];
      int wq1 = mc_children_index->at(windex)[0];
      int wq2 = mc_children_index->at(windex)[1];
      if(fabs(mc_pdgId->at(wq1))>5 || fabs(mc_pdgId->at(wq2))>5) continue;
      tops.push_back( imc );
      Wq1s.push_back( wq1 );
      Wq2s.push_back( wq2 );
      bs.push_back( bindex );
      toppt->push_back( mc_pt->at(imc) );
    }//endif

  for (int it=0;it<tops.size();++it){
    fastjet::PseudoJet wq1; wq1.reset_PtYPhiM(1e-10,mc_eta->at(Wq1s[it]),mc_phi->at(Wq1s[it]));
    fastjet::PseudoJet wq2; wq2.reset_PtYPhiM(1e-10,mc_eta->at(Wq2s[it]),mc_phi->at(Wq2s[it]));
    fastjet::PseudoJet bq; bq.reset_PtYPhiM(1e-10,mc_eta->at(bs[it]),mc_phi->at(bs[it]));
    wq1.set_user_info(new MyUserInfo(it, false));
    wq1.set_user_info(new MyUserInfo(it, false));
    bq.set_user_info(new MyUserInfo(it, true));
    pseudojets.push_back( wq1 );
    pseudojets.push_back( wq2 );
    pseudojets.push_back( bq );
  }// top loop

  fastjet::contrib::VariableRPlugin lvjet_pluginAKT(rho, min_r, max_r, fastjet::contrib::VariableRPlugin::AKTLIKE);
  fastjet::JetDefinition jet_def(&lvjet_pluginAKT);
  fastjet::ClusterSequence clust_seqAKT(pseudojets, jet_def);
  vector<fastjet::PseudoJet> inclusive_jetsAKT = clust_seqAKT.inclusive_jets(ptmin);

  for (int ijet=0;ijet<inclusive_jetsAKT.size();++ijet){
    fastjet::PseudoJet *jet = &(inclusive_jetsAKT[ijet]);
    jpt->push_back( jet->pt() );
    jeta->push_back( jet->eta() );
    jphi->push_back( jet->phi() );
    jmass->push_back( jet->m() );
    int ntruth=0;
    vector<int> hasb;
    vector<int> hasq;
    for (int iconst=0;iconst<jet->constituents().size();++iconst){
      fastjet::PseudoJet *jetconst = &(jet->constituents()[iconst]);
      if (jetconst->has_user_info<MyUserInfo>()){
	ntruth++;
	int topid = jetconst->user_info<MyUserInfo>().top();
	bool isbq = jetconst->user_info<MyUserInfo>().isbq();
	if(isbq) hasb.push_back(topid);
	else hasq.push_back(topid);
      }//endif is truth
    }//loop constituents
    jconst->push_back( jet->constituents().size()-ntruth );
    jhasb->push_back( hasb );
    jhasq->push_back( hasq );
  }// loop reclustered jets

  outtree->Fill();

  return kTRUE;
}
예제 #11
0
void data13TeV() {
  //TFile f1("/tmp/rchawla/eos/cms/store/group/phys_smp/rchawla/nTuples/analysis_4March/SE_Run2015.root")
  TFile f1("eos/cms/store/group/phys_higgs/cmshww/arun/DYAnalysis_76X_Calibrated/Data/SE_2015.root");
  TTree *T1 = (TTree*)f1.Get("ntupler/ElectronTree");

  vector<float>   *genPostFSR_Pt;
  vector<float>   *genPostFSR_Eta;
  vector<float>   *genPostFSR_Rap;
  vector<float>   *genPostFSR_Phi;
  vector<float>   *genPostFSR_En;
  vector<int>     *passVetoId;
  vector<int>     *passLooseId;
  vector<int>     *passMediumId;
  vector<int>     *passTightId;
  vector<int>     *passHEEPId;
  vector<int>     *isPassMedium_NoPt;
  vector<int>     *isPassMedium_NoScEta;
  vector<int>     *isPassMedium_NoDEta;
  vector<int>     *isPassMedium_NoDPhi;
  vector<int>     *isPassMedium_NoSigmaEtaEta;
  vector<int>     *isPassMedium_NoHOverE;
  vector<int>     *isPassMedium_NoDxy;
  vector<int>     *isPassMedium_NoDz;
  vector<int>     *isPassMedium_NoEInvP;
  vector<int>     *isPassMedium_NoPFIso;
  vector<int>     *isPassMedium_NoConVeto;
  vector<int>     *isPassMedium_NoMissHits;
  vector<float>   *ptElec;
  vector<float>   *etaElec;
  vector<float>   *rapElec;
  vector<float>   *phiElec;
  vector<float>   *energyElec;
  vector<float>   *etaSC;
  Int_t           tauFlag;
  Double_t        theWeight;
  Bool_t          Ele23_WPLoose;
  Int_t           nPV;
  vector<double>  *pt_Ele23;
  vector<double>  *eta_Ele23;
  vector<double>  *phi_Ele23;

  genPostFSR_Pt = 0;
  genPostFSR_Eta = 0;
  genPostFSR_Rap = 0;
  genPostFSR_Phi = 0;
  genPostFSR_En = 0;
  ptElec = 0;
  etaElec = 0;
  rapElec = 0;
  phiElec = 0;
  energyElec = 0;
  etaSC = 0;
  passVetoId = 0;
  passLooseId = 0;
  passMediumId = 0;
  passTightId = 0;
  passHEEPId = 0;
  isPassMedium_NoPt = 0;
  isPassMedium_NoScEta = 0;
  isPassMedium_NoDEta = 0;
  isPassMedium_NoDPhi = 0;
  isPassMedium_NoSigmaEtaEta = 0;
  isPassMedium_NoHOverE = 0;
  isPassMedium_NoDxy = 0;
  isPassMedium_NoDz = 0;
  isPassMedium_NoEInvP = 0;
  isPassMedium_NoPFIso = 0;
  isPassMedium_NoConVeto = 0;
  isPassMedium_NoMissHits = 0;
  pt_Ele23 = 0;
  eta_Ele23 = 0;
  phi_Ele23 = 0;

  T1->SetBranchAddress("genPostFSR_Pt", &genPostFSR_Pt);
  T1->SetBranchAddress("genPostFSR_Eta", &genPostFSR_Eta);
  T1->SetBranchAddress("genPostFSR_Rap", &genPostFSR_Rap);
  T1->SetBranchAddress("genPostFSR_Phi", &genPostFSR_Phi);
  T1->SetBranchAddress("genPostFSR_En", &genPostFSR_En);
  T1->SetBranchAddress("ptElec", &ptElec);
  T1->SetBranchAddress("etaElec", &etaElec);
  T1->SetBranchAddress("rapElec", &rapElec);
  T1->SetBranchAddress("phiElec", &phiElec);
  T1->SetBranchAddress("energyElec", &energyElec);
  T1->SetBranchAddress("etaSC", &etaSC);
  T1->SetBranchAddress("passVetoId", &passVetoId);
  T1->SetBranchAddress("passLooseId", &passLooseId);
  T1->SetBranchAddress("passMediumId", &passMediumId);
  T1->SetBranchAddress("passTightId", &passTightId);
  T1->SetBranchAddress("passHEEPId", &passHEEPId);
  T1->SetBranchAddress("isPassMedium_NoPt", &isPassMedium_NoPt);
  T1->SetBranchAddress("isPassMedium_NoScEta", &isPassMedium_NoScEta);
  T1->SetBranchAddress("isPassMedium_NoDEta", &isPassMedium_NoDEta);
  T1->SetBranchAddress("isPassMedium_NoDPhi", &isPassMedium_NoDPhi);
  T1->SetBranchAddress("isPassMedium_NoSigmaEtaEta", &isPassMedium_NoSigmaEtaEta);
  T1->SetBranchAddress("isPassMedium_NoHOverE", &isPassMedium_NoHOverE);
  T1->SetBranchAddress("isPassMedium_NoDxy", &isPassMedium_NoDxy);
  T1->SetBranchAddress("isPassMedium_NoDz", &isPassMedium_NoDz);
  T1->SetBranchAddress("isPassMedium_NoEInvP", &isPassMedium_NoEInvP);
  T1->SetBranchAddress("isPassMedium_NoPFIso", &isPassMedium_NoPFIso);
  T1->SetBranchAddress("isPassMedium_NoConVeto", &isPassMedium_NoConVeto);
  T1->SetBranchAddress("isPassMedium_NoMissHits", &isPassMedium_NoMissHits);
  T1->SetBranchAddress("tauFlag", &tauFlag);
  T1->SetBranchAddress("theWeight", &theWeight);
  T1->SetBranchAddress("Ele23_WPLoose", &Ele23_WPLoose);
  T1->SetBranchAddress("nPV", &nPV);
  T1->SetBranchAddress("Ele23_WPLoose", &Ele23_WPLoose);
  T1->SetBranchAddress("pt_Ele23", &pt_Ele23);
  T1->SetBranchAddress("eta_Ele23", &eta_Ele23);
  T1->SetBranchAddress("phi_Ele23", &phi_Ele23);

  TFile *file = new TFile("MediumId_Calibrated/SingleElectron_UnScaleCorr.root", "recreate");
  TTree *tree = new TTree("tree"," after preselections tree");

  int mediumId, dzMaskId, passId;
  bool trigMatch_lead, trigMatch_slead;
  double dR, dR1, dR2;
  TLorentzVector ele1,ele2,dielectron;
  TLorentzVector recoElec;

  // Branch variable declaration
  double primVtx;
  double Ele1PT, Ele2PT, Ele1Eta, Ele2Eta, Ele1Phi, Ele2Phi, Ele1Enr, Ele2Enr;
  double ZMass, ZPT, ZEta, ZRapidity, ZPhi;
  bool BB, BE, EE;

  // Branch declaration
  tree->Branch("primVtx", &primVtx, "primVtx/D");
  tree->Branch("Ele1PT", &Ele1PT, "Ele1PT/D");
  tree->Branch("Ele2PT", &Ele2PT, "Ele2PT/D");
  tree->Branch("Ele1Eta", &Ele1Eta, "Ele1Eta/D");
  tree->Branch("Ele2Eta", &Ele2Eta, "Ele2Eta/D");
  tree->Branch("Ele1Phi", &Ele1Phi, "Ele1Phi/D");
  tree->Branch("Ele2Phi", &Ele2Phi, "Ele2Phi/D");
   tree->Branch("Ele1Enr", &Ele1Enr, "Ele1Enr/D");
    tree->Branch("Ele2Enr", &Ele2Enr, "Ele2Enr/D");
  tree->Branch("ZMass", &ZMass, "ZMass/D");
  tree->Branch("ZPT", &ZPT, "ZPT/D");
  tree->Branch("ZEta", &ZEta, "ZEta/D");
  tree->Branch("ZRapidity", &ZRapidity, "ZRapidity/D");
  tree->Branch("ZPhi", &ZPhi, "ZPhi/D");
  tree->Branch("BB", &BB, "BB/B");
  tree->Branch("BE", &BE, "BE/B");
  tree->Branch("EE", &EE, "EE/B");

  vector <double> newelePt; vector <double> neweleEta; vector <double> neweleEnr; vector <double> newelePhi;vector <double> newscEta;
  vector <double> elePt; vector <double> eleEta; vector <double> eleEnr; vector <double> elePhi; vector <double> elescEta;
  TClonesArray *eleP4 = new TClonesArray("TLorentzVector", 1500);

  int nentries = T1->GetEntries();
  //int nentries = 10000;
  cout<<"entries: "<<nentries<<endl;
  for (unsigned int jentry=0; jentry < nentries; jentry++) {
    T1->GetEntry(jentry);

    if(jentry%1000000 == 0){
      cout << "Events Processed :  " << jentry << endl;
    }

    trigMatch_lead = false; trigMatch_slead = false;
    dR = 0.; dR1 = 0.; dR2 = 0.;
    BB=false; BE=false; EE=false;
    mediumId = 0; dzMaskId = 0; passId =0;

    newelePt.clear(); neweleEta.clear(); newelePhi.clear(); neweleEnr.clear();newscEta.clear();
    elePt.clear(); eleEta.clear(); elePhi.clear(); eleEnr.clear();elescEta.clear();
    recoElec.SetPtEtaPhiE(0.,0.,0.,0.);
    eleP4->Clear();

    primVtx = nPV;

    if(!Ele23_WPLoose) continue;

    for(int i=0;i<ptElec->size();i++){

      recoElec.SetPtEtaPhiE(ptElec->at(i),etaElec->at(i), phiElec->at(i), energyElec->at(i));
      new ((*eleP4)[i]) TLorentzVector(recoElec);
      TLorentzVector* fourmom = (TLorentzVector*) eleP4->At(i);

   //  if(fourmom->Eta() < 1.4442) *fourmom *= 0.9994;
   //   if(fourmom->Eta() > 1.566) *fourmom *= 1.0034;

      if(fourmom->Eta() < 1.4442) *fourmom *= 1.0;
      if(fourmom->Eta() > 1.566) *fourmom *= 1.0;

     //   mediumId = passHEEPId->at(i);
       mediumId = passMediumId->at(i);

       passId = mediumId;

//      if (ptElec->at(i) < 500.) { passId = mediumId; }
//     else { passId = dzMaskId; }

      if(passId) {
	if(fabs(etaSC->at(i)) < 2.5 && !(fabs(etaSC->at(i)) > 1.4442 && fabs(etaSC->at(i)) < 1.566)){

	  newelePt.push_back(fourmom->Pt());
	  neweleEta.push_back(fourmom->Eta());
	  neweleEnr.push_back(fourmom->Energy());
	  newelePhi.push_back(fourmom->Phi());
          newscEta.push_back(etaSC->at(i));
	}
      }
    }

    // Sorting
    int index[newelePt.size()];
    float pt[newelePt.size()];

    for(unsigned int el=0; el<newelePt.size(); el++)
    { 
      pt[el]=newelePt.at(el);
    }

    int size = sizeof(pt)/sizeof(pt[0]);
    TMath::Sort(size,pt,index,true);

    if(newelePt.size()==2){

      for(unsigned int j = 0; j < pt_Ele23->size(); j++){

	double dR1_comp = 1000.;
	double dR2_comp = 1000.;

	dR1 = deltaR(neweleEta.at(index[0]), newelePhi.at(index[0]), eta_Ele23->at(j), phi_Ele23->at(j));
	dR2 = deltaR(neweleEta.at(index[1]), newelePhi.at(index[1]), eta_Ele23->at(j), phi_Ele23->at(j));

	if(dR1 < 0.1){
	  if (dR1 < dR1_comp)
	  {
	    dR1_comp = dR1;
	    trigMatch_lead = true;
	  }
	} // dR1

	if(dR2 < 0.1){
	  if (dR2 < dR2_comp)
	  {
	    dR2_comp = dR2; 
	    trigMatch_slead = true; 
	  }
	} // dR2
      } // pt_Ele23

      if(trigMatch_lead || trigMatch_slead){

	if(newelePt.at(index[0]) > 30. && newelePt.at(index[1]) > 10.) {

	  ele1.SetPtEtaPhiE(newelePt.at(index[0]),neweleEta.at(index[0]),newelePhi.at(index[0]),neweleEnr.at(index[0]));
	  ele2.SetPtEtaPhiE(newelePt.at(index[1]),neweleEta.at(index[1]),newelePhi.at(index[1]),neweleEnr.at(index[1]));
	  dielectron=ele1+ele2;

	  Ele1PT  = newelePt.at(index[0]);
	  Ele2PT  = newelePt.at(index[1]);
	  Ele1Eta = neweleEta.at(index[0]);
	  Ele2Eta = neweleEta.at(index[1]);
	  Ele1Phi = newelePhi.at(index[0]);
	  Ele2Phi = newelePhi.at(index[1]);

	  ZMass = dielectron.M();
	  ZPT = dielectron.Pt();
	  ZEta = dielectron.Eta();
	  ZRapidity = dielectron.Rapidity();
	  ZPhi = dielectron.Phi();
/*
	  if(fabs(neweleEta.at(index[0])) < 1.4442 && fabs(neweleEta.at(index[1])) < 1.4442) BB = true;
	  if((fabs(neweleEta.at(index[0])) < 1.4442 && fabs(neweleEta.at(index[1])) > 1.566) || (fabs(neweleEta.at(index[0])) > 1.566 && fabs(neweleEta.at(index[1])) < 1.4442)) BE =true;
	  if(fabs(neweleEta.at(index[0])) > 1.566 && fabs(neweleEta.at(index[1])) > 1.566) EE =true;
*/

          if(fabs(newscEta.at(index[0])) < 1.4442 && fabs(newscEta.at(index[1])) < 1.4442) BB = true;
          if((fabs(newscEta.at(index[0])) < 1.4442 && fabs(newscEta.at(index[1])) > 1.566) || (fabs(newscEta.at(index[0])) > 1.566 && fabs(newscEta.at(index[1])) < 1.4442)) BE =true;
          if(fabs(newscEta.at(index[0])) > 1.566 && fabs(newscEta.at(index[1])) > 1.566) EE =true;
	  tree->Fill();

	} // pt
      } // trig matching
    } // size==2
  } // event

  file->Write();
  file->Close();
}
예제 #12
0
void MassPlotterSingleTop::singleTopAnalysis(TList* allCuts, Long64_t nevents ,TString myfileName ){

  TopUtilities topUtils ;

  int lumi = 0;

  TIter nextcut(allCuts); 
  TObject *objcut; 

  std::vector<TString> alllabels;
  while( objcut = nextcut() ){
    ExtendedCut* thecut = (ExtendedCut*)objcut ;
    alllabels.push_back( thecut->Name );
  }  
  //alllabels.push_back( "NoCut" );
  alllabels.push_back( "Trigger" );
  //alllabels.push_back( "MuonSelection" );
  //alllabels.push_back( "MuonVeto1" );
  //alllabels.push_back( "MuonVeto" );
  alllabels.push_back( "== 1#mu" );
  alllabels.push_back( "== 2-Jets" );
  alllabels.push_back( "== 1-bJet" );
  alllabels.push_back( "MT >50 GeV" );
  //alllabels.push_back( "j'-bVeto" );
  alllabels.push_back( "mtop" );
  //cout << alllabels.size() << endl;

  ExtendedObjectProperty cutflowtable("" , "cutflowtable" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  ExtendedObjectProperty cutflowtablew1("" , "cutflowtablew1" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  

  TString fileName = fOutputDir;
  if(!fileName.EndsWith("/")) fileName += "/";
  Util::MakeOutputDir(fileName);

  bool printEventIds = false;
  vector< ofstream* > EventIdFiles;
  if(printEventIds){
    for( int i = 0 ; i < alllabels.size() ; i++ ){
      ofstream* filetxt = new ofstream(fileName + "/IPM_" + myfileName  + "_step" + boost::lexical_cast<string>(i) + ".txt" );
      EventIdFiles.push_back( filetxt );
    }
  }


  ExtendedObjectProperty nJetsBeforeCut("LeptonVeto" , "nJets" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_47("OneBjet" , "nJets20_47" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_24("OneBjet" , "nJets20_24" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nbJets("Jets" , "nbJets" , "1" , 3 , 0 , 3 , "2", {});

  ExtendedObjectProperty MTBeforeCut("OneBjetNoMT" , "MT" , "1" , 30 , 0 , 300 , "2", {});

  ExtendedObjectProperty nPVBeforeCutsUnCorr("nPVBeforeCutsUnCorr" , "nPVBeforeCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVBeforeCuts("nPVBeforeCuts" , "nPVBeforeCuts" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCutsUnCorr("nPVAfterCutsUnCorr" , "nPVAfterCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCuts("nPVAfterCuts" , "nPVAfterCuts" , "1" , 100 , 0 , 100 , "2", {});

  ExtendedObjectProperty TopMass("OneBjet" , "TopMass" , "1" , 30 , 100 , 400 , "2", {});
  ExtendedObjectProperty jprimeEta("OneBjet" , "jPrimeEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimeEtaSB("SideBand" , "jPrimeEtaSB" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimePt("OneBjet" , "jPrimePt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty muPtOneB("OneBjet" , "muPt" , "1" , 20 , 20 , 120 , "2", {});
  ExtendedObjectProperty muCharge("OneBjet" , "muCharge" , "1" , 40 , -2 , 2 , "2", {});
  ExtendedObjectProperty muEtaOneB("OneBjet" , "muEta" , "1" , 10 , -2.5 , 2.5 , "2", {});
  ExtendedObjectProperty METOneBSR("OneBjet" , "MET_SR" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBSB("OneBjet" , "MET_SB" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBAll("OneBjet" , "MET_ALL" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty bPtOneB("OneBjet" , "bPt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty bEtaOneB("OneBjet" , "bEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty nonbCSV("OneBjet" , "jpCSV" , "1" , 20 , 0 , 1.0 , "2", {});

  ExtendedObjectProperty nLbjets1EJ24("1EJ24" , "nLbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ24("1EJ24" , "nTbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ24("2EJ24" , "nLbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ24("2EJ24" , "nTbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ24("3EJ24" , "nLbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ24("3EJ24" , "nTbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ24("4EJ24" , "nLbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ24("4EJ24" , "nTbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});

  ExtendedObjectProperty nLbjets1EJ47("1EJ47" , "nLbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ47("1EJ47" , "nTbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ47("2EJ47" , "nLbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ47("2EJ47" , "nTbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ47("3EJ47" , "nLbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ47("3EJ47" , "nTbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ47("4EJ47" , "nLbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ47("4EJ47" , "nTbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});

  TH1* hTopMass = new TH1D("hTopMass" , "Top Mass" , 500 , 0 , 500 );
  TH1* hTopMassEtaJ = new TH2D( "hTopMassEtaJ" , "Top Mass" , 500 , 0 , 500 , 20 , 0 , 5.0 );

  TH1* hEtajPDFScales[102];
  double ScalesPDF[102];
  double CurrentPDFWeights[102];
  for(int i=0 ; i < 102 ; i++){
    TString s(to_string(i));
    hEtajPDFScales[i] = new TH1D( TString("hEtaJp_PDF")+s , "" , 10 , 0 , 5.0 );
    ScalesPDF[i] = 0 ;
    CurrentPDFWeights[i] = 0;
  }

  TH1* hEtajWScales[9];
  double WScalesTotal[9];
  double CurrentLHEWeights[9];
  for(int i=0; i < 9; i++){
    TString s(to_string(i));
    hEtajWScales[i] = new TH1D( TString("hEtaJp_")+s , "" , 10 , 0 , 5.0 );
    WScalesTotal[i] = 0 ;
    CurrentLHEWeights[i] = 0;
  }

  std::vector<ExtendedObjectProperty*> allProps = {&cutflowtable, &cutflowtablew1 , &nJetsBeforeCut , &nbJets , &MTBeforeCut, &TopMass , &jprimeEta , &jprimeEtaSB , &jprimePt , &muPtOneB, &muCharge, &muEtaOneB , &METOneBSR ,&METOneBSB , &METOneBAll , & bPtOneB , &bEtaOneB , &nonbCSV ,&nJets20_24, &nJets20_47,&nPVAfterCuts, &nPVBeforeCuts , &nPVAfterCutsUnCorr , &nPVBeforeCutsUnCorr};

  std::vector<ExtendedObjectProperty*> JbJOptimizationProps = {&nLbjets1EJ24,&nTbjets1EJ24,&nLbjets2EJ24,&nTbjets2EJ24,&nLbjets3EJ24,&nTbjets3EJ24,&nLbjets4EJ24,&nTbjets4EJ24,&nLbjets1EJ47,&nTbjets1EJ47,&nLbjets2EJ47,&nTbjets2EJ47,&nLbjets3EJ47,&nTbjets3EJ47,&nLbjets4EJ47,&nTbjets4EJ47};
  nextcut.Reset();


  //codes for 2j0t selection
  TFile *theTreeFile = NULL;
  if(IsQCD==1)
    theTreeFile = new TFile( (fileName+ myfileName + "_Trees.root" ).Data(), "RECREATE");    

  double MT_QCD_Tree , TOPMASS_QCD_Tree , MuIso_QCD_Tree , Weight_QCD_Tree;

  TTree* theQCD_Tree = NULL;
  //end of 2j0t

  for(int ii = 0; ii < fSamples.size(); ii++){

    int data = 0;
    sample Sample = fSamples[ii];

    TEventList* list = 0;
   
    if(Sample.type == "data"){
      data = 1;
    }else
      lumi = Sample.lumi; 

    if( theTreeFile ){
      TString treename = Sample.sname ;
      if( data )
	treename = "Data";
      if( theTreeFile->Get( treename ) ){
	theQCD_Tree = (TTree*) (theTreeFile->Get( treename )) ; 
      }else{
	theTreeFile->cd();
	theQCD_Tree = new TTree( treename , treename + " tree for QCD shape/normalization studies" );
	theQCD_Tree->Branch( "MT/D" , &MT_QCD_Tree );
	theQCD_Tree->Branch( "TOPMASS/D" , &TOPMASS_QCD_Tree );
	theQCD_Tree->Branch( "MuIso/D" , &MuIso_QCD_Tree );
	theQCD_Tree->Branch( "Weight/D" , &Weight_QCD_Tree );
      }
    }


    double Weight = Sample.xsection * Sample.kfact * Sample.lumi / (Sample.nevents*Sample.PU_avg_weight);
    //Weight = 1.0;
    if(data == 1)
      Weight = 1.0;

    Sample.Print(Weight);

    SingleTopTree fTree( Sample.tree );
    Sample.tree->SetBranchStatus("*", 1);

    string lastFileName = "";

    Long64_t nentries =  Sample.tree->GetEntries();
    Long64_t maxloop = min(nentries, nevents);

    int counter = 0;
    double EventsIsPSeudoData ;
    int cutPassCounter = 0;
    for (Long64_t jentry=0; jentry<maxloop;jentry++, counter++) {
      Sample.tree->GetEntry(jentry);
      // //cout << fTree.Event_EventNumber << endl;
      // if(  !(fTree.Event_EventNumber == 11112683 || fTree.Event_EventNumber == 11112881 ) ){
      // 	//cout << " " ;
      // 	continue;
      // }
      // else{
      // 	cutPassCounter ++ ;
      // 	cout << cutPassCounter << " : " << fTree.Event_EventNumber << " : " << endl;
      // }
      EventsIsPSeudoData = PSeudoDataRandom->Uniform();

      if( lastFileName.compare( ((TChain*)Sample.tree)->GetFile()->GetName() ) != 0 ) {
	for(auto prop : allProps)
	  prop->SetTree( Sample.tree , Sample.type, Sample.sname );
	for(auto prop2 : JbJOptimizationProps ) 
	  prop2->SetTree( Sample.tree , Sample.type, Sample.sname );

	nextcut.Reset();
	while( objcut = nextcut() ){
	  ExtendedCut* thecut = (ExtendedCut*)objcut ;
	  thecut->SetTree( Sample.tree ,  Sample.name , Sample.sname , Sample.type , Sample.xsection, Sample.nevents, Sample.kfact , Sample.PU_avg_weight);
	}

	lastFileName = ((TChain*)Sample.tree)->GetFile()->GetName() ;
	cout << "new file : " << lastFileName << endl;
      }

      if ( counter == 100000 ){  
	fprintf(stdout, "\rProcessed events: %6d of %6d ", jentry + 1, nentries);
	fflush(stdout);
	counter = 0;
      }
 
      nextcut.Reset();
      double weight = Weight;

      if( !data ){
	weight *= fTree.Event_puWeight ;
      }

      if( Sample.UseLHEWeight ){
	//cout << "SIGNAL" << endl;
	weight *= fTree.Event_LHEWeightSign ;
	// if(fTree.Event_LHEWeightSign < 0.0)
	//   cout << fTree.Event_LHEWeightSign << endl;
      }

      #ifdef SingleTopTreeLHEWeights_h
      for( int i = 0 ; i < 102 ; i++ ){
	CurrentPDFWeights[i] = fTree.GetPDFWeight(i)/fabs(fTree.Event_LHEWeight) ;
	ScalesPDF[i] += CurrentPDFWeights[i] ;
      }

      if( Sample.name == "WJets" || Sample.name == "Signal" ){

	
	if(fTree.GetLHEWeight(0) != fTree.Event_LHEWeight0) cout << "Wrong GetLHEWeight(0) Value" << endl;
	if(fTree.GetLHEWeight(1) != fTree.Event_LHEWeight1) cout << "Wrong GetLHEWeight(1) Value" << endl;
	if(fTree.GetLHEWeight(2) != fTree.Event_LHEWeight2) cout << "Wrong GetLHEWeight(2) Value" << endl;
	if(fTree.GetLHEWeight(3) != fTree.Event_LHEWeight3) cout << "Wrong GetLHEWeight(3) Value" << endl;
	if(fTree.GetLHEWeight(4) != fTree.Event_LHEWeight4) cout << "Wrong GetLHEWeight(4) Value" << endl;
	if(fTree.GetLHEWeight(5) != fTree.Event_LHEWeight5) cout << "Wrong GetLHEWeight(5) Value" << endl;
	if(fTree.GetLHEWeight(6) != fTree.Event_LHEWeight6) cout << "Wrong GetLHEWeight(6) Value" << endl;
	if(fTree.GetLHEWeight(7) != fTree.Event_LHEWeight7) cout << "Wrong GetLHEWeight(7) Value" << endl;
	if(fTree.GetLHEWeight(8) != fTree.Event_LHEWeight8) cout << "Wrong GetLHEWeight(8) Value" << endl;
	
	// CurrentLHEWeights[0] = fTree.Event_LHEWeight /fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[1] = fTree.Event_LHEWeight1/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[2] = fTree.Event_LHEWeight2/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[3] = fTree.Event_LHEWeight3/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[4] = fTree.Event_LHEWeight4/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[5] = fTree.Event_LHEWeight5/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[6] = fTree.Event_LHEWeight6/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[7] = fTree.Event_LHEWeight7/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[8] = fTree.Event_LHEWeight8/fabs(fTree.Event_LHEWeight) ;
	
	for(int i = 0 ; i<9 ;i++){
	  CurrentLHEWeights[i] = fTree.GetLHEWeight(i)/fabs(fTree.Event_LHEWeight) ;
	  WScalesTotal[i] += CurrentLHEWeights[i];
	}
      }
      #endif
      
      double cutindex = 0.5;
      bool pass=true;
      while( objcut = nextcut() ){
	ExtendedCut* thecut = (ExtendedCut*)objcut ;
	pass &= thecut->Pass(jentry , weight);
	if(! pass ){
	  break;
	}else{
	  if( isfinite (weight) ){
	    cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	    cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	  }
	  else
	    cout << "non-finite weight : " << weight << endl;
	}
	cutindex+=1.0;
      }

      if(! pass)
	continue;

      int cut = 0;

      //cout << alllabels[ int(cutindex) ] << endl;
//       cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
//       cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
//       cutindex ++ ;

      // if( data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v2 > 0.5) )
      // 	continue;
      
      // if( !data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v1 > 0.5) )
      // 	continue;

      nPVBeforeCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , false , true );
      nPVBeforeCuts.Fill( fTree.Event_nPV , weight , false, true);

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl; 
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;
      
      if( data && !(fTree.Event_passesHLT_IsoMu20_v2 > 0.5 || fTree.Event_passesHLT_IsoMu20_v1 > 0.5 || fTree.Event_passesHLT_IsoMu20_v3 > 0.5)  )
	continue;
      if(!data && !(fTree.Event_passesHLT_IsoMu20_v1 > 0.5) )
	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      

      //cout << "nMuons : " << fTree.muons_size << endl;
      int tightMuIndex =-1;
      int nonTightMuIndex = -1;
      int nLooseMuos   = 0;
      int nTightMuons = 0;
      int nTightNonIsoMuons = 0;

      for( int imu=0 ; imu < fTree.muons_size ; imu++ ){
	// cout << imu << " : " << fTree.muons_Pt[imu] << "-" << fTree.muons_Eta[imu] << "-"
	//      << fTree.muons_IsTightMuon[imu] << "-" << fTree.muons_Iso04[imu] << endl;
	
	bool isTight = false;
      	if( fTree.muons_Pt[imu] > 22.0 &&
	    fabs(fTree.muons_Eta[imu]) < 2.1 &&
	    fTree.muons_IsTightMuon[imu] > 0.5 ){


	  if( fTree.muons_Iso04[imu] < 0.06 ){ 
	    isTight = true;
	    nTightMuons ++;
	    if( tightMuIndex == -1 )
	      tightMuIndex = imu;
	  }else if( fTree.muons_Iso04[imu] < 0.15 ){
	    nTightNonIsoMuons ++;
	    if( nonTightMuIndex == -1 )
	      nonTightMuIndex = imu;
	  }
	}

	if( ! isTight )
	  if( fTree.muons_Pt[ imu ] > 10.0 &&
	      fTree.muons_IsLooseMuon[ imu ] > 0.5 &&
	      fabs(fTree.muons_Eta[imu]) < 2.5 && 
	      fTree.muons_Iso04[imu] < 0.20 ){
	    nLooseMuos++;
	  }
      }      

      if(IsQCD){
	nLooseMuos = nTightMuons ;	
	nTightMuons = nTightNonIsoMuons ;
	tightMuIndex = nonTightMuIndex ;
      }


      if( nTightMuons != 1 )
	  continue;

      bool isiso = true;

      if( nLooseMuos > 0 )
      	continue;

#ifdef MUONCHARGEP
      if(fTree.muons_Charge[tightMuIndex] < 0)
	continue;
#endif
#ifdef MUONCHARGEN
      if(fTree.muons_Charge[tightMuIndex] > 0)
	continue;
#endif

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      int nLooseElectrons = 0;
      for( int iele = 0 ; iele < fTree.electrons_size;iele ++ ){
      	if( fTree.electrons_Pt[iele] > 20 &&
	    fabs(fTree.electrons_Eta[iele]) < 2.5 && 
	    ( fabs(fTree.electrons_Eta[iele]) < 1.4442 || fabs(fTree.electrons_Eta[iele]) > 1.566) &&
	    fTree.electrons_vidVeto[iele] > 0.5 )
	  nLooseElectrons++;
      }
      
      if( nLooseElectrons > 0 )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      int j1index = -1;
      int j2index = -1;
      int j3index = -1;
      int nJets = 0 ;
      int howManyBJets = 0;
      int bjIndex = -1;
      int bj2Index = -1;
      int jprimeIndex ; 

      int nJetsPt20_47 = 0;

      int nJetsPt20_24 = 0;
      int nLbJetsPt20 = 0;
      int nTbJetsPt20 = 0;

      TLorentzVector muon;
      muon.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[tightMuIndex] , fTree.muons_E[tightMuIndex] );
      if( muon.Energy() == 0.0 )
	cout << "ZERO???" <<endl;
      for( int jid = 0 ; jid < fTree.jetsAK4_size ; jid++ ){

	float NHF = fTree.jetsAK4_JetID_neutralHadronEnergyFraction[jid] ;
	float NEMF = fTree.jetsAK4_JetID_neutralEmEnergyFraction[jid] ;
	float NumConst = fTree.jetsAK4_JetID_numberOfDaughters[jid] ;
	float eta = fTree.jetsAK4_Eta[jid] ;
	float CHF = fTree.jetsAK4_JetID_chargedHadronEnergyFraction[jid] ;
	float CHM = fTree.jetsAK4_JetID_chargedMultiplicity[jid] ;
	float CEMF = fTree.jetsAK4_JetID_chargedEmEnergyFraction[jid] ;
	float NumNeutralParticle = fTree.jetsAK4_JetID_neutralMultiplicity[jid] ;


	bool looseid ;
	if(  abs(eta)<=3.0 ) {
	  looseid = (NHF<0.99 && NEMF<0.99 && NumConst>1) && ((abs(eta)<=2.4 && CHF>0 && CHM>0 && CEMF<0.99) || abs(eta)>2.4) ;
	}
	else
	  looseid = (NEMF<0.90 && NumNeutralParticle>10) ;

      	if( fTree.jetsAK4_CorrPt[jid] > 20 &&
	    fabs( fTree.jetsAK4_Eta[jid] ) < 4.7 &&
	    looseid
	    ){
	  TLorentzVector jet;
	  jet.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[jid] , fTree.jetsAK4_Eta[jid] , fTree.jetsAK4_Phi[jid] , fTree.jetsAK4_CorrE[jid] );
	  double DR = muon.DeltaR( jet );

	  if ( DR > 0.3 ){

	    if( fTree.jetsAK4_CorrPt[jid] <= 40 ){
	      nJetsPt20_47 ++ ;
	      if( fabs( fTree.jetsAK4_Eta[jid] ) < 2.4 ){
		nJetsPt20_24 ++;
		if( fTree.jetsAK4_CSV[jid] > 0.97 )
		  nTbJetsPt20++;
		else if( fTree.jetsAK4_CSV[jid] > 0.605 )
		  nLbJetsPt20++;
	      }
	      
	      continue;
	    }	    
	    nJets++;
	    if( nJets == 1 )
	      j1index = jid ;
	    else if(nJets == 2 )
	      j2index = jid ;
	    else if( nJets == 3 )
	      j3index = jid ;
	    
	    if( fTree.jetsAK4_IsCSVT[jid] == true  && fabs( fTree.jetsAK4_Eta[jid] ) <= 2.4 ){
	      howManyBJets ++;
	      if(howManyBJets==1)
		bjIndex = jid ;
	      else if(howManyBJets==2)
		bj2Index = jid ;
	    }else
	      jprimeIndex = jid ;
	  }
	}
      }
      
      nJetsBeforeCut.Fill( nJets , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      if (nJets != NUMBEROFJETS)
	continue;


      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      
      nbJets.Fill( howManyBJets , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      if( howManyBJets != NUMBEROFBJETS )
	continue;

      if( !data ){
	if( NUMBEROFBJETS == 2 )
	  weight *= fTree.Event_bWeight2CSVT ;
	else if (NUMBEROFBJETS == 1 )
	  weight *= fTree.Event_bWeight1CSVT ;
      }

      //weight = 1.0;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

     
      double MT = sqrt( 2*fTree.met_Pt* fTree.muons_Pt[tightMuIndex]*(1-TMath::Cos( Util::DeltaPhi(fTree.met_Phi , fTree.muons_Phi[tightMuIndex]) ) )  ) ;
      MTBeforeCut.Fill( MT , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      // if( fTree.met_Pt < 45 )
      // 	continue;
      if( MT < 50 && (NUMBEROFBJETS == 1 && NUMBEROFJETS == 2) && !IsQCD )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
     
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      nonbCSV.Fill( fTree.jetsAK4_CSV[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);

//       if( fTree.jetsAK4_CSV[jprimeIndex] > 0.605 )
// 	continue;

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      nJets20_47.Fill( nJetsPt20_47 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      nJets20_24.Fill( nJetsPt20_24 , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(nJetsPt20_24 < 2){
	nLbjets1EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 3){
	nLbjets2EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 4){
	nLbjets3EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 5){
	nLbjets4EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      if(nJetsPt20_47 < 2){
	nLbjets1EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 3){
	nLbjets2EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 4){
	nLbjets3EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 5){
	nLbjets4EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }


      if( NUMBEROFBJETS == 2 )
	if( fTree.jetsAK4_CSV[bj2Index] > fTree.jetsAK4_CSV[bjIndex] )
	  std::swap( bj2Index , bjIndex );

      //int jprimeIndex = (bjIndex == j1index) ? j2index : j1index ;
      TLorentzVector muLV;
      muLV.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[ tightMuIndex ] , fTree.muons_E[tightMuIndex] );
      TLorentzVector bjetLV;
      bjetLV.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[ bjIndex ] , fTree.jetsAK4_Eta[ bjIndex ] , fTree.jetsAK4_Phi[ bjIndex ] , fTree.jetsAK4_CorrE[ bjIndex ] ) ; 
      double topMass = topUtils.top4Momentum( muLV , bjetLV , fTree.met_Px , fTree.met_Py ).mass();
      TopMass.Fill( topMass , weight , EventsIsPSeudoData < fabs(weight) , isiso ); //fTree.resolvedTopSemiLep_Mass[0]

      MT_QCD_Tree = MT;
      TOPMASS_QCD_Tree = topMass ;
      MuIso_QCD_Tree = fTree.muons_Iso04[tightMuIndex];
      Weight_QCD_Tree = weight ;

      if( IsQCD )
	theQCD_Tree->Fill();



      if( (130. < topMass && topMass < 225.) || NUMBEROFBJETS == 2 ){

	nPVAfterCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , EventsIsPSeudoData < fabs(weight) , isiso );
	nPVAfterCuts.Fill( fTree.Event_nPV , weight , EventsIsPSeudoData < fabs(weight) , isiso );

#ifdef SingleTopTreeLHEWeights_h
	for(int i = 0 ; i< 102 ; i++){
	  hEtajPDFScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentPDFWeights[i] ) );
	}
	if( Sample.name == "WJets" || Sample.name == "Signal"){
	  for(int i=0;i<9;i++)
	    hEtajWScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentLHEWeights[i] ) );
	}
#endif
	
	jprimeEta.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	jprimePt.Fill( fTree.jetsAK4_CorrPt[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muPtOneB.Fill( fTree.muons_Pt[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muCharge.Fill( fTree.muons_Charge[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muEtaOneB.Fill( fabs(fTree.muons_Eta[tightMuIndex]) , weight , EventsIsPSeudoData < fabs(weight), isiso );
	METOneBSR.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	bPtOneB.Fill( fTree.jetsAK4_CorrPt[bjIndex] , weight , EventsIsPSeudoData < fabs(weight), isiso );
	bEtaOneB.Fill(fabs( fTree.jetsAK4_Eta[bjIndex] ) , weight , EventsIsPSeudoData < fabs(weight), isiso );

	if( printEventIds )
	  (*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
	cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	cutindex++;
      }else{
	jprimeEtaSB.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso );
	METOneBSB.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      METOneBAll.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(Sample.name == "Signal" )
	hTopMass->Fill( topMass , weight );
      if(Sample.name == "WJets")
	hTopMassEtaJ->Fill( topMass ,fabs( fTree.jetsAK4_Eta[jprimeIndex] )  );
    }
    theQCD_Tree->Write();
    
  }

  theTreeFile->Close();
      

  // TString fileName = fOutputDir;
  // if(!fileName.EndsWith("/")) fileName += "/";
  // Util::MakeOutputDir(fileName);
  fileName += myfileName + ".root" ;

  TFile *theFile = new TFile(fileName.Data(), "RECREATE");

  nonbCSV.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nonbCSV.CalcSig( 0 , 4 , -1 , 0.1); 
  nonbCSV.CalcSig( 0 , 2 , -1 , 0 ) ; 

  nJets20_24.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_24.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_24.CalcSig( 0 , 2 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_47.CalcSig( 0 , 2 , -1 , 0 ) ; 

  muCharge.CalcSig( 0 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 0 , 2 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 1 , 2 , -1 , 0 ) ; 

  for(auto prop : allProps)
    prop->Write( theFile , 1000  );

#ifdef SingleTopTreeLHEWeights_h
  TDirectory* dirWScales = theFile->mkdir("WJScales");
  dirWScales->cd();
  for(int i=0;i<9;i++){
    cout << "WScalesTotal[i]" << WScalesTotal[i] << "," << WScalesTotal[0]/WScalesTotal[i] << endl;
    hEtajWScales[i]->Scale( WScalesTotal[0]/WScalesTotal[i] );
    hEtajWScales[i]->Write();
  }

  TDirectory* dirPDFScales = theFile->mkdir("PDFScales");
  dirPDFScales->cd();
  for(int i=0;i<102;i++){
    cout << "PDFScales[i]" << ScalesPDF[i] << "," << WScalesTotal[0]/ScalesPDF[i] << endl;
    hEtajPDFScales[i]->Scale( WScalesTotal[0]/ScalesPDF[i] );
    hEtajPDFScales[i]->Write();
  }
#endif

  TDirectory* dir2 = theFile->mkdir("JbJOptimizationProps");
  dir2->cd();

  for(auto prop2 : JbJOptimizationProps){
    prop2->CalcSig( 0 , 0 , -1 , 0 ) ; 
    prop2->CalcSig( 0 , 4 , -1 , 0.1 ) ; 
    prop2->CalcSig( 0 , 2 , -1 , 0 ) ; 
    prop2->Write( dir2 , 1000  );
  }

  theFile->cd();
  hTopMass->Write();
  hTopMassEtaJ->Write();
  //cutflowtable.Print("cutflowtable");
  theFile->Close();
  if( printEventIds )
    for( auto a : EventIdFiles ){
      a->close();
    }
}
예제 #13
0
void TagAndProbeAnalysis::Loop()
{
  if (fChain == 0) return;

  readR9Weights();
  
  // output file
  TFile *outFile[5];
  outFile[0] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+".root","RECREATE");
  outFile[1] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"30.root","RECREATE");
  outFile[2] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"50.root","RECREATE");
  outFile[3] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"75.root","RECREATE");
  outFile[4] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"90.root","RECREATE");

  // output trees declaration
  TTree *myTree[5];
  for (int ii=0; ii<5; ii++) {
    outFile[ii]->cd();
    TDirectory* outputDirectory = outFile[ii]->mkdir("myTaPDir");
    outputDirectory->cd();
    myTree[ii] = new TTree();
    myTree[ii] -> SetName("myTree");
  }

  float mass;
  float probe_eta, probe_abseta, probe_phi, probe_pt, probe_r9;
  int numvtx;
  float rho;
  float r9weight_EB;
  float r9weight_EE;
  float puW;
  float puW30, puW50, puW75, puW90;  
  int okLooseElePtEta,  okLooseEleID;
  int okMediumElePtEta, okMediumEleID; 
  int okTightElePtEta,  okTightEleID; 
  int okMVA_005, okMVA_01, okMVA_02;
  int hasPromptElectronMatched;
  

  for (int ii=0; ii<5; ii++) {
    myTree[ii] -> Branch("mass",&mass,"mass/F");
    myTree[ii] -> Branch("probe_eta",&probe_eta,"probe_eta/F");
    myTree[ii] -> Branch("probe_abseta",&probe_abseta,"probe_abseta/F");
    myTree[ii] -> Branch("probe_phi",&probe_phi,"probe_phi/F");
    myTree[ii] -> Branch("probe_pt",&probe_pt,"probe_pt/F");
    myTree[ii] -> Branch("probe_r9",&probe_r9,"probe_r9/F");
    myTree[ii] -> Branch("numvtx",&numvtx,"numvtx/I");
    myTree[ii] -> Branch("rho",&rho,"rho/F");
    myTree[ii] -> Branch("puW",  &puW,  "puW/F");
    myTree[ii] -> Branch("r9WeightEB",  &r9weight_EB,  "r9WeightEB/F");
    myTree[ii] -> Branch("r9WeightEE",  &r9weight_EE,  "r9WeightEE/F");
    myTree[ii] -> Branch("puW30",&puW30,"puW30/F");
    myTree[ii] -> Branch("puW50",&puW50,"puW50/F");
    myTree[ii] -> Branch("puW75",&puW75,"puW75/F");
    myTree[ii] -> Branch("puW90",&puW90,"puW90/F");
    myTree[ii] -> Branch("okLooseElePtEta",&okLooseElePtEta,"okLooseElePtEta/I");
    myTree[ii] -> Branch("okLooseEleID",&okLooseEleID,"okLooseEleID/I");
    myTree[ii] -> Branch("okMediumElePtEta",&okMediumElePtEta,"okMediumElePtEta/I");
    myTree[ii] -> Branch("okMediumEleID",&okMediumEleID,"okMediumEleID/I");
    myTree[ii] -> Branch("okTightElePtEta",&okTightElePtEta,"okTightElePtEta/I");
    myTree[ii] -> Branch("okTightEleID",&okTightEleID,"okTightEleID/I");
    myTree[ii] -> Branch("okMVA_005",&okMVA_005,"okMVA_005/I");
    myTree[ii] -> Branch("okMVA_01",&okMVA_01,"okMVA_01/I");
    myTree[ii] -> Branch("okMVA_02",&okMVA_02,"okMVA_02/I");
    myTree[ii] -> Branch("hasPromptElectronMatched",&hasPromptElectronMatched,"hasPromptElectronMatched/I");
  }

  // Loop over events
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;

  cout << "Going to loop over " << nentries << " events" << endl;
  cout << endl;
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    Long64_t ientry = LoadTree(jentry);

    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    if (jentry%5000==0) cout << "Read entry " << jentry << endl;

    for (int iEle=0; iEle<nEle; iEle++) {
      if (isMC && mcMatch)
	if (!isGenMatchEle[iEle])
	  continue;

      if (tagTightnessLevel=="Tight")
	{
	  if (!isTagTightEle[iEle])
	    continue;
	}
      else if (tagTightnessLevel=="Medium")
	{
	  if (!isTagMediumEle[iEle])
	    continue;
	}
      else if (tagTightnessLevel=="Loose")
	{
	  if (!isTagLooseEle[iEle])
	    continue;
	}
      else
	{
	  std::cout << "Tag Selection undefined" << std::endl;
	  exit(-1);
	}

      TLorentzVector theEle;
      //      theEle.SetPtEtaPhiE(electron_pt[iEle], electron_eta[iEle], electron_phi[iEle], electron_energy[iEle]);
      theEle.SetPtEtaPhiM(electron_pt[iEle], electron_eta[iEle], electron_phi[iEle], 0.);

      for (int iPho=0; iPho<nPhot; iPho++) {
	if (isMC && mcMatch)
	  if (!isGenMatchPhot[iPho])
	    continue;

	//apply preselection as probe selection for photons (should be loosened to measure preselection SF)
	if (!isProbePreselPhot[iPho])
	  continue;

	TLorentzVector thePho;
	thePho.SetPtEtaPhiE(ptPhot[iPho], etaPhot[iPho], phiPhot[iPho], ePhot[iPho]);
      
	TLorentzVector theTaP = theEle + thePho;
	float theMass = theTaP.M();
      
	if (fabs(theMass-91.181)>DeltaMZ)
	  continue;

	// filling the tree
	mass = theMass;
	
	probe_eta    = etascPhot[iPho];
	probe_abseta = fabs(etascPhot[iPho]);
	probe_phi    = phiPhot[iPho];
	probe_pt     = ptPhot[iPho];
	probe_r9     = r9Phot[iPho];
	
	numvtx = nvtx;
	rho=rhoAllJets;

	if(isMC) {
	  puW   = pu_weight;
	  puW30 = pu_weight30;
	  puW50 = pu_weight50;
	  puW75 = pu_weight75;
	  puW90 = pu_weight90;
	} else {
	  puW   = 1.;
	  puW30 = 1.;
	  puW50 = 1.;
	  puW75 = 1.;
	  puW90 = 1.;
	}
	

	if (r9Reweight)
	  {
	    r9weight_EB=r9weights_EB->GetBinContent(r9weights_EB->FindBin(r9Phot[iPho]));
	    r9weight_EE=r9weights_EE->GetBinContent(r9weights_EE->FindBin(r9Phot[iPho]));
	  }
	else
	  {
	    r9weight_EB=1.;
	    r9weight_EE=1.;
	  }


	okLooseElePtEta  = 1;
	okLooseEleID     = isProbeLoosePhot[iPho];
	okMediumElePtEta = 1;
	okMediumEleID    = isProbeMediumPhot[iPho];
	okTightElePtEta  = 1;
	okTightEleID     = isProbeTightPhot[iPho];

	hasPromptElectronMatched = hasMatchedPromptElePhot[iPho];

	// MVA WPs
	okMVA_005 = 0;
	okMVA_01  = 0;
	okMVA_02  = 0;
	if (isEBPhot[iPho]) {
	  if ( mvaIDPhot[iPho]>0.711099 ) okMVA_005 = 1;
	  if ( mvaIDPhot[iPho]>0.812948 ) okMVA_01  = 1;
	  if ( mvaIDPhot[iPho]>0.878893 ) okMVA_02  = 1;
	} else {
	  if ( mvaIDPhot[iPho]>0.581733 ) okMVA_005 = 1;
	  if ( mvaIDPhot[iPho]>0.73721  ) okMVA_01  = 1;
	  if ( mvaIDPhot[iPho]>0.850808 ) okMVA_02  = 1;
	}
	
	// check HLT and pT range
	if (!isMC) {
	  if ( isHLT_TandP() )                                           myTree[0]->Fill();
	  if ( isHLT_30() && ptPhot[iPho]>=40 && ptPhot[iPho]<65 )       myTree[1]->Fill();
	  if ( isHLT_50() && ptPhot[iPho]>=65 && ptPhot[iPho]<90 )       myTree[2]->Fill();
	  if ( isHLT_75() && ptPhot[iPho]>=90 && ptPhot[iPho]<105 )      myTree[3]->Fill();
	  if ( isHLT_90() && ptPhot[iPho]>=105 && ptPhot[iPho]<200000 )  myTree[4]->Fill();
	}
	if (isMC) {
	  myTree[0]->Fill();
	  if ( ptPhot[iPho]>=40 && ptPhot[iPho]<65 )       myTree[1]->Fill();
	  if ( ptPhot[iPho]>=65 && ptPhot[iPho]<90 )       myTree[2]->Fill();
	  if ( ptPhot[iPho]>=90 && ptPhot[iPho]<105 )      myTree[3]->Fill();
	  if ( ptPhot[iPho]>=105 && ptPhot[iPho]<200000 )  myTree[4]->Fill();
	}
	
      
      } // loop over photons
    }   // loop over electrons
  }

  for (int ii=0; ii<5; ii++) {
    outFile[ii]->cd("myTaPDir");
    myTree[ii]->Write();
    outFile[ii]->Close();
  }
}
예제 #14
0
void MakeHist(TString infilename = "Graviton_genlevel_3000.root")
{
	TChain * chain = new TChain("demo/ExTree");
	chain->Add(infilename);


	vector<const reco::Candidate *> *phig;
	vector<const reco::Candidate *> *pmu;
	vector<const reco::Candidate *> *pele;
	vector<const reco::Candidate *> *pjet;
	vector<const reco::Candidate *> *pnu;
	vector<const reco::Candidate *> *pwplus;
	vector<const reco::Candidate *> *pwminus;
	chain-> SetBranchAddress("phig", &phig);
	chain-> SetBranchAddress("pmu", &pmu);
	chain-> SetBranchAddress("pele", &pele);
	chain-> SetBranchAddress("pjet", &pjet);
	chain-> SetBranchAddress("pnu", &pnu);
	chain-> SetBranchAddress("pwplus", &pwplus);
	chain-> SetBranchAddress("pwminus", &pwminus);

	//---------------------------------get  hist-----------------------------------------------
	//const float normal = 1000;// number of entries normalize to 1000

	//eta bin
	float inix= -2.5;
	float finx= 2.5;
	float nbinx= 20.0; 
	//pt bin
	float iniy= 0.0;
	float finy= 100.0;
	float nbiny= 20.0; 


	TH2F *h1= new TH2F("h1","h1",nbinx,inix,finx,nbiny,iniy,finy);
	h1->Sumw2();


	int nbins_lvjj      = 300;
	int masswindow_low  = 200;
	int masswindow_high = 4000;

	//histograms for differeny methods
	TH1F * hlvjj0 = new TH1F ("hlvjj0","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj1 = new TH1F ("hlvjj1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj2 = new TH1F ("hlvjj2","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj2_1 = new TH1F ("hlvjj2_1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj3 = new TH1F ("hlvjj3","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj4 = new TH1F ("hlvjj4","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5 = new TH1F ("hlvjj5","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5_1 = new TH1F ("hlvjj5_1","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj5_2 = new TH1F ("hlvjj5_2","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);
	TH1F * hlvjj6 = new TH1F ("hlvjj6","hlvjj",nbins_lvjj,masswindow_low,masswindow_high);

	TH2F * h2= new TH2F("h2","h2",100,0,200,100,0,200); // for wlv and wjj
	TH2F * h3= new TH2F("h3","h3",5,0,200,5,0,200); // for percentage

	TH2F * hjjpt = new TH2F("hjjpt","hjjpt",10,0,1000,10,0,1000);
	TH2F * hlvpt = new TH2F("hlvpt","hlvpt",10,0,1000,10,0,1000);

	TH1F * hwlv = new TH1F("hwlv","hwlv",100,0,200);

	TH1F * hleppz_all = new TH1F("hleppz_all","hleppz_all",100,0,80);
	TH1F * hleppz_low = new TH1F("hleppz_low","hleppz_low",100,0,80);

	TH2F * hlvpz = new TH2F("hlvpz","hlvpz",10,0,1000,10,0,1000);

	double xbins[4] = {0,65,95,200};
	double ybins[4] = {0,65,95,200};
	h3->GetXaxis()->Set(3,xbins);
	h3->GetYaxis()->Set(3,ybins);


	//comparison hists
	TH1F * pz_comparison1 = new TH1F("pz_comparison1","pz_comparison",200,-1,1);
	TH1F * pz_comparison2 = new TH1F("pz_comparison2","pz_comparison",200,-1,1);
	TH1F * pz_comparison2_1 = new TH1F("pz_comparison2_1","pz_comparison",200,-1,1);
	TH1F * pz_comparison3 = new TH1F("pz_comparison3","pz_comparison",200,-1,1);
	TH1F * pz_comparison4 = new TH1F("pz_comparison4","pz_comparison",200,-1,1);
	TH1F * pz_comparison5 = new TH1F("pz_comparison5","pz_comparison",200,-1,1);
	TH1F * pz_comparison5_2 = new TH1F("pz_comparison5_2","pz_comparison",200,-1,1);
	TH1F * pz_comparison5_1 = new TH1F("pz_comparison5_1","pz_comparison",200,-1,1);
	TH1F * pz_comparison6 = new TH1F("pz_comparison6","pz_comparison",200,-1,1);
	TH1F * lvjj_comparison1 = new TH1F("lvjj_comparison1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison2 = new TH1F("lvjj_comparison2","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison2_1 = new TH1F("lvjj_comparison2_1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison3 = new TH1F("lvjj_comparison3","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison4 = new TH1F("lvjj_comparison4","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5 = new TH1F("lvjj_comparison5","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5_1 = new TH1F("lvjj_comparison5_1","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison5_2 = new TH1F("lvjj_comparison5_2","lvjj_comparison",200,-1,1);
	TH1F * lvjj_comparison6 = new TH1F("lvjj_comparison6","lvjj_comparison",200,-1,1); 

	TCanvas * c1 = new TCanvas();	

	TLorentzVector lep;
	TLorentzVector jet1;
	TLorentzVector jet2;
	TLorentzVector neu;
	TLorentzVector temp;

	double mlvjj;
	double lvjjmass_true;
	cout<<chain->GetEntries()<<endl;
	for(int i=0; i<chain->GetEntries(); i++)
	{
		//if(i>5000)break;//for test
		if(i%5000==0)cout<<"Processing the events: "<<i<<endl;
		chain->GetEntry(i);
		//higgs 2D
		//h1->Fill(phig->at(0)->eta(),phig->at(0)->pt(),normal/(float)chain->GetEntries());

		//------------------------------neutrino pz
		if(!pmu->empty())lep.SetPtEtaPhiE(pmu->at(0)->pt(), pmu->at(0)->eta(),pmu->at(0)->phi(),pmu->at(0)->energy());
		else if(!pele->empty())lep.SetPtEtaPhiE(pele->at(0)->pt(), pele->at(0)->eta(),pele->at(0)->phi(),pele->at(0)->energy());
		else {
				cout<<"skip event: "<<i<<"  no lepton here"<<endl;
				//cout<<phig->size()<<endl;
				continue;
			}
		if(pjet->size()!=2)
		{
			cout<<"skip event: "<<i<<" jet sise != 2 "<<endl;
			continue;
		}
		jet1.SetPtEtaPhiE(pjet->at(0)->pt(), pjet->at(0)->eta(),pjet->at(0)->phi(),pjet->at(0)->energy());
		jet2.SetPtEtaPhiE(pjet->at(1)->pt(), pjet->at(1)->eta(),pjet->at(1)->phi(),pjet->at(1)->energy());
		if(jet1.Pt()<jet2.Pt())
		{
			temp=jet1;
			jet1=jet2;
			jet2=temp;
		}
		neu.SetPxPyPzE(pnu->at(0)->px(), pnu->at(0)->py(),pnu->at(0)->pz(),pnu->at(0)->energy());//real neutrino
		double px = pnu->at(0)->px();
		double py = pnu->at(0)->py();
		double pz=0;


		// ------------------------------- make cuts----------------------------
		//mt
		//double mt = sqrt(2. * lep.Pt() * neu.Pt() * ( 1 - cos(deltaPhi(lep.Phi(), neu.Phi()) ) ) );
		//if(mt>20)continue;

		//lepton pt,eta
		if(lep.Pt()<50)continue;
		//if(!pmu->empty()&&pmu->at(0)->pt()<24)continue;
		//if(!pele->empty()&&pele->at(0)->pt()<27)continue;
		//if(lep.Eta()>2.5)continue;

		//jet pt,eta
		if(jet1.Pt()<50)continue;
		//if(jet1.Eta()>2.4)continue;
		if(jet2.Pt()<50)continue;
		//if(jet2.Eta()>2.4)continue;

		//met or neutrino pt
		//double met = sqrt(px*px+py*py);
		if(neu.Pt()<50)continue;

		//mjj
		//double mjj = (jet1+jet2).M();
		//if(mjj>95||mjj<65)continue; //wjj on
		//if(mjj<95&&mjj>65)continue;   //wjj off


		// 0---------direct method
		pz = pnu->at(0)->pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj0->Fill(mlvjj);
		lvjjmass_true = mlvjj;

/*
		// 1----------nu pz = 0
		pz = 0;
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj1->Fill(mlvjj);
        pz_comparison1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		// 2----------nu pz = lep pz
		pz=lep.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2->Fill(mlvjj);
        pz_comparison2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		//--check pz
		//hleppz_all->Fill(pz);
		//if(mlvjj>130)continue;
		//hleppz_low->Fill(pz);

		//2_1 ---------nu pz =lep pz -x 
		pz=lep.Pz();
		int pz_correct=20;
		if(pz>pz_correct)pz=pz-pz_correct;
		if(pz<-pz_correct)pz=pz+pz_correct;
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2_1->Fill(mlvjj);
        pz_comparison2_1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2_1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



		// 3----------nu pz = far jet pz----------------use theta to choose
		double angle1 = lep.Vect().Angle(jet1.Vect());
		double angle2 = lep.Vect().Angle(jet2.Vect());
		if(angle1>angle2)pz=jet1.Pz();
		else pz = jet2.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj3->Fill(mlvjj);
        pz_comparison3->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison3->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



		//4 ---------nu pz = far jet pz--------------------use DetaR to choose
		double dR1 = deltaR(lep.Eta(),lep.Phi(),jet1.Eta(),jet1.Phi());
		double dR2 = deltaR(lep.Eta(),lep.Phi(),jet2.Eta(),jet2.Phi());
		if(dR1>dR2)pz=jet1.Pz();
		else pz = jet2.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj4->Fill(mlvjj);
        pz_comparison4->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison4->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

*/
		// 5 ---------------------slove the function ------------milano

		float alpha = lep.Px()*pnu->at(0)->px() + lep.Py()*pnu->at(0)->py();

		float delta = (alpha + 0.5*80.399*80.399)*(alpha + 0.5*80.399*80.399) - lep.Pt()*lep.Pt()*pnu->at(0)->pt()*pnu->at(0)->pt();
		if( delta < 0. ) {
			delta = 0.;
		}
			//double wlv = (lep+neu).M();
			//hwlv->Fill(wlv);
			//cout<<"event with imaginary roots :"<<i<<" mwlv is  "<<wlv<<endl;
		
		//else continue;//use only imaginary root

		float pz1 = ( lep.Pz()*(alpha + 0.5*80.399*80.399) + lep.Energy()*sqrt(delta) ) / lep.Pt() / lep.Pt();
		float pz2 = ( lep.Pz()*(alpha + 0.5*80.399*80.399) - lep.Energy()*sqrt(delta) ) / lep.Pt() / lep.Pt();

		if( delta >= 0. )//choose the larger pz
		{
			if(fabs(pz1)<fabs(pz2))pz=pz2;
			else pz=pz1;   
		}
		//else continue;//discard unreal pz
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5->Fill(mlvjj);
        pz_comparison5->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison5->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);


		//4 choose the smaller pz
		if( delta >= 0. )
        {   
            if(fabs(pz1)>fabs(pz2))pz=pz2;
            else pz=pz1;   
        }
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj4->Fill(mlvjj);
        pz_comparison4->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison4->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

		//3 choose the one closest to lep pz
		
		if(fabs(pz1-lep.Pz())>fabs(pz2-lep.Pz()))pz=pz2;
		else pz=pz1;
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj3->Fill(mlvjj);
        pz_comparison3->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison3->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);


		//2  feimilab ---- choose the one closest to lep pz, when it is over 300, choose the central one
		if(pz>300)
		{
			if(fabs(pz1)>fabs(pz2))pz=pz2;
			else pz=pz1;
		}
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj2->Fill(mlvjj);
        pz_comparison2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);



/*		
		// 5_1 ---------------- Sara---if you have real roots, take the solutions where neutrino and charged lepton are the closest in DR.
		if( delta >= 0. )	
		{
			pz=pz1;
			temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
			//cout<<temp.Phi()<<" "<<neu.Phi()<<endl;
			double dR1 = deltaR(lep.Eta(),lep.Phi(),temp.Eta(),temp.Phi());
			pz=pz2;
			temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
			double dR2 = deltaR(lep.Eta(),lep.Phi(),temp.Eta(),temp.Phi());
			if(dR1>dR2)pz=pz2;
			else pz=pz1;
		}
		//else continue;//discard unreal pz
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5_1->Fill(mlvjj);
		pz_comparison5_1->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
		lvjj_comparison5_1->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);
*/

		//5_2 -------------------- another method to select right real root
			//use also delta = 0 in real root case
			//use +delta root
		pz=pz1;		
        temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
        mlvjj = (lep + jet1 + jet2 + temp).M();
        if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj5_2->Fill(mlvjj);
        pz_comparison5_2->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison5_2->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);
		
/*
		// 6 --------------------- Fracesco----boost case lepton and neutrino are like parallel
		pz = neu.Pt()/lep.Pt()*lep.Pz();
		temp.SetPxPyPzE(px,py,pz,sqrt(px*px+py*py+pz*pz));
		mlvjj = (lep + jet1 + jet2 + temp).M();
		if (mlvjj>masswindow_low&&mlvjj<masswindow_high)hlvjj6->Fill(mlvjj);
        pz_comparison6->Fill((pz-pnu->at(0)->pz())/pnu->at(0)->pz());
        lvjj_comparison6->Fill((mlvjj-lvjjmass_true)/lvjjmass_true);

*/


		//------------------------------2D plots of Wjj and Wlv mass----------------------------------------
		//double wlv = (lep+neu).M();
		//double wjj = (jet1+jet2).M();

		//hwlv->Fill(wlv);

		//h2-> Fill(wlv,wjj);
		//h3-> Fill(wlv,wjj,1.0/(float)chain->GetEntries());
		//h3-> Fill(wlv,wjj);

		//hjjpt->Fill(jet1.Pt(),jet2.Pt());
		//hlvpt->Fill(lep.Pt(),neu.Pt());
		//hlvpz->Fill(abs(lep.Pz()),abs(neu.Pz()));

	}

/*
	h2-> GetXaxis()->SetTitle("wlv");
	h2-> GetYaxis()->SetTitle("wjj");

	h3-> GetXaxis()->SetTitle("wlv");
	h3-> GetYaxis()->SetTitle("wjj");
	h3->Draw("COLZ");
	h3->Draw("TEXTEsame");
	h3->SetStats(0);
	c1->Print("percent.png","png");
	//h1->Draw("SURF1");


	hjjpt-> GetXaxis()->SetTitle("leading jet pt");
	hjjpt-> GetYaxis()->SetTitle("jet2 pt");
	hlvpt-> GetXaxis()->SetTitle("lepton pt");
	hlvpt-> GetYaxis()->SetTitle("neotrino pt");
	hjjpt->Draw("COLZ");
	hjjpt->Draw("TEXTEsame");
	c1->Print("jjpt.png","png");
	hlvpt->Draw("COLZ");
	hlvpt->Draw("TEXTEsame");
	c1->Print("lvpt.png","png");


	hlvpz-> GetXaxis()->SetTitle("lepton pz");
	hlvpz-> GetYaxis()->SetTitle("neotrino pz");
	hlvpz->Draw("COLZ");
	hlvpz->Draw("TEXTEsame");
	c1->Print("lvpz.png","png");

*/

	hlvjj0->Draw();
	hlvjj0->SetTitle("lvjj_original");
	c1->Print("lvjj_original.png","png");

/*
	hlvjj1->Draw();
	hlvjj1->SetTitle("lvjj_pz0");
	c1->Print("lvjj_pz0.png","png");
*/
	hlvjj2->Draw();
	hlvjj2->SetTitle("lvjj_fermilab");
	c1->Print("lvjj_fermilab.png","png");

//	hlvjj2_1->Draw();
//	hlvjj2_1->SetTitle("lvjj_leptonpz_improve");
//	c1->Print("lvjj_leptonpz_improve.png","png");

	hlvjj3->Draw();
	hlvjj3->SetTitle("lvjj_close_to_lep_pz");
	c1->Print("lvjj_close_to_lep_pz.png","png");

	hlvjj4->Draw();
	//hlvjj4->SetTitle("lvjj_jetpz_DeltaR");
	//c1->Print("lvjj_jetpz_DeltaR.png","png");
	hlvjj4->SetTitle("lvjj_function_smaller");
	c1->Print("lvjj_function_smaller.png","png");

	hlvjj5->Draw();
	hlvjj5->SetTitle("lvjj_function_larger");
	c1->Print("lvjj_function_larger.png","png");

	hlvjj5_1->Draw();
	hlvjj5_1->SetTitle("lvjj_function_sara");
	c1->Print("lvjj_function_sara.png","png");

    hlvjj5_2->Draw();
    hlvjj5_2->SetTitle("lvjj_function_pz1");
    c1->Print("lvjj_function_pz1.png","png");


	hlvjj6->Draw();
	hlvjj6->SetTitle("lvjj_Francesco");
	c1->Print("lvjj_Francesco.png","png");

	//hwlv->Draw();
	//hwlv->SetTitle("hwlv");
	//c1->Print("hwlv.png","png");

	//hleppz_all->Draw();
	//c1->Print("hleppz_all.png","png");
	//hleppz_low->Draw();
	//c1->Print("hleppz_low.png","png");


	TLegend *leg = new TLegend(0.65, 0.5, 1, 1, NULL, "brNDC");
	/*
	leg->AddEntry (pz_comparison1,"neu pz = 0","l") ;
*/
	leg->AddEntry (pz_comparison2,"neu pz = fermilab","l") ;
//	leg->AddEntry (pz_comparison2_1,"neu pz = lep pz - 20","l") ;
	leg->AddEntry (pz_comparison3,"neu pz = close to lep pz","l") ;
	//leg->AddEntry (pz_comparison4,"neu pz = dltaR far jet pz","l") ;

	leg->AddEntry (pz_comparison4,"neu pz = slove function smaller","l");
	leg->AddEntry (pz_comparison5,"neu pz = slove function larger","l") ;
	//leg->AddEntry (pz_comparison5_1,"neu pz = slove function sara","l") ;
	leg->AddEntry (pz_comparison5_2,"neu pz = slove function +delta","l") ;
	//leg->AddEntry (pz_comparison6,"neu pz = Francesco","l") ;

/*
	pz_comparison1->SetLineColor(kYellow+3);
	pz_comparison1->Draw();
*/
    pz_comparison2->SetLineColor(kOrange+7);
    pz_comparison2->Draw();
//    pz_comparison2_1->SetLineColor(kGrey;
//    pz_comparison2_1->Draw("same");

    pz_comparison3->SetLineColor(kYellow-2);
    pz_comparison3->Draw("same");

    pz_comparison4->SetLineColor(kMagenta+1);
    pz_comparison4->Draw("same");
    pz_comparison5->SetLineColor(kBlue);
    pz_comparison5->Draw("same");
	pz_comparison5_1->SetLineColor(kSpring-7);
	pz_comparison5_1->Draw("same");
	pz_comparison5_2->SetLineColor(kAzure+10);
	pz_comparison5_2->Draw("same");
    pz_comparison6->SetLineColor(kRed);
    pz_comparison6->Draw("same");
	leg->Draw();
	c1->Print("pz_comparison.png","png");

/*
    lvjj_comparison1->SetLineColor(kYellow+3);
    lvjj_comparison1->Draw();
*/
    lvjj_comparison2->SetLineColor(kOrange+7);
    lvjj_comparison2->Draw();
//    lvjj_comparison2_1->SetLineColor(kGrey);
//    lvjj_comparison2_1->Draw("same");
    lvjj_comparison3->SetLineColor(kYellow-2);
    lvjj_comparison3->Draw("same");

    lvjj_comparison4->SetLineColor(kMagenta+1);
    lvjj_comparison4->Draw("same");
    lvjj_comparison5->SetLineColor(kBlue);
    lvjj_comparison5->Draw("same");
	lvjj_comparison5_1->SetLineColor(kSpring-7);
	lvjj_comparison5_1->Draw("same");
    lvjj_comparison5_2->SetLineColor(kAzure+10);
    lvjj_comparison5_2->Draw("same");
    lvjj_comparison6->SetLineColor(kRed);
    lvjj_comparison6->Draw("same");
	leg->Draw();
    c1->Print("lvjj_comparison.png","png");

	leg->AddEntry (hlvjj0,"neu pz = true","l") ;

	hlvjj0->SetLineColor(kBlack);
	hlvjj0->SetTitle("hlvjj_allin");
	hlvjj0->Draw();
    /*
	hlvjj1->SetLineColor(kYellow+3);
    hlvjj1->Draw("same");
*/
    hlvjj2->SetLineColor(kOrange+7);
    hlvjj2->Draw("same");
//    hlvjj2_1->SetLineColor(kGrey);
//    hlvjj2_1->Draw("same");
    hlvjj3->SetLineColor(kYellow-2);
    hlvjj3->Draw("same");

    hlvjj4->SetLineColor(kMagenta+1);
    hlvjj4->Draw("same");
	hlvjj5->SetLineColor(kBlue);
    hlvjj5->Draw("same");
	hlvjj5_1->SetLineColor(kSpring-7);
	hlvjj5_1->Draw("same");
    hlvjj5_2->SetLineColor(kAzure+10);
    hlvjj5_2->Draw("same");
    hlvjj6->SetLineColor(kRed);
    hlvjj6->Draw("same");
	leg->Draw();
    c1->Print("hlvjj_allin.png","png");



}
void Ntp1Finalizer_ComputeQGLikelihood::finalize() {

  if( outFile_==0 ) this->createOutputFile();



  const int nBins = 18;
  Double_t ptBins[nBins+1];
  fitTools::getBins_int( nBins, ptBins, 20., 1000. );
  ptBins[nBins] = 3500.;


  std::vector<TH1D*> vh1_QGLikelihood_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_quark;

  std::vector<TH1D*> vh1_QGLikelihood_norms_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_norms_quark;

  std::vector<TH1D*> vh1_QGLikelihood_noptD_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_noptD_quark;

  std::vector<TH1D*> vh1_QGLikelihood_norms_noptD_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_norms_noptD_quark;

  std::vector<TH1D*> vh1_QGLikelihood_onlyNch_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_onlyNch_quark;

  std::vector<TH1D*> vh1_rmsCand_cutOnQGLikelihood_norms_gluon;
  std::vector<TH1D*> vh1_rmsCand_cutOnQGLikelihood_norms_quark;

  std::vector<TH1D*> vh1_QGLikelihood_eta35_gluon;
  std::vector<TH1D*> vh1_QGLikelihood_eta35_quark;


  for( unsigned iBin=0; iBin<nBins; iBin++ ) {

    float ptMin = ptBins[iBin];
    float ptMax = ptBins[iBin+1];

    char histoname[500];
    
    sprintf( histoname, "QGLikelihood_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_gluon_new->Sumw2();
    vh1_QGLikelihood_gluon.push_back(h1_QGLikelihood_gluon_new);

    sprintf( histoname, "QGLikelihood_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_quark_new->Sumw2();
    vh1_QGLikelihood_quark.push_back(h1_QGLikelihood_quark_new);


    sprintf( histoname, "QGLikelihood_norms_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_norms_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_norms_gluon_new->Sumw2();
    vh1_QGLikelihood_norms_gluon.push_back(h1_QGLikelihood_norms_gluon_new);

    sprintf( histoname, "QGLikelihood_norms_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_norms_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_norms_quark_new->Sumw2();
    vh1_QGLikelihood_norms_quark.push_back(h1_QGLikelihood_norms_quark_new);


    sprintf( histoname, "QGLikelihood_noptD_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_noptD_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_noptD_gluon_new->Sumw2();
    vh1_QGLikelihood_noptD_gluon.push_back(h1_QGLikelihood_noptD_gluon_new);

    sprintf( histoname, "QGLikelihood_noptD_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_noptD_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_noptD_quark_new->Sumw2();
    vh1_QGLikelihood_noptD_quark.push_back(h1_QGLikelihood_noptD_quark_new);


    sprintf( histoname, "QGLikelihood_norms_noptD_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_norms_noptD_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_norms_noptD_gluon_new->Sumw2();
    vh1_QGLikelihood_norms_noptD_gluon.push_back(h1_QGLikelihood_norms_noptD_gluon_new);

    sprintf( histoname, "QGLikelihood_norms_noptD_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_norms_noptD_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_norms_noptD_quark_new->Sumw2();
    vh1_QGLikelihood_norms_noptD_quark.push_back(h1_QGLikelihood_norms_noptD_quark_new);


    sprintf( histoname, "QGLikelihood_onlyNch_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_onlyNch_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_onlyNch_gluon_new->Sumw2();
    vh1_QGLikelihood_onlyNch_gluon.push_back(h1_QGLikelihood_onlyNch_gluon_new);

    sprintf( histoname, "QGLikelihood_onlyNch_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_onlyNch_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_onlyNch_quark_new->Sumw2();
    vh1_QGLikelihood_onlyNch_quark.push_back(h1_QGLikelihood_onlyNch_quark_new);


    sprintf( histoname, "rmsCand_cutOnQGLikelihood_norms_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_rmsCand_cutOnQGLikelihood_norms_gluon_new = new TH1D(histoname, "", 100, 0., 0.1 );
    h1_rmsCand_cutOnQGLikelihood_norms_gluon_new->Sumw2();
    vh1_rmsCand_cutOnQGLikelihood_norms_gluon.push_back(h1_rmsCand_cutOnQGLikelihood_norms_gluon_new);

    sprintf( histoname, "rmsCand_cutOnQGLikelihood_norms_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_rmsCand_cutOnQGLikelihood_norms_quark_new = new TH1D(histoname, "", 100, 0., 0.1 );
    h1_rmsCand_cutOnQGLikelihood_norms_quark_new->Sumw2();
    vh1_rmsCand_cutOnQGLikelihood_norms_quark.push_back(h1_rmsCand_cutOnQGLikelihood_norms_quark_new);

    sprintf( histoname, "QGLikelihood_eta35_gluon_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_eta35_gluon_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_eta35_gluon_new->Sumw2();
    vh1_QGLikelihood_eta35_gluon.push_back(h1_QGLikelihood_eta35_gluon_new);

    sprintf( histoname, "QGLikelihood_eta35_quark_pt%.0f_%.0f", ptMin, ptMax);
    TH1D* h1_QGLikelihood_eta35_quark_new = new TH1D(histoname, "", 50, 0., 1.);
    h1_QGLikelihood_eta35_quark_new->Sumw2();
    vh1_QGLikelihood_eta35_quark.push_back(h1_QGLikelihood_eta35_quark_new);



  } //for bins


  Int_t run;
  tree_->SetBranchAddress("run", &run);
  Float_t eventWeight;
  tree_->SetBranchAddress("eventWeight", &eventWeight);
  Float_t rhoPF;
  tree_->SetBranchAddress("rhoPF", &rhoPF);

  Float_t ptHat;
  tree_->SetBranchAddress("ptHat", &ptHat);

  Int_t nJet;
  tree_->SetBranchAddress("nJet", &nJet);
  Float_t eJet[20];
  tree_->SetBranchAddress("eJet", eJet);
  Float_t ptJet[20];
  tree_->SetBranchAddress("ptJet", ptJet);
  Float_t etaJet[20];
  tree_->SetBranchAddress("etaJet", etaJet);
  Float_t phiJet[20];
  tree_->SetBranchAddress("phiJet", phiJet);
  Int_t nChargedJet[20];
  tree_->SetBranchAddress("nChargedJet", nChargedJet);
  Int_t nNeutralJet[20];
  tree_->SetBranchAddress("nNeutralJet", nNeutralJet);
  Float_t rmsCandJet[20];
  tree_->SetBranchAddress("rmsCandJet", rmsCandJet);
  Float_t ptDJet[20];
  tree_->SetBranchAddress("ptDJet", ptDJet);

  Int_t nPart;
  tree_->SetBranchAddress("nPart", &nPart);
  Float_t ePart[20];
  tree_->SetBranchAddress("ePart", ePart);
  Float_t ptPart[20];
  tree_->SetBranchAddress("ptPart", ptPart);
  Float_t etaPart[20];
  tree_->SetBranchAddress("etaPart", etaPart);
  Float_t phiPart[20];
  tree_->SetBranchAddress("phiPart", phiPart);
  Int_t pdgIdPart[20];
  tree_->SetBranchAddress("pdgIdPart", pdgIdPart);


  //QGLikelihoodCalculator *qglikeli = new QGLikelihoodCalculator("QG_QCD_Pt_15to3000_TuneZ2_Flat_7TeV_pythia6_Fall10.root", nBins);
  //QGLikelihoodCalculator *qglikeli = new QGLikelihoodCalculator("QG_QCD_Pt_15to3000_TuneZ2_Flat_7TeV_pythia6_Spring11-PU_S1_START311_V1G1-v1.root", nBins);
  QGLikelihoodCalculator *qglikeli = new QGLikelihoodCalculator("QG_QCD_Pt-15to3000_TuneZ2_Flat_7TeV_pythia6_Summer11-PU_S3_START42_V11-v2.root", nBins);


  int nEntries = tree_->GetEntries();
  //nEntries = 10000;

  for(int iEntry=0; iEntry<nEntries; ++iEntry) {
  //for(int iEntry=0; iEntry<500000; ++iEntry) {

    if( (iEntry % 100000)==0 ) std::cout << "Entry: " << iEntry << " /" << nEntries << std::endl;

    tree_->GetEntry(iEntry);

    if( eventWeight <= 0. ) eventWeight = 1.;


    //for( unsigned iJet=0; iJet<nJet; ++iJet ) {
    for( unsigned iJet=0; (iJet<nJet && iJet<3); ++iJet ) { //only 3 leading jets considered

      TLorentzVector thisJet;
      thisJet.SetPtEtaPhiE( ptJet[iJet], etaJet[iJet], phiJet[iJet], eJet[iJet]);

      float deltaRmin=999.;
      int partFlavor=-1;
      TLorentzVector foundPart;

      for( unsigned iPart=0; iPart<nPart; iPart++ ) {

        TLorentzVector thisPart;
        thisPart.SetPtEtaPhiE( ptPart[iPart], etaPart[iPart], phiPart[iPart], ePart[iPart]);

        float thisDeltaR = thisJet.DeltaR(thisPart);

        if( thisDeltaR < deltaRmin ) {
          deltaRmin = thisDeltaR;
          partFlavor = pdgIdPart[iPart];
          foundPart = thisPart;
        }

      } //for partons

      if( deltaRmin > 0.5 ) continue;
      //if( deltaRmin > 0.5 ) partFlavor=21; //lets try this


      int thisBin=-1;
      if( thisJet.Pt() > ptBins[nBins] ) {
        thisBin = nBins-1;
      } else {
        for( unsigned int iBin=0; iBin<nBins; ++iBin ) {
          if( thisJet.Pt()>ptBins[iBin] && thisJet.Pt()<ptBins[iBin+1] ) {
            thisBin = iBin;
            break;
          }
        }
      }

      if( thisBin==-1 ) continue;

    //float QGLikelihood = qglikeli->computeQGLikelihood( thisJet.Pt(), nChargedJet[iJet], nNeutralJet[iJet], ptDJet[iJet], rmsCandJet[iJet] );
    //float QGLikelihood_norms = qglikeli->computeQGLikelihood( thisJet.Pt(), nChargedJet[iJet], nNeutralJet[iJet], ptDJet[iJet], -1. );
    //float QGLikelihood_noptD = qglikeli->computeQGLikelihood( thisJet.Pt(), nChargedJet[iJet], nNeutralJet[iJet], -1., rmsCandJet[iJet] );
    //float QGLikelihood_norms_noptD = qglikeli->computeQGLikelihood( thisJet.Pt(), nChargedJet[iJet], nNeutralJet[iJet], -1., -1. );
    //float QGLikelihood_onlyNch = qglikeli->computeQGLikelihood( thisJet.Pt(), nChargedJet[iJet], -1., -1., -1. );


      // change to new var: -ln rmsCand:
      rmsCandJet[iJet] = -log(rmsCandJet[iJet]);

      if( fabs(thisJet.Eta())<2. ) {

        float QGLikelihood = qglikeli->computeQGLikelihoodPU( thisJet.Pt(), rhoPF, nChargedJet[iJet], nNeutralJet[iJet], ptDJet[iJet], rmsCandJet[iJet] );
        float QGLikelihood_norms = qglikeli->computeQGLikelihoodPU( thisJet.Pt(), rhoPF, nChargedJet[iJet], nNeutralJet[iJet], ptDJet[iJet], -1. );
    
        float QGLikelihood_noptD = -1.;
        float QGLikelihood_norms_noptD = -1.;
        float QGLikelihood_onlyNch = -1.;
    
        //float QGLikelihood_noptD = qglikeli->computeQGLikelihoodPU( thisJet.Pt(), rhoPF, nChargedJet[iJet], nNeutralJet[iJet], -1., rmsCandJet[iJet] );
        //float QGLikelihood_norms_noptD = qglikeli->computeQGLikelihoodPU( thisJet.Pt(), rhoPF, nChargedJet[iJet], nNeutralJet[iJet], -1., -1. );
        //float QGLikelihood_onlyNch = qglikeli->computeQGLikelihoodPU( thisJet.Pt(), rhoPF, nChargedJet[iJet], -1., -1., -1. );
    
        if( abs(partFlavor)< 4 ) { //light quark
          
          vh1_QGLikelihood_quark[thisBin]->Fill( QGLikelihood, eventWeight );
          vh1_QGLikelihood_norms_quark[thisBin]->Fill( QGLikelihood_norms, eventWeight );
          vh1_QGLikelihood_noptD_quark[thisBin]->Fill( QGLikelihood_noptD, eventWeight );
          vh1_QGLikelihood_norms_noptD_quark[thisBin]->Fill( QGLikelihood_norms_noptD, eventWeight );
          if( QGLikelihood_norms<0.9 ) vh1_rmsCand_cutOnQGLikelihood_norms_quark[thisBin]->Fill( rmsCandJet[iJet], eventWeight );
          vh1_QGLikelihood_onlyNch_quark[thisBin]->Fill( QGLikelihood_onlyNch, eventWeight );
    
        } else if( partFlavor==21 ) { //gluon
    
          vh1_QGLikelihood_gluon[thisBin]->Fill( QGLikelihood, eventWeight );
          vh1_QGLikelihood_norms_gluon[thisBin]->Fill( QGLikelihood_norms, eventWeight );
          vh1_QGLikelihood_noptD_gluon[thisBin]->Fill( QGLikelihood_noptD, eventWeight );
          vh1_QGLikelihood_norms_noptD_gluon[thisBin]->Fill( QGLikelihood_norms_noptD, eventWeight );
          if( QGLikelihood_norms<0.9 ) vh1_rmsCand_cutOnQGLikelihood_norms_gluon[thisBin]->Fill( rmsCandJet[iJet], eventWeight );
          vh1_QGLikelihood_onlyNch_gluon[thisBin]->Fill( QGLikelihood_onlyNch, eventWeight );
    
        }

      } else if( fabs(thisJet.Eta())>3. && fabs(thisJet.Eta())<5. ) {

        float QGLikelihood = qglikeli->computeQGLikelihoodFwd( thisJet.Pt(), rhoPF, ptDJet[iJet], rmsCandJet[iJet] );
    
        if( abs(partFlavor)< 4 ) { //light quark
          
          vh1_QGLikelihood_eta35_quark[thisBin]->Fill( QGLikelihood, eventWeight );
    
        } else if( partFlavor==21 ) { //gluon
    
          vh1_QGLikelihood_eta35_gluon[thisBin]->Fill( QGLikelihood, eventWeight );

        } //if gluon

      } //if eta
    
    } // for jets


  } //for entries


  std::vector<TGraphErrors*> vgr_eff_vs_rej;
  std::vector<TGraphErrors*> vgr_eff_vs_rej_norms;
  std::vector<TGraphErrors*> vgr_eff_vs_rej_noptD;
  std::vector<TGraphErrors*> vgr_eff_vs_rej_norms_noptD;
  std::vector<TGraphErrors*> vgr_eff_vs_rej_onlyNch;

  for( unsigned iBin=0; iBin<nBins; ++iBin ) {

    float ptMin = ptBins[iBin];
    float ptMax = ptBins[iBin+1];

    char graphName[200];
    sprintf( graphName, "eff_vs_rej_pt%.0f_%.0f", ptMin, ptMax );
    TGraphErrors* newGraph = new TGraphErrors(0);
    newGraph->SetName(graphName);
    vgr_eff_vs_rej.push_back(newGraph);

    sprintf( graphName, "eff_vs_rej_norms_pt%.0f_%.0f", ptMin, ptMax );
    TGraphErrors* newGraph_norms = new TGraphErrors(0);
    newGraph_norms->SetName(graphName);
    vgr_eff_vs_rej_norms.push_back(newGraph_norms);

    sprintf( graphName, "eff_vs_rej_noptD_pt%.0f_%.0f", ptMin, ptMax );
    TGraphErrors* newGraph_noptD = new TGraphErrors(0);
    newGraph_noptD->SetName(graphName);
    vgr_eff_vs_rej_noptD.push_back(newGraph_noptD);

    sprintf( graphName, "eff_vs_rej_norms_noptD_pt%.0f_%.0f", ptMin, ptMax );
    TGraphErrors* newGraph_norms_noptD = new TGraphErrors(0);
    newGraph_norms_noptD->SetName(graphName);
    vgr_eff_vs_rej_norms_noptD.push_back(newGraph_norms_noptD);

    sprintf( graphName, "eff_vs_rej_onlyNch_pt%.0f_%.0f", ptMin, ptMax );
    TGraphErrors* newGraph_onlyNch = new TGraphErrors(0);
    newGraph_onlyNch->SetName(graphName);
    vgr_eff_vs_rej_onlyNch.push_back(newGraph_onlyNch);

  }


  // compute eff-rej curves:
  for( unsigned iBin=0; iBin<nBins; ++iBin ) {

    for( unsigned iHistoBin=1; iHistoBin<vh1_QGLikelihood_quark[iBin]->GetNbinsX(); ++iHistoBin ) {

      float eff_q = vh1_QGLikelihood_quark[iBin]->Integral(iHistoBin, vh1_QGLikelihood_quark[iBin]->GetNbinsX())/vh1_QGLikelihood_quark[iBin]->Integral(1, vh1_QGLikelihood_quark[iBin]->GetNbinsX());
      float eff_g = vh1_QGLikelihood_gluon[iBin]->Integral(iHistoBin, vh1_QGLikelihood_gluon[iBin]->GetNbinsX())/vh1_QGLikelihood_gluon[iBin]->Integral(1, vh1_QGLikelihood_gluon[iBin]->GetNbinsX());

      float eff_q_norms = vh1_QGLikelihood_norms_quark[iBin]->Integral(iHistoBin, vh1_QGLikelihood_norms_quark[iBin]->GetNbinsX())/vh1_QGLikelihood_norms_quark[iBin]->Integral(1, vh1_QGLikelihood_norms_quark[iBin]->GetNbinsX());
      float eff_g_norms = vh1_QGLikelihood_norms_gluon[iBin]->Integral(iHistoBin, vh1_QGLikelihood_norms_gluon[iBin]->GetNbinsX())/vh1_QGLikelihood_norms_gluon[iBin]->Integral(1, vh1_QGLikelihood_norms_gluon[iBin]->GetNbinsX());

      float eff_q_noptD = vh1_QGLikelihood_noptD_quark[iBin]->Integral(iHistoBin, vh1_QGLikelihood_noptD_quark[iBin]->GetNbinsX())/vh1_QGLikelihood_noptD_quark[iBin]->Integral(1, vh1_QGLikelihood_noptD_quark[iBin]->GetNbinsX());
      float eff_g_noptD = vh1_QGLikelihood_noptD_gluon[iBin]->Integral(iHistoBin, vh1_QGLikelihood_noptD_gluon[iBin]->GetNbinsX())/vh1_QGLikelihood_noptD_gluon[iBin]->Integral(1, vh1_QGLikelihood_noptD_gluon[iBin]->GetNbinsX());

      float eff_q_norms_noptD = vh1_QGLikelihood_norms_noptD_quark[iBin]->Integral(iHistoBin, vh1_QGLikelihood_norms_noptD_quark[iBin]->GetNbinsX())/vh1_QGLikelihood_norms_noptD_quark[iBin]->Integral(1, vh1_QGLikelihood_norms_noptD_quark[iBin]->GetNbinsX());
      float eff_g_norms_noptD = vh1_QGLikelihood_norms_noptD_gluon[iBin]->Integral(iHistoBin, vh1_QGLikelihood_norms_noptD_gluon[iBin]->GetNbinsX())/vh1_QGLikelihood_norms_noptD_gluon[iBin]->Integral(1, vh1_QGLikelihood_norms_noptD_gluon[iBin]->GetNbinsX());

      float eff_q_onlyNch = vh1_QGLikelihood_onlyNch_quark[iBin]->Integral(iHistoBin, vh1_QGLikelihood_onlyNch_quark[iBin]->GetNbinsX())/vh1_QGLikelihood_onlyNch_quark[iBin]->Integral(1, vh1_QGLikelihood_onlyNch_quark[iBin]->GetNbinsX());
      float eff_g_onlyNch = vh1_QGLikelihood_onlyNch_gluon[iBin]->Integral(iHistoBin, vh1_QGLikelihood_onlyNch_gluon[iBin]->GetNbinsX())/vh1_QGLikelihood_onlyNch_gluon[iBin]->Integral(1, vh1_QGLikelihood_onlyNch_gluon[iBin]->GetNbinsX());

      vgr_eff_vs_rej[iBin]->SetPoint( vgr_eff_vs_rej[iBin]->GetN(), eff_q, 1.-eff_g ); 
      vgr_eff_vs_rej_norms[iBin]->SetPoint( vgr_eff_vs_rej_norms[iBin]->GetN(), eff_q_norms, 1.-eff_g_norms ); 
      vgr_eff_vs_rej_noptD[iBin]->SetPoint( vgr_eff_vs_rej_noptD[iBin]->GetN(), eff_q_noptD, 1.-eff_g_noptD ); 
      vgr_eff_vs_rej_norms_noptD[iBin]->SetPoint( vgr_eff_vs_rej_norms_noptD[iBin]->GetN(), eff_q_norms_noptD, 1.-eff_g_norms_noptD ); 
      vgr_eff_vs_rej_onlyNch[iBin]->SetPoint( vgr_eff_vs_rej_onlyNch[iBin]->GetN(), eff_q_onlyNch, 1.-eff_g_onlyNch ); 

    }

  }


  outFile_->cd();


  for( unsigned iBin=0; iBin<nBins; ++iBin ) {

    vh1_QGLikelihood_gluon[iBin]->Write();
    vh1_QGLikelihood_quark[iBin]->Write();

    vh1_QGLikelihood_norms_gluon[iBin]->Write();
    vh1_QGLikelihood_norms_quark[iBin]->Write();

    vh1_QGLikelihood_noptD_gluon[iBin]->Write();
    vh1_QGLikelihood_noptD_quark[iBin]->Write();

    vh1_QGLikelihood_norms_noptD_gluon[iBin]->Write();
    vh1_QGLikelihood_norms_noptD_quark[iBin]->Write();

    vh1_QGLikelihood_onlyNch_gluon[iBin]->Write();
    vh1_QGLikelihood_onlyNch_quark[iBin]->Write();

    vh1_QGLikelihood_eta35_gluon[iBin]->Write();
    vh1_QGLikelihood_eta35_quark[iBin]->Write();

    vh1_rmsCand_cutOnQGLikelihood_norms_gluon[iBin]->Write();
    vh1_rmsCand_cutOnQGLikelihood_norms_quark[iBin]->Write();

    vgr_eff_vs_rej[iBin]->Write();
    vgr_eff_vs_rej_norms[iBin]->Write();
    vgr_eff_vs_rej_noptD[iBin]->Write();
    vgr_eff_vs_rej_norms_noptD[iBin]->Write();
    vgr_eff_vs_rej_onlyNch[iBin]->Write();

  }

  outFile_->Close();

}
예제 #16
0
파일: tupelanalyzer.C 프로젝트: UGent/Tupel
void tree1r()
{
 bool muon=0;
//JetCorrectionUncertainty *jecUnc;
// jecUnc= new JetCorrectionUncertainty("Fall12_V7_DATA_Uncertainty_AK5PFchs.txt");

  TChain myTree("analyzeBasicPat/MuonTree");
  myTree.Add("/afs/cern.ch/user/b/bbilin/eos/cms/store/group/phys_smp/ZPlusJets/8TeV/ntuples/2111/skimmed/EE_hadd_2012ABCD.root");

  TH1::AddDirectory(true);



  Double_t        PU_npT;
  Double_t        PU_npIT;
  double           EvtInfo_NumVtx;
  double          MyWeight;
   double nup;
  Int_t          event;
  double          realdata;
  int          run;
//  int          lumi;
  double HLT_Elec17_Elec8;

  std::vector<double> *Dr01LepPt=0;
  std::vector<double> *Dr01LepEta=0;
  std::vector<double> *Dr01LepPhi=0;
  std::vector<double> *Dr01LepE=0;
  std::vector<double> *Dr01LepM=0;
  std::vector<double> *Dr01LepId=0;
  std::vector<double> *Dr01LepStatus=0;

  std::vector<double>  *Bare01LepPt=0;
  std::vector<double> *Bare01LepEta=0;
  std::vector<double> *Bare01LepPhi=0;
  std::vector<double> *Bare01LepE=0;
  std::vector<double> *Bare01LepM=0;
  std::vector<double> *Bare01LepId=0;
  std::vector<double> *Bare01LepStatus=0;

  std::vector<double> *St01PhotonPt=0;
  std::vector<double> *St01PhotonEta=0;
  std::vector<double> *St01PhotonPhi=0;
  std::vector<double> *St01PhotonE=0;
  std::vector<double> *St01PhotonM=0;
  std::vector<double> *St01PhotonId=0;
  std::vector<double> *St01PhotonMomId=0;
  std::vector<double> *St01PhotonNumberMom=0;
  std::vector<double> *St01PhotonStatus=0;



  std::vector<double> *St03Pt=0;
  std::vector<double> *St03Eta=0;
  std::vector<double> *St03Phi=0;
  std::vector<double> *St03E=0;
  std::vector<double> *St03M=0;
  std::vector<double> *St03Id=0;
  std::vector<double> *St03Status=0;

  std::vector<double> *GjPt=0;
  std::vector<double> *Gjeta=0;
  std::vector<double> *Gjphi=0;
  std::vector<double> *GjE=0;
  std::vector<double> *GjPx=0;
  std::vector<double> *GjPy=0;
  std::vector<double> *GjPz=0;

  vector<double>  *patMuonEn_ =0; 
  vector<double>  *patMuonCharge_ =0;
  vector<double>  *patMuonPt_ =0;
  vector<double>  *patMuonEta_=0;
  vector<double>  *patMuonPhi_ =0;
  vector<double>  *patMuonCombId_ =0;
  vector<double>  *patMuonTrig_ =0;
  vector<double>  *patMuonDetIsoRho_ =0;
  vector<double>  *patMuonPfIsoDbeta_ =0;

  std::vector<double> *patElecTrig_ =0;
  std::vector<double> *patElecCharge_ =0;
  std::vector<double> *patElecEnergy_ =0;
  std::vector<double> *patElecEta_ =0;
  std::vector<double> *patElecScEta_ =0;
  std::vector<double> *patElecPhi_ =0;
//  std::vector<double> *patElecEcalEnergy_ =0;
  std::vector<double> *patElecPt_ =0;
  std::vector<double> *patElecPfIso_ =0;
  std::vector<double> *patElecPfIsodb_ =0;
  std::vector<double> *patElecPfIsoRho_ =0;
  std::vector<double>   *patElecMediumIDOff_ =0;
//  std::vector<double> *patElecMVATrigId_ =0;
//  std::vector<double> *patElecMVANonTrigId_ =0;

  vector<double>  *patJetPfAk05En_ =0;
  vector<double>  *patJetPfAk05Pt_ =0;
  vector<double>  *patJetPfAk05Eta_ =0;
  vector<double>  *patJetPfAk05Phi_ =0;
//  vector<double>  *patJetPfAk05JesUncert_ =0;
  vector<double>  *patJetPfAk05LooseId_ =0;
  vector<double>  *patJetPfAk05Et_ =0;
//  vector<double>  *patJetPfAk05HadEHF_ =0;
//  vector<double>  *patJetPfAk05EmEHF_ =0;
//  vector<double>  *patJetPfAk05RawPt_ =0;

  vector<double>  *patJetPfAk05RawEn_ =0;
//  vector<double>  *patJetPfAk05jetBetaClassic_ =0;
//  vector<double>  *patJetPfAk05jetBeta_ =0;
//  vector<double>  *patJetPfAk05jetBetaStar_ =0;
//  vector<double>  *patJetPfAk05jetBetaStarClassic_ =0;
  vector<double>  *patJetPfAk05jetpuMVA_ =0;

  vector<bool>  *patJetPfAk05jetpukLoose_ =0;
  vector<bool>  *patJetPfAk05jetpukMedium_ =0;
  vector<bool>  *patJetPfAk05jetpukTight_ =0;


  vector<double> *patJetPfAk05chf_=0;
  vector<double> *patJetPfAk05nhf_=0;
  vector<double> *patJetPfAk05cemf_=0;
  vector<double> *patJetPfAk05nemf_=0;
  vector<double> *patJetPfAk05cmult_=0;
  vector<double> *patJetPfAk05nconst_=0;



  myTree.SetBranchAddress("event",&event);


  myTree.SetBranchAddress("MyWeight",&MyWeight);
  myTree.SetBranchAddress("realdata",&realdata);
  myTree.SetBranchAddress("run",&run);
//  myTree.SetBranchAddress("lumi",&lumi);
  myTree.SetBranchAddress("PU_npT", &PU_npT);
  myTree.SetBranchAddress("PU_npIT", &PU_npIT);
  myTree.SetBranchAddress("nup", &nup);
  myTree.SetBranchAddress("EvtInfo_NumVtx", &EvtInfo_NumVtx);

  myTree.SetBranchAddress("patMuonEn_", &patMuonEn_);
  myTree.SetBranchAddress("patMuonCharge_", &patMuonCharge_);
  myTree.SetBranchAddress("patMuonPt_", &patMuonPt_);
  myTree.SetBranchAddress("patMuonEta_", &patMuonEta_);
  myTree.SetBranchAddress("patMuonPhi_", &patMuonPhi_);
  myTree.SetBranchAddress("patMuonCombId_", &patMuonCombId_);
  myTree.SetBranchAddress("patMuonTrig_", &patMuonTrig_);
  myTree.SetBranchAddress("patMuonDetIsoRho_", &patMuonDetIsoRho_);
  myTree.SetBranchAddress("patMuonPfIsoDbeta_", &patMuonPfIsoDbeta_);



  myTree.SetBranchAddress("patElecCharge_",&patElecCharge_);
  myTree.SetBranchAddress("patElecPt_",&patElecPt_);
  myTree.SetBranchAddress("patElecEnergy_",&patElecEnergy_);
//  myTree.SetBranchAddress("patElecEcalEnergy_",&patElecEcalEnergy_);
  myTree.SetBranchAddress("patElecEta_",&patElecEta_);
  myTree.SetBranchAddress("patElecScEta_",&patElecScEta_);
  myTree.SetBranchAddress("patElecPhi_",&patElecPhi_);
  myTree.SetBranchAddress("patElecPfIso_",&patElecPfIso_);
  myTree.SetBranchAddress("patElecPfIsodb_",&patElecPfIsodb_);
  myTree.SetBranchAddress("patElecPfIsoRho_",&patElecPfIsoRho_);
  myTree.SetBranchAddress("patElecMediumIDOff_",&patElecMediumIDOff_);
//  myTree.SetBranchAddress("patElecMVATrigId_",&patElecMVATrigId_);
//  myTree.SetBranchAddress("patElecMVANonTrigId_",&patElecMVANonTrigId_);
  myTree.SetBranchAddress("patElecTrig_",&patElecTrig_);

  myTree.SetBranchAddress("patJetPfAk05RawEn_",&patJetPfAk05RawEn_);
   //myTree.SetBranchAddress("patJetPfAk05HadEHF_",&patJetPfAk05HadEHF_);
   //myTree.SetBranchAddress("patJetPfAk05EmEHF_",&patJetPfAk05EmEHF_);
  myTree.SetBranchAddress("patJetPfAk05chf_",&patJetPfAk05chf_);
  myTree.SetBranchAddress("patJetPfAk05nhf_",&patJetPfAk05nhf_);
  myTree.SetBranchAddress("patJetPfAk05cemf_",&patJetPfAk05cemf_);
  myTree.SetBranchAddress("patJetPfAk05nemf_",&patJetPfAk05nemf_);
  myTree.SetBranchAddress("patJetPfAk05cmult_",&patJetPfAk05cmult_);
  myTree.SetBranchAddress("patJetPfAk05nconst_",&patJetPfAk05nconst_);
  myTree.SetBranchAddress("patJetPfAk05En_", &patJetPfAk05En_);
  myTree.SetBranchAddress("patJetPfAk05Pt_", &patJetPfAk05Pt_);
  myTree.SetBranchAddress("patJetPfAk05Eta_", &patJetPfAk05Eta_);
  myTree.SetBranchAddress("patJetPfAk05Phi_", &patJetPfAk05Phi_);
//  myTree.SetBranchAddress("patJetPfAk05JesUncert_", &patJetPfAk05JesUncert_);
  myTree.SetBranchAddress("patJetPfAk05LooseId_", &patJetPfAk05LooseId_);
  myTree.SetBranchAddress("patJetPfAk05Et_", &patJetPfAk05Et_);
//  myTree.SetBranchAddress("patJetPfAk05HadEHF_", &patJetPfAk05HadEHF_);
//  myTree.SetBranchAddress("patJetPfAk05EmEHF_", &patJetPfAk05EmEHF_);
//  myTree.SetBranchAddress("patJetPfAk05RawPt_", &patJetPfAk05RawPt_);
//  myTree.SetBranchAddress("patJetPfAk05RawEn_", &patJetPfAk05RawEn_);
//  myTree.SetBranchAddress("patJetPfAk05jetBetaClassic_", &patJetPfAk05jetBetaClassic_);
//  myTree.SetBranchAddress("patJetPfAk05jetBeta_", &patJetPfAk05jetBeta_);
//  myTree.SetBranchAddress("patJetPfAk05jetBetaStar_", &patJetPfAk05jetBetaStar_);
//  myTree.SetBranchAddress("patJetPfAk05jetBetaStarClassic_", &patJetPfAk05jetBetaStarClassic_);
  myTree.SetBranchAddress("patJetPfAk05jetpuMVA_", &patJetPfAk05jetpuMVA_);
  myTree.SetBranchAddress("patJetPfAk05jetpukLoose_", &patJetPfAk05jetpukLoose_);
  myTree.SetBranchAddress("patJetPfAk05jetpukMedium_", &patJetPfAk05jetpukMedium_);
  myTree.SetBranchAddress("patJetPfAk05jetpukTight_", &patJetPfAk05jetpukTight_);
  myTree.SetBranchAddress("HLT_Elec17_Elec8",&HLT_Elec17_Elec8);
//Gen jets//
  myTree.SetBranchAddress("GjPt",&GjPt);
  myTree.SetBranchAddress("Gjeta",&Gjeta);
  myTree.SetBranchAddress("Gjphi",&Gjphi);
  myTree.SetBranchAddress("GjE",&GjE);
  myTree.SetBranchAddress("GjPx",&GjPx);
  myTree.SetBranchAddress("GjPy",&GjPy);
  myTree.SetBranchAddress("GjPz",&GjPz); 
  //Dressed Leptons//
  myTree.SetBranchAddress("Dr01LepPt",&Dr01LepPt);
  myTree.SetBranchAddress("Dr01LepEta",&Dr01LepEta);
  myTree.SetBranchAddress("Dr01LepPhi",&Dr01LepPhi);
  myTree.SetBranchAddress("Dr01LepE",&Dr01LepE);
  myTree.SetBranchAddress("Dr01LepM",&Dr01LepM);
  myTree.SetBranchAddress("Dr01LepId",&Dr01LepId);
  myTree.SetBranchAddress("Dr01LepStatus",&Dr01LepStatus);

  myTree.SetBranchAddress("Bare01LepPt",&Bare01LepPt);
  myTree.SetBranchAddress("Bare01LepEt",&Bare01LepEta);
  myTree.SetBranchAddress("Bare01LepPhi",&Bare01LepPhi);
  myTree.SetBranchAddress("Bare01LepE",&Bare01LepE);
  myTree.SetBranchAddress("Bare01LepM",&Bare01LepM);
  myTree.SetBranchAddress("Bare01LepId",&Bare01LepId);
  myTree.SetBranchAddress("Bare01LepStatus",&Bare01LepStatus);

  myTree.SetBranchAddress("St01PhotonPt",&St01PhotonPt);
  myTree.SetBranchAddress("St01PhotonEta",&St01PhotonEta);
  myTree.SetBranchAddress("St01PhotonPhi",&St01PhotonPhi);
  myTree.SetBranchAddress("St01PhotonE",&St01PhotonE);
  myTree.SetBranchAddress("St01PhotonM",&St01PhotonM);
  myTree.SetBranchAddress("St01PhotonId",&St01PhotonId);
  myTree.SetBranchAddress("St01PhotonMomId",&St01PhotonMomId);
  myTree.SetBranchAddress("St01PhotonNumberMom",&St01PhotonNumberMom);
  myTree.SetBranchAddress("St01PhotonStatus",&St01PhotonStatus);


  myTree.SetBranchAddress("St03Pt",&St03Pt);
  myTree.SetBranchAddress("St03Eta",&St03Eta);
  myTree.SetBranchAddress("St03Phi",&St03Phi);
  myTree.SetBranchAddress("St03E",&St03E);
  myTree.SetBranchAddress("St03M",&St03M);
  myTree.SetBranchAddress("St03Id",&St03Id);
  myTree.SetBranchAddress("St03Status",&St03Status);





  ////Histogram booking///////////
 
  TFile *theFile = new TFile ("test.root","RECREATE");
  theFile->cd();
  TH1D* h_MZ = new TH1D("MZ","M(Z)#rightarrow #mu#mu",40, 71,111.);
  TH1D* h_GMZElec = new TH1D("GMZElec","M(Z)#rightarrow #mu#mu",40, 71,111.);



  int puYear(2013);
    cout << "Pile Up Distribution: " << puYear << endl;
    standalone_LumiReWeighting puWeight(puYear), puUp(puYear,1), puDown(puYear,-1);


  Int_t nevent = myTree.GetEntries();
  nevent =100000;
  for (Int_t iev=0;iev<nevent;iev++) {


    if (iev%100000 == 0) cout<<"DATA"<<" ===>>> "<<iev<<"/"<<nevent<<endl;
    myTree.GetEntry(iev);    

    if(HLT_Elec17_Elec8!=1)continue; //require global trigger fired 


  ///////////////////////////////
    double PUweight =1;
    double PUweightUp =1;
    double PUweightDn =1;

    if (PU_npT > 0) PUweight = PUweight * puWeight.weight(int(PU_npT));
    if (PU_npT > 0) PUweightUp = PUweightUp * puUp.weight(int(PU_npT));
    if (PU_npT > 0) PUweightDn = PUweightDn * puDown.weight(int(PU_npT));

 
    int Gcommon = 0;
 
    int Gindex1[10],Gindex2[10];



    for (unsigned int j = 0; j < Dr01LepPt->size(); ++j){  

      for (unsigned int jk = j; jk < Dr01LepPt->size(); ++jk){
       // if(fabs(Dr01LepId->at(j))==11)cout<<Dr01LepId->at(j)<<endl;
        if (j == jk) continue;

        if ( Dr01LepStatus->at(j) == 1 && Dr01LepStatus->at(jk) == 1 &&
	     (Dr01LepId->at(j)*Dr01LepId->at(jk)) == -121 && //common1
	     Dr01LepPt->at(j) > 30. && Dr01LepPt->at(jk) > 30. && //common2
	     fabs(Dr01LepEta->at(j)) <2.4 && fabs(Dr01LepEta->at(jk)) <2.4 //common3
            ){

          Gindex1[Gcommon] = j;
          Gindex2[Gcommon] = jk;
          Gcommon++;
        }
      }
    }

 //   cout<<Gcommon<<endl;

    float GMZElec = 0;
//    float Gdielecpt =0;
//    float Gdielecrapidity =0;
//    float Gdielecphi =0;
 

    int Gind1 = -99;
    int Gind2 = -99;
 
    for (int gg = 0;gg<Gcommon;++gg){
      Gind1 = Gindex1[gg];
      Gind2 = Gindex2[gg];
    }




    if (Gind1 != -99 && Gind2 != -99){

      TLorentzVector m1;
      TLorentzVector m2;
      m1.SetPtEtaPhiE(Dr01LepPt->at(Gind1), Dr01LepEta->at(Gind1) ,Dr01LepPhi->at(Gind1),Dr01LepE->at(Gind1) );
      m2.SetPtEtaPhiE(Dr01LepPt->at(Gind2), Dr01LepEta->at(Gind2) ,Dr01LepPhi->at(Gind2),Dr01LepE->at(Gind2) );
      GMZElec= (m1+m2).M();

      if (GMZElec > 20.){
//        Gdielecpt = (m1+m2).Perp(); 
//        Gdielecrapidity = (m1+m2).Rapidity();
//        Gdielecphi=(m1+m2).Phi();
        if (GMZElec > 71.&& GMZElec < 111.){
   
          h_GMZElec->Fill(GMZElec,PUweight);
        }
      }
    }


     int common = 0;
    int select_dielec=0;
    int index1[100],index2[100];
    //if(doUnf)cout<<"NEW EVENT"<<endl;
    if(muon==0){
      for (unsigned int j = 0; j < patElecPt_->size(); ++j){ 
     
        for (unsigned int jk = j; jk < patElecPt_->size(); ++jk){
	  if (j == jk) continue;
          if (select_dielec==1) continue;
	  if ( (patElecCharge_->at(j)*patElecCharge_->at(jk)) == -1 && 
	      patElecPt_->at(j) > 20. && patElecPt_->at(jk) > 20. && 
	      fabs(patElecScEta_->at(j)) <=2.4 && fabs(patElecScEta_->at(jk)) <=2.4 &&
              (
               !(fabs(patElecScEta_->at(j)) >1.4442 && fabs(patElecScEta_->at(j))<1.566) && 
	       !(fabs(patElecScEta_->at(jk)) >1.4442 && fabs(patElecScEta_->at(jk))<1.566)
              ) &&
              patElecTrig_->at(j) > 0 && patElecTrig_->at(jk) > 0 &&
              patElecPfIsoRho_->at(j)<0.150 && patElecPfIsoRho_->at(jk)<0.150 &&
              patElecMediumIDOff_->at(j) >0 && patElecMediumIDOff_->at(jk) >0
	    ){

              select_dielec=1;
              if(fabs(patElecScEta_->at(j)) >1.4442 && fabs(patElecScEta_->at(j))<1.566)cout<<"Elektron gap dışlanmamış!!"<<endl;
              TLorentzVector e1_tmp;
              TLorentzVector e2_tmp;
              e1_tmp.SetPtEtaPhiE(patElecPt_->at(j), patElecEta_->at(j) ,patElecPhi_->at(j),patElecEnergy_->at(j) );
              e2_tmp.SetPtEtaPhiE(patElecPt_->at(jk), patElecEta_->at(jk) ,patElecPhi_->at(jk),patElecEnergy_->at(jk) );

              float MZElec_tmp= (e1_tmp+e2_tmp).M();

              if(MZElec_tmp<71. || MZElec_tmp>111.)continue;            
         

	      index1[common] = j;
	      index2[common] = jk;
	      common++;
	    
          }
        }
      }
    }


      double ptcut = 20;
    if(muon==1){
      for (unsigned int j = 0; j < patMuonPt_->size(); ++j){
        for (unsigned int jk = j; jk < patMuonPt_->size(); ++jk){
          if (j == jk) continue;
          if ((patMuonCharge_->at(j)*patMuonCharge_->at(jk)) == -1 &&
                patMuonPt_->at(j) > ptcut && patMuonPt_->at(jk) > ptcut && 
                fabs(patMuonEta_->at(j)) <2.4 && fabs(patMuonEta_->at(jk)) <2.4 &&
                patMuonTrig_->at(j) ==1  && patMuonTrig_->at(jk) == 1 &&
                patMuonPfIsoDbeta_->at(j)<0.2 && patMuonPfIsoDbeta_->at(jk)<0.2 &&
                patMuonCombId_->at(j) ==1 && patMuonCombId_->at(jk) ==1
               )
          {

            index1[common] = j;
            index2[common] = jk;
            common++;

          }
        }
      }
    }

    int ind1 = -99;
    int ind2 = -99;
    if(common>0){
      ind1 = index1[0];
      ind2 = index2[0];
    }


    float MZ = 0;
//    float Zpt =0;
//    float Zphi =0;
//    float Zrapidity =0;

    TLorentzVector l1;
    TLorentzVector l2;



    if (ind1 != -99 && ind2 != -99 &&common>0 /*&&common==1*/){
 
      if(muon==0){
        l1.SetPtEtaPhiE(patElecPt_->at(ind1), patElecEta_->at(ind1) ,patElecPhi_->at(ind1),patElecEnergy_->at(ind1) );
        l2.SetPtEtaPhiE(patElecPt_->at(ind2), patElecEta_->at(ind2) ,patElecPhi_->at(ind2),patElecEnergy_->at(ind2) );
      }

      if(muon==1){
        l1.SetPtEtaPhiE(patMuonPt_->at(ind1), patMuonEta_->at(ind1) ,patMuonPhi_->at(ind1),patMuonEn_->at(ind1) );
        l2.SetPtEtaPhiE(patMuonPt_->at(ind2), patMuonEta_->at(ind2) ,patMuonPhi_->at(ind2),patMuonEn_->at(ind2) );
      }
      MZ= (l1+l2).M();
      if ( MZ > 20.){
//      Zpt= (l1+l2).Perp();           
//	Zrapidity = (l1+l2).Rapidity();
//      Zphi = (l1+l2).Phi();

	if (MZ>71 && MZ<111){

          h_MZ->Fill(MZ,PUweight);

        }
      }
    }
    TLorentzVector j1_BEF;
    TLorentzVector j2_BEF;
 
    TLorentzVector j1G_BE;
    TLorentzVector j2G_BE;




    int Gn_jet_30_n=0;
    int n_jet_30_n_bef=0;

   /////////////Gen Jets///////////////////////
      for (unsigned int pf=0;pf < GjPt->size();pf++){

	if (GjPt->at(pf) > 30. && fabs(Gjeta->at(pf))<2.4){             

	  Gn_jet_30_n++;	 	  
	  if(Gn_jet_30_n==1){
	    j1G_BE.SetPtEtaPhiE(GjPt->at(pf),Gjeta->at(pf),Gjphi->at(pf),GjE->at(pf));
          }
          if(Gn_jet_30_n==2){
	    j2G_BE.SetPtEtaPhiE(GjPt->at(pf),Gjeta->at(pf),Gjphi->at(pf),GjE->at(pf));
          }
        }
      }/// end Gen jet loop

    /////////////Jets///////////////////////




      for (unsigned int pf=0;pf < patJetPfAk05Pt_->size();pf++){

          if(patJetPfAk05Pt_->at(pf) > 30.&&0.0<fabs(patJetPfAk05Eta_->at(pf)) && fabs(patJetPfAk05Eta_->at(pf))<4.7  
             ){           
            if ( patJetPfAk05LooseId_->at(pf)>=1 && patJetPfAk05jetpukLoose_->at(pf)==1){
              n_jet_30_n_bef++;

	      TLorentzVector j;
              j.SetPtEtaPhiE(patJetPfAk05Pt_->at(pf),patJetPfAk05Eta_->at(pf),patJetPfAk05Phi_->at(pf),patJetPfAk05En_->at(pf));

    	      if(n_jet_30_n_bef==1){
	        j1_BEF.SetPtEtaPhiE(j.Pt(),j.Eta(),j.Phi(),j.E());          
              }
              if(n_jet_30_n_bef==2){
	        j2_BEF.SetPtEtaPhiE(j.Pt(),j.Eta(),j.Phi(),j.E());
              }
            }  
          }
      }

  }// end of event loop
  theFile->Write();
  theFile->Close();

}//end void  
예제 #17
0
int xAna::HggTreeWriteLoop(const char* filename, int ijob, 
					  bool correctVertex, bool correctEnergy, 
					  bool setRho0
					  ) {

  //bool invDRtoTrk = false;


  if( _config == 0 ) {
    cout << " config file was not set properly... bail out" << endl;
    return -1;
  }

  if (fChain == 0) return -1;
  
  Long64_t nentries = fChain->GetEntriesFast();
  //  nentries = 10000;
  cout << "nentries: " << nentries << endl;  
  Long64_t entry_start = ijob    *_config->nEvtsPerJob();
  Long64_t entry_stop  = (ijob+1)*_config->nEvtsPerJob();
  if( _config->nEvtsPerJob() < 0 ) {
    entry_stop = nentries;
  }
  if( entry_stop  > nentries ) entry_stop = nentries;
  cout << "   *** doing entries from: " << entry_start << " -> " << entry_stop << endl;
  if( entry_start > entry_stop ) return -1;

  
  EnergyScaleReader enScaleSkimEOS; /// skim EOS bugged so need to undo the energy scale in the skim
  EnergyScaleReader enScale;
  //  enScaleSkimEOS.setup( "ecalCalibFiles/EnergyScale2012_Lisbon_9fb.txt" );
  enScale.setup( _config->energyScaleFile() );


  Float_t HiggsMCMass =  _weight_manager->getCrossSection()->getHiggsMass();
  Float_t HiggsMCPt   = -1;
  bool isHiggsSignal = false;
  if( HiggsMCMass > 0 ) isHiggsSignal = true;

  mode_ = _weight_manager->getCrossSection()->mode();
  isData = false;
  if(mode_==-1) isData = true;        

//  mode_ = ijob; //  

  DoCorrectVertex_ = correctVertex;
  DoCorrectEnergy_ = correctEnergy;
  DoSetRho0_ = setRho0;

  doJetRegression = _config->getDoJetRegression();
  doControlSample = _config->getDoControlSample();
  
  phoID_2011[0] = new TMVA::Reader("!Color:Silent");
  phoID_2011[1] = new TMVA::Reader("!Color:Silent");
  phoID_2012[0] = new TMVA::Reader("!Color:Silent");
  phoID_2012[1] = new TMVA::Reader("!Color:Silent");
  DiscriDiPho_2011 = new TMVA::Reader("!Color:Silent");
  DiscriDiPho_2012 = new TMVA::Reader("!Color:Silent");
  if(doJetRegression!=0) jetRegres = new TMVA::Reader("!Color:Silent");
  Setup_MVA();
  
  if( _config->setup() == "ReReco2011" )  for( int i = 0 ; i < 2; i++ ) phoID_mva[i] = phoID_2011[i];
  else                                    for( int i = 0 ; i < 2; i++ ) phoID_mva[i] = phoID_2012[i];

  MassResolution massResoCalc;
  massResoCalc.addSmearingTerm();
  if( _config->setup() == "ReReco2011" )  Ddipho_mva = DiscriDiPho_2011;
  else                                    Ddipho_mva = DiscriDiPho_2012;

  float Ddipho_cat[5]; Ddipho_cat[4] = -1; 
  if( _config->setup() == "ReReco2011" ) { Ddipho_cat[0] = 0.89; Ddipho_cat[1] = 0.72; Ddipho_cat[2] = 0.55; Ddipho_cat[3] = +0.05; }
  else                                   { Ddipho_cat[0] = 0.91; Ddipho_cat[1] = 0.79; Ddipho_cat[2] = 0.49; Ddipho_cat[3] = -0.05; }
  //  else                                   { Ddipho_cat[0] = 0.88; Ddipho_cat[1] = 0.71; Ddipho_cat[2] = 0.50; Ddipho_cat[3] = -0.05; }

  DiscriVBF_UseDiPhoPt = true;
  DiscriVBF_UsePhoPt   = true;
  DiscriVBF_cat.resize(2); DiscriVBF_cat[0] = 0.985; DiscriVBF_cat[1] = 0.93;
  DiscriVBF_useMvaSel  = _config->doVBFmvaCat();


  


  /// depending on the selection veto or not on electrons (can do muele, elemu,eleele)
  bool vetoElec[2] = {true,true};
  if( _config->invertElectronVeto() ) { vetoElec[0] = false; vetoElec[1] = false; }
  if( _config->isEleGamma()         ) { vetoElec[0] = false; vetoElec[1] = true ; }
  if( _config->isGammaEle()         ) { vetoElec[0] = true ; vetoElec[1] = false; }
  cout << " --------- veto electron config -----------" << endl;
  cout << " Leading  Pho VetoElec: " << vetoElec[0] << endl;
  cout << " Trailing Pho VetoElec: " << vetoElec[1] << endl;
  

  DoDebugEvent = true;
  
  bool DoPreselection = true;
  //  bool DoPrint = true;
  
  
  TString VertexFileNamePrefix;
  
  TRandom3 *rnd = new TRandom3();
  rnd->SetSeed(0);
  
  /// output tree and cross check file
   _xcheckTextFile.open(TString(filename)+".xcheck.txt");
   // _xcheckTextFile = cout;

  _minitree = new MiniTree( filename );
  TTree * tSkim = 0;
  if( _config->doSkimming() ) tSkim = (TTree*) fChain->CloneTree(0);

  InitHists();
  _minitree->mc_wXsec = _weight_manager->xSecW();
  _minitree->mc_wNgen = 100000./_weight_manager->getNevts();
  if( isData ) {
    _minitree->mc_wXsec = 1;
    _minitree->mc_wNgen = 1;
  }
    
  Int_t isprompt0 = -1;
  Int_t isprompt1 = -1;
  
  set<Long64_t> syncEvt;

  cout <<" ================ mode  "  << mode_   <<" ===============================  "<<endl;
  /// setupType has to be passed via config file
  //  photonOverSmearing overSmearICHEP("Test52_ichep");
  photonOverSmearing overSmearHCP( "oversmear_hcp2012" );
  photonOverSmearing overSmear(    _config->setup()    );
  int overSmearSyst = _config->getEnergyOverSmearingSyst();

  Long64_t nbytes = 0, nb = 0;
  ////////////////////////////////////////////////////////////////////////////
  //////////////////////////// Start the loop ////////////////////////////////
  ////////////////////////////////////////////////////////////////////////////
  vector<int>    nEvts;
  vector<string> nCutName;
  nCutName.push_back("TOTAL          :"); nEvts.push_back(0);
  nCutName.push_back("2 gammas       :"); nEvts.push_back(0);
  nCutName.push_back("triggers       :"); nEvts.push_back(0);
  nCutName.push_back("nan weight     :"); nEvts.push_back(0);
  nCutName.push_back("presel kin cuts:"); nEvts.push_back(0);
  nCutName.push_back("pass 2 gam incl:"); nEvts.push_back(0);
  nCutName.push_back("pass all       :"); nEvts.push_back(0);
  nCutName.push_back("   --> pass 2 gam lep: "); nEvts.push_back(0);
  nCutName.push_back("   --> pass 2 gam vbf: "); nEvts.push_back(0);

  vector<int> selVtxSumPt2(3);  selVtxSumPt2[0] = 0; selVtxSumPt2[1] = -1;   selVtxSumPt2[2] = -1;

  for (Long64_t jentry=entry_start; jentry< entry_stop ; ++jentry) {
    Long64_t ientry = LoadTree(jentry);

    if (ientry < -9999) break;
    if( jentry % 10000 == 0) cout<<"processing event "<<jentry<<endl;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    /// reset minitree variables
    _minitree->initEvent();

    // study mc truth block
    if( !isData ) {
      fillMCtruthInfo_HiggsSignal();
      _minitree->fillMCtrueOnly();
    }

    /// reco analysis
    unsigned icutlevel = 0;
    nEvts[icutlevel++]++;
    if( nPho < 2 ) continue; 
    nEvts[icutlevel++]++;
    
    /// set synchronisation flag
    if( syncEvt.find(event) != syncEvt.end() ) DoDebugEvent = true;
    else                                       DoDebugEvent = false;
    if( DoDebugEvent ) _xcheckTextFile << "==========================================================" << endl;
    if( DoDebugEvent ) _xcheckTextFile << "================= debugging event: " << event << endl;
    
    /// PU & BSz reweightings
    if( !isData ) {
      int itpu = 1;  /// 0 without OOT PU - 1 with OOT PU
      _minitree->mc_wPU  = _weight_manager->puW( nPU[itpu] );
     // PUwei  = _weight_manager->puWTrue( puTrue[itpu] );      
    }
    hTotEvents->Fill(1,_minitree->mc_wPU);


    
    bool sigWH = false ;
    bool sigZH = false ;    
    int  mc_whzh_type = 0;
    _minitree->mc_wHQT = 1;
    if( isHiggsSignal ) {
      if ( _weight_manager->getCrossSection()->getMCType() == "vh" ) 
      for( Int_t i=0; i < nMC && i <= 1; ++i ) { 
	  if( abs(mcPID[i]) == 24 ) sigWH=true;
	  if( abs(mcPID[i]) == 23 ) sigZH=true;
	}
      if( sigWH ) mc_whzh_type = 1;
      if( sigZH ) mc_whzh_type = 2;
      
      for( Int_t i=0; i<nMC; ++i)
      if ( abs(mcPID[i]) == 25 ) HiggsMCPt   = mcPt[i];

      if( _weight_manager->getCrossSection()->getMCType() == "ggh" && 
	  _config->setup().find( "ReReco2011" ) != string::npos )
	_minitree->mc_wHQT = getHqTWeight(HiggsMCMass, HiggsMCPt);      
    }
    


    
    if ((mode_ == 2 || mode_ ==1 ||  mode_ == 18 || mode_ == 19) && processID==18) continue;      
    
    // Remove double counting in gamma+jets and QCDjets
    
    Int_t mcIFSR_pho = 0;
    Int_t mcPartonic_pho = 0;
    if (mode_ == 1 || mode_ == 2 || mode_ == 3  ||  mode_ == 18 ||  mode_ == 19 ) {
      for (Int_t i=0; i<nMC; ++i) {    
	if (mcPID[i] == 22 && (fabs(mcMomPID[i]) < 6 || mcMomPID[i] == 21)) mcIFSR_pho++;
	if (mcPID[i] == 22 && mcMomPID[i] == 22) mcPartonic_pho++;
      }
    }
    
    // if pythia is used for diphoton.. no IFSR removing from QCD and Gjets!!!!!!      
    if ((mode_==1 || mode_ == 2  ||   mode_ == 18 ) && mcIFSR_pho >= 1 && mcPartonic_pho >=1) continue;
    if ((mode_ == 3 ||  mode_ == 19 )&& mcIFSR_pho == 2) continue;   

 
    bool prompt2= false;
    bool prompt1= false;
    bool prompt0= false;
    vertProb = -1;
    
    if (mode_ == 2  || mode_ == 1    ||   mode_ == 18     ){
      if      ( mcPartonic_pho >= 1 &&  mcIFSR_pho >= 1 ) prompt2 = true;
      else if ( mcPartonic_pho >= 1 &&  mcIFSR_pho == 0 ) prompt1 = true;
      else if ( mcPartonic_pho == 0 &&  mcIFSR_pho == 0 ) prompt0 = true;
    } else if(mode_ == 3 ||  mode_ == 19   ){
      if      ( mcIFSR_pho >= 2 ) prompt2 = true;
      else if ( mcIFSR_pho == 1 ) prompt1 = true;
      else if ( mcIFSR_pho == 0 ) prompt0 = true;
      if( prompt1 ) _minitree->mc_wXsec = 1.3*_weight_manager->xSecW();
    }
    
    if(mode_==1 || mode_==2 || mode_==3 || mode_==18 || mode_==19){
      if(prompt0)isprompt0=1;
      else isprompt0=0;
      if(prompt1)isprompt1=1;
      else isprompt1=0;
    }
    
    if( mode_ == 20 && isZgamma() ) continue;

    /// wei weight is just temporary and may not contain all info.
    float wei = _minitree->mc_wXsec * _minitree->mc_wPU  
      * _minitree->mc_wNgen * _minitree->mc_wHQT;

    if( isData && !PassTriggerSelection() ) continue;      nEvts[icutlevel++]++;
    if( std::isinf( wei ) || std::isnan( wei ) )continue;  nEvts[icutlevel++]++;
    
    
    
    //// ********************* define S4 variable **********************////
    for( int i=0; i<nPho; ++i){
      if( _config->setup() == "ReReco2011" ) phoS4ratio[i] = 1;
      else                                   phoS4ratio[i] = phoE2x2[i] / phoE5x5[i];
    }
    //// ************************************************************* ////

    if( !isData ) {
      //// ************** MC corrections (mostly MC) ******************* //// 
      // 1. energy shifting / smearing
      for( int i=0; i<nPho; ++i)
	if( fabs(phoSCEta[i]) <= 2.5 ) {
	  float smearing = overSmear.randOverSmearing(phoSCEta[i],phoR9[i],isInGAP_EB(i),overSmearSyst);
	  phoRegrE[i] *= (1 + smearing); 
	  phoE[i]     *= (1 + smearing); 
	  /// from MassFactorized in gglobe:   energyCorrectedError[ipho] *=(l.pho_isEB[ipho]) ? 1.07 : 1.045 ;
	  float smearFactor = 1;
	  if( _config->setup() == "ReReco2011" ) smearFactor = fabs(phoSCEta[i]) < 1.45 ? 1.07: 1.045;
	  phoRegrErr[i] *= smearFactor;
	}  
      
      
      // 2. reweighting of photon id variables (R9...)
      for (int i=0; i<nPho; ++i) ReweightMC_phoIdVar(i);
      //// ************************************************************* ////
    }
    
    //// ********** Apply regression energy ************* ////
    float phoStdE[500];
    for( int i=0; i<nPho; ++i)
      if( fabs(phoSCEta[i]) <= 2.5 ) {
	if( isData ){
	  float enCorrSkim = 1;//enScaleSkimEOS.energyScale( phoR9[i], phoSCEta[i], run);
	  float phoEnScale = enScale.energyScale( phoR9[i], phoSCEta[i], run)/enCorrSkim;
	  phoRegrE[i]  *= phoEnScale;
	  phoE[i]      *= phoEnScale;
	}
	phoStdE[i] = phoE[i];
	phoE[i]   = phoRegrE[i];
	
	/// transform calo position abd etaVtx, phiVtx with SC position
	for( int x = 0 ; x < 3; x++ )  phoCaloPos[i][x] = phoSCPos[i][x];
	for( int ivtx = 0 ; ivtx < nVtxBS; ivtx++ ) {
	  TVector3 xxi = getCorPhotonTVector3(i,ivtx);
	  phoEtaVtx[i][ivtx] = xxi.Eta();
	  phoPhiVtx[i][ivtx] = xxi.Phi();
	}
	
	/// additionnal smearing to go to data energy resolution
	phoRegrSmear[i] = phoE[i]*overSmearHCP.meanOverSmearing(phoSCEta[i],phoR9[i],isInGAP_EB(i),0);
	phoEt[i] = phoE[i] / cosh(phoEta[i]);  
      }    
    //// ************************************************* ////
     

    /// lepton selection
    int iElecVtx(-1), iMuonVtx(-1);
    vector<int> elecIndex = selectElectronsHCP2012( wei, iElecVtx );
    vector<int> muonIndex = selectMuonsHCP2012(     wei, iMuonVtx );

    vector<int>             event_vtx; 
    vector<int>             event_ilead ;
    vector<int>             event_itrail;
    vector<TLorentzVector>  event_plead ;
    vector<TLorentzVector>  event_ptrail;
    TLorentzVector leptag;
    
    int lepCat = -1;
    bool exitLoop = false;
    for( int ii = 0     ; ii < nPho ; ++ii ) {
      for( int jj = (ii+1); jj < nPho ; ++jj ) {
	// Preselection 2nd leg
	if (DoPreselection && !preselectPhoton(ii,phoEt[ii])) continue;
	if (DoPreselection && !preselectPhoton(jj,phoEt[jj])) continue;
	
	/// define i, j locally, so when they are inverted this does not mess up the loop
	int i = ii; 
	int j = jj;
	if(phoEt[j] > phoEt[i]){ i = jj; j = ii; }	  
	
	// Select vertex
	int selVtx  = 0;
	TLorentzVector gi,gj;
	double mij(-1);
	
	vector<int> selVtxIncl;      
	if(_config->vtxSelType()==0)
	  selVtxIncl = getSelectedVertex(i,j,true,true );
	else //use sumpt2 ranking
	  selVtxIncl = selVtxSumPt2;
	selVtx = selVtxIncl[0];
	if( selVtx < 0 ) continue;

	/// check lepton tag
	if( muonIndex.size() > 0 ) {
	  //selVtx = iMuonVtx;	  
	  leptag.SetPtEtaPhiM( muPt[muonIndex[0]], muEta[muonIndex[0]], muPhi[muonIndex[0]],0);
	  if( selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) {
	    lepCat = 0;
	  }
	}
	
	/// check electron tag only if muon tag failed
	if( elecIndex.size() > 0 && lepCat == -1 ) {
	  //selVtx = iElecVtx;
	  leptag.SetPtEtaPhiM( elePt[elecIndex[0]], eleEta[elecIndex[0]], elePhi[elecIndex[0]],0);
	  if( selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) {
	    lepCat = 1;
	    if( fabs( (leptag+gi).M() - 91.19 ) < 10 || fabs( (leptag+gj).M() - 91.19 ) < 10 ) lepCat = -1;
	    /// this is not actually the cut, but it should be but ok (dR(pho,eleTrk) > 1 no dR(pho,anyTrk) > 1 )
	    if(phoCiCdRtoTrk[i] < 1 || phoCiCdRtoTrk[j] <1 ) lepCat = -1;
	  }
	}
	

	if( lepCat >= 0 ) {
	  mij = (gi+gj).M();
          if( _config->analysisType() == "MVA" )
	        if( gi.Pt() / mij < 45./120. || gj.Pt() / mij < 30./120. ) lepCat = -1;
          if( _config->analysisType() == "baselineCiC4PF" )
	        if( gi.Pt() / mij < 45./120. || gj.Pt() < 25. ) lepCat = -1;
	  if( leptag.DeltaR(gi) < 1.0  || leptag.DeltaR(gj) < 1.0  ) lepCat = -1;
	}
	if( lepCat >= 0 ) {
	  cout << " ****** keep leptag event pts[photons] i: " << i << " j: " << j << "   -> event: " << ientry <<  endl;
	  cout << "        leptonCat: " << lepCat << endl;
	  /// if one pair passes lepton tag then no need to go further
	  /// fill in variables
	  event_vtx.resize(   1); event_vtx[0]    = selVtx;
	  event_ilead.resize( 1); event_ilead[0]  = i;
	  event_itrail.resize(1); event_itrail[0] = j;
	  event_plead.resize( 1); event_plead[0]  = gi;
	  event_ptrail.resize(1); event_ptrail[0] = gj;
	  exitLoop = true;
	  break;	
	} else {
	  /// inclusive + VBF + MetTag preselection
	  
	  /// apply kinematic cuts
	  if( !selectTwoPhotons(i,j,selVtx,gi,gj,vetoElec) ) continue;
	  /// drop photon pt cuts from inclusive cuts (add them in categorisation only)
	  mij = (gi+gj).M();	
	  if( ! _config->doSkimming() && 
	      ( gi.Pt()     < _config->pt1Cut() || gi.Pt() < _config->pt2Cut() ||
		gi.Pt()/mij < _config->loosePt1MCut() ||
		gj.Pt()/mij < _config->loosePt2MCut() ) ) continue;
	}
	
	/// here i = lead; j = trail (selectTwoPhotons does that)
	/// fill in variables
	event_vtx.push_back( selVtx );
	event_ilead.push_back(   i  );
	event_itrail.push_back(  j  );
	event_plead.push_back(  gi  );
	event_ptrail.push_back( gj  );   	  
      }
      if( exitLoop ) break;
    }
      
    if(event_ilead.size()==0 || event_itrail.size()==0)continue;
    if(event_vtx.size() == 0 ) continue;  // no pairs selected
    nEvts[icutlevel++]++;

    // Now decide which photon-photon pair in the event to select
    // for lepton tag (size of arrays is 1, so dummy selection)
    unsigned int selectedPair = 0;
    float sumEt = -1;
    for (unsigned int p=0; p < event_vtx.size(); p++) {
      float tempSumEt = event_plead[p].Pt() + event_ptrail[p].Pt();
      if( tempSumEt > sumEt) {
	sumEt = tempSumEt;
      selectedPair = p;
      }
    } 
    

    int ilead  = event_ilead[  selectedPair ];
    int itrail = event_itrail[ selectedPair ];
    int selVtx = event_vtx[    selectedPair ];
    TLorentzVector glead  = event_plead[selectedPair];
    TLorentzVector gtrail = event_ptrail[selectedPair];
    TLorentzVector hcand  = glead + gtrail;

    int CAT4 = cat4(phoR9[ilead], phoR9[itrail], phoSCEta[ilead], phoSCEta[itrail]);
    
    if( glead.Pt()  < _config->pt1Cut() ) continue;
    if( gtrail.Pt() < _config->pt2Cut() ) continue;
    if( hcand.M()   < _config->mggCut() ) continue;
    nEvts[icutlevel++]++;

    _minitree->mtree_runNum = run;
    _minitree->mtree_evtNum = event;
    _minitree->mtree_lumiSec = lumis;

    //    TLorentzVector g1,g2;
    //    g1.SetPtEtaPhiM(phoE[ilead ]/cosh(phoEta[ilead]),phoEta[ilead ], phoPhi[ilead ], 0);
    //    g2.SetPtEtaPhiM(phoE[itrail]/cosh(phoEta[ilead]),phoEta[itrail], phoPhi[itrail], 0);
    //    TLorentzVector lgg = g1 + g2;
    //_minitree->mtree_massDefVtx = lgg.M();
    _minitree->mtree_massDefVtx = hcand.M()/sqrt(phoE[ilead]*phoE[itrail])*sqrt(phoStdE[ilead]*phoStdE[itrail]);

    // calc again vertex to get correct vertex probability (can be different from last one in loop)
    vector<int> sortedVertex;
    if(_config->vtxSelType()==0)
      sortedVertex = getSelectedVertex( ilead, itrail, true, true );
    else //use sumpt2 ranking
      sortedVertex = selVtxSumPt2;

    if( sortedVertex.size() < 2 ) sortedVertex.push_back(-1);
    if( sortedVertex.size() < 3 ) sortedVertex.push_back(-1);

    if( lepCat >= 0 ) {
      /// lepton tag
      sortedVertex[0] = selVtx;  
      sortedVertex[1] = -1; 
      sortedVertex[2] = -1; 
      //      vertProb = 1;
    } 

    _minitree->mtree_rho   = rho2012;
    _minitree->mtree_rho25 = rho25;    
    _minitree->mtree_zVtx  = vtxbs[selVtx][2];
    _minitree->mtree_nVtx  = nVtxBS;
    _minitree->mtree_ivtx1 = selVtx;
    _minitree->mtree_ivtx2 = sortedVertex[1];
    _minitree->mtree_ivtx3 = sortedVertex[2];
    _minitree->mtree_vtxProb = vertProb;
    _minitree->mtree_vtxMva  = vertMVA;

    _minitree->mtree_mass  = hcand.M();
    _minitree->mtree_pt    = hcand.Pt();
    _minitree->mtree_piT   = hcand.Pt()/hcand.M();
    _minitree->mtree_y     = hcand.Rapidity();

    /// spin variables
    TLorentzVector gtmp1 = glead;  gtmp1.Boost( -hcand.BoostVector() );
    TLorentzVector gtmp2 = gtrail; gtmp2.Boost( -hcand.BoostVector() );
    _minitree->mtree_cThetaLead_heli  = cos( gtmp1.Angle(hcand.BoostVector()) );
    _minitree->mtree_cThetaTrail_heli = cos( gtmp2.Angle(hcand.BoostVector()) );
    _minitree->mtree_cThetaStar_CS    = 2*(glead.E()*gtrail.Pz() - gtrail.E()*glead.Pz())/(hcand.M()*sqrt(hcand.M2()+hcand.Pt()*hcand.Pt()));
    
    /// fill photon id variables in main tree
    _minitree->mtree_minR9      = +999;
    _minitree->mtree_minPhoIdEB = +999;
    _minitree->mtree_minPhoIdEE = +999;
    _minitree->mtree_maxSCEta   =   -1;
    _minitree->mtree_minSCEta   = +999;
    for( int i = 0 ; i < 2; i++ ) {
      int ipho = -1;
      if( i == 0 ) ipho = ilead;
      if( i == 1 ) ipho = itrail;
      fillPhotonVariablesToMiniTree( ipho, selVtx, i );      
      if( _minitree->mtree_r9[i] < _minitree->mtree_minR9 ) _minitree->mtree_minR9 = _minitree->mtree_r9[i];
      if( fabs( _minitree->mtree_sceta[i] ) <  1.5 &&  _minitree->mtree_mvaid[i] <  _minitree->mtree_minPhoIdEB ) _minitree->mtree_minPhoIdEB = _minitree->mtree_mvaid[i];
      if( fabs( _minitree->mtree_sceta[i] ) >= 1.5 &&  _minitree->mtree_mvaid[i] <  _minitree->mtree_minPhoIdEE ) _minitree->mtree_minPhoIdEE = _minitree->mtree_mvaid[i];
      if( fabs( _minitree->mtree_sceta[i] ) > _minitree->mtree_maxSCEta ) _minitree->mtree_maxSCEta =  fabs(_minitree->mtree_sceta[i]);
      if( fabs( _minitree->mtree_sceta[i] ) < _minitree->mtree_minSCEta ) _minitree->mtree_minSCEta =  fabs(_minitree->mtree_sceta[i]);
    }
    
    //------------ compute diphoton mva (add var to minitree inside function) ----------------//
    massResoCalc.setP4CalPosVtxResoSmear( glead,gtrail, 
					  TVector3(phoCaloPos[ilead ][0], phoCaloPos[ilead ][1],phoCaloPos[ilead ][2]),
					  TVector3(phoCaloPos[itrail][0], phoCaloPos[itrail][1],phoCaloPos[itrail][2]),
					  TVector3(vtxbs[selVtx][0], vtxbs[selVtx][1], vtxbs[selVtx][2]),
					  _minitree->mtree_relResOverE, _minitree->mtree_relSmearing );

    
    _minitree->mtree_massResoTot = massResoCalc.relativeMassResolutionFab_total( vertProb );    
    _minitree->mtree_massResoEng = massResoCalc.relativeMassResolutionFab_energy( );    
    _minitree->mtree_massResoAng = massResoCalc.relativeMassResolutionFab_angular();    
   
    float diphotonmva = DiPhoID_MVA( glead, gtrail, hcand, massResoCalc, vertProb, 
				     _minitree->mtree_mvaid[0],_minitree->mtree_mvaid[1] );

    
    // ---- Start categorisation ---- //
    _minitree->mtree_lepTag  = 0;
    _minitree->mtree_metTag  = 0;
    _minitree->mtree_vbfTag  = 0;
    _minitree->mtree_hvjjTag = 0;

    // 1. lepton tag
    if( lepCat >= 0 ) {
      _minitree->mtree_lepTag = 1;
      _minitree->mtree_lepCat = lepCat;
      _minitree->mtree_fillLepTree  = true;
      // if( lepCat == 0 ) fillMuonTagVariables(lepTag,glead,gtrail,elecIndex[0],selVtx);
      // if( lepCat == 1 ) fillElecTagVariables(lepTag,glead,gtrail,muonIndex[0],selVtx);
    }

    // 3. met tag (For the jet energy regression, MET needs to be corrected first.)
    _minitree->mtree_rawMet    = recoPfMET;
    _minitree->mtree_rawMetPhi = recoPfMETPhi;
    //    if( !isData ) {
      /// bug in data skim, met correction already applied
      //3.1 Soft Jet correction (FC?)    
      applyJEC4SoftJets();
      //3.2 smearing
      if( !isData ) METSmearCorrection(ilead, itrail);
      //3.3 shifting (even in data? but different in data and MC)
      METPhiShiftCorrection();
      //3.4 scaling
      if( isData) METScaleCorrection(ilead, itrail);
      //    }
    _minitree->mtree_corMet    = recoPfMET;
    _minitree->mtree_corMetPhi = recoPfMETPhi;
    
    // 2. dijet tag
    Int_t nVtxJetID = -1;
    if( _config->doPUJetID() ) nVtxJetID = nVtxBS;
    //vector<int> goodJetsIndex = selectJets( ilead, itrail, nVtxJetID, wei, selVtx );
    vector<int> goodJetsIndex = selectJetsJEC(  ilead, itrail, nVtxJetID, wei, selVtx );
    int vbftag(-1),hstratag(-1),catjet(-1);
    dijetSelection( glead, gtrail, goodJetsIndex, wei, selVtx, vbftag, hstratag, catjet);
    _minitree->mtree_vbfTag  = vbftag;
    _minitree->mtree_hvjjTag = hstratag;
    _minitree->mtree_vbfCat  = catjet;      

    // 2x. radion analysis

    // take the very same photon candidates as in the H->GG analysis above
    _minitree->radion_evtNum = event;
    *(_minitree->radion_gamma1) = glead;
    *(_minitree->radion_gamma2) = gtrail;

    vector<int> goodJetsIndexRadion = selectJetsRadion(nVtxJetID, selVtx);
    _minitree->radion_bJetTags->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_genJetPt        ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_eta             ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_cef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_mef		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nconstituents	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_chf		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_JECUnc	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_ptLeadTrack	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtxPt		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtx3dL	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptPtCut	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_dPhiMETJet	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_nch		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtx3deL	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_vtxMass	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_ptRaw		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_EnRaw		  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptptRelCut->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_SoftLeptdRCut	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_partonID	  ->Set(goodJetsIndexRadion.size());
    _minitree->radion_jet_dRJetGenJet         ->Set(goodJetsIndexRadion.size());
    _minitree->radion_MET = recoPfMET;
    _minitree->radion_rho25 = rho25;

    for (unsigned i = 0; i < goodJetsIndexRadion.size(); i++) {
      int iJet = goodJetsIndexRadion[i];

      //_minitree->radion_bJetTags->AddAt(jetCombinedSecondaryVtxMVABJetTags[iJet], i);
      _minitree->radion_bJetTags->AddAt(jetCombinedSecondaryVtxBJetTags[iJet], i);
      _minitree->radion_jet_genJetPt         ->AddAt(jetGenJetPt[iJet], i);
      _minitree->radion_jet_eta              ->AddAt(jetEta[iJet], i);
      _minitree->radion_jet_cef		     ->AddAt(jetCEF[iJet], i);
      _minitree->radion_jet_nef		     ->AddAt(jetNEF[iJet], i);
      _minitree->radion_jet_mef		     ->AddAt(jetMEF[iJet], i);
      _minitree->radion_jet_nconstituents    ->AddAt(jetNConstituents[iJet], i);
      _minitree->radion_jet_chf		     ->AddAt(jetCHF[iJet], i);
      _minitree->radion_jet_JECUnc	     ->AddAt(jetJECUnc[iJet], i);
      _minitree->radion_jet_ptLeadTrack	     ->AddAt(jetLeadTrackPt[iJet], i);
      _minitree->radion_jet_vtxPt	     ->AddAt(jetVtxPt[iJet], i);
      _minitree->radion_jet_vtx3dL	     ->AddAt(jetVtx3dL[iJet], i);
      _minitree->radion_jet_SoftLeptPtCut    ->AddAt(jetSoftLeptPt[iJet], i);
      _minitree->radion_jet_nch		     ->AddAt(jetNCH[iJet], i);
      _minitree->radion_jet_vtx3deL	     ->AddAt(jetVtx3deL[iJet], i);
      _minitree->radion_jet_vtxMass	     ->AddAt(jetVtxMass[iJet], i);
      _minitree->radion_jet_ptRaw	     ->AddAt(jetRawPt[iJet], i);
      _minitree->radion_jet_EnRaw	     ->AddAt(jetRawEn[iJet], i);
      _minitree->radion_jet_SoftLeptptRelCut ->AddAt(jetSoftLeptPtRel[iJet], i);
      _minitree->radion_jet_SoftLeptdRCut    ->AddAt(jetSoftLeptdR[iJet], i);
      _minitree->radion_jet_partonID	     ->AddAt(jetPartonID[iJet], i);
      _minitree->radion_jet_dRJetGenJet      ->AddAt(sqrt(pow(jetEta[iJet]-jetGenEta[iJet],2)+pow(jetPhi[iJet]-jetGenPhi[iJet],2)), i);
      float tmpPi = 3.1415927, tmpDPhi=fabs(jetPhi[iJet]-recoPfMETPhi);
      if(tmpDPhi>tmpPi) tmpDPhi=2*tmpPi-tmpDPhi;
      _minitree->radion_jet_dPhiMETJet	     ->AddAt(tmpDPhi, i);

      TLorentzVector* jet = new((*(_minitree->radion_jets))[_minitree->radion_jets->GetEntriesFast()]) TLorentzVector();
      jet->SetPtEtaPhiE(jetPt[iJet], jetEta[iJet], jetPhi[iJet], jetEn[iJet]);
    }

    // Continue step 3.
    if (  MetTagSelection(glead,gtrail,goodJetsIndex) && _minitree->mtree_vbfTag == 0 && _minitree->mtree_lepTag == 0   && 
	 _minitree->mtree_corMet > 70.  &&	 
	 fabs( phoSCEta[ilead] ) < 1.45 && fabs( phoSCEta[itrail]) < 1.45 ) _minitree->mtree_metTag = 1;

    //----------- categorisation (for now incl + vbf + lep + met) -----------//
    _minitree->mtree_catBase = CAT4;
    _minitree->mtree_catMva  = -1;
    for( int icat_mva = 0 ; icat_mva < 4; icat_mva++ )
      if( diphotonmva >= Ddipho_cat[icat_mva] ) { _minitree->mtree_catMva = icat_mva; break; }
    if       ( _minitree->mtree_lepTag == 1 ) {
      _minitree->mtree_catBase = _minitree->mtree_lepCat + 6;
      _minitree->mtree_catMva  = _minitree->mtree_lepCat + 6;
    } else if( _minitree->mtree_vbfTag == 1 ) {
      _minitree->mtree_catBase = _minitree->mtree_vbfCat + 4;
      _minitree->mtree_catMva  = _minitree->mtree_vbfCat + 4;
    } else if( _minitree->mtree_metTag == 1 ) {
      _minitree->mtree_catBase = 8;
      _minitree->mtree_catMva  = 8;
    }
    if( diphotonmva < Ddipho_cat[3] )  _minitree->mtree_catMva  = -1;
    
    /// photon pt cut was dropped from the inclusive cuts
    if(  _minitree->mtree_catMva  < 4 && (glead.Pt()/hcand.M() < 1./3. || gtrail.Pt()/hcand.M() < 1./4.) ) 
       _minitree->mtree_catMva  = -1;

    if(  _minitree->mtree_catBase < 4 && (glead.Pt()/hcand.M() < 1./3. || gtrail.Pt()/hcand.M() < 1./4.) ) 
       _minitree->mtree_catBase  = -1;
    
    //------------ MC weighting factors and corrections    
    if( !isData ) {
      /// needs to be recomputed for each event (because reinit var for each event)
      _minitree->mc_wNgen = 100000./_weight_manager->getNevts();
      _minitree->mc_wXsec  = _weight_manager->xSecW(mc_whzh_type);      
      if( ( mode_ == 3 ||  mode_ == 19 ) && isprompt1 == 1 ) _minitree->mc_wXsec  *= 1.3;
      _minitree->mc_wBSz   = _weight_manager->bszW(vtxbs[selVtx][2]-mcVtx[0][2]);
      _minitree->mc_wVtxId = _weight_manager->vtxPtCorrW( hcand.Pt() );
      
      /// photon identification
      float wPhoId[] = { 1., 1.};
      for( int i = 0 ; i < 2; i++ ) {
	wPhoId[i] = 1;
	int index = -1;
	if( i == 0 ) index = ilead;
	if( i == 1 ) index = itrail;
	wPhoId[i] *= _weight_manager->phoIdPresel(phoR9[index],phoSCEta[index]);
	if( _config->analysisType() == "baselineCiC4PF" ) wPhoId[i] *= _weight_manager->phoIdCiC(phoR9[index],phoSCEta[index]);
	if( _config->analysisType() == "MVA"            ) wPhoId[i] *= _weight_manager->phoIdMVA(phoR9[index],phoSCEta[index]);
	if( vetoElec[i] ) wPhoId[i] *= _weight_manager->phoIdEleVeto(phoR9[index],phoSCEta[index]);	      
      }
      _minitree->mc_wPhoEffi   = wPhoId[0]*wPhoId[1];
      
      /// trigger efficiency
      _minitree->mc_wTrigEffi = 0.9968; /// FIX ME

      /// cross section volontary not included in total weight
      _minitree->mc_wei = 
	_minitree->mc_wPU       *
	_minitree->mc_wBSz      *
	_minitree->mc_wHQT      *  /// = 1 but in 2011
	_minitree->mc_wVtxId    *
	_minitree->mc_wPhoEffi  *
	_minitree->mc_wTrigEffi *
	_minitree->mc_wNgen;

      wei =  _minitree->mc_wei;
    }
    nEvts[icutlevel++]++;
    if( _minitree->mtree_lepTag ) nEvts[icutlevel+0]++;
    if( _minitree->mtree_vbfTag ) nEvts[icutlevel+1]++;
    
    //// following crap can be removed when the synchornization will be successfull. 
    if( DoDebugEvent ) {
      _minitree->setSynchVariables();
      _xcheckTextFile << " pho1 pos: " << phoPos[ilead]  << endl;
      _xcheckTextFile << " ieta1 : " << phoSeedDetId1[ilead] << " iphi1: " << phoSeedDetId2[ilead] << endl;
      _xcheckTextFile << " pho2 pos: " << phoPos[itrail] << endl;
      _xcheckTextFile << " ieta1 : " << phoSeedDetId1[itrail] << " iphi1: " << phoSeedDetId2[itrail] << endl;

      _xcheckTextFile << " oversmear 1: " << overSmear.meanOverSmearing(phoSCEta[ilead],phoR9[ilead]  ,isInGAP_EB(ilead),0) << endl;
      _xcheckTextFile << " oversmear 2: " << overSmear.meanOverSmearing(phoSCEta[itrail],phoR9[itrail],isInGAP_EB(itrail),0) << endl;
      _xcheckTextFile << " mass reso (eng only): " << _minitree->mtree_massResoEng << endl;
      _xcheckTextFile << " mass reso (ang only): " << _minitree->mtree_massResoAng << endl;

      for( unsigned i = 0 ; i < _minitree->sync_iName.size(); i++ )
	cout  << _minitree->sync_iName[i] << ":" << *_minitree->sync_iVal[i]  << "  ";
      for( unsigned i = 0 ; i < _minitree->sync_lName.size(); i++ )
	cout << _minitree->sync_lName[i] << ":" << *_minitree->sync_lVal[i]  << "  ";
      for( unsigned i = 0 ; i < _minitree->sync_fName.size(); i++ )
	cout << _minitree->sync_fName[i] << ":" << *_minitree->sync_fVal[i]  << "  ";
      cout << endl;	
      

      cout << "  myVtx = " << selVtx << "; 1=" << sortedVertex[1] << " 2= " << sortedVertex[2] << endl;
      for( int ivtx = 0; ivtx < nVtxBS; ivtx++ ) {
	cout << " etas[ ivtx = " << ivtx << "] = " << phoEtaVtx[ilead][ivtx] << " - " << phoEtaVtx[itrail][ivtx] << "  - zVtx = " << vtxbs[ivtx][2] << endl;

      }
    }

    _minitree->fill();    
    if( _config->doSkimming() && tSkim ) {
      /// undo all modifs before filling the skim
      fChain->GetEntry(jentry);
      tSkim->Fill();
    }
    //---------------      
    
  //   }    
  }// end for entry
  if( _config->doSkimming() ) {
    _minitree->mtree_file->cd();
    TH1F *hEvents = new TH1F("hEvents","hEvents",2,0,2);
    hEvents->SetBinContent(1,_weight_manager->getNevts());
    hEvents->SetBinContent(2,nEvts[nEvts.size()-1]);
    hEvents->Write();
    tSkim->Write();
    _minitree->mtree_file->Close();
  } else  _minitree->end();

  for( unsigned icut = 0 ; icut < nEvts.size(); icut++ )
    cout << nCutName[icut] << nEvts[icut] << endl;
  
  delete rnd;  

  return nEvts[nEvts.size()-1];
}
예제 #18
0
void Ntp1Analyzer_QG::Loop()
{


   DEBUG_VERBOSE_ = false;

   if (fChain == 0) return;


   Long64_t nentries;

   if( DEBUG_ ) nentries = 100000;
   else nentries = fChain->GetEntries();


   Long64_t nbytes = 0, nb = 0;

   TRandom3 rand;

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
     Long64_t ientry = LoadTree(jentry);
     if (ientry < 0) break;
     nb = fChain->GetEntry(jentry);   nbytes += nb;
     // if (Cut(ientry) < 0) continue;

if( DEBUG_VERBOSE_ ) std::cout << "entry n." << jentry << std::endl;

     if( (jentry%100000) == 0 ) std::cout << "Event #" << jentry  << " of " << nentries << std::endl;


   //HLT_Mu11_ = this->PassedHLT("HLT_Mu11");
   //HLT_Ele17_SW_EleId_L1R_ = this->PassedHLT("HLT_Ele17_SW_EleId_L1R");
   //HLT_DoubleMu3_ = this->PassedHLT("HLT_DoubleMu3");

     run_ = runNumber;
     LS_ = lumiBlock;
     event_ = eventNumber;
     eventWeight_ = -1.; //default
     nvertex_ = nPV;
     rhoPF_ = rhoFastjet;

     if( !isGoodEvent(jentry) ) continue; //this takes care also of integrated luminosity and trigger

     if( nPV==0 ) continue;
     bool goodVertex = (ndofPV[0] >= 4.0 && sqrt(PVxPV[0]*PVxPV[0]+PVyPV[0]*PVyPV[0]) < 2. && fabs(PVzPV[0]) < 24. );
     if( !goodVertex ) continue;
  
     for( unsigned iBX=0; iBX<nBX; ++iBX ) {
       if( bxPU[iBX]==0 ) nPU_ = nPU[iBX]; 
     }


     ptHat_ = (isMC_) ? genPtHat : ptHat_;

     if( isMC_ ) 
       if( (ptHat_ > ptHatMax_) || (ptHat_ < ptHatMin_) ) continue;


     bool noLeptons = false;
     TLorentzVector lept1MC, lept2MC;
     int zIndexqq=-1;
     int zIndexll=-1;



     // -----------------------------
     //      FROM NOW ON RECO
     // -----------------------------




     // ------------------
     // MUONS
     // ------------------

     std::vector<TLorentzVector> muons;
     int chargeFirstMuon;

     for( unsigned int iMuon=0; iMuon<nMuon && (muons.size()<2); ++iMuon ) {

       TLorentzVector thisMuon( pxMuon[iMuon], pyMuon[iMuon], pzMuon[iMuon], energyMuon[iMuon] );

       // --------------
       // kinematics:
       // --------------
       if( thisMuon.Pt() < 20. ) continue;


       // --------------
       // ID:
       // --------------
       if( !( (muonIdMuon[iMuon]>>8)&1 ) ) continue; //GlobalMuonPromptTight
       if( !( (muonIdMuon[iMuon]>>11)&1 ) ) continue; //AllTrackerMuons
       if( pixelHitsTrack[trackIndexMuon[iMuon]]==0 ) continue;


       // to compute dxy, look for primary vertex:
       int hardestPV = -1;
       float sumPtMax = 0.0;
       for(int v=0; v<nPV; v++) {
         if(SumPtPV[v] > sumPtMax) {
           sumPtMax = SumPtPV[v];
           hardestPV = v;
         }
       }  
   
       float dxy;
       if( hardestPV==-1 ) {
         dxy = 0.;
       } else {
         dxy = fabs(trackDxyPV(PVxPV[hardestPV], PVyPV[hardestPV], PVzPV[hardestPV],
                              trackVxTrack[trackIndexMuon[iMuon]], trackVyTrack[trackIndexMuon[iMuon]], trackVzTrack[trackIndexMuon[iMuon]],
                              pxTrack[trackIndexMuon[iMuon]], pyTrack[trackIndexMuon[iMuon]], pzTrack[trackIndexMuon[iMuon]]));
       }

       if( dxy > 0.02 ) continue;


       float dz = fabs(trackVzTrack[trackIndexMuon[iMuon]]-PVzPV[hardestPV]);
       if(dz > 1.0) continue;



       // --------------
       // isolation:
       // --------------
       // (this is sum pt tracks)
       //if( sumPt03Muon[iMuon] >= 3. ) continue;
       // combined isolation < 15%:
       if( (sumPt03Muon[iMuon] + emEt03Muon[iMuon] + hadEt03Muon[iMuon]) >= 0.15*thisMuon.Pt() ) continue;



       // for now simple selection, will have to optimize this (T&P?)
       if( muons.size()==0 ) {
         muons.push_back( thisMuon );
         chargeFirstMuon = chargeMuon[iMuon];
       } else {
         if( chargeMuon[iMuon]==chargeFirstMuon ) continue;
         if( fabs(muons[0].Eta())>2.1 && fabs(thisMuon.Eta())>2.1 ) continue;
         muons.push_back(thisMuon);
       }

     } //for muons



     // ------------------
     // ELECTRONS
     // ------------------

     std::vector<TLorentzVector> electrons;
     int chargeFirstEle = 0;
     bool firstPassedVBTF80 = false;

     for( unsigned int iEle=0; (iEle<nEle) && (electrons.size()<2); ++iEle ) {

       TLorentzVector thisEle( pxEle[iEle], pyEle[iEle], pzEle[iEle], energyEle[iEle] );

       // --------------
       // kinematics:
       // --------------
       if( thisEle.Pt() < 20. ) continue;
       if( (fabs(thisEle.Eta()) > 2.5) || ( fabs(thisEle.Eta())>1.4442 && fabs(thisEle.Eta())<1.566) ) continue;


       Float_t dr03TkSumPt_thresh95;
       Float_t dr03EcalRecHitSumEt_thresh95;
       Float_t dr03HcalTowerSumEt_thresh95;
       Float_t combinedIsoRel_thresh95;
       Float_t sigmaIetaIeta_thresh95;
       Float_t deltaPhiAtVtx_thresh95;
       Float_t deltaEtaAtVtx_thresh95;
       Float_t hOverE_thresh95;

       Float_t dr03TkSumPt_thresh80;
       Float_t dr03EcalRecHitSumEt_thresh80;
       Float_t dr03HcalTowerSumEt_thresh80;
       Float_t combinedIsoRel_thresh80;
       Float_t sigmaIetaIeta_thresh80;
       Float_t deltaPhiAtVtx_thresh80;
       Float_t deltaEtaAtVtx_thresh80;
       Float_t hOverE_thresh80;

       if( fabs(thisEle.Eta())<1.4442 ) {
         dr03TkSumPt_thresh95 = 0.15;
         dr03EcalRecHitSumEt_thresh95 = 2.;
         dr03HcalTowerSumEt_thresh95 = 0.12;
         combinedIsoRel_thresh95 = 0.15;

         dr03TkSumPt_thresh80 = 0.09;
         dr03EcalRecHitSumEt_thresh80 = 0.07;
         dr03HcalTowerSumEt_thresh80 = 0.10;
         combinedIsoRel_thresh80 = 0.07;

         sigmaIetaIeta_thresh95 = 0.01;
         deltaPhiAtVtx_thresh95 = 0.8;
         deltaEtaAtVtx_thresh95 = 0.007;
         hOverE_thresh95 = 0.15;

         sigmaIetaIeta_thresh80 = 0.01;
         deltaPhiAtVtx_thresh80 = 0.06;
         deltaEtaAtVtx_thresh80 = 0.004;
         hOverE_thresh80 = 0.04;
       } else {
         dr03TkSumPt_thresh95 = 0.08;
         dr03EcalRecHitSumEt_thresh95 = 0.06;
         dr03HcalTowerSumEt_thresh95 = 0.05;
         combinedIsoRel_thresh95 = 0.1;

         dr03TkSumPt_thresh80 = 0.04;
         dr03EcalRecHitSumEt_thresh80 = 0.05;
         dr03HcalTowerSumEt_thresh80 = 0.025;
         combinedIsoRel_thresh80 = 0.06;

         sigmaIetaIeta_thresh80 = 0.03;
         deltaPhiAtVtx_thresh80 = 0.7;
         deltaEtaAtVtx_thresh80 = 0.007;
         hOverE_thresh80 = 0.025;

         sigmaIetaIeta_thresh95 = 0.03;
         deltaPhiAtVtx_thresh95 = 0.7;
         deltaEtaAtVtx_thresh95 = 0.01; 
         hOverE_thresh95 = 0.07;
       }


       // --------------
       // isolation:
       // --------------
     //// no relative iso, using combined
     //if( dr03TkSumPtEle[iEle]/thisEle.Pt() > dr03TkSumPt_thresh ) continue;
     //if( dr03EcalRecHitSumEtEle[iEle]/thisEle.Pt() > dr03EcalRecHitSumEt_thresh ) continue;
     //if( dr03HcalTowerSumEtEle[iEle]/thisEle.Pt() > dr03HcalTowerSumEt_thresh ) continue;

       Float_t combinedIsoRel;
       if( fabs(thisEle.Eta())<1.4442 )
         combinedIsoRel = ( dr03TkSumPtEle[iEle] + TMath::Max(0., dr03EcalRecHitSumEtEle[iEle] - 1.) + dr03HcalTowerSumEtEle[iEle] ) / thisEle.Pt();
       else
         combinedIsoRel = ( dr03TkSumPtEle[iEle] + dr03EcalRecHitSumEtEle[iEle] + dr03HcalTowerSumEtEle[iEle] ) / thisEle.Pt();

       bool iso_VBTF95 = (combinedIsoRel < combinedIsoRel_thresh95);
       bool iso_VBTF80 = (combinedIsoRel < combinedIsoRel_thresh80);

       
       // --------------
       // electron ID:
       // --------------
       bool eleID_VBTF95 = (covIEtaIEtaSC[iEle] < sigmaIetaIeta_thresh95) &&
                           (fabs(deltaPhiAtVtxEle[iEle]) < deltaPhiAtVtx_thresh95) &&
                           (fabs(deltaEtaAtVtxEle[iEle]) < deltaEtaAtVtx_thresh95) &&
                           (hOverEEle[iEle] < hOverE_thresh95);

       bool eleID_VBTF80 = (covIEtaIEtaSC[iEle] < sigmaIetaIeta_thresh80) &&
                           (fabs(deltaPhiAtVtxEle[iEle]) < deltaPhiAtVtx_thresh80) &&
                           (fabs(deltaEtaAtVtxEle[iEle]) < deltaEtaAtVtx_thresh80) &&
                           (hOverEEle[iEle] < hOverE_thresh80);

       bool passed_VBTF95 = (iso_VBTF95 && eleID_VBTF95);
       bool passed_VBTF80 = (iso_VBTF80 && eleID_VBTF80);


       if( !passed_VBTF95 ) continue;

       // check that not matched to muon (clean electrons faked by muon MIP):
       bool matchedtomuon=false;
       for( std::vector<TLorentzVector>::iterator iMu=muons.begin(); iMu!=muons.end(); ++iMu )
         if( iMu->DeltaR(thisEle)<0.1 ) matchedtomuon=true;

       if( matchedtomuon ) continue;


       // for now simple selection, will have to optimize this (T&P?)
       // one electron required to pass VBTF80, the other VBTF95
       if( electrons.size()==0 ) {
         electrons.push_back( thisEle );
         chargeFirstEle = chargeEle[iEle];
         if( passed_VBTF80 ) firstPassedVBTF80 = true;
       } else if( chargeEle[iEle] != chargeFirstEle && ( firstPassedVBTF80||passed_VBTF80 ) ) {
         electrons.push_back( thisEle );
       }


     } //for electrons


     if( requireLeptons_ )
       if( electrons.size() < 2 && muons.size() < 2 ) continue;


     std::vector< TLorentzVector > leptons;

     if( electrons.size() == 2 && muons.size() == 2 ) { //veto H->ZZ->4l

       continue;

     } else if( electrons.size() == 2 ) {

       leptType_ = 1;

       if( electrons[0].Pt() > electrons[1].Pt() ) {

         leptons.push_back( electrons[0] );
         leptons.push_back( electrons[1] );

       } else {

         leptons.push_back( electrons[1] );
         leptons.push_back( electrons[0] );

       }

     } else if( muons.size() == 2 ) {

       leptType_ = 0;

       if( muons[0].Pt() > muons[1].Pt() ) {

         leptons.push_back( muons[0] );
         leptons.push_back( muons[1] );

       } else {

         leptons.push_back( muons[1] );
         leptons.push_back( muons[0] );

       }

     } else {

     //std::cout << "There must be an error this is not possible." << std::endl;
     //exit(9101);

     }

     
     eLept1_ = (leptons.size()>0) ? leptons[0].Energy() : 0.;
     ptLept1_ = (leptons.size()>0) ? leptons[0].Pt() : 0.;
     etaLept1_ = (leptons.size()>0) ? leptons[0].Eta() : 0.;
     phiLept1_ = (leptons.size()>0) ? leptons[0].Phi() : 0.;
     
     eLept2_ = (leptons.size()>1) ? leptons[1].Energy() : 0.;
     ptLept2_ = (leptons.size()>1) ? leptons[1].Pt() : 0.;
     etaLept2_ = (leptons.size()>1) ? leptons[1].Eta() : 0.;
     phiLept2_ = (leptons.size()>1) ? leptons[1].Phi() : 0.;


     // --------------------
     // match leptons to MC:
     // --------------------
     int correctIdMc = (leptType_==0 ) ? 13 : 11;

     for( unsigned iLept=0; iLept<leptons.size(); ++iLept ) {

       float deltaRmin = 100.;
       TLorentzVector matchedLeptonMC;

       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         if( statusMc[iMc]==1 && fabs(idMc[iMc])==correctIdMc && idMc[mothMc[mothMc[iMc]]]==23 ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );
           float thisDeltaR = leptons[iLept].DeltaR( *thisParticle );
           if( thisDeltaR < deltaRmin ) {
             deltaRmin = thisDeltaR;
             matchedLeptonMC = *thisParticle;
           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc


     } //for i leptons



     // ------------------
     // JETS
     // ------------------

     float jetPt_thresh = 20.;

     // first save leading jets in event:
     std::vector<AnalysisJet> leadJets;
     std::vector<int> leadJetsIndex; //index in the event collection (needed afterwards for PFCandidates)


     if( chargedHadronSubtraction_ ) {

       for( unsigned int iJet=0; iJet<nAK5PFNoPUJet; ++iJet ) {

         AnalysisJet thisJet( pxAK5PFNoPUJet[iJet], pyAK5PFNoPUJet[iJet], pzAK5PFNoPUJet[iJet], energyAK5PFNoPUJet[iJet] );

         // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
         if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

         // far away from leptons:
         if( leptons.size()>0 )
           if( thisJet.DeltaR( leptons[0] ) <= 0.5 ) continue;
         if( leptons.size()>1 )
           if( thisJet.DeltaR( leptons[1] ) <= 0.5 ) continue;

         thisJet.nCharged = chargedHadronMultiplicityAK5PFNoPUJet[iJet] +
                            electronMultiplicityAK5PFNoPUJet[iJet] + 
                            muonMultiplicityAK5PFNoPUJet[iJet];
         thisJet.nNeutral = neutralHadronMultiplicityAK5PFNoPUJet[iJet] +
                            photonMultiplicityAK5PFNoPUJet[iJet] + 
                            HFHadronMultiplicityAK5PFNoPUJet[iJet] +
                            HFEMMultiplicityAK5PFNoPUJet[iJet];
         thisJet.ptD = ptDAK5PFNoPUJet[iJet];
         thisJet.rmsCand = rmsCandAK5PFNoPUJet[iJet];

         thisJet.axis1 = axis1AK5PFNoPUJet[iJet];
         thisJet.axis2 = axis2AK5PFNoPUJet[iJet];
         thisJet.pull = pullAK5PFNoPUJet[iJet];
         thisJet.tana = tanaAK5PFNoPUJet[iJet];

         thisJet.ptD_QC = ptD_QCAK5PFNoPUJet[iJet];
         thisJet.rmsCand_QC = rmsCand_QCAK5PFNoPUJet[iJet];
         thisJet.axis1_QC = axis1_QCAK5PFNoPUJet[iJet];
         thisJet.axis2_QC = axis2_QCAK5PFNoPUJet[iJet];
         thisJet.pull_QC = pull_QCAK5PFNoPUJet[iJet];
         thisJet.tana_QC = tana_QCAK5PFNoPUJet[iJet];

         thisJet.nChg_ptCut = nChg_ptCutAK5PFNoPUJet[iJet];
         thisJet.nChg_QC = nChg_QCAK5PFNoPUJet[iJet];
         thisJet.nChg_ptCut_QC = nChg_ptCut_QCAK5PFNoPUJet[iJet];
         thisJet.nNeutral_ptCut = nNeutral_ptCutAK5PFNoPUJet[iJet];

         thisJet.Rchg = RchgAK5PFNoPUJet[iJet];
         thisJet.Rneutral = RneutralAK5PFNoPUJet[iJet];
         thisJet.R = RAK5PFNoPUJet[iJet];
         thisJet.Rchg_QC = Rchg_QCAK5PFNoPUJet[iJet];

         thisJet.pTMax = pTMaxAK5PFNoPUJet[iJet];
         thisJet.pTMaxChg = pTMaxChgAK5PFNoPUJet[iJet];
         thisJet.pTMaxNeutral = pTMaxNeutralAK5PFNoPUJet[iJet];
         thisJet.pTMaxChg_QC = pTMaxChg_QCAK5PFNoPUJet[iJet];

         thisJet.betastar = betastarAK5PFNoPUJet[iJet];


         leadJets.push_back(thisJet);
         leadJetsIndex.push_back(iJet);


       } //for jets

     } else { // 'normal' PFJets:

       for( unsigned int iJet=0; iJet<nAK5PFPUcorrJet; ++iJet ) {

         AnalysisJet thisJet( pxAK5PFPUcorrJet[iJet], pyAK5PFPUcorrJet[iJet], pzAK5PFPUcorrJet[iJet], energyAK5PFPUcorrJet[iJet] );

         // save at least 3 lead jets (if event has them) and all jets with pt>thresh:
         if( leadJets.size()>=3 && thisJet.Pt()<jetPt_thresh ) break;

         // far away from leptons:
         if( leptons.size()>0 )
           if( thisJet.DeltaR( leptons[0] ) <= 0.5 ) continue;
         if( leptons.size()>1 )
           if( thisJet.DeltaR( leptons[1] ) <= 0.5 ) continue;

         thisJet.nCharged = chargedHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            electronMultiplicityAK5PFPUcorrJet[iJet] + 
                            muonMultiplicityAK5PFPUcorrJet[iJet];
         thisJet.nNeutral = neutralHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            photonMultiplicityAK5PFPUcorrJet[iJet] + 
                            HFHadronMultiplicityAK5PFPUcorrJet[iJet] +
                            HFEMMultiplicityAK5PFPUcorrJet[iJet];
         thisJet.ptD = ptDAK5PFPUcorrJet[iJet];
         thisJet.rmsCand = rmsCandAK5PFPUcorrJet[iJet];

         thisJet.axis1 = axis1AK5PFPUcorrJet[iJet];
         thisJet.axis2 = axis2AK5PFPUcorrJet[iJet];
         thisJet.pull = pullAK5PFPUcorrJet[iJet];
         thisJet.tana = tanaAK5PFPUcorrJet[iJet];

         thisJet.ptD_QC = ptD_QCAK5PFPUcorrJet[iJet];
         thisJet.rmsCand_QC = rmsCand_QCAK5PFPUcorrJet[iJet];
         thisJet.axis1_QC = axis1_QCAK5PFPUcorrJet[iJet];
         thisJet.axis2_QC = axis2_QCAK5PFPUcorrJet[iJet];
         thisJet.pull_QC = pull_QCAK5PFPUcorrJet[iJet];
         thisJet.tana_QC = tana_QCAK5PFPUcorrJet[iJet];

         thisJet.nChg_ptCut = nChg_ptCutAK5PFPUcorrJet[iJet];
         thisJet.nChg_QC = nChg_QCAK5PFPUcorrJet[iJet];
         thisJet.nChg_ptCut_QC = nChg_ptCut_QCAK5PFPUcorrJet[iJet];
         thisJet.nNeutral_ptCut = nNeutral_ptCutAK5PFPUcorrJet[iJet];

         thisJet.Rchg = RchgAK5PFPUcorrJet[iJet];
         thisJet.Rneutral = RneutralAK5PFPUcorrJet[iJet];
         thisJet.R = RAK5PFPUcorrJet[iJet];
         thisJet.Rchg_QC = Rchg_QCAK5PFPUcorrJet[iJet];

         thisJet.pTMax = pTMaxAK5PFPUcorrJet[iJet];
         thisJet.pTMaxChg = pTMaxChgAK5PFPUcorrJet[iJet];
         thisJet.pTMaxNeutral = pTMaxNeutralAK5PFPUcorrJet[iJet];
         thisJet.pTMaxChg_QC = pTMaxChg_QCAK5PFPUcorrJet[iJet];

         thisJet.betastar = betastarAK5PFPUcorrJet[iJet];


         leadJets.push_back(thisJet);
         leadJetsIndex.push_back(iJet);

       } //for jets

     } //if/else CHS


     nJet_ = 0;
     nPart_ = 0;


     for( unsigned iJet=0; iJet<leadJets.size(); ++iJet ) {
   
       AnalysisJet thisJet = leadJets[iJet];

       // --------------
       // kinematics:
       // --------------
       if( thisJet.Pt() < jetPt_thresh ) continue;
       //if( fabs(thisJet.Eta()) > 2.4 ) continue;


       if( nJet_ < 20 ) {

         eJet_[nJet_] = leadJets[nJet_].Energy();
         ptJet_[nJet_] = leadJets[nJet_].Pt();
         etaJet_[nJet_] = leadJets[nJet_].Eta();
         phiJet_[nJet_] = leadJets[nJet_].Phi();
         nCharged_[nJet_] = leadJets[nJet_].nCharged;
         nNeutral_[nJet_] = leadJets[nJet_].nNeutral;
         ptD_[nJet_] = leadJets[nJet_].ptD;
         rmsCand_[nJet_] = leadJets[nJet_].rmsCand;

         axis1_[nJet_] = thisJet.axis1;
         axis2_[nJet_] = thisJet.axis2;
         pull_[nJet_] = thisJet.pull;
         tana_[nJet_] = thisJet.tana;

         ptD_QC_[nJet_] = thisJet.ptD_QC;
         rmsCand_QC_[nJet_] = thisJet.rmsCand_QC;
         axis1_QC_[nJet_] = thisJet.axis1_QC;
         axis2_QC_[nJet_] = thisJet.axis2_QC;
         pull_QC_[nJet_] = thisJet.pull_QC;
         tana_QC_[nJet_] = thisJet.tana_QC;

         nChg_ptCut_[nJet_] = thisJet.nChg_ptCut;
         nChg_QC_[nJet_] = thisJet.nChg_QC;
         nChg_ptCut_QC_[nJet_] = thisJet.nChg_ptCut_QC;
         nNeutral_ptCut_[nJet_] = thisJet.nNeutral_ptCut;

         Rchg_[nJet_] = thisJet.Rchg;
         Rneutral_[nJet_] = thisJet.Rneutral;
         R_[nJet_] = thisJet.R;
         Rchg_QC_[nJet_] = thisJet.Rchg_QC;

         pTMax_[nJet_] = thisJet.pTMax;
         pTMaxChg_[nJet_] = thisJet.pTMaxChg;
         pTMaxNeutral_[nJet_] = thisJet.pTMaxNeutral;
         pTMaxChg_QC_[nJet_] = thisJet.pTMaxChg_QC;

         betastar_[nJet_] = thisJet.betastar;

         // match to gen jet:
         float deltaR_genJet_best = 999.;
         TLorentzVector foundGenJet;
         for( unsigned iGenJet=0; iGenJet<nAK5GenJet; ++iGenJet ) {

           TLorentzVector* thisGenJet = new TLorentzVector( pxAK5GenJet[iGenJet], pyAK5GenJet[iGenJet], pzAK5GenJet[iGenJet], energyAK5GenJet[iGenJet] );
           
           if( thisGenJet->Pt()<3. ) continue;
           float deltaR = thisGenJet->DeltaR(leadJets[nJet_]);

           if( deltaR<deltaR_genJet_best ) {
             deltaR_genJet_best = deltaR;
             foundGenJet = *thisGenJet;
           }
           
         } //for genjets

         if( deltaR_genJet_best<999. ) {

           eJetGen_[nJet_]   = foundGenJet.Energy();
           ptJetGen_[nJet_]  = foundGenJet.Pt();
           etaJetGen_[nJet_] = foundGenJet.Eta();
           phiJetGen_[nJet_] = foundGenJet.Phi();

         } else {

           eJetGen_[nJet_]   = 0.;
           ptJetGen_[nJet_]  = 0.;
           etaJetGen_[nJet_] = 0.;
           phiJetGen_[nJet_] = 0.;

         } 

         nJet_++;
          
       } //if less than 20

            
     } //for i



     if( isMC_ ) {

       // store event partons in tree:
       for( unsigned iMc=0; iMc<nMc; ++iMc ) {

         if( statusMc[iMc]==3 && (fabs(idMc[iMc])<=6 || idMc[iMc]==21) ) {

           TLorentzVector* thisParticle = new TLorentzVector();
           thisParticle->SetPtEtaPhiE( pMc[iMc]*sin(thetaMc[iMc]), etaMc[iMc], phiMc[iMc], energyMc[iMc] );

           if( nPart_<20 ) {

             ptPart_[nPart_] = thisParticle->Pt();
             etaPart_[nPart_] = thisParticle->Eta();
             phiPart_[nPart_] = thisParticle->Phi();
             ePart_[nPart_] = thisParticle->Energy();
             pdgIdPart_[nPart_] = idMc[iMc];

             nPart_++;

           } else {
      
             std::cout << "Found more than 20 partons, skipping." << std::endl;

           }

           delete thisParticle;
           thisParticle = 0;

         } //if correct id mc

       } // for i mc

     } // if is mc


     reducedTree_->Fill(); 


   } //for entries

} //loop