Example #1
0
void smearEmEnergy( const EnergyScaleCorrection_class& egcor, TLorentzVector& p, const ZGTree& myTree, float r9 ) {

    float smearSigma =  egcor.getSmearingSigma(myTree.run, fabs(p.Eta())<1.479, r9, p.Eta(), p.Pt(), 0., 0.);
    float cor = myRandom_.Gaus( 1., smearSigma );
    p.SetPtEtaPhiM( p.Pt()*cor, p.Eta(), p.Phi(), p.M() );

}
Example #2
0
void fillCorrectEtaBin(TH1D* hist[nEtaBins], TLorentzVector sumVect, double phiSR, TH1D* polHist[nEtaBins][nPhisrBins], double polarization, TH1D* etaHist[nEtaBins]){
	
	for (int iEta = 0; iEta < nEtaBins; iEta++)
	{
		if (sumVect.Eta() >= etaBinStart[iEta] && sumVect.Eta() < etaBinEnd[iEta])
		{
			hist[iEta]->Fill(phiSR);
			etaHist[iEta]->Fill(sumVect.Eta());

			int phiSRbin = hist[iEta]->FindBin(phiSR);			
			polHist[iEta][phiSRbin-1]->Fill(polarization);
		}
	}
}
Example #3
0
void rochcor::momcor_data( TLorentzVector& mu, float charge, float sysdev, int runopt, float& qter){
  
  float ptmu = mu.Pt();

  float muphi = mu.Phi();
  float mueta = mu.Eta(); // same with mu.Eta() in Root

  float px = mu.Px();
  float py = mu.Py();
  float pz = mu.Pz();
  float e = mu.E();
  
  int mu_phibin = phibin(muphi);
  int mu_etabin = etabin(mueta);
  
  //float mptsys1 = sran.Gaus(0.0,sysdev);
  
  float dm = 0.0;
  float da = 0.0;
  
  if(runopt==0){
    dm = (dcor_bfA[mu_phibin][mu_etabin] + mptsys_da_dm[mu_phibin][mu_etabin]*dcor_bfAer[mu_phibin][mu_etabin])/dmavgA[mu_phibin][mu_etabin];
    da = dcor_maA[mu_phibin][mu_etabin] + mptsys_da_da[mu_phibin][mu_etabin]*dcor_maAer[mu_phibin][mu_etabin];
  }else if(runopt==1){
    dm = (dcor_bfB[mu_phibin][mu_etabin] + mptsys_da_dm[mu_phibin][mu_etabin]*dcor_bfBer[mu_phibin][mu_etabin])/dmavgB[mu_phibin][mu_etabin];
    da = dcor_maB[mu_phibin][mu_etabin] + mptsys_da_da[mu_phibin][mu_etabin]*dcor_maBer[mu_phibin][mu_etabin];
  }
  
  float cor = 1.0/(1.0 + dm + charge*da*ptmu);
  
  px *= cor;
  py *= cor;
  pz *= cor;
  e  *= cor;
  
  //after Z pt correction
  float recm = 0.0;
  float gscler = 0.0;
  
  if(runopt==0){
    recm = drecmA;
    gscler = TMath::Sqrt( TMath::Power(dgsclA_stat,2) + TMath::Power(dgsclA_syst,2) );
  }else if(runopt==1){
    recm = drecmB;
    gscler = TMath::Sqrt( TMath::Power(dgsclB_stat,2) + TMath::Power(dgsclB_syst,2) );
  }
  
  float gscl = (genm_smr/recm);
  
  px *= (gscl + gscler_da_dev*gscler);
  py *= (gscl + gscler_da_dev*gscler);
  pz *= (gscl + gscler_da_dev*gscler);
  e  *= (gscl + gscler_da_dev*gscler);
  
  float momscl = sqrt(px*px + py*py)/ptmu;
  qter *= momscl;

  mu.SetPxPyPzE(px,py,pz,e);
  
}
Example #4
0
void ZgSelectData::printEvent(int index_e1, int index_e2, int index_pho, vector<Float_t> elePt_){
	cout << "PassedZeeGamma: run " << run << " event " << event << " rho " << rho << endl ;
	cout << "electron :index,pt,eta,phi,En " << endl ;
	cout << index_e1 << " , " << elePt_[index_e1] << " , " << eleEta[index_e1] ;
	cout << " , " << elePhi[index_e1] << " , " << eleEn[index_e1] << endl ;
	cout << index_e2 << " , " << elePt_[index_e2] << " , " << eleEta[index_e2] ;
	cout << " , " << elePhi[index_e2] << " , " << eleEn[index_e2] << endl ;

	cout << "Electron Pass " << endl ;
	cout << "TrackIso " << eleIsoTrkDR03[index_e1] << " EcalIso " << eleIsoEcalDR03[index_e1] << " HcalSolidIso ";
	cout << eleIsoHcalSolidDR03[index_e1] << " passID = " << elePassID(index_e1,3,elePt_) << endl ;
	cout << "TrackIso " << eleIsoTrkDR03[index_e2] << " EcalIso " << eleIsoEcalDR03[index_e2] << " HcalSolidIso ";
	cout << eleIsoHcalSolidDR03[index_e2] << " passID = " << elePassID(index_e2,3,elePt_) <<  endl ;
	TLorentzVector ve1, ve2, vZ ;
	ve1.SetPtEtaPhiE(elePt[index_e1],eleEta[index_e1],elePhi[index_e1],eleEn[index_e1]);
	ve2.SetPtEtaPhiE(elePt[index_e2],eleEta[index_e2],elePhi[index_e2],eleEn[index_e2]);
	vZ = ve1 + ve2 ;
	
	cout << "ZMass = " << vZ.M() << endl ;

	cout << "Photon : index, pt, eta, phi, dr1, dr2 " << endl ;
	TLorentzVector vp ;
	vp.SetPtEtaPhiM(phoEt[index_pho],phoEta[index_pho],phoPhi[index_pho],0);
	cout << index_pho << " , " << vp.Pt() << " , " << vp.Eta() << " , " << vp.Phi() ;
	cout << " , " << vp.DeltaR(ve1) << " , " << vp.DeltaR(ve2) << endl ;
	cout << "=================================================================" << endl ;

}
Example #5
0
void UEAnalysisMPI::mpiAnalysisRECO(float weight,float etaRegion,float ptThreshold,TClonesArray * TracksJet)
{
  std::vector<TLorentzVector*> JetRECO;
  JetRECO.clear();
  
  for(int j=0;j<TracksJet->GetSize();++j){
    TLorentzVector *v = (TLorentzVector*)TracksJet->At(j);
    if(fabs(v->Eta())<etaRegion){
      JetRECO.push_back(v);
    }
  }
  
  std::vector<AssociatedObject> assoJetRECO;
  assoJetRECO.clear();

  while(JetRECO.size()>1){
    int oldSize = JetRECO.size();
    std::vector<TLorentzVector*>::iterator itH = JetRECO.begin();
    if((*itH)->Pt()>=ptThreshold){
      for(std::vector<TLorentzVector*>::iterator it=JetRECO.begin();it!=JetRECO.end();it++){
	float azimuthDistanceJet = fabs( (*itH)->Phi() - (*it)->Phi() );
	if((*it)->Pt()/(*itH)->Pt()>=0.3){
	  if( (piG - rangePhi) <  azimuthDistanceJet && azimuthDistanceJet < (piG + rangePhi)) {
	    AssociatedObject tmpPair((*itH),(*it));
	    assoJetRECO.push_back(tmpPair);
	    JetRECO.erase(it);
	    int newSize = oldSize -1;
	    oldSize = newSize;
	    JetRECO.resize(newSize);
	    break;
	  }
	}
      }
    }
    JetRECO.erase(itH);
    int newSize = oldSize -1;
    JetRECO.resize(newSize);
  }
  
  if(assoJetRECO.size()){
    fNumbMPIRECO->Fill(assoJetRECO.size());
    std::vector<AssociatedObject>::iterator at= assoJetRECO.begin();
    
    const TLorentzVector* leadingJet((*at).first);
    const TLorentzVector* secondJet((*at).second);

    pPtRatio_vs_PtJleadRECO->Fill(leadingJet->Pt(),(secondJet->Pt()/leadingJet->Pt()));
    pPtRatio_vs_EtaJleadRECO->Fill(fabs(leadingJet->Eta()),(secondJet->Pt()/leadingJet->Pt()));
    pPtRatio_vs_PhiJleadRECO->Fill(leadingJet->Phi(),(secondJet->Pt()/leadingJet->Pt()));
    
    fdEtaLeadingPairRECO->Fill(leadingJet->Eta()-secondJet->Eta());
    float dPhiJet = fabs(leadingJet->Phi()-secondJet->Phi());
    if(dPhiJet> piG) dPhiJet = 2*piG -dPhiJet;
    dPhiJet = (180*dPhiJet)/piG;
    fdPhiLeadingPairRECO->Fill(dPhiJet);
    fptRatioLeadingPairRECO->Fill(secondJet->Pt()/leadingJet->Pt());
  }
}
Example #6
0
void rochcor2012::momcor_mc( TLorentzVector& mu, float charge, float sysdev, int runopt,bool sync=false){
  
  //sysdev == num : deviation = num

  float ptmu = mu.Pt();
  float muphi = mu.Phi();
  float mueta = mu.Eta(); // same with mu.Eta() in Root

  float px = mu.Px();
  float py = mu.Py();
  float pz = mu.Pz();
  float e = mu.E();

  int mu_phibin = phibin(muphi);
  int mu_etabin = etabin(mueta);

  //float mptsys = sran.Gaus(0.0,sysdev);
  
  float dm = (mcor_bf[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfer[mu_phibin][mu_etabin])/mmavg[mu_phibin][mu_etabin];
  float da = mcor_ma[mu_phibin][mu_etabin] + mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maer[mu_phibin][mu_etabin];
  
  float cor = 1.0/(1.0 + dm + charge*da*ptmu);

  //for the momentum tuning - eta,phi,Q correction
  px *= cor;
  py *= cor;
  pz *= cor;
  e *= cor;
  
  float gscler = 0.0;
  float deltaer = 0.0;
  float sfer = 0.0;
  
  gscler = TMath::Sqrt( TMath::Power(mgscl_stat,2) + TMath::Power(mgscl_syst,2) );
  deltaer = TMath::Sqrt( TMath::Power(delta_stat,2) + TMath::Power(delta_syst,2) );
  sfer = TMath::Sqrt( TMath::Power(sf_stat,2) + TMath::Power(sf_syst,2) );

  float tune;
  if (sync) tune = 1.0/(1.0 + (delta + sysdev*deltaer)*sqrt(px*px + py*py)*(1.0 + (sf + sysdev*sfer)));
  else tune = 1.0/(1.0 + (delta + sysdev*deltaer)*sqrt(px*px + py*py)*eran.Gaus(1.0,(sf + sysdev*sfer)));
  
  px *= (tune);
  py *= (tune);
  pz *= (tune);
  e *= (tune);
  
  float gscl = (genm_smr/mrecm);
  
  px *= (gscl + gscler_mc_dev*gscler);
  py *= (gscl + gscler_mc_dev*gscler);
  pz *= (gscl + gscler_mc_dev*gscler);
  e *= (gscl + gscler_mc_dev*gscler);

  mu.SetPxPyPzE(px,py,pz,e);
  
}
Example #7
0
void printJet(Jet *jet)
{

  GenParticle *particle;
  Muon *muon;

  Track *track;
  Tower *tower;

  TObject *object;
  TLorentzVector momentum;
      momentum.SetPxPyPzE(0.0, 0.0, 0.0, 0.0);
      //TRefArray constituentarray(jet->Constituents);
      TRefArray particlearray(jet->Particles);
      cout<<"Looping over jet constituents. Jet pt: "<<jet->PT<<", eta: "<<jet->Eta<<", phi: "<<jet->Phi<<endl;      

      // Loop over all jet's constituents
      for(Int_t j = 0; j < jet->Constituents.GetEntriesFast(); ++j)
      {
        object = jet->Constituents.At(j);
        // Check if the constituent is accessible
        if(object == 0) continue;

        if(object->IsA() == GenParticle::Class())
        {
          particle = (GenParticle*) object;
          cout << "    GenPart pt: " << particle->PT << ", eta: " << particle->Eta << ", phi: " << particle->Phi << endl;
          momentum += particle->P4();
        }
        else if(object->IsA() == Track::Class())
        {
          track = (Track*) object;
          cout << "    Track pt: " << track->PT << ", eta: " << track->Eta << ", phi: " << track->Phi << endl;
          momentum += track->P4();
        }
        else if(object->IsA() == Tower::Class())
        {
          tower = (Tower*) object;
          cout << "    Tower pt: " << tower->ET << ", eta: " << tower->Eta << ", phi: " << tower->Phi << endl;
          momentum += tower->P4();
        }
        else if(object->IsA() == Muon::Class())
        {
          muon = (Muon*) object;
          cout << "    Muon pt: " << muon->PT << ", eta: " << muon->Eta << ", phi: " << muon->Phi << endl;
          momentum += muon->P4();
        }
      }
      cout << " constituent sum pt:  " << momentum.Pt() <<" eta "<< momentum.Eta()  <<"  phi " << momentum.Phi() << std::endl;


      for (Int_t j =0; j<jet->Particles.GetEntries();  j++){
     		GenParticle *p_tmp = (GenParticle*) particlearray.At(j);
		printGenParticle(p_tmp);
	}
}
Example #8
0
void rochcor2012::momcor_mc( TLorentzVector& mu, float charge, float sysdev, int runopt, float& qter){
  
  //sysdev == num : deviation = num

  float ptmu = mu.Pt();
  float muphi = mu.Phi();
  float mueta = mu.Eta(); // same with mu.Eta() in Root

  float px = mu.Px();
  float py = mu.Py();
  float pz = mu.Pz();
  float e = mu.E();

  int mu_phibin = phibin(muphi);
  int mu_etabin = etabin(mueta);

  //float mptsys = sran.Gaus(0.0,sysdev);
  
  float Mf = (mcor_bf[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfer[mu_phibin][mu_etabin])/(mpavg[mu_phibin][mu_etabin]+mmavg[mu_phibin][mu_etabin]);
  float Af = ((mcor_ma[mu_phibin][mu_etabin]+mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maer[mu_phibin][mu_etabin]) - Mf*(mpavg[mu_phibin][mu_etabin]-mmavg[mu_phibin][mu_etabin]));     
  
  float cor = 1.0/(1.0 + 2.0*Mf + charge*Af*ptmu);
  
  //for the momentum tuning - eta,phi,Q correction
  px *= cor;
  py *= cor;
  pz *= cor;
  e  *= cor;
  
  float gscler = mgscl_stat;
  float deltaer = delta_stat;
  float sfer = sf_stat;
    
  float gscl = (genm_smr/mrecm);
  
  px *= (gscl + gscler_mc_dev*gscler);
  py *= (gscl + gscler_mc_dev*gscler);
  pz *= (gscl + gscler_mc_dev*gscler);
  e  *= (gscl + gscler_mc_dev*gscler);
  
  float momscl = sqrt(px*px + py*py)/ptmu;
  
  float tune = 1.0/(1.0 + (delta + sysdev*deltaer)*sqrt(px*px + py*py)*eran.Gaus(1.0,(sf + sysdev*sfer)));
  
  px *= (tune); 
  py *= (tune);  
  pz *= (tune);  
  e  *= (tune);   
  
  qter *= (momscl*momscl + (1.0-tune)*(1.0-tune));
  
  mu.SetPxPyPzE(px,py,pz,e);
  
}
Example #9
0
double Histogrammer::minDrPhoB(int PhoInd, EventTree* tree){
	// find the closest b-jet
	TLorentzVector b;
	TLorentzVector bBar;
	int phoGen=-1;
	double mindr = 999.0;
	for( int mcI = 0; mcI < tree->nMC_; ++mcI){
		if( tree->mcIndex->at(mcI) == tree->phoGenIndex_->at(PhoInd) ) 
			phoGen=mcI;
		if( tree->mcPID->at(mcI) == 5) 
			b.SetPtEtaPhiM(tree->mcPt->at(mcI), tree->mcEta->at(mcI), tree->mcPhi->at(mcI), tree->mcMass->at(mcI));
		if( tree->mcPID->at(mcI) == -5) 
			bBar.SetPtEtaPhiM(tree->mcPt->at(mcI), tree->mcEta->at(mcI), tree->mcPhi->at(mcI), tree->mcMass->at(mcI));
	}
	if( phoGen > 0 && b.Pt() > 0.0001 && bBar.Pt() > 0.0001 ) {
		mindr = std::min(dR(tree->mcEta->at(phoGen), tree->mcPhi->at(phoGen), b.Eta(), b.Phi()),
						 dR(tree->mcEta->at(phoGen), tree->mcPhi->at(phoGen), bBar.Eta(), bBar.Phi()));
	}
	return mindr;
}
Example #10
0
TLorentzVector selectPhoton( const ZGConfig& cfg, const ZGTree& myTree, int index, const TLorentzVector& lept0, const TLorentzVector& lept1, EnergyScaleCorrection_class egcor ) {

    TLorentzVector photon;
    if( myTree.ngamma<=index ) {
        photon.SetPtEtaPhiM( 0.01, 0., 0., 0. );
        return photon;
    }
    photon.SetPtEtaPhiM( myTree.gamma_pt[index], myTree.gamma_eta[index], myTree.gamma_phi[index], myTree.gamma_mass[index] );

    // photon energy corrections/smearing
    if( !myTree.isData ) {
        if( cfg.smearing() ) {
            smearEmEnergy( egcor, photon, myTree, myTree.gamma_r9[0] );
        }
    } else {
        if( cfg.smearing() ) {
            applyEmEnergyScale( egcor, photon, myTree, myTree.gamma_r9[0] );
        }
    }

    bool goodPhoton = true;
    if( photon.Pt()<40. ) goodPhoton=false;
    if( fabs(photon.Eta())>1.4442 && fabs(photon.Eta())<1.566 ) goodPhoton=false;
    if( fabs(photon.Eta())>2.5 ) goodPhoton=false;
    if( myTree.gamma_idCutBased[index]==0 ) goodPhoton=false;
    if( myTree.gamma_chHadIso[index]>2.5 ) goodPhoton=false;
    if( fabs(myTree.gamma_eta[index])<1.44 ) {
        if( myTree.gamma_sigmaIetaIeta[index]>0.0102 ) goodPhoton=false;
    } else {
        if( myTree.gamma_sigmaIetaIeta[index]>0.0274 ) goodPhoton=false;
    }
    float deltaR_thresh = 0.4;
    if( photon.DeltaR(lept0)<deltaR_thresh || photon.DeltaR(lept1)<deltaR_thresh ) goodPhoton=false;


    if( !goodPhoton )
        photon.SetPtEtaPhiM( 0.01, 0., 0., 0. );

    return photon;

}
void rochcor2012::momcor_data( TLorentzVector& mu, float charge, int runopt, float& qter){
  
  float ptmu = mu.Pt();

  float muphi = mu.Phi();
  float mueta = mu.Eta(); // same with mu.Eta() in Root

  float px = mu.Px();
  float py = mu.Py();
  float pz = mu.Pz();
  float e = mu.E();
  
  int mu_phibin = phibin(muphi);
  int mu_etabin = etabin(mueta);

  float Mf = 0.0;
  float Af = 0.0;

  if(runopt==0){
    Mf = (dcor_bf[mu_phibin][mu_etabin]+mptsys_da_dm[mu_phibin][mu_etabin]*dcor_bfer[mu_phibin][mu_etabin])/(dpavg[mu_phibin][mu_etabin]+dmavg[mu_phibin][mu_etabin]);
    Af = ((dcor_ma[mu_phibin][mu_etabin]+mptsys_da_da[mu_phibin][mu_etabin]*dcor_maer[mu_phibin][mu_etabin]) - Mf*(dpavg[mu_phibin][mu_etabin]-dmavg[mu_phibin][mu_etabin]));     
  }else if(runopt==1){
    Mf = (dcor_bfD[mu_phibin][mu_etabin]+mptsys_da_dm[mu_phibin][mu_etabin]*dcor_bfDer[mu_phibin][mu_etabin])/(dpavgD[mu_phibin][mu_etabin]+dmavgD[mu_phibin][mu_etabin]);
    Af = ((dcor_maD[mu_phibin][mu_etabin]+mptsys_da_da[mu_phibin][mu_etabin]*dcor_maDer[mu_phibin][mu_etabin]) - Mf*(dpavgD[mu_phibin][mu_etabin]-dmavgD[mu_phibin][mu_etabin]));     
  }
  
  float cor = 1.0/(1.0 + 2.0*Mf + charge*Af*ptmu);
  
  px *= cor;
  py *= cor;
  pz *= cor;
  e  *= cor;
  
  //after Z pt correction
  float gscler = dgscl_stat;
  float gscl = (genm_smr/drecm);
  
  px *= (gscl + gscler_da_dev*gscler);
  py *= (gscl + gscler_da_dev*gscler);
  pz *= (gscl + gscler_da_dev*gscler);
  e  *= (gscl + gscler_da_dev*gscler);
  
  float momscl = sqrt(px*px + py*py)/ptmu;
  qter *= momscl;
  
  mu.SetPxPyPzE(px,py,pz,e);
  
}
Example #12
0
void rochcor::momcor_data( TLorentzVector& mu, float charge, float sysdev, int runopt){
  
  float ptmu = mu.Pt();

  float muphi = mu.Phi();
  float mueta = mu.Eta(); // same with mu.Eta() in Root

  float px = mu.Px();
  float py = mu.Py();
  float pz = mu.Pz();
  float e = mu.E();
  
  int mu_phibin = phibin(muphi);
  int mu_etabin = etabin(mueta);
  
  //float mptsys1 = sran.Gaus(0.0,sysdev);
  
  float dm = (dcor_bf[mu_phibin][mu_etabin] + mptsys_da_dm[mu_phibin][mu_etabin]*dcor_bfer[mu_phibin][mu_etabin])/dmavg[mu_phibin][mu_etabin];
  float da = dcor_ma[mu_phibin][mu_etabin] + mptsys_da_da[mu_phibin][mu_etabin]*dcor_maer[mu_phibin][mu_etabin];
  
  float cor = 1.0/(1.0 + dm + charge*da*ptmu);
  
  px *= cor;
  py *= cor;
  pz *= cor;
  e  *= cor;
  
  //after Z pt correction
  float gscler = 0.0;
  
  gscler = TMath::Sqrt( TMath::Power(dgscl_stat,2) + TMath::Power(dgscl_syst,2) );
  
  float gscl = (genm_smr/drecm);
  
  px *= (gscl + gscler_da_dev*gscler);
  py *= (gscl + gscler_da_dev*gscler);
  pz *= (gscl + gscler_da_dev*gscler);
  e  *= (gscl + gscler_da_dev*gscler);
  
  mu.SetPxPyPzE(px,py,pz,e);
  
}
void smearEmEnergy( TLorentzVector& p ) {

    float smearEBlowEta     = 0.013898;
    float smearEBhighEta    = 0.0189895;
    float smearEElowEta     = 0.027686;
    float smearEEhighEta    = 0.031312;
    float theGaussMean      = 1.;
    float pt = p.Pt();
    float eta = p.Eta();
    float phi = p.Phi();
    float mass = p.M();
    float theSmear = 0.;
    if      (fabs(eta)<1.                   )  theSmear = smearEBlowEta;
    else if (fabs(eta)>=1.  && fabs(eta)<1.5)  theSmear = smearEBhighEta;
    else if (fabs(eta)>=1.5 && fabs(eta)<2. )  theSmear = smearEElowEta;
    else if (fabs(eta)>=2.  && fabs(eta)<2.5)  theSmear = smearEEhighEta;
    float fromGauss = myRandom_.Gaus(theGaussMean,theSmear);
    p.SetPtEtaPhiM( fromGauss*pt, eta, phi, mass ); // keep mass and direction same

}
Example #14
0
void Output_Delphes::AnalyseParticles(ExRootTreeBranch *branch, const HepMC::GenEvent& evt)
{
  TRootC::GenParticle *element;
  TLorentzVector momentum;
  Double_t signPz;
  ReadStats();
  for(int n=1; n<=evt.particles_size(); n++) {
    int mo1, mo2, da1, da2, status, pid;
    getStatsFromTuple(mo1,mo2,da1,da2,status,pid,n);
    element = static_cast<TRootC::GenParticle*>(branch->NewEntry());
    element->PID = pid;
    element->Status = status;
    element->M1 = mo1 - 1; // added -1 as the numbering in the tree starts from 0
    element->M2 = mo2 - 1;
    element->D1 = da1 - 1;
    element->D2 = da2 - 1;
    element->E = index_to_particle[n]->momentum().e();
    element->Px = index_to_particle[n]->momentum().px();
    element->Py = index_to_particle[n]->momentum().py();
    element->Pz = index_to_particle[n]->momentum().pz();
    element->PT = sqrt(pow(element->Px,2)+pow(element->Py,2));
    momentum.SetPxPyPzE(element->Px, element->Py, element->Pz, element->E);
    signPz = (element->Pz >= 0.0) ? 1.0 : -1.0;
    element->Eta = element->PT < 1e-6 ? signPz*999.9 : momentum.Eta();
    element->Phi = index_to_particle[n]->momentum().phi();
    HepMC::GenVertex* vrtI = (index_to_particle[n])->production_vertex();
    HepMC::GenVertex::particles_in_const_iterator partI;
    if(vrtI) {
      element->T = vrtI->position().t();
      element->X = vrtI->position().x();
      element->Y = vrtI->position().y();
      element->Z = vrtI->position().z();
    }
    else {
      element->T = 0.;
      element->X = 0.;
      element->Y = 0.;
      element->Z = 0.;
    }  
  }
}
void AnalyseParticles(LHEF::Reader *reader, ExRootTreeBranch *branch)
{
  const LHEF::HEPEUP &hepeup = reader->hepeup;

  Int_t particle;
  Double_t signPz, cosTheta;

  TLorentzVector momentum;

  TRootLHEFParticle *element;

  for(particle = 0; particle < hepeup.NUP; ++particle)
  {
    element = (TRootLHEFParticle*) branch->NewEntry();

    element->PID = hepeup.IDUP[particle];
    element->Status = hepeup.ISTUP[particle];
    element->Mother1 = hepeup.MOTHUP[particle].first;
    element->Mother2 = hepeup.MOTHUP[particle].second;
    element->ColorLine1 = hepeup.ICOLUP[particle].first;
    element->ColorLine2 = hepeup.ICOLUP[particle].second;
    element->Px = hepeup.PUP[particle][0];
    element->Py = hepeup.PUP[particle][1];
    element->Pz = hepeup.PUP[particle][2];
    element->E = hepeup.PUP[particle][3];
    element->M = hepeup.PUP[particle][4];

    momentum.SetPxPyPzE(element->Px, element->Py, element->Pz, element->E);

    cosTheta = TMath::Abs(momentum.CosTheta());
    signPz = (momentum.Pz() >= 0.0) ? 1.0 : -1.0;

    element->PT = momentum.Perp();
    element->Eta = (cosTheta == 1.0 ? signPz*999.9 : momentum.Eta());
    element->Phi = (cosTheta == 1.0 ? signPz*999.9 : momentum.Rapidity());
    element->Rapidity = (cosTheta == 1.0 ? signPz*999.9 : momentum.Rapidity());

    element->LifeTime = hepeup.VTIMUP[particle];
    element->Spin = hepeup.SPINUP[particle];
  }
}
std::vector<double> CalculateDeltaEtaAndPhi(bool possibleMultW, bool possibleMultAntiW, int w1, TLorentzVector TL_munu){

  //Don't take into account the events with multiple W's. Think of something

  double deltaphi, deltaeta;
  if(possibleMultW == false && possibleMultAntiW == false){
    deltaphi = TMath::Abs(TVector2::Phi_mpi_pi(TL_munu.Phi() - genPhi[w1]) );
     deltaeta = TMath::Abs(TL_munu.Eta() - genEta[w1] );
  } else {
    deltaphi = 99.;
    deltaeta = 99.;
  }

  std::vector<double> EtaAndPhi;

  EtaAndPhi.push_back(deltaeta);
  EtaAndPhi.push_back(deltaphi);

  return EtaAndPhi;

}
void xAna_ele_subleading_ele_pt_optimize(TString inputFile, TCanvas *c1 , TCanvas *c2 , TCanvas *c3 ,TCanvas *c4 ,TCanvas *c5 , TCanvas *c6 ,
int mass_point ,double eff,double eff_err, TString dir_name, int dir_flag ,int signal_background_flag, int background_file_index ){


  // define histograms

  TString title2 = Form("ele pT for Zprime mass = %d",mass_point);
  TString title3 = Form("lepton pairs' pT for Zprime mass = %d",mass_point);
  TString title4 = Form("SD mass for Zprime mass = %d",mass_point);
  TString title5 = Form("Z mass for Zprime mass = %d",mass_point);
  TString title6 = Form("Zprime mass for Zprime mass = %d",mass_point);

  TH1D* h_ele_pT = new TH1D("h_ele_pT", title2 ,3000 , 0,3000 );
  TH1D* h_lepton_pair_pT = new TH1D("h_lepton_pair_pT", title3 ,400 , 0,4000 );
  TH1D* h_SD =new TH1D("h_SD",title4 ,100,0,200);
  TH1D* h_Z_mass= new TH1D("h_Z_mass",title5 ,250,0,500);
  TH1D* h_Zprime_mass= new TH1D("h_Zprime_mass",title6 ,1000,0,5000);

  //get TTree from file ...
//  TreeReader data(inputFile.data());
  TreeReader data(inputFile.Data());

  Long64_t nTotal=0;
  Long64_t nPass[20]={0};
  ofstream fout;
  fout.open("ele_Eiko.txt");

  //Event loop
  for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){

    if (jEntry % 50000 == 0)
      fprintf(stderr, "Processing event %lli of %lli\n", jEntry + 1, data.GetEntriesFast());

    data.GetEntry(jEntry);
    nTotal ++;

    // 0. check the generator-level information and make sure there is a Z->e+e-

/*
    Int_t nGenPar        = data.GetInt("nGenPar");
    Int_t* genParId      = data.GetPtrInt("genParId");
    Int_t* genParSt      = data.GetPtrInt("genParSt");
    Int_t* genMomParId   = data.GetPtrInt("genMomParId");
    Int_t* genDa1      = data.GetPtrInt("genDa1");
    Int_t* genDa2      = data.GetPtrInt("genDa2");
    Int_t* genMo1      = data.GetPtrInt("genMo1");
    Int_t* genMo2      = data.GetPtrInt("genMo2");

    bool hasLepton=false;

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=23)continue;


      int da1=genDa1[ig];
      int da2=genDa2[ig];


      if(da1<0 || da2<0)continue;
      int da1pdg = genParId[da1];
      int da2pdg = genParId[da2];


      if(abs(da1pdg)==11)
     	hasLepton=true;

      if(hasLepton)break;

    }
*/

/*
    // 1. make sure there is a h-> bb, Yu-Hsiang change it
    bool hasHadron=false;

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=25)continue;
      int da1=genDa1[ig];
      int da2=genDa2[ig];

      if(da1<0 || da2<0)continue;
      int da1pdg = genParId[da1];
      int da2pdg = genParId[da2];

      if(abs(da1pdg)==5)
     	hasHadron=true;

      if(hasHadron)break;

    }
*/  
  
 //   if(!hasLepton)continue;
    nPass[0]++;
//    if(!hasHadron)continue;
    nPass[1]++;
     
    //2. pass electron or muon trigger
    std::string* trigName = data.GetPtrString("hlt_trigName");
    vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
    const Int_t nsize = data.GetPtrStringSize();

    bool passTrigger=false;
    for(int it=0; it< nsize; it++)
      {
 	std::string thisTrig= trigName[it];
 	bool results = trigResult[it];

	// std::cout << thisTrig << " : " << results << std::endl;
	
 	if( (thisTrig.find("HLT_Ele105")!= std::string::npos && results==1)
	    ||
	    (thisTrig.find("HLT_Mu45")!= std::string::npos && results==1)
	    )
 	  {
 	    passTrigger=true;
 	    break;
 	  }


      }


    if(!passTrigger)continue;
    nPass[2]++;


    //3. has a good vertex
    Int_t nVtx        = data.GetInt("nVtx");
    if(nVtx<1)continue;
    nPass[3]++;

    //4. look for good electrons first
    Int_t nEle         = data.GetInt("nEle");
    Int_t run          = data.GetInt("runId");
    Int_t lumi         = data.GetInt("lumiSection");
    Int_t event        = data.GetInt("eventId");
    vector<bool> &passHEEPID = *((vector<bool>*) data.GetPtr("eleIsPassHEEPNoIso"));
    vector<bool> &passLoose = *((vector<bool>*) data.GetPtr("eleIsPassLoose"));
    TClonesArray* eleP4 = (TClonesArray*) data.GetPtrTObject("eleP4");
    Float_t* eleSCEta         = data.GetPtrFloat("eleScEta");
    Float_t* eleSCEt          = data.GetPtrFloat("eleScEt");
    Float_t* eleMiniIso       = data.GetPtrFloat("eleMiniIso");
    Int_t*   eleCharge        = data.GetPtrInt("eleCharge");

    //5. select good electrons

    // save index of electron accepted by ElectronSelection.h
    std::vector<int> accepted;
    select_electrons(data, &accepted);

    std::vector<int> goodElectrons;

    for(int ie=0; ie< nEle; ie++)
      {

        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);

        if(fabs(thisEle->Eta())>2.5)continue;

        if(! (fabs(eleSCEta[ie])<1.442 || fabs(eleSCEta[ie])>1.566))continue;

	float ele_pt = thisEle->Pt();
//	cout<<"ie: "<< ie <<endl;
//        cout<<"before accepted" <<endl;
//        cout<<"ele_pt: "<< ele_pt <<endl;

//        if      (dir_flag == 1) {if(!passHEEPID[ie])continue;}
//        else if (dir_flag == 2) {if(!passLoose[ie])continue;}

	// using the cut in ElectronSelection.h
        bool has_accepted = false;
	for(int j=0; j< accepted.size();j++)
		{ if(ie == accepted[j]){has_accepted=true; break;}  }
	if(!has_accepted)continue;

//        cout<<"after accepted" <<endl;
//        cout<<"ele_pt: "<< ele_pt <<endl;

        if(eleMiniIso[ie]>0.1)continue;

        goodElectrons.push_back(ie);
      }

    // 

	
    //6. select a good Z boson
    bool findEPair=false;
    TLorentzVector l4_Z(0,0,0,0);
    std::vector<double> LeptonPairPt;
    std::vector<double> LeptonPairM;
    std::vector<int> leading_ele_index;
    std::vector<int> subleading_ele_index;


    for(unsigned int i=0; i< goodElectrons.size(); i++)
      {
        int ie = goodElectrons[i];
        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);

        for(unsigned int j=0; j< i; j++)
          {
            int je= goodElectrons[j];

            if(eleCharge[ie]*eleCharge[je]>0)continue;


            TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(je);

//	    float pt1 = thisEle->Pt();
//          float pt2 = thatEle->Pt();

            float pt1 = eleSCEt[ie];// use Super Cluster Et to replace using pt
            float pt2 = eleSCEt[je];

            float ptmax = TMath::Max(pt1,pt2);
            float ptmin = TMath::Min(pt1,pt2);
            if(ptmax<115)continue;
//            if(ptmin<35)continue;
            if(ptmin<10)continue;

            int leadingIndex = pt1>pt2? ie : je;
            int subleadingIndex = pt1 > pt2? je : ie;

            Float_t ptll = (*thisEle+*thatEle).Pt();
            Float_t mll  = (*thisEle+*thatEle).M();
            if(mll<70 || mll>110)continue;
//	    if(ptll<100)continue;
            if(ptll<120)continue;

            leading_ele_index.push_back(leadingIndex);
            subleading_ele_index.push_back(subleadingIndex);

            LeptonPairPt.push_back(ptll);
            LeptonPairM.push_back(mll);


            if(!findEPair)l4_Z=(*thisEle+*thatEle);

            findEPair=true;
          }
      }


    if(!findEPair)
      continue;
    nPass[4]++;


    //7.select a good CA8 and cleaned jet

    // first select muons for cleaning against jet
    std::vector<int> goodMuons;
    Int_t nMu          = data.GetInt("nMu");
    vector<bool> &isHighPtMuon = *((vector<bool>*) data.GetPtr("isHighPtMuon"));
    vector<bool> &isCustomTrackerMuon = *((vector<bool>*) data.GetPtr("isCustomTrackerMuon"));
    TClonesArray* muP4 = (TClonesArray*) data.GetPtrTObject("muP4");
    Float_t* muMiniIso       = data.GetPtrFloat("muMiniIso");

    for(int im=0; im< nMu; im++)
      {

    	TLorentzVector* thisMu = (TLorentzVector*)muP4->At(im);

    	if(!isHighPtMuon[im] && !isCustomTrackerMuon[im])continue;
    	
    	if(muMiniIso[im]>0.1)continue;	

        if ( goodMuons.size()==1 ) {
	  bool highPt_AND_tracker = isHighPtMuon[0] && isCustomTrackerMuon[im];
	  bool tracker_AND_highPt = isHighPtMuon[im] && isCustomTrackerMuon[0]; 
            if ( !(highPt_AND_tracker or tracker_AND_highPt) ) continue; 
        }

    	if(fabs(thisMu->Eta())>2.1)continue;

    	if(thisMu->Pt() < 50)continue;

    	goodMuons.push_back(im);
      }

	
    Int_t nJet         = data.GetInt("FATnJet");
    TClonesArray* jetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    Float_t*  jetSDmass = data.GetPtrFloat("FATjetSDmass");
    Float_t*  jetPRmass = data.GetPtrFloat("FATjetPRmass");

    std::vector<double> SD_Mass;
    TLorentzVector l4_leadingJet(0,0,0,0);
    bool findAJet=false;
    for(int ij=0; ij<nJet; ij++)
      {
    	
     	TLorentzVector* thisJet = (TLorentzVector*)jetP4->At(ij);


//        double SD_low = 60, SD_high = 140;
//        if(jetSDmass[ij]<SD_low || jetSDmass[ij]>SD_high)continue;

        double PR_low = 95, PR_high = 130;
        if(jetPRmass[ij]<PR_low || jetPRmass[ij]>PR_high)continue;


	bool hasOverLap=false;

{
        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(leading_ele_index[0]);
        if(thisEle->DeltaR(*thisJet)<0.8)hasOverLap=true;

        TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(subleading_ele_index[0]);
        if(thatEle->DeltaR(*thisJet)<0.8)hasOverLap=true;
}
	for(unsigned int im=0; im < goodMuons.size(); im++)
	  {
	    TLorentzVector* thisMuo = (TLorentzVector*)muP4->At(goodMuons[im]);
	    if(thisMuo->DeltaR(*thisJet)<0.8)hasOverLap=true;
	    if(hasOverLap)break;
	    
	  }
	
	if(hasOverLap)continue;
	
	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;

     	if(!findAJet)
	  {
	    l4_leadingJet = *thisJet;
//	    h_SD->Fill(jetSDmass[ij]);
            SD_Mass.push_back( jetSDmass[ij] );
	  }
	    
     	findAJet=true;
//        SD_Mass.push_back( jetSDmass[ij] ); // change to this place so that loop to all jets passing cuts    	

      }
    
    if(!findAJet)
      continue;
    nPass[5]++;

     Float_t MGrav = (l4_leadingJet + l4_Z).M();

     double Mass_Point = mass_point;
     double mass_upper = Mass_Point + Mass_Point*0.15;
     double mass_lower = Mass_Point - Mass_Point*0.15;
//     cout<<"Mass_Point: "<<Mass_Point  <<" mass_upper: "<< mass_upper <<" mass_lower: "<< mass_lower <<endl;

     if( MGrav< mass_lower || MGrav>mass_upper )continue;
     h_Zprime_mass->Fill( MGrav );
     nPass[6]++;

  // if event can go here, then fill the histograms to plot the distributions. Yu-Hsiang add 


{

//    int ie = leading_ele_index[0];
    int ie = subleading_ele_index[0];
//    TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
//    h_ele_pT->Fill( thisEle->Pt() );
//    if(eleSCEt[ie]<10){    cout<<"eleSCEt[ie]: "<< eleSCEt[ie] << endl;}
//   cout<<"eleSCEt[ie]: "<< eleSCEt[ie] << endl;
    h_ele_pT->Fill( eleSCEt[ie] );

//cout<<endl;
//cout<< "jEntry: "<< jEntry <<endl;

//cout<<"ie: " << ie<< endl;
//cout<<"thisEle->Pt(): " << thisEle->Pt()<< endl;


}
/*
    for(unsigned int i=0; i< LeadingElectrons.size(); i++)
      {         int ie = LeadingElectrons[i];
		TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
		h_ele_pT->Fill( thisEle->Pt() );
      }
*/
    for(unsigned int i=0; i< LeptonPairPt.size(); i++)
      {         
                
                h_lepton_pair_pT->Fill( LeptonPairPt[i] );
      }

    for(unsigned int i=0; i< LeptonPairM.size(); i++)
      {

                h_Z_mass->Fill( LeptonPairM[i] );
      }

    for(unsigned int i=0; i< SD_Mass.size(); i++)
      {

                h_SD->Fill( SD_Mass[i] );
      }

  ////////

    fout << run << " " << lumi << " " << event << endl;
    

  } // end of loop over entries





  fout.close();
  std::cout << "nTotal    = " << nTotal << std::endl;
  for(int i=0;i<20;i++)
    if(nPass[i]>0)
      std::cout << "nPass[" << i << "]= " << nPass[i] << std::endl;




  //  Yu-Hsiang add calulation of total efficiency and eff uncertainty


  double pass =-99,fail=-99,f_over_p=-99,f_over_p_error=-99;
//  double n_total = nTotal;// from int to double
  double n_total = nPass[1];// from int to double

eff = nPass[6]/n_total;
pass = nPass[6];
fail = nTotal -  nPass[6];
f_over_p = fail/pass;
f_over_p_error = f_over_p * sqrt( (1/fail) + (1/pass) );
eff_err = f_over_p_error/pow( 1 + f_over_p ,2);

cout<<"eff: "<< eff << "   eff_err: "<< eff_err <<endl;





  // Yu-Hsiang add cut flow figure


  TString title1 = Form("Cut Flow for Zprime mass = %d, eff=%f +/- %f",mass_point,eff,eff_err);

  TH1D* h_CutFlow = new TH1D("h_CutFlow", title1 ,8 , 0,8 );

  char* cut_name[8] = {"Began","Z->ee in Gen","H->bb in Gen","HLT","Vertex","Leptons","V-jet","Zprime mass"};

	for(int i=1;i<=8;i++){ // i is the index of column of cut flow plot 
		if(i==1) {h_CutFlow->SetBinContent(i,nTotal); }
        	else {h_CutFlow->SetBinContent(i,nPass[i-2]); }
		h_CutFlow->GetXaxis()->SetBinLabel( i , cut_name[i-1] );
	}

//

  TString png1_name = Form("Zprime_Cut_Flow_M_%d.png",mass_point);
  TString png2_name = Form("Zprime_ele_pT_M_%d.png",mass_point);
  TString png3_name = Form("Zprime_ll_pT_M_%d.png",mass_point);
  TString png4_name = Form("Zprime_SD_mass_M_%d.png",mass_point);
  TString png5_name = Form("Zprime_Z_mass_M_%d.png",mass_point);



//   TCanvas *c1 = new TCanvas("c1","try to show cut flow ",200,10,700,500);
  c1->cd();

  gPad->SetGridx();
//  gPad->SetLogy();

  h_CutFlow->SetMarkerStyle(8);
  h_CutFlow->SetMarkerSize(1);
  h_CutFlow->GetXaxis()->SetLabelSize(0.041);
//  h_CutFlow->GetYaxis()->SetLabelSize(0.035);

  h_CutFlow->SetStats(0);
  h_CutFlow->SetMarkerSize(2.0);

  h_CutFlow->Draw();
  h_CutFlow->Draw("HIST TEXT0 SAME");


//
    // Yu-Hsiang add drawing histogram of distributuion

  c2->cd();
  h_ele_pT->Draw();

  c3->cd();
  h_lepton_pair_pT->Draw();

  c4->cd();
  h_SD->Draw();

  c5->cd();
  h_Z_mass->Draw();

  c6->cd();
  h_Zprime_mass->Draw();
  

////

   // Yu-Hsiang add that save TH1D in the ROOT file


   TString ROOT_name;

   // when read signal sample
   if (signal_background_flag ==0){

   ROOT_name = Form("signal_shape_in_Zprime_M-%d.root",mass_point);
   ROOT_name = dir_name + ROOT_name; 
//   ROOT_name = dir_name +"no_zprime_cut_"+ ROOT_name;
   }

   // when read background sample
   if (signal_background_flag ==1){
     if ( background_file_index ==0) { ROOT_name = Form("background_shape_DYJets_HT100to200_in_Zprime_M-%d.root",mass_point);}
     if ( background_file_index ==1) { ROOT_name = Form("background_shape_DYJets_HT200to400_in_Zprime_M-%d.root",mass_point);}
     if ( background_file_index ==2) { ROOT_name = Form("background_shape_DYJets_HT400to600_in_Zprime_M-%d.root",mass_point);}
     if ( background_file_index ==3) { ROOT_name = Form("background_shape_DYJets_HT600toInf_in_Zprime_M-%d.root",mass_point);}

   ROOT_name = dir_name + ROOT_name;
//   ROOT_name = dir_name +"no_zprime_cut_"+ ROOT_name;
   }


bool save_flag = false;
save_flag = true;
if(save_flag){
 
   TFile *myFile = new TFile(ROOT_name,"recreate");

   h_CutFlow->Write();
   h_ele_pT->Write();
   h_lepton_pair_pT->Write();
   h_SD->Write();
   h_Z_mass->Write();
   h_Zprime_mass->Write();

   myFile->Close();
   delete myFile;
}


   // delete the finished used TH1D so it will not replacing the existing TH1 (no potential memory leak warning) when loop again 
/*
   delete h_CutFlow;
   delete h_ele_pT;
   delete h_lepton_pair_pT;
   delete h_SD;
   delete h_Z_mass;
*/
}
void xAna_ele_subleading_ele_study(TString inputFile, TCanvas *c1 , TCanvas *c2 , TCanvas *c3 ,TCanvas *c4 ,TCanvas *c5 ,
int mass_point ,double eff,double eff_err, TString dir_name, int dir_flag ){


  // define histograms

 TString title2 = Form("ele pT for Zprime mass = %d",mass_point);
 TString title3 = Form("lepton pairs' pT for Zprime mass = %d",mass_point);
 TString title4 = Form("SD mass for Zprime mass = %d",mass_point);
 TString title5 = Form("Z mass for Zprime mass = %d",mass_point);

 TH1D* h_ele_pT = new TH1D("h_ele_pT", title2 ,300 , 0,3000 );
 TH1D* h_lepton_pair_pT = new TH1D("h_lepton_pair_pT", title3 ,400 , 0,4000 );
 TH1D* h_SD =new TH1D("h_SD",title4 ,100,0,200);
 TH1D* h_Z_mass= new TH1D("h_Z_mass",title5 ,250,0,500);

  //get TTree from file ...
  TreeReader data(inputFile.Data());

  Long64_t nTotal=0;
  Long64_t nPass[20]={0};
  ofstream fout;
  fout.open("ele_Eiko.txt");

  //Event loop
  for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){

    if (jEntry % 50000 == 0)
      fprintf(stderr, "Processing event %lli of %lli\n", jEntry + 1, data.GetEntriesFast());

    data.GetEntry(jEntry);
    nTotal ++;

    // 0. check the generator-level information and make sure there is a Z->e+e-
    Int_t nGenPar        = data.GetInt("nGenPar");
    Int_t* genParId      = data.GetPtrInt("genParId");
    Int_t* genParSt      = data.GetPtrInt("genParSt");
    Int_t* genMomParId   = data.GetPtrInt("genMomParId");
    Int_t* genDa1      = data.GetPtrInt("genDa1");
    Int_t* genDa2      = data.GetPtrInt("genDa2");


    bool hasLepton=false;

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=23)continue;
      int da1=genDa1[ig];
      int da2=genDa2[ig];

      if(da1<0 || da2<0)continue;
      int da1pdg = genParId[da1];
      int da2pdg = genParId[da2];

      if(abs(da1pdg)==11)
     	hasLepton=true;

      if(hasLepton)break;

    }

    // 1. make sure there is a h-> bb, Yu-Hsiang change it
    bool hasHadron=false;

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=25)continue;
      int da1=genDa1[ig];
      int da2=genDa2[ig];

      if(da1<0 || da2<0)continue;
      int da1pdg = genParId[da1];
      int da2pdg = genParId[da2];

      if(abs(da1pdg)==5)
     	hasHadron=true;

      if(hasHadron)break;

    }
    
    if(!hasLepton)continue;
    nPass[0]++;
    if(!hasHadron)continue;
    nPass[1]++;
     
    //2. pass electron or muon trigger
    std::string* trigName = data.GetPtrString("hlt_trigName");
    vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
    const Int_t nsize = data.GetPtrStringSize();

    bool passTrigger=false;
    for(int it=0; it< nsize; it++)
      {
 	std::string thisTrig= trigName[it];
 	bool results = trigResult[it];

	// std::cout << thisTrig << " : " << results << std::endl;
	
 	if( (thisTrig.find("HLT_Ele105")!= std::string::npos && results==1)
	    ||
	    (thisTrig.find("HLT_Mu45")!= std::string::npos && results==1)
	    )
 	  {
 	    passTrigger=true;
 	    break;
 	  }


      }


    if(!passTrigger)continue;
    nPass[2]++;


    //3. has a good vertex
    Int_t nVtx        = data.GetInt("nVtx");
    if(nVtx<1)continue;
    nPass[3]++;

    //4. look for good electrons first
    Int_t nEle         = data.GetInt("nEle");
    Int_t run          = data.GetInt("runId");
    Int_t lumi         = data.GetInt("lumiSection");
    Int_t event        = data.GetInt("eventId");
    vector<bool> &passHEEPID = *((vector<bool>*) data.GetPtr("eleIsPassHEEPNoIso"));
    vector<bool> &passLoose = *((vector<bool>*) data.GetPtr("eleIsPassLoose"));
    TClonesArray* eleP4 = (TClonesArray*) data.GetPtrTObject("eleP4");
    Float_t* eleSCEta         = data.GetPtrFloat("eleScEta");
    Float_t* eleMiniIso       = data.GetPtrFloat("eleMiniIso");
    Int_t*   eleCharge        = data.GetPtrInt("eleCharge");

    //5. select good electrons

    std::vector<int> LeadingElectrons;

    for(int ie=0; ie< nEle; ie++)// save the electrons satisfied the leading electron requirement 
      {

        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);

        if(fabs(thisEle->Eta())>2.5)continue;

        if(! (fabs(eleSCEta[ie])<1.442 || fabs(eleSCEta[ie])>1.566))continue;

        double ele_pt_threshold = 115;

        if(thisEle->Pt() < ele_pt_threshold )continue;

        if      (dir_flag == 1) {if(!passHEEPID[ie])continue;}
        else if (dir_flag == 2)	{if(!passLoose[ie])continue;}

        if(eleMiniIso[ie]>0.1)continue;

        LeadingElectrons.push_back(ie);
      }

    std::vector<int> SubLeadingElectrons;

    for(int ie=0; ie< nEle; ie++)// save the electrons satisfied the sub-leading electron requirement 
      {

        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);

        if(fabs(thisEle->Eta())>2.5)continue;

        if(! (fabs(eleSCEta[ie])<1.442 || fabs(eleSCEta[ie])>1.566))continue;

//        double ele_pt_threshold = 115;
        double ele_pt_threshold = 0;

        if(thisEle->Pt() < ele_pt_threshold )continue;

        if      (dir_flag == 1) {if(!passHEEPID[ie])continue;}
        else if (dir_flag == 2) {if(!passLoose[ie])continue;}

        if(eleMiniIso[ie]>0.1)continue;

        SubLeadingElectrons.push_back(ie);
      }

	
    //6. select a good Z boson
    bool findEPair=false;
    TLorentzVector l4_Z(0,0,0,0);
    std::vector<double> LeptonPairPt;
    std::vector<double> LeptonPairM;

    for(unsigned int i=0; i< LeadingElectrons.size(); i++)
      {
        int ie = LeadingElectrons[i];
        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);

        for(unsigned int j=0; j< SubLeadingElectrons.size(); j++)
          {
            int je= SubLeadingElectrons[j];

	    if(ie == je)continue; // avoid to use the same electron twice to be the pair
            if(eleCharge[ie]*eleCharge[je]>0)continue;

            TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(je);

            Float_t mll  = (*thisEle+*thatEle).M();
            Float_t ptll = (*thisEle+*thatEle).Pt();
            

            if(mll<70 || mll>110)continue;

            double ll_pt_threshold = 200;

            if(ptll<ll_pt_threshold )continue;


            LeptonPairPt.push_back(ptll);
            LeptonPairM.push_back(mll);

            if(!findEPair)l4_Z=(*thisEle+*thatEle);

            findEPair=true;
          }     
      }



    if(!findEPair)
      continue;
    nPass[4]++;


    //7.select a good CA8 and cleaned jet

    // first select muons for cleaning against jet
    std::vector<int> goodMuons;
    Int_t nMu          = data.GetInt("nMu");
    vector<bool> &isHighPtMuon = *((vector<bool>*) data.GetPtr("isHighPtMuon"));
    vector<bool> &isCustomTrackerMuon = *((vector<bool>*) data.GetPtr("isCustomTrackerMuon"));
    TClonesArray* muP4 = (TClonesArray*) data.GetPtrTObject("muP4");
    Float_t* muMiniIso       = data.GetPtrFloat("muMiniIso");

    for(int im=0; im< nMu; im++)
      {

    	TLorentzVector* thisMu = (TLorentzVector*)muP4->At(im);

    	if(!isHighPtMuon[im] && !isCustomTrackerMuon[im])continue;
    	
    	if(muMiniIso[im]>0.1)continue;	

        if ( goodMuons.size()==1 ) {
	  bool highPt_AND_tracker = isHighPtMuon[0] && isCustomTrackerMuon[im];
	  bool tracker_AND_highPt = isHighPtMuon[im] && isCustomTrackerMuon[0]; 
            if ( !(highPt_AND_tracker or tracker_AND_highPt) ) continue; 
        }

    	if(fabs(thisMu->Eta())>2.1)continue;

    	if(thisMu->Pt() < 50)continue;

    	goodMuons.push_back(im);
      }

	
    Int_t nJet         = data.GetInt("FATnJet");
    TClonesArray* jetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    Float_t*  jetSDmass = data.GetPtrFloat("FATjetSDmass");

    std::vector<double> SD_Mass;
    TLorentzVector l4_leadingJet(0,0,0,0);
    bool findAJet=false;
    for(int ij=0; ij<nJet; ij++)
      {
    	
     	TLorentzVector* thisJet = (TLorentzVector*)jetP4->At(ij);


        double SD_low = 60, SD_high = 140;

        if(jetSDmass[ij]<SD_low || jetSDmass[ij]>SD_high)continue;

	bool hasOverLap=false;
        for(unsigned int ie=0; ie < LeadingElectrons.size(); ie++)
            {
              TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(LeadingElectrons[ie]);
              if(thisEle->DeltaR(*thisJet)<0.8)hasOverLap=true;
              if(hasOverLap)break;
            
            }
        for(unsigned int ie=0; ie < SubLeadingElectrons.size(); ie++)
            {
              TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(SubLeadingElectrons[ie]);
              if(thisEle->DeltaR(*thisJet)<0.8)hasOverLap=true;
              if(hasOverLap)break;

            }
	for(unsigned int im=0; im < goodMuons.size(); im++)
	  {
	    TLorentzVector* thisMuo = (TLorentzVector*)muP4->At(goodMuons[im]);
	    if(thisMuo->DeltaR(*thisJet)<0.8)hasOverLap=true;
	    if(hasOverLap)break;
	    
	  }
	
	if(hasOverLap)continue;
	
	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;

     	if(!findAJet)
	  {
	    l4_leadingJet = *thisJet;
//	    h_SD->Fill(jetSDmass[ij]);
            SD_Mass.push_back( jetSDmass[ij] );
	  }
	    
     	findAJet=true;

      }
    
    if(!findAJet)
      continue;
    nPass[5]++;

     Float_t MGrav = (l4_leadingJet + l4_Z).M();
     if(MGrav<400)continue;
     nPass[6]++;

  // if event can go here, then fill the histograms to plot the distributions. Yu-Hsiang add 

    for(unsigned int i=0; i< LeadingElectrons.size(); i++)
      {         int ie = LeadingElectrons[i];
		TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
		h_ele_pT->Fill( thisEle->Pt() );
      }

    for(unsigned int i=0; i< LeptonPairPt.size(); i++)
      {         
                
                h_lepton_pair_pT->Fill( LeptonPairPt[i] );
      }

    for(unsigned int i=0; i< LeptonPairM.size(); i++)
      {

                h_Z_mass->Fill( LeptonPairM[i] );
      }

    for(unsigned int i=0; i< SD_Mass.size(); i++)
      {

                h_SD->Fill( SD_Mass[i] );
      }

  ////////

    fout << run << " " << lumi << " " << event << endl;
    

  } // end of loop over entries

  fout.close();
  std::cout << "nTotal    = " << nTotal << std::endl;
  for(int i=0;i<20;i++)
    if(nPass[i]>0)
      std::cout << "nPass[" << i << "]= " << nPass[i] << std::endl;




  //  Yu-Hsiang add calulation of total efficiency and eff uncertainty


  double pass =-99,fail=-99,f_over_p=-99,f_over_p_error=-99;
//  double n_total = nTotal;// from int to double
  double n_total = nPass[1];// from int to double

eff = nPass[6]/n_total;
pass = nPass[6];
fail = nTotal -  nPass[6];
f_over_p = fail/pass;
f_over_p_error = f_over_p * sqrt( (1/fail) + (1/pass) );
eff_err = f_over_p_error/pow( 1 + f_over_p ,2);

cout<<"eff: "<< eff << "   eff_err: "<< eff_err <<endl;





  // Yu-Hsiang add cut flow figure


  TString title1 = Form("Cut Flow for Zprime mass = %d, eff=%f +/- %f",mass_point,eff,eff_err);

  TH1D* h_CutFlow = new TH1D("h_CutFlow", title1 ,8 , 0,8 );

  char* cut_name[8] = {"Began","Z->ee in Gen","H->bb in Gen","HLT","Vertex","Leptons","V-jet","Zprime mass"};

	for(int i=1;i<=8;i++){ // i is the index of column of cut flow plot 
		if(i==1) {h_CutFlow->SetBinContent(i,nTotal); }
        	else {h_CutFlow->SetBinContent(i,nPass[i-2]); }
		h_CutFlow->GetXaxis()->SetBinLabel( i , cut_name[i-1] );
	}

//

  TString png1_name = Form("Zprime_Cut_Flow_M_%d.png",mass_point);
  TString png2_name = Form("Zprime_ele_pT_M_%d.png",mass_point);
  TString png3_name = Form("Zprime_ll_pT_M_%d.png",mass_point);
  TString png4_name = Form("Zprime_SD_mass_M_%d.png",mass_point);
  TString png5_name = Form("Zprime_Z_mass_M_%d.png",mass_point);



//   TCanvas *c1 = new TCanvas("c1","try to show cut flow ",200,10,700,500);
  c1->cd();

  gPad->SetGridx();
//  gPad->SetLogy();

  h_CutFlow->SetMarkerStyle(8);
  h_CutFlow->SetMarkerSize(1);
  h_CutFlow->GetXaxis()->SetLabelSize(0.041);
//  h_CutFlow->GetYaxis()->SetLabelSize(0.035);

  h_CutFlow->SetStats(0);
  h_CutFlow->SetMarkerSize(2.0);

  h_CutFlow->Draw();
  h_CutFlow->Draw("HIST TEXT0 SAME");


//
    // Yu-Hsiang add drawing histogram of distributuion

  c2->cd();
  h_ele_pT->Draw();

  c3->cd();
  h_lepton_pair_pT->Draw();

  c4->cd();
  h_SD->Draw();

  c5->cd();
  h_Z_mass->Draw();
////

   // Yu-Hsiang add that save TH1D in the ROOT file


//   TString ROOT_name = Form("test_ROOT_name_M-%d.root",mass_point);
//   TString ROOT_name = Form("plot_TurnOff3Cuts/Zprime_shape_M-%d.root",mass_point);

//   TString ROOT_name = Form("plot_Cut_SD40to140_ElePt85_llPt200/Zprime_shape_M-%d.root",mass_point);
//   TString ROOT_name = Form("plot_Cut_SD50to140_ElePt85_llPt200/Zprime_shape_M-%d.root",mass_point);
//   TString ROOT_name = Form("plot_Cut_SD60to140_ElePt100_llPt200/Zprime_shape_M-%d.root",mass_point);
//   TString ROOT_name = Form("plot_Cut_SD60to140_ElePt115_llPt200/Zprime_shape_M-%d.root",mass_point);
//   TString ROOT_name = Form("plot_Cut_SD60to140_ElePt85_llPt200/Zprime_shape_M-%d.root",mass_point);

   TString ROOT_name = Form("Zprime_shape_M-%d.root",mass_point);
   ROOT_name = dir_name + ROOT_name; 

   TFile *myFile = new TFile(ROOT_name,"recreate");

   h_CutFlow->Write();
   h_ele_pT->Write();
   h_lepton_pair_pT->Write();
   h_SD->Write();
   h_Z_mass->Write();

   myFile->Close();
   delete myFile;

   // delete the finished used TH1D so it will not replacing the existing TH1 (no potential memory leak warning) when loop again 
/*
   delete h_CutFlow;
   delete h_ele_pT;
   delete h_lepton_pair_pT;
   delete h_SD;
   delete h_Z_mass;
*/
}
void HHbbbbMikeBase(int wMs,int wM, string st,string st2,string option=""){	
	//1=signal ,0=QCD ,2=data-----------------------------------------------------------
	int nameRoot=1;
	if(st2.find("QCD")!= std::string::npos)nameRoot=0;
	if(st2.find("data")!= std::string::npos)nameRoot=2;
	//---------------------Thea correction
	TFile *f3;
	f3=TFile::Open("puppiCorr.root");
	TF1 * puppisd_corrGEN,* puppisd_corrRECO_cen,* puppisd_corrRECO_for;
	puppisd_corrGEN=(TF1 *) f3->FindObjectAny("puppiJECcorr_gen");
	puppisd_corrRECO_cen=(TF1 *) f3->FindObjectAny("puppiJECcorr_reco_0eta1v3");
	puppisd_corrRECO_for=(TF1 *) f3->FindObjectAny("puppiJECcorr_reco_1v3eta2v5");
	TF1* tf1[3];
	tf1[0]=puppisd_corrGEN;
	tf1[1]=puppisd_corrRECO_cen;
	tf1[2]=puppisd_corrRECO_for;
	//option-----------------------------------------------------------
	int JESOption=0;
	if(option.find("JESUp")!= std::string::npos)JESOption=1;
	if(option.find("JESDown")!= std::string::npos)JESOption=2;
	if(option.find("BtagUp")!= std::string::npos)JESOption=3;
	if(option.find("BtagDown")!= std::string::npos)JESOption=4;
	if(option.find("tau21Up")!= std::string::npos)JESOption=5;
	if(option.find("tau21Down")!= std::string::npos)JESOption=6;
	cout<<"JESOption = "<<JESOption<<endl;
	bool printHighPtSubjet=0;
	bool isFast=1;
	//tuple tree and cutflow variables------------------------------------------------------------------------------------
	TFile *f;
	TTree *tree;
	int nPass[20]={0},total=0,dataPassingcsc=0;
	double nPassB[6]={0};
	double fixScaleNum[2]={0};
	//using for Btag Eff -----------------------------------------------------------------------------
	string btagsystematicsType="central";
	if(JESOption==3)btagsystematicsType="up";
	else if(JESOption==4)btagsystematicsType="down";
	BTagCalibration calib("CSVv2L", "subjet_CSVv2_ichep.csv");
	BTagCalibrationReader LF(BTagEntry::OP_LOOSE,"central", {"up", "down"});  
	BTagCalibrationReader HFC(BTagEntry::OP_LOOSE, "central", {"up", "down"});      // other sys types
	BTagCalibrationReader HF(BTagEntry::OP_LOOSE,"central",{"up", "down"});      // other sys types
	LF.load(calib, BTagEntry::FLAV_UDSG,    // btag flavour
            "incl");               // measurement type
	HFC.load(calib, BTagEntry::FLAV_C,    // btag flavour
            "lt");               // measurement type
	HF.load(calib, BTagEntry::FLAV_B,    // btag flavour
            "lt");               // measurement type
	
	TFile *f1;
	if(nameRoot==2)f1=TFile::Open("btagEffSource/data.root");
	else if (nameRoot!=2 && (JESOption==0||JESOption==3||JESOption==4||JESOption==5||JESOption==6))f1=TFile::Open(Form("btagEffSource/%s.root",st2.data()));
	else if (nameRoot!=2 && JESOption==1)f1=TFile::Open(Form("btagEffSource/%s_JESUp.root",st2.data()));
	else if (nameRoot!=2 && JESOption==2)f1=TFile::Open(Form("btagEffSource/%s_JESDown.root",st2.data()));
	TH1D* th1[6];
	string btaggingEff[6]={"effD_b","effN_b","effD_c","effN_c","effD_l","effN_l"};
	for(int i=0;i<6;i++){
		th1[i]=(TH1D*)f1->FindObjectAny(Form("%s_1d",btaggingEff[i].data()));
		if(i==1||i==3||i==5)th1[i]->Divide(th1[i-1]);
	}
	//check for zero btagging SF----------------------------------------------------------------------------------------
	TH2D* th3[6];
	th3[0]=new TH2D("zeroSF_b","zeroSF_b",200,0,2000,60,-3,3);
	th3[1]=new TH2D("zeroSF_c","zeroSF_c",200,0,2000,60,-3,3);
	th3[2]=new TH2D("zeroSF_l","zeroSF_l",200,0,2000,60,-3,3);
	th3[3]=new TH2D("SF_vs_Pt_b","SF_vs_Pt_b",120,0,1200,40,0.8,1.2);
	th3[4]=new TH2D("SF_vs_Pt_c","SF_vs_Pt_c",120,0,1200,40,0.8,1.2);
	th3[5]=new TH2D("SF_vs_Pt_l","SF_vs_Pt_l",120,0,1200,40,0.8,1.2);
	for(int i=0;i<6;i++)th3[i]->Sumw2();
	//check for high btagging SF----------------------------------------------------------------------------------------
	TH1D* th4[14];
	string SF_jet_sub[8]={"SF_jet0_sub0_pass","SF_jet0_sub1_pass","SF_jet1_sub0_pass","SF_jet1_sub1_pass","SF_jet0_sub0_fail","SF_jet0_sub1_fail","SF_jet1_sub0_fail","SF_jet1_sub1_fail"};
	for(int i=0;i<8;i++)th4[i]=new TH1D(Form("%s",SF_jet_sub[i].data()),Form("%s",SF_jet_sub[i].data()),40,0.8,1.2);
	string weightName[6]={"weight","weight_0b","weight_1b","weight_2b","weight_2b_ll","weight_2b_onel"};
	for(int i=0;i<6;i++)th4[i+8]=new TH1D(Form("%s",weightName[i].data()),Form("%s",weightName[i].data()),40,0,2);
	for(int i=0;i<14;i++)th4[i]->Sumw2();
	//saving variables----------------------------------------------------------------------------------------
	TH1D * th5[300],* th6[300];
	for(int i=0;i<2;i++){
		for(int j=0;j<2;j++){
			for(int k=0;k<5;k++){
				th5[(i*2+j)*5+k]=new TH1D(Form("Pt_j%d_sj%d_%db",i,j,k),Form("Pt_j%d_sj%d_%db",i,j,k),200,0,2000);
				th5[(i*2+j)*5+k+20]=new TH1D(Form("Eta_j%d_sj%d_%db",i,j,k),Form("Eta_j%d_sj%d_%db",i,j,k),60,-3,3);
				th5[(i*2+j)*5+k+85]=new TH1D(Form("subCSV_j%d_sj%d_%db",i,j,k),Form("subCSV_j%d_sj%d_%db",i,j,k),20,0,1);
				th5[(i*2+j)*5+k+194]=new TH1D(Form("subCSVCut_j%d_sj%d_%db",i,j,k),Form("subCSVCut_j%d_sj%d_%db",i,j,k),20,0,1);
			}
		}
		for(int k=0;k<5;k++){
			th5[i*5+k+40]=new TH1D(Form("deltaR_j%d_%db",i,k),Form("deltaR_j%d_%db",i,k),20,0,1);
			th5[i*5+k+50]=new TH1D(Form("Pt_j%d_%db",i,k),Form("Pt_j%d_%db",i,k),200,0,2000);
			th5[i*5+k+60]=new TH1D(Form("Eta_j%d_%db",i,k),Form("Eta_j%d_%db",i,k),60,-3,3);
			th5[i*5+k+70]=new TH1D(Form("prMassL2L3_j%d_%db",i,k),Form("prMassL2L3_j%d_%db",i,k),15,90,150);
			th5[i*5+k+105]=new TH1D(Form("tau21_j%d_%db",i,k),Form("tau21_j%d_%db",i,k),25,0,1);
			th5[i*5+k+120]=new TH1D(Form("PuppiSDMassL2L3_j%d_%db",i,k),Form("PuppiSDMassL2L3_j%d_%db",i,k),15,90,150);
			th5[i*5+k+130]=new TH1D(Form("puppiTau21_j%d_%db",i,k),Form("puppiTau21_j%d_%db",i,k),25,0,1);
			th5[i*5+k+140]=new TH1D(Form("prMass_j%d_%db",i,k),Form("prMass_j%d_%db",i,k),15,90,150);
			th5[i*5+k+150]=new TH1D(Form("PuppiSDMass_j%d_%db",i,k),Form("PuppiSDMass_j%d_%db",i,k),15,90,150);
			th5[i*5+k+170]=new TH1D(Form("doubleSV_j%d_%db",i,k),Form("doubleSV_j%d_%db",i,k),40,-1,1);
			th5[i*5+k+184]=new TH1D(Form("FatSV_j%d_%db",i,k),Form("FatSV_j%d_%db",i,k),20,0,1);
			th5[i*5+k+250]=new TH1D(Form("PuppiSDMassThea_j%d_%db",i,k),Form("PuppiSDMassThea_j%d_%db",i,k),15,90,150);
		}
	}
	for(int k=0;k<5;k++){
		th5[k+80]=new TH1D(Form("totalMass_%db",k),Form("totalMass_%db",k),200,1000,5000);
		th5[k+115]=new TH1D(Form("deltaEta_%db",k),Form("deltaEta_%db",k),40,0,2);
		th5[k+160]=new TH1D(Form("logPt_%db",k),Form("logPt_%db",k),70,0,7);
		th5[k+165]=new TH1D(Form("totalMassRed_%db",k),Form("totalMassRed_%db",k),200,1000,5000);
	}
	th5[180]= new TH1D("h_nvtx","h_nvtx",60,0,60);
	th5[181]= new TH1D("h_ntrue","h_ntrue",60,0,60);
	th5[182]= new TH1D("h_nvtx_cut","h_nvtx_cut",60,0,60);
	th5[183]= new TH1D("h_ntrue_cut","h_ntrue_cut",60,0,60);
	
	string prMass_no[4]={"prMass","prMassL2L3","PuppiSDMass","PuppiSDMassL2L3"};
	string tau21_no[2]={"tau21","puppiTau21"};
	for (int i=0;i<4;i++){
		th5[214+i*2]=new TH1D(Form("%s_j0_noPr_noTau21",prMass_no[i].data()),Form("%s_j0_noPr_noTau21",prMass_no[i].data()),200,0,200);
		th5[215+i*2]=new TH1D(Form("%s_j1_noPr_noTau21",prMass_no[i].data()),Form("%s_j1_noPr_noTau21",prMass_no[i].data()),200,0,200);
		th5[222+i*2]=new TH1D(Form("%s_j0_noPr",prMass_no[i].data()),Form("%s_j0_noPr",prMass_no[i].data()),200,0,200);
		th5[223+i*2]=new TH1D(Form("%s_j1_noPr",prMass_no[i].data()),Form("%s_j1_noPr",prMass_no[i].data()),200,0,200);
		th5[230+i*2]=new TH1D(Form("%s_j0_noTau21",prMass_no[i].data()),Form("%s_j0_noTau21",prMass_no[i].data()),15,90,150);
		th5[231+i*2]=new TH1D(Form("%s_j1_noTau21",prMass_no[i].data()),Form("%s_j1_noTau21",prMass_no[i].data()),15,90,150);
	}
	for (int i=0;i<2;i++){
		th5[238+i*2]=new TH1D(Form("%s_j0_noPr_noTau21",tau21_no[i].data()),Form("%s_j0_noPr_noTau21",tau21_no[i].data()),25,0,1);
		th5[239+i*2]=new TH1D(Form("%s_j1_noPr_noTau21",tau21_no[i].data()),Form("%s_j1_noPr_noTau21",tau21_no[i].data()),25,0,1);
		th5[242+i*2]=new TH1D(Form("%s_j0_noPr",tau21_no[i].data()),Form("%s_j0_noPr",tau21_no[i].data()),25,0,1);
		th5[243+i*2]=new TH1D(Form("%s_j1_noPr",tau21_no[i].data()),Form("%s_j1_noPr",tau21_no[i].data()),25,0,1);
		th5[246+i*2]=new TH1D(Form("%s_j0_noTau21",tau21_no[i].data()),Form("%s_j0_noTau21",tau21_no[i].data()),25,0,1);
		th5[247+i*2]=new TH1D(Form("%s_j1_noTau21",tau21_no[i].data()),Form("%s_j1_noTau21",tau21_no[i].data()),25,0,1);
	}
	string flavor[4]={"bb","b","cc","udscg"};
	for (int i=0;i<4;i++){
		th5[260+i]=new TH1D(Form("Pt_j0_0b_%s",flavor[i].data()),Form("Pt_j0_0b_%s",flavor[i].data()),200,0,2000);
		th5[264+i]=new TH1D(Form("Pt_j0_1b_%s",flavor[i].data()),Form("Pt_j0_1b_%s",flavor[i].data()),200,0,2000);
		th5[268+i]=new TH1D(Form("Pt_j0_2b_%s",flavor[i].data()),Form("Pt_j0_2b_%s",flavor[i].data()),200,0,2000);
		th5[272+i]=new TH1D(Form("Pt_j0_DSV_%s",flavor[i].data()),Form("Pt_j0_DSV_%s",flavor[i].data()),200,0,2000);
	}
	
	for(int i=0;i<276;i++){
		th6[i]=(TH1D* )th5[i]->Clone(Form("%ss",th5[i]->GetTitle()));
		th5[i]->Sumw2();
		th6[i]->Sumw2();
	}
	//pileup uncertainty----------------------------------------------------------------------------------------
	TH1D* th7[14];
	th7[0]=new TH1D("totalMass","totalMass",200,1000,5000);
	th7[1]=new TH1D("totalMass_pileup_up","totalMass_pileup_up",200,1000,5000);
	th7[2]=new TH1D("totalMass_pileup_down","totalMass_pileup_down",200,1000,5000);
	th7[3]=new TH1D("pileupEff","pileupEff",15,0.5,15.5);
	double totalPileup[3]={0},passPileup[3]={0};
	standalone_LumiReWeighting LumiWeights_central(0),LumiWeights_up(1),LumiWeights_down(-1);
	//PDF uncertainty
	th7[4]=new TH1D("PDFEff","PDFEff",101,0.5,101.5);
	double passPDF[101]={0},totalPDF[101]={0};
	//QCD uncertainty
	for(int i=5;i<14;i++)th7[i]=new TH1D(Form("uns_QCD_%d",i-5),Form("uns_QCD_%d",i-5),200,1000,5000);
	
	
	
	//NCUtuple loop----------------------------------------------------------------------------------------
	for (int w=wMs;w<wM;w++){
		if(w%20==0)cout<<w<<endl;
		//Get ntuple----------------------------------------------------------------------------------------
		if (nameRoot!=1)f = TFile::Open(Form("%s%d.root",st.data(),w));
		else f = TFile::Open(st.data());
		if (!f || !f->IsOpen())continue;
		TDirectory * dir;
		if (nameRoot!=1)dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
		else dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));
		dir->GetObject("treeMaker",tree);
		TreeReader data(tree);
		total+=data.GetEntriesFast();
		
		
		
		for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){//event loop----------------------------------------------------------------------------------------
			data.GetEntry(jEntry);
			
			
			Int_t nVtx        = data.GetInt("nVtx");
			Float_t ntrue= data.GetFloat("pu_nTrueInt");
			//Float_t*  pdfscaleSysWeights= data.GetPtrFloat("pdfscaleSysWeights");
			th5[180]->Fill(nVtx);
			th5[181]->Fill(ntrue);
			double PU_weight[3]={1,1,1};
			
			if(nameRoot!=2){
				if(ntrue<51){
					PU_weight[0] = LumiWeights_central.weight(ntrue);
					PU_weight[1]= LumiWeights_up.weight(ntrue);
					PU_weight[2] = LumiWeights_down.weight(ntrue);
				}
				else {
					PU_weight[0] = LumiWeights_central.weight(50);
					PU_weight[1] = LumiWeights_up.weight(50);
					PU_weight[2]= LumiWeights_down.weight(50);
				}
			}
			
			th6[180]->Fill(nVtx,PU_weight[0]);
			th6[181]->Fill(ntrue,PU_weight[0]);
			fixScaleNum[0]+=PU_weight[0];
			for(int i=0;i<3;i++)totalPileup[i]+=PU_weight[i];
			for(int i=0;i<101;i++)totalPDF[i]+=PU_weight[0];
			
			
			
			//1.trigger
			std::string* trigName = data.GetPtrString("hlt_trigName");
		 	vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
			bool passTrigger=false;
			for(int it=0; it< data.GetPtrStringSize(); it++){
				std::string thisTrig= trigName[it];
				bool results = trigResult[it];
				if( ((thisTrig.find("HLT_PFHT800")!= std::string::npos
						) && results==1)){
					passTrigger=true;
					break;
				}
			}
			if(!passTrigger && nameRoot==2)continue;nPass[1]++;
			
			Float_t HT= data.GetFloat("HT");
			if(nameRoot!=2 && HT<800)continue;
			
			
			int nFATJet         = data.GetInt("FATnJet");
			TClonesArray* fatjetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
			float*  FATjetCorrUncUp = data.GetPtrFloat("FATjetCorrUncUp"); 
			float*  FATjetCorrUncDown = data.GetPtrFloat("FATjetCorrUncDown"); 
			vector<bool>    &FATjetPassIDTight = *((vector<bool>*) data.GetPtr("FATjetPassIDTight"));
			//2.nJets
			if(nFATJet<2)continue;nPass[2]++;
			TLorentzVector* thisJet ,* thatJet;
			if (JESOption==1){
				TLorentzVector test0= (*((TLorentzVector*)fatjetP4->At(0)))*(1+FATjetCorrUncUp[0] );
				TLorentzVector test1= (*((TLorentzVector*)fatjetP4->At(1)))*(1+FATjetCorrUncUp[1] );
				thisJet= &test0;
				thatJet= &test1;
			}
			else if (JESOption==2){
				TLorentzVector test0= (*((TLorentzVector*)fatjetP4->At(0)))*(1-FATjetCorrUncDown[0] );
				TLorentzVector test1= (*((TLorentzVector*)fatjetP4->At(1)))*(1-FATjetCorrUncDown[1] );
				thisJet= &test0;
				thatJet= &test1;
			}
			else{
				thisJet= (TLorentzVector*)fatjetP4->At(0);
				thatJet = (TLorentzVector*)fatjetP4->At(1);
			}
			//3. Pt 
			if(thisJet->Pt()<200||thatJet->Pt()<200)continue;
			nPass[3]++;
			//4tightId-----------------------------------------
			if(FATjetPassIDTight[0]==0||FATjetPassIDTight[1]==0)continue;
			nPass[4]++;
			//5. Eta-----------------------------------------
			if(fabs(thisJet->Eta())>2.4||fabs(thatJet->Eta())>2.4)continue;
			nPass[5]++;
			//6. DEta-----------------------------------------
			float dEta = fabs(thisJet->Eta()-thatJet->Eta());
			if(dEta>1.3)continue;
			nPass[6]++;
			//7. Mjj-----------------------------------------
			float mjj = (*thisJet+*thatJet).M();
			float mjjRed = (*thisJet+*thatJet).M()+250-thisJet->M()-thatJet->M();
			//if(mjjRed<1000)continue;
			nPass[7]++;
			//8. fatjetPRmassL2L3Corr-----------------------------------------
			Float_t*  fatjetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
			
			
			vector<float>   *subjetSDCSV =  data.GetPtrVectorFloat("FATsubjetSDCSV");
			vector<Int_t>   *FATsubjetSDHadronFlavor =  data.GetPtrVectorInt("FATsubjetSDHadronFlavor");
			int nbtag=0,nbtag2=0;
			float MaxBJetPt = 670., MaxLJetPt = 1000.;
			double sf[2][2],eta[2],pt[2],dr[2],subjetPt[2][2],subjetEta[2][2],eff[2][2],btaggingscaleFactor=1;
			pt[0]=thisJet->Pt();
			pt[1]=thatJet->Pt();
			
			
			
			double scaleFactor=PU_weight[0]*btaggingscaleFactor;
			Float_t*  fatjetTau1 = data.GetPtrFloat("FATjetTau1");
			Float_t*  fatjetTau2 = data.GetPtrFloat("FATjetTau2");
			Float_t*  FATjetPuppiTau1 = data.GetPtrFloat("FATjetPuppiTau1");
			Float_t*  FATjetPuppiTau2 = data.GetPtrFloat("FATjetPuppiTau2");
			double tau21[2];
			tau21[0]=(fatjetTau2[0]/fatjetTau1[0]),tau21[1]=(fatjetTau2[1]/fatjetTau1[1]);
			double puppiTau21[2];
			puppiTau21[0]=(FATjetPuppiTau2[0]/FATjetPuppiTau1[0]),puppiTau21[1]=(FATjetPuppiTau2[1]/FATjetPuppiTau1[1]);
			
			
			
			
			if(fatjetPRmassL2L3Corr[0]<50||fatjetPRmassL2L3Corr[0]>300)continue;
			if(fatjetPRmassL2L3Corr[1]<50||fatjetPRmassL2L3Corr[1]>300)continue;
			nPass[8]++;
			
			
			//9.-----------------------------------------
			if(tau21[0]>0.6 || tau21[1]>0.6) continue;
			nPass[9]++;
			
			
			Int_t* FATjetHadronFlavor        = data.GetPtrInt("FATjetHadronFlavor");
			
			if(subjetSDCSV[0][0]<0.605 && subjetSDCSV[0][1]<0.605){
				if(FATjetHadronFlavor[0]==5 && FATsubjetSDHadronFlavor[0][0]==5 && FATsubjetSDHadronFlavor[0][1]==5)th5[260]->Fill(thisJet->Pt());
				else if(FATjetHadronFlavor[0]==5 && (FATsubjetSDHadronFlavor[0][0]==5 || FATsubjetSDHadronFlavor[0][1]==5))th5[261]->Fill(thisJet->Pt());
				else if(FATjetHadronFlavor[0]==4 && FATsubjetSDHadronFlavor[0][0]==4 && FATsubjetSDHadronFlavor[0][1]==4)th5[262]->Fill(thisJet->Pt());
				else th5[263]->Fill(thisJet->Pt());
			}
			else if (subjetSDCSV[0][0]>0.605 && subjetSDCSV[0][1]>0.605){
				if(FATjetHadronFlavor[0]==5 && FATsubjetSDHadronFlavor[0][0]==5 && FATsubjetSDHadronFlavor[0][1]==5)th5[268]->Fill(thisJet->Pt());
				else if(FATjetHadronFlavor[0]==5 && (FATsubjetSDHadronFlavor[0][0]==5 || FATsubjetSDHadronFlavor[0][1]==5))th5[269]->Fill(thisJet->Pt());
				else if (FATjetHadronFlavor[0]==4 && FATsubjetSDHadronFlavor[0][0]==4 && FATsubjetSDHadronFlavor[0][1]==4)th5[270]->Fill(thisJet->Pt());
				else th5[271]->Fill(thisJet->Pt());
			}
			else {
				if(FATjetHadronFlavor[0]==5 && FATsubjetSDHadronFlavor[0][0]==5 && FATsubjetSDHadronFlavor[0][1]==5)th5[264]->Fill(thisJet->Pt());
				else if(FATjetHadronFlavor[0]==5 && (FATsubjetSDHadronFlavor[0][0]==5 || FATsubjetSDHadronFlavor[0][1]==5))th5[265]->Fill(thisJet->Pt());
				else if (FATjetHadronFlavor[0]==4 && FATsubjetSDHadronFlavor[0][0]==4 && FATsubjetSDHadronFlavor[0][1]==4)th5[266]->Fill(thisJet->Pt());
				else th5[267]->Fill(thisJet->Pt());
			}
			
			
			
			
			
			
			 fixScaleNum[1]+=PU_weight[0];
			
			
			Float_t*  ADDjet_DoubleSV = data.GetPtrFloat("ADDjet_DoubleSV");
			Float_t  FATjet_DoubleSV[2]={0};
			
			Int_t ADDnJet        = data.GetInt("ADDnJet");
			bool matchThis=0,matchThat=0;
			TClonesArray* ADDjetP4 = (TClonesArray*) data.GetPtrTObject("ADDjetP4");
			for(int i=0;i<ADDnJet;i++){
				TLorentzVector* thisAddJet ;
				thisAddJet= (TLorentzVector*)ADDjetP4->At(i);
				if(!matchThis && thisAddJet->DeltaR(*thisJet)<0.8){
					matchThis=1;
					FATjet_DoubleSV[0]=ADDjet_DoubleSV[i];
					continue;
				}
				if(!matchThat && thisAddJet->DeltaR(*thatJet)<0.8){
					matchThat=1;
					FATjet_DoubleSV[1]=ADDjet_DoubleSV[i];
				}
				if(matchThis&& matchThat){
					//cout<<"match"<<FATjet_DoubleSV[0]<<","<<FATjet_DoubleSV[0]<<endl;
					break;
				}
				
			}
			
			if(FATjet_DoubleSV[0]>-0.8){
				if(FATjetHadronFlavor[0]==5 && FATsubjetSDHadronFlavor[0][0]==5 && FATsubjetSDHadronFlavor[0][1]==5)th5[272]->Fill(thisJet->Pt());
				else if(FATjetHadronFlavor[0]==5 && (FATsubjetSDHadronFlavor[0][0]==5 || FATsubjetSDHadronFlavor[0][1]==5))th5[273]->Fill(thisJet->Pt());
				else if (FATjetHadronFlavor[0]==4 && FATsubjetSDHadronFlavor[0][0]==4 && FATsubjetSDHadronFlavor[0][1]==4)th5[274]->Fill(thisJet->Pt());
				else th5[275]->Fill(thisJet->Pt());
			}
			
			

		}//end event loop----------------------------------------------------------------------------------------
	}	//end ntuple loop----------------------------------------------------------------------------------------
	cout<<"entries="<<total<<endl;	
	for(int i=0;i<6;i++)cout<<"nPassB["<<i<<"]="<<nPassB[i]<<endl;
	for(int i=0;i<16;i++)cout<<"nPass["<<i<<"]="<<nPass[i]<<endl;
	
	for(int i=0;i<3;i++)th7[3]->SetBinContent(i+1,passPileup[i]/totalPileup[i]);
	for(int i=0;i<101;i++)th7[4]->SetBinContent(i+1,passPDF[i]/totalPDF[i]);
	
	TH1D * th2o=new TH1D("Nbtagjet","Nbtagjet",5,-0.5,4.5);
	for (int i=0;i<5;i++){
		if(nameRoot==2 && i>2)continue;
		th2o->SetBinContent(i+1,nPass[i+10]);
	}
	TH1D * th2ob=new TH1D("NbtagjetB","NbtagjetB",5,-0.5,4.5);
	for (int i=0;i<5;i++){
		if(nameRoot==2 && i>2)continue;
		th2ob->SetBinContent(i+1,nPassB[i]);
	}
	
	TH1D * fixScale=new TH1D("fixScale","fixScale",2,-0.5,1.5);
	fixScale->SetBinContent(1,fixScaleNum[0]);
	fixScale->SetBinContent(2,fixScaleNum[1]);
	TH1D * cutflow=new TH1D("cutflow","cutflow",16,0.5,16.5);
	cutflow->SetBinContent(1,total);
	if(nameRoot==2)for(int ii=1;ii<14;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	else for(int ii=1;ii<16;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	
	TFile* outFile = new TFile(Form("root_file_mike/%s.root",st2.data()),"recreate");
	th2o->Write();
	th2ob->Write();
	fixScale->Write();
	cutflow->Write();
	for(int i=0;i<6;i++)th3[i]->Write();
	for(int i=0;i<14;i++)th4[i]->Write();
	for(int i=0;i<276;i++){
		th5[i]->Write();
		th6[i]->Write();
	}
	for(int i=0;i<14;i++)th7[i]->Write();
	outFile->Close();
}
Example #20
0
int main(int argc, char** argv) {
    std::vector<std::string> inputFileNames;
    std::string plotFileName;
    TH1D * METResolutions = 0;
    double doJES = 1;
    bool isData = false;
    bool applyJetPt = false;
    bool e_mtw = false;
    int smearingSkim = 1;
    string sample = "";
    string ttDecayMode = "";
    string prefix = "";
    string myFlavor = "";
    int ptrw = 0;
    int metphi = 0;
    int nWM = 0;
    int nWP = 0;
    int nSRP = 0;
    int nSRM = 0;
    int nSBP = 0;
    int nSBM = 0;
    TString dirName = "";
    bool isStack = false;
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));
        if (arg_fth == "prefix") {
            f++;
            std::string in(*(argv + f));
            prefix = in + string("_");
        } else if (arg_fth == "input") {
            f++;
            std::string in(*(argv + f));
            if (dirName == "TreesEle" && in == "Data")
                inputFileNames.push_back(string("~/work/samples/postMoriond/Aug2013/" + prefix + in + "_Ele.root"));
            else
                inputFileNames.push_back(string("~/work/samples/postMoriond/Aug2013/" + prefix + in + ".root"));
            sample = in;
            plotFileName = prefix + in + "_plots.root";
        } else if (arg_fth == "JES") {
            f++;
            std::string in(*(argv + f));
            doJES = atof(in.c_str());
        } else if (arg_fth == "isData") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                isData = true;
            else
                isData = false;
        } else if (arg_fth == "METResolFileName") {
            f++;
            std::string in(*(argv + f));
            TFile * METResolFileName = TFile::Open(in.c_str());
            METResolutions = (TH1D*) METResolFileName->Get("METresolutions");
        } else if (arg_fth == "smearingSkim") {
            f++;
            std::string in(*(argv + f));
            smearingSkim = atof(in.c_str());
        } else if (arg_fth == "ttDecayMode") {
            f++;
            std::string in(*(argv + f));
            ttDecayMode = in;
        } else if (arg_fth == "dirName") {
            f++;
            std::string in(*(argv + f));
            dirName = in.c_str();
        } else if (arg_fth == "stack") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                isStack = true;
            else
                isStack = false;
        } else if (arg_fth == "dojetpt") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                applyJetPt = true;
            else
                applyJetPt = false;
        } else if (arg_fth == "flavor") {
            f++;
            std::string in(*(argv + f));
            myFlavor = in;
        } else if (arg_fth == "ptrw") {
            f++;
            std::string in(*(argv + f));
            ptrw = atof(in.c_str());
        } else if (arg_fth == "metphi") {
            f++;
            std::string in(*(argv + f));
            metphi = atof(in.c_str());
            cout << "================ " << metphi << endl;
        } else if (arg_fth == "emtw") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                e_mtw = true;
            else
                e_mtw = false;
        }
    }
    int channel = 0;
    if (dirName == "TreesEle")
        channel = 1;
    PVHists atLeastOnGPV("DefW_PV");
    JetHists Jets("DefW_Jet", 2);
    if (!isStack)
        Jets.SetErrors(true);
    JetHists BJets("DefW_BJet", 2);
    if (!isStack)
        BJets.SetErrors(true);
    JetHists nonBJets("DefW_nonBJet", 2);
    if (!isStack)
        nonBJets.SetErrors(true);
    JetHists FwDJet("DefW_FwD", 2);
    if (!isStack)
        FwDJet.SetErrors(true);
    MuonHists GoldenFinalPUMuons("DefW_Muon", 3);
    if (!isStack)
        GoldenFinalPUMuons.SetErrors(true);
    MetHists MetHist("DefW_Met");
    if (!isStack)
        MetHist.SetErrors(true);

    PVHists atLeastOnGPV_PuW("PuW_PV");
    JetHists Jets_PuW("PuW_Jet", 2);
    if (!isStack)
        Jets_PuW.SetErrors(true);
    JetHists BJets_PuW("PuW_BJet", 2);
    if (!isStack)
        BJets_PuW.SetErrors(true);
    JetHists nonBJets_PuW("PuW_nonBJet", 2);
    if (!isStack)
        nonBJets_PuW.SetErrors(true);
    JetHists FwDJet_PuW("PuW_FwD", 2);
    if (!isStack)
        FwDJet_PuW.SetErrors(true);
    MuonHists GoldenFinalPUMuons_PuW("PuW_Muon", 3);
    if (!isStack)
        GoldenFinalPUMuons_PuW.SetErrors(true);
    MetHists MetHist_PuW("PuW_Met");
    if (!isStack)
        MetHist_PuW.SetErrors(true);

    PVHists atLeastOnGPV_BtagPuW("BtagPuW_PV");
    JetHists Jets_BtagPuW("BtagPuW_Jet", 2);
    if (!isStack)
        Jets_BtagPuW.SetErrors(true);
    JetHists BJets_BtagPuW("BtagPuW_BJet", 2);
    if (!isStack)
        BJets_BtagPuW.SetErrors(true);
    JetHists nonBJets_BtagPuW("BtagPuW_nonBJet", 2);
    if (!isStack)
        nonBJets_BtagPuW.SetErrors(true);
    JetHists FwDJet_BtagPuW("BtagPuW_FwD", 2);
    if (!isStack)
        FwDJet_BtagPuW.SetErrors(true);
    MuonHists GoldenFinalPUMuons_BtagPuW("BtagPuW_Muon", 3);
    if (!isStack)
        GoldenFinalPUMuons_BtagPuW.SetErrors(true);
    MetHists MetHist_BtagPuW("BtagPuW_Met");
    if (!isStack)
        MetHist_BtagPuW.SetErrors(true);

    PVHists atLeastOnGPV_allW("allW_PV");
    JetHists Jets_allW("allW_Jet", 2);
    if (!isStack)
        Jets_allW.SetErrors(true);
    JetHists BJets_allW("allW_BJet", 2);
    if (!isStack)
        BJets_allW.SetErrors(true);
    JetHists nonBJets_allW("allW_nonBJet", 2);
    if (!isStack)
        nonBJets_allW.SetErrors(true);
    JetHists FwDJet_allW("allW_FwD", 2);
    if (!isStack)
        FwDJet_allW.SetErrors(true);
    MuonHists GoldenFinalPUMuons_allW("allW_Muon", 3);
    if (!isStack)
        GoldenFinalPUMuons_allW.SetErrors(true);
    MetHists MetHist_allW("allW_Met");
    if (!isStack)
        MetHist_allW.SetErrors(true);

    SingleTopHistograms Default_Def("Default_Def");
    if (!isStack)
        Default_Def.SetErrors(true);
    SingleTopHistograms EtaCut_Def("EtaFwD_Def");
    if (!isStack)
        EtaCut_Def.SetErrors(true);
    SingleTopHistograms HtCut_Def("HtCut_Def");
    if (!isStack)
        HtCut_Def.SetErrors(true);
    SingleTopHistograms AntiEtaCut_allW("antiEtaFwD_allW");
    if (!isStack)
        AntiEtaCut_allW.SetErrors(true);
    SingleTopHistograms AntiHtCut_Def("antiHtCut_Def");
    if (!isStack)
        AntiHtCut_Def.SetErrors(true);

    SingleTopHistograms DefaultTrue_Def("DefaultTrue_Def");
    if (!isStack)
        DefaultTrue_Def.SetErrors(true);
    SingleTopHistograms EtaCutTrue_Def("EtaFwDTrue_Def");
    if (!isStack)
        EtaCutTrue_Def.SetErrors(true);
    SingleTopHistograms HtCutTrue_Def("HtCutTrue_Def");
    if (!isStack)
        HtCutTrue_Def.SetErrors(true);
    SingleTopHistograms AntiEtaCutTrue_Def("antiEtaFwDTrue_Def");
    if (!isStack)
        AntiEtaCutTrue_Def.SetErrors(true);
    SingleTopHistograms AntiHtCutTrue_Def("antiHtCutTrue_Def");
    if (!isStack)
        AntiHtCutTrue_Def.SetErrors(true);

    SingleTopHistograms Default_PuW("Default_PuW");
    if (!isStack)
        Default_PuW.SetErrors(true);
    SingleTopHistograms Default_BtagPuW("Default_BtagPuW");
    if (!isStack)
        Default_BtagPuW.SetErrors(true);
    SingleTopHistograms Default_allW("Default_allW");
    if (!isStack)
        Default_allW.SetErrors(true);

    SingleTopHistograms EtaCut_PuW("EtaFwD_PuW");
    if (!isStack)
        EtaCut_PuW.SetErrors(true);
    SingleTopHistograms EtaCut_BtagPuW("EtaFwD_BtagPuW");
    if (!isStack)
        EtaCut_BtagPuW.SetErrors(true);
    SingleTopHistograms EtaCut_allW("EtaFwD_allW");
    if (!isStack)
        EtaCut_allW.SetErrors(true);

    SingleTopHistograms DefaultTrue_PuW("DefaultTrue_PuW");
    if (!isStack)
        DefaultTrue_PuW.SetErrors(true);
    SingleTopHistograms DefaultTrue_BtagPuW("DefaultTrue_BtagPuW");
    if (!isStack)
        DefaultTrue_BtagPuW.SetErrors(true);
    SingleTopHistograms DefaultTrue_allW("DefaultTrue_allW");
    if (!isStack)
        DefaultTrue_allW.SetErrors(true);

    SingleTopHistograms EtaCutTrue_PuW("EtaFwDTrue_PuW");
    if (!isStack)
        EtaCutTrue_PuW.SetErrors(true);
    SingleTopHistograms EtaCutTrue_BtagPuW("EtaFwDTrue_BtagPuW");
    if (!isStack)
        EtaCutTrue_BtagPuW.SetErrors(true);
    SingleTopHistograms EtaCutTrue_allW("EtaFwDTrue_allW");
    if (!isStack)
        EtaCutTrue_allW.SetErrors(true);

    DiLeptonHistograms DiLep_Default_Def("Default_Def");
    if (!isStack)
        DiLep_Default_Def.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCut_Def("EtaFwD_Def");
    if (!isStack)
        DiLep_EtaCut_Def.SetErrors(true);
    DiLeptonHistograms DiLep_HtCut_Def("HtCut_Def");
    if (!isStack)
        DiLep_HtCut_Def.SetErrors(true);
    DiLeptonHistograms DiLep_AntiEtaCut_allW("antiEtaFwD_allW");
    if (!isStack)
        DiLep_AntiEtaCut_allW.SetErrors(true);
    DiLeptonHistograms DiLep_AntiHtCut_Def("antiHtCut_Def");
    if (!isStack)
        DiLep_AntiHtCut_Def.SetErrors(true);

    DiLeptonHistograms DiLep_DefaultTrue_Def("DefaultTrue_Def");
    if (!isStack)
        DiLep_DefaultTrue_Def.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCutTrue_Def("EtaFwDTrue_Def");
    if (!isStack)
        DiLep_EtaCutTrue_Def.SetErrors(true);
    DiLeptonHistograms DiLep_HtCutTrue_Def("HtCutTrue_Def");
    if (!isStack)
        DiLep_HtCutTrue_Def.SetErrors(true);
    DiLeptonHistograms DiLep_AntiEtaCutTrue_Def("antiEtaFwDTrue_Def");
    if (!isStack)
        DiLep_AntiEtaCutTrue_Def.SetErrors(true);
    DiLeptonHistograms DiLep_AntiHtCutTrue_Def("antiHtCutTrue_Def");
    if (!isStack)
        DiLep_AntiHtCutTrue_Def.SetErrors(true);

    DiLeptonHistograms DiLep_Default_PuW("Default_PuW");
    if (!isStack)
        DiLep_Default_PuW.SetErrors(true);
    DiLeptonHistograms DiLep_Default_BtagPuW("Default_BtagPuW");
    if (!isStack)
        DiLep_Default_BtagPuW.SetErrors(true);
    DiLeptonHistograms DiLep_Default_allW("Default_allW");
    if (!isStack)
        DiLep_Default_allW.SetErrors(true);

    DiLeptonHistograms DiLep_EtaCut_PuW("EtaFwD_PuW");
    if (!isStack)
        DiLep_EtaCut_PuW.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCut_BtagPuW("EtaFwD_BtagPuW");
    if (!isStack)
        DiLep_EtaCut_BtagPuW.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCut_allW("EtaFwD_allW");
    if (!isStack)
        DiLep_EtaCut_allW.SetErrors(true);

    DiLeptonHistograms DiLep_DefaultTrue_PuW("DefaultTrue_PuW");
    if (!isStack)
        DiLep_DefaultTrue_PuW.SetErrors(true);
    DiLeptonHistograms DiLep_DefaultTrue_BtagPuW("DefaultTrue_BtagPuW");
    if (!isStack)
        DiLep_DefaultTrue_BtagPuW.SetErrors(true);
    DiLeptonHistograms DiLep_DefaultTrue_allW("DefaultTrue_allW");
    if (!isStack)
        DiLep_DefaultTrue_allW.SetErrors(true);

    DiLeptonHistograms DiLep_EtaCutTrue_PuW("EtaFwDTrue_PuW");
    if (!isStack)
        DiLep_EtaCutTrue_PuW.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCutTrue_BtagPuW("EtaFwDTrue_BtagPuW");
    if (!isStack)
        DiLep_EtaCutTrue_BtagPuW.SetErrors(true);
    DiLeptonHistograms DiLep_EtaCutTrue_allW("EtaFwDTrue_allW");
    if (!isStack)
        DiLep_EtaCutTrue_allW.SetErrors(true);



    TH1D * HT = new TH1D("HT", " ;p_{T,jet}^{2nd}(second)", 500, 0., 500.);
    if (!isStack)
        HT->Sumw2();
    TH1D * RMS = new TH1D("RMS", " ;f_{RMS}^{jet}(non-tagged)", 1000, 0., 1.);
    if (!isStack)
        RMS->Sumw2();
    TH1D * def_finalMT = new TH1D("def_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    if (!isStack)
        def_finalMT->Sumw2();
    def_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * PuW_finalMT = new TH1D("PuW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    if (!isStack)
        PuW_finalMT->Sumw2();
    PuW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * BtagPuW_finalMT = new TH1D("BtagPuW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    BtagPuW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    if (!isStack)
        BtagPuW_finalMT->Sumw2();
    TH1D * allW_finalMT = new TH1D("allW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    allW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    if (!isStack)
        allW_finalMT->Sumw2();
    TH2D * nVtx_cosTheta = new TH2D("nVtxcosTheta", "nVtxcosTheta;N_{vtx};cos(#theta_{l}*)", 100, 0, 100, 100, -1., 1.);
    if (!isStack)
        nVtx_cosTheta->Sumw2();

    TH1D * TOPPT = new TH1D("TOPPT", "top pt", 1000, 0., 10000.);
    TOPPT->GetXaxis()->SetTitle("p_{T}(top)");
    if (!isStack)
        TOPPT->Sumw2();
    TH1D * AntiTOPPT = new TH1D("AntiTOPPT", "anti top pt", 1000, 0., 10000.);
    AntiTOPPT->GetXaxis()->SetTitle("p_{T}(anti-top)");
    if (!isStack)
        AntiTOPPT->Sumw2();
    TH1D * hMetphi = 0;
    TH2D * hMetXNvtx = 0;
    TH2D * hMetYNvtx = 0;
    TH1D * hMetphiCorr = 0;
    TH2D * hMetXNvtxCorr = 0;
    TH2D * hMetYNvtxCorr = 0;
    if (metphi != 0) {
        hMetphiCorr = new TH1D("hMetphiCorr", "hMetphiCorr", 640, -3.2, 3.2);
        hMetXNvtxCorr = new TH2D("hMetXNvtxCorr", "hMetXNvtxCorr", 120, 0, 120, 200, 0, 200);
        hMetYNvtxCorr = new TH2D("hMetYNvtxCorr", "hMetYNvtxCorr", 120, 0, 120, 200, 0, 200);
        hMetphi = new TH1D("hMetPhi", "hMetPhi", 640, -3.2, 3.2);
        hMetXNvtx = new TH2D("hMetXNvtx", "hMetXNvtx", 120, 0, 120, 200, 0, 200);
        hMetYNvtx = new TH2D("hMetYNvtx", "hMetYNvtx", 120, 0, 120, 200, 0, 200);
    }

    //    TH2D * met_cosTheta = new TH2D("metcosTheta_true", "metcosTheta;cos(#theta_{l}*);MET", 100, -1., 1., 100, 0, 300);
    //    TH2D * mt_cosTheta = new TH2D("mtcosTheta_true", "mtcosTheta;M_{T}^{W};cos(#theta_{l}*)", 100, -1., 1., 100, 0, 300);
    //    TH2D * met_cosTheta2 = new TH2D("metcosTheta", "metcosTheta;cos(#theta_{l}*);MET", 100, -1., 1., 100, 0, 300);
    //    TH2D * mt_cosTheta2 = new TH2D("mtcosTheta", "mtcosTheta;M_{T}^{W};cos(#theta_{l}*)", 100, -1., 1., 100, 0, 300);

    cout << "START" << endl;

    TFile * f = 0;
    TApplication theApp("App", &argc, argv);
    double nInit = 0;
    double nFinal = 0;
    double nHLTrunB = 0;
    double nMt = 0;
    double nGoodSolution = 0;
    plotFileName = dirName + string("_") + myFlavor + plotFileName;
#if defined ISDATA || defined   Wtemplate     
    MuonTree * myMuonTree = 0;
#endif
#if !defined  ISDATA && !defined   Wtemplate 
    GenInfoMuonTree * myMuonTree = 0;
#endif
    TTree * eventTree = 0;


    GenSingleTopMaker * genSingleTop = 0;
    TRootGenEventMaker * genEvtMaker = 0;
    TRandom3 tr(154456);
    for (unsigned int fNumber = 0; fNumber < inputFileNames.size(); fNumber++) {
        cout << "file number " << fNumber + 1 << ": " << inputFileNames.at(fNumber) << endl;
        TFile* f = TFile::Open(inputFileNames.at(fNumber).c_str());

#ifdef ISDATA
#if !defined QCD && !defined Wtemplate
        myMuonTree = new MuonTree(eventTree, f, sample + "_2J_1T_noSyst", dirName);
#endif /*QCD*/
#if defined QCD  && !defined Wtemplate
        myMuonTree = new MuonTree(eventTree, f, sample + "_2J_1T_QCD_noSyst", dirName);
#endif /*QCD*/
#if !defined QCD  && defined Wtemplate
        myMuonTree = new MuonTree(eventTree, f, sample + "_2J_0T_noSyst", dirName);
#endif /*Wtemplate*/
#if defined QCD  && defined Wtemplate
        myMuonTree = new MuonTree(eventTree, f, sample + "_2J_0T_QCD_noSyst", dirName);
#endif /*Wtemplate*/
#endif /*ISDATA*/
#if !defined ISDATA && !defined Wtemplate
        if (prefix != string("")) {
            cout << "sample name has _" << endl;
            myMuonTree = new GenInfoMuonTree(eventTree, f, sample + "_2J_1T_noSyst", dirName);
        } else {
            //            cout << "sample name does not have _: " << string(sample + "_2J_0T_noSyst") << endl;
            if (sample.find("Comphep") != 0 && fabs(sample.find("Comphep")) < sample.size())
                myMuonTree = new GenInfoMuonTree(eventTree, f, "TChannel_2J_1T_noSyst", dirName);
            else
                myMuonTree = new GenInfoMuonTree(eventTree, f, sample + "_2J_1T_noSyst", dirName);
        }
#endif /*ISDATA*/
#if defined Wtemplate && !defined QCD
        myMuonTree = new MuonTree(eventTree, f, sample + "_2J_0T_noSyst", dirName);
#endif

        if (string(myMuonTree->fChain->GetName()) == string("Data_2J_1T_QCD_noSyst") ||
                string(myMuonTree->fChain->GetName()) == string("Data_2J_0T_QCD_noSyst")) {
            plotFileName = dirName + "_QCD_plots.root";
        }
        if (string(myMuonTree->fChain->GetName()) == string("Data_2J_0T_noSyst")) {
            plotFileName = dirName + "_WTemplateDefFormat_plots.root";
            //            plotFileName = dirName + "_WTemplate_plots.root";
        }
        cout << "tree name: " << myMuonTree->fChain->GetName() << endl;
        METPhiCorrector metCorr;

        for (int eventNumber = 0; eventNumber < myMuonTree->fChain->GetEntriesFast(); eventNumber++) {
            //            cout << "New event: " << eventNumber << "--------------------" << endl;
            myMuonTree->GetEntry(eventNumber);
            HT->Fill(myMuonTree->secondJetPt, 1);
            if (metphi != 0) {
                hMetphi->Fill(myMuonTree->metPhi);
                hMetXNvtx->Fill(myMuonTree->nGoodVertices, myMuonTree->metPt * cos(myMuonTree->metPhi));
                hMetYNvtx->Fill(myMuonTree->nGoodVertices, myMuonTree->metPt * sin(myMuonTree->metPhi));
                if (isData)
                    CorrectMetPhi(myMuonTree);
                else
                    myMuonTree->SetMetPhi(metCorr.CorrectPhi(myMuonTree->metPt, myMuonTree->metPhi, myMuonTree->nGoodVertices));
                hMetphiCorr->Fill(myMuonTree->metPhi);
                hMetXNvtxCorr->Fill(myMuonTree->nGoodVertices, myMuonTree->metPt * cos(myMuonTree->metPhi));
                hMetYNvtxCorr->Fill(myMuonTree->nGoodVertices, myMuonTree->metPt * sin(myMuonTree->metPhi));
            }
            if (!myMuonTree->passExtraSelection(applyJetPt, e_mtw)) {
                continue;
            }
            if (!isDesiredWJetsFlavor(myMuonTree, myFlavor))
                continue;
            //            cout << "I passed" << endl;
            nFinal++;
#if defined Wtemplate && defined ISDATA
            //            if (!myMuonTree->jetsForWtemplate()) {
            //                continue;
            //            }
#endif /*Wtemplate*/
            bool isLeptonicTop = false;
            bool isHadronicTop = false;
            std::vector<int> nonTopW;
#if !defined ISDATA && !defined Wtemplate
            if (myMuonTree->SampleRecognizer(sample) > 0) {
                cout << "I am a top-contained sample :-)" << endl;
                genEvtMaker = new TRootGenEventMaker(myMuonTree, sample);
                genSingleTop = new GenSingleTopMaker(&(genEvtMaker->output), channel);
                isLeptonicTop = (genEvtMaker->output.tops()[0].isLeptonicMu()
                        || genEvtMaker->output.tops()[0].isLeptonicEl());
                isHadronicTop = genEvtMaker->output.tops()[0].isHadronic();
                nonTopW = genEvtMaker->output.getNonTopWList();
                delete genEvtMaker;
            } else {
                //                    cout << "I am not a top-contained sample :-(\t" << genEvtMaker << "\t" << genSingleTop << endl;
            }
#endif /*ISDATA*/

            //            cout << "Number of tops at analysis level: " << genSingleTop->ntops << endl;
            Event myEvent_tmp = myEventPreparation(myMuonTree);

            double mt = myMuonTree->GetMTW();
            TLorentzVector fwdJet = myMuonTree->GetMostFwDJet();
            double eta = fabs(fwdJet.Eta());
            double ht = myMuonTree->GetHT();
            if (string(myMuonTree->fChain->GetName()) == string("Data_2J_1T_QCD_noSyst") ||
                    string(myMuonTree->fChain->GetName()) == string("Data_2J_0T_QCD_noSyst")) {
                //                cout << "QCD template" << endl;
                DR<TLorentzVector> dr;
                dr.SetVectors(myEvent_tmp.Dmuons[0], myEvent_tmp.BPFJets[0]);
                if (dr.getValue() < 0.3)
                    continue;
                if (dirName == "TreesEle") {
                    dr.SetVectors(myEvent_tmp.Dmuons[0], myEvent_tmp.GPFJets[1]);
                    if (dr.getValue() < 0.3)
                        continue;
                    if (myMuonTree->leptonRhoCorrectedRelIso <= 0.1)
                        continue;
                    if (cos(myMuonTree->leptonPhi - myMuonTree->metPhi) >= 0.8)
                        continue;
                }
            }
            //            if(string(myMuonTree->fChain->GetName()) == string("Data_2J_0T_QCD_noSyst")){
            //                if(cos(myMuonTree->leptonPhi-myMuonTree->metPhi) >= 0.8)
            //                    continue;
            //            }

            double puOnlyW = 1;
            double btagpuW = 1;
            double lumiWeight3D = 1;
            if (genSingleTop != 0) {
                if (genSingleTop->isDesiredSemiLepton(channel)) {
                    cout << genSingleTop->genSingleTop.MuCharge() << "\t" << myMuonTree->charge;
                    if (isLeptonicTop) {
                        cout << ": leptonic top" << endl;
                    } else if (isHadronicTop) {
                        cout << ": hadronic top" << endl;
                    } else {
                        cout << endl;
                    }
                    cout << "Second W status: " << endl;
                    for (int s = 0; s < nonTopW.size(); s++) {
                        if (nonTopW[s] == 1)
                            cout << "\tW decays to Electron" << endl;
                        if (nonTopW[s] == 2)
                            cout << "\tW decays to Muon" << endl;
                        if (nonTopW[s] == 3)
                            cout << "\tW decays to Tau" << endl;
                        if (nonTopW[s] == 4)
                            cout << "\tW decays to Hadron" << endl;
                    }
                }
            }
            if (!isData) {
                //                GetWeightsNoPu(myMuonTree, lumiWeight3D, puOnlyW, btagpuW);
                puOnlyW *= myMuonTree->GetPUOnlyWeight();
                btagpuW *= myMuonTree->GetPUbTagWeight();
                lumiWeight3D = myMuonTree->GetTotalWeight();
#if !defined ISDATA && !defined Wtemplate
                if (ptrw != 0 && (string(myMuonTree->fChain->GetName()).find("TTBar") >= 0
                        && string(myMuonTree->fChain->GetName()).find("TTBar") <
                        string(myMuonTree->fChain->GetName()).size())) {
                    TopPtReweighter topptrw;
                    TLorentzVector antitop;
                    TLorentzVector top;
                    double myTopW = 1.;
                    if (myMuonTree->GetGenTop(1).type() == -6) {
                        antitop = myMuonTree->GetGenTop(1);
                        top = myMuonTree->GetGenTop(2);
                        myTopW = topptrw.Weight(top.Pt(), antitop.Pt());
                    } else if (myMuonTree->GetGenTop(1).type() == 6) {
                        antitop = myMuonTree->GetGenTop(2);
                        top = myMuonTree->GetGenTop(1);
                        myTopW = topptrw.Weight(top.Pt(), antitop.Pt());
                    } else {
                        cout << "***************bad top id value*************" << endl;
                    }
                    TOPPT->Fill(top.Pt());
                    AntiTOPPT->Fill(antitop.Pt());
                    puOnlyW *= myTopW;
                    btagpuW *= myTopW;
                    lumiWeight3D *= myTopW;
                }
#endif
            }
            SemiLepTopQuark myLeptonicTop(myEvent_tmp.BPFJets[0], myEvent_tmp.mets[0], myEvent_tmp.Dmuons[0],
                    myEvent_tmp.GPFJets[1], fwdJet, METResolutions);
            myLeptonicTop.setMuCharge((int) myMuonTree->charge);
            //            cout << "Before CosTheta Fill" << endl;
            if (myMuonTree->charge > 0)
                nWP++;
            if (myMuonTree->charge < 0)
                nWM++;
            /*
             * Filling CosTheta Histograms
             */
            if (ttDecayMode == "") {
                if (myLeptonicTop.hasNeutrinoSolution()) {
                    nGoodSolution++;
                    //                    nVtx_cosTheta->Fill(myMuonTree->nGoodVertices, myLeptonicTop.cosThetaStar());
                    //                    met_cosTheta->Fill(myLeptonicTop.cosThetaStar(), myMuonTree->GetMET().Pt());
                    //                    mt_cosTheta->Fill(myLeptonicTop.cosThetaStar(), myMuonTree->GetMTW());
                    DefaultTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                    DefaultTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                    DefaultTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                    DefaultTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);

                    if (ht >= 180)
                        HtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                    else
                        AntiHtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                    if (eta > 1.5) {
                        EtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                        EtaCutTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                        EtaCutTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                        EtaCutTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
                    } else
                        AntiEtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                }
                Default_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                Default_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                Default_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                Default_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
                nVtx_cosTheta->Fill(myMuonTree->nGoodVertices, myLeptonicTop.cosThetaStar());
                //                met_cosTheta2->Fill(myLeptonicTop.cosThetaStar(), myMuonTree->GetMET().Pt());
                //                mt_cosTheta2->Fill(myLeptonicTop.cosThetaStar(), myMuonTree->GetMTW());

                if (ht >= 180)
                    HtCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                else
                    AntiHtCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                if (eta > 1.5) {
                    EtaCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                    EtaCut_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                    EtaCut_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                    EtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
                } else
                    AntiEtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
            } else {//Dimuon, muTau, muE TtBar
                if (myLeptonicTop.hasNeutrinoSolution()) {
                    nGoodSolution++;
                    DiLep_DefaultTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                    DiLep_DefaultTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                    DiLep_DefaultTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                    DiLep_DefaultTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);

                    if (ht >= 180)
                        DiLep_HtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                    else
                        DiLep_AntiHtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                    if (eta > 1.5) {
                        DiLep_EtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                        DiLep_EtaCutTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                        DiLep_EtaCutTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                        DiLep_EtaCutTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
                    } else
                        DiLep_AntiEtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                }
                DiLep_Default_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                DiLep_Default_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                DiLep_Default_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                DiLep_Default_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);

                if (ht >= 180)
                    DiLep_HtCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                else
                    DiLep_AntiHtCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);
                if (eta > 1.5) {
                    DiLep_EtaCut_Def.Fill(myLeptonicTop, 1, genSingleTop, channel);

                    DiLep_EtaCut_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop, channel);
                    DiLep_EtaCut_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop, channel);
                    DiLep_EtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
                } else
                    DiLep_AntiEtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop, channel);
            }
            //            cout << "After CosTheta Fill" << endl;

            if (genSingleTop != NULL) {
                //                cout << "genSingleTop: " << genSingleTop << endl;
                delete genSingleTop;
            }

            /*
             * Filling Event Histograms
             */
            //            cout << "Before Event Fill" << endl;
            TRootPFJet FWDJET(fwdJet);
            std::vector<TRootPFJet> sortedJetsbyEta;
            sortedJetsbyEta.push_back(FWDJET);
            std::vector<TRootPFJet> nonBs;
            nonBs.push_back(myMuonTree->GetFJet());


            atLeastOnGPV.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), 1);
            GoldenFinalPUMuons.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), 1);
            Jets.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, 1);
            BJets.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, 1);
            nonBJets.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, 1);
            FwDJet.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, 1);
            MetHist.Fill(&myEvent_tmp.mets.at(0), 1);
            def_finalMT->Fill(mt, 1);

            atLeastOnGPV_PuW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), puOnlyW);
            GoldenFinalPUMuons_PuW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), puOnlyW);
            Jets_PuW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            BJets_PuW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            nonBJets_PuW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            FwDJet_PuW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            MetHist_PuW.Fill(&myEvent_tmp.mets.at(0), puOnlyW);
            PuW_finalMT->Fill(mt, puOnlyW);

            atLeastOnGPV_BtagPuW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), btagpuW);
            GoldenFinalPUMuons_BtagPuW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), btagpuW);
            Jets_BtagPuW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            BJets_BtagPuW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            nonBJets_BtagPuW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            FwDJet_BtagPuW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            MetHist_BtagPuW.Fill(&myEvent_tmp.mets.at(0), btagpuW);
            BtagPuW_finalMT->Fill(mt, btagpuW);

            atLeastOnGPV_allW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), lumiWeight3D);
            GoldenFinalPUMuons_allW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), lumiWeight3D);
            Jets_allW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            BJets_allW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            nonBJets_allW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            FwDJet_allW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            MetHist_allW.Fill(&myEvent_tmp.mets.at(0), lumiWeight3D);
            allW_finalMT->Fill(mt, lumiWeight3D);
            //            cout<<"End of event loop --------------------"<<endl;
            if (myLeptonicTop.top().M() > 130 && myLeptonicTop.top().M() < 220) {
                if (myMuonTree->charge > 0)
                    nSRP++;
                else if (myMuonTree->charge < 0)
                    nSRM++;
            } else {
                if (myMuonTree->charge > 0)
                    nSBP++;
                else if (myMuonTree->charge < 0)
                    nSBM++;
            }
        }

        cout << "before closing file input " << f->GetName() << endl;
        f->Close();
        delete f;

    }
    cout << "before endjob" << endl;
    TFile * fout = new TFile(plotFileName.c_str(), "recreate");
    fout->cd();

    atLeastOnGPV.WriteAll(fout);
    GoldenFinalPUMuons.WriteAll(fout);
    Jets.WriteAll(fout);
    BJets.WriteAll(fout);
    nonBJets.WriteAll(fout);
    FwDJet.WriteAll(fout);
    MetHist.WriteAll(fout);
    def_finalMT->Write();

    atLeastOnGPV_PuW.WriteAll(fout);
    GoldenFinalPUMuons_PuW.WriteAll(fout);
    Jets_PuW.WriteAll(fout);
    BJets_PuW.WriteAll(fout);
    nonBJets_PuW.WriteAll(fout);
    FwDJet_PuW.WriteAll(fout);
    MetHist_PuW.WriteAll(fout);
    PuW_finalMT->Write();

    atLeastOnGPV_BtagPuW.WriteAll(fout);
    GoldenFinalPUMuons_BtagPuW.WriteAll(fout);
    Jets_BtagPuW.WriteAll(fout);
    BJets_BtagPuW.WriteAll(fout);
    nonBJets_BtagPuW.WriteAll(fout);
    FwDJet_BtagPuW.WriteAll(fout);
    MetHist_BtagPuW.WriteAll(fout);
    BtagPuW_finalMT->Write();

    atLeastOnGPV_allW.WriteAll(fout);
    GoldenFinalPUMuons_allW.WriteAll(fout);
    Jets_allW.WriteAll(fout);
    BJets_allW.WriteAll(fout);
    nonBJets_allW.WriteAll(fout);
    FwDJet_allW.WriteAll(fout);
    MetHist_allW.WriteAll(fout);
    allW_finalMT->Write();
    if (ttDecayMode == "") {
        Default_Def.Write(fout);

        Default_PuW.Write(fout);
        Default_BtagPuW.Write(fout);
        Default_allW.Write(fout);

        EtaCut_Def.Write(fout);
        EtaCut_PuW.Write(fout);
        EtaCut_BtagPuW.Write(fout);
        EtaCut_allW.Write(fout);

        AntiEtaCut_allW.Write(fout);
        HtCut_Def.Write(fout);
        AntiHtCut_Def.Write(fout);
        DefaultTrue_Def.Write(fout);
        EtaCutTrue_Def.Write(fout);
        DefaultTrue_allW.Write(fout);
        EtaCutTrue_allW.Write(fout);
        AntiEtaCutTrue_Def.Write(fout);
        HtCutTrue_Def.Write(fout);
        AntiHtCutTrue_Def.Write(fout);
    } else {
        DiLep_Default_Def.Write(fout);

        DiLep_Default_PuW.Write(fout);
        DiLep_Default_BtagPuW.Write(fout);
        DiLep_Default_allW.Write(fout);

        DiLep_EtaCut_Def.Write(fout);
        DiLep_EtaCut_PuW.Write(fout);
        DiLep_EtaCut_BtagPuW.Write(fout);
        DiLep_EtaCut_allW.Write(fout);

        DiLep_AntiEtaCut_allW.Write(fout);
        DiLep_HtCut_Def.Write(fout);
        DiLep_AntiHtCut_Def.Write(fout);
        DiLep_DefaultTrue_Def.Write(fout);
        DiLep_EtaCutTrue_Def.Write(fout);
        DiLep_DefaultTrue_allW.Write(fout);
        DiLep_EtaCutTrue_allW.Write(fout);
        DiLep_AntiEtaCutTrue_Def.Write(fout);
        DiLep_HtCutTrue_Def.Write(fout);
        DiLep_AntiHtCutTrue_Def.Write(fout);
    }
    HT->Write();
    RMS->Write();
    nVtx_cosTheta->Write();
    //    TOPPT->Write();
    //    AntiTOPPT->Write();
    //    met_cosTheta->Write();
    //    mt_cosTheta->Write();
    //    met_cosTheta2->Write();
    //    mt_cosTheta2->Write();
    if (metphi != 0) {
        hMetphi->Write();
        hMetXNvtx->Write();
        hMetYNvtx->Write();
        hMetphiCorr->Write();
        hMetXNvtxCorr->Write();
        hMetYNvtxCorr->Write();
    }
    fout->Write();
    fout->Close();

    cout << nInit << "\n" << nHLTrunB << "\n" << nMt << "\n" << nFinal << "\n" << nGoodSolution << endl;
    cout << "nW+: " << nWP << "\tnW-: " << nWM << endl;
    cout << "SR+" << nSRP << endl;
    cout << "SR-" << nSRM << endl;
    cout << "SB+" << nSBP << endl;
    cout << "SB-" << nSBM << endl;
    return 0;
}
void xAna_hh_massResolutionBase(std::string inputFile,TString outputFile,bool matchb=false, bool debug=false, bool cut=false){


  cout << "output file name = " << outputFile.Data() << endl;

  //get TTree from file ...
  TreeReader data(inputFile.data());
  
  Long64_t nTotal=0;
  Long64_t nPass[20]={0};

  const int nHistos=3;

  TH1F* h_massDiff = new TH1F("h_massDiff","",100,-0.5,0.5);
  //TH1F* h_mass     = new TH1F("h_mass","",100,0,200);
  TH1F* h_mass     = new TH1F("h_mass","",100,62.5,187.5);

  TH1F* h_AK8SD[nHistos];
  TH1F* h_AK8SDCorrThea[nHistos];
  TH1F* h_AK8SDHCorr[nHistos];
  TH1F* h_PR[nHistos];
  TH1F* h_PRCorr[nHistos];

  TH1F* h_diff_PR[nHistos];
  TH1F* h_diff_PRCorr[nHistos];
  TH1F* h_diff_AK8SD[nHistos];
  TH1F* h_diff_AK8SDCorrThea[nHistos];
  TH1F* h_diff_AK8SDHCorr[nHistos];
  
  std::string prefix[]={"leading","subleading","both"};
  for(int i=0; i<nHistos; i++)
    {

	h_AK8SD[i] = (TH1F*)h_mass->Clone(Form("h_AK8SD_%s",prefix[i].data()));
      h_AK8SD[i]->SetXTitle("AK8 Raw Puppi+Softdrop mass [GeV]");

	h_AK8SDCorrThea[i] = (TH1F*)h_mass->Clone(Form("h_AK8SDCorrThea_%s",prefix[i].data()));
      h_AK8SDCorrThea[i]->SetXTitle("AK8 Thea-corrected Puppi+Softdrop mass [GeV]");
	
	h_AK8SDHCorr[i] = (TH1F*)h_mass->Clone(Form("h_AK8SDHCorr_%s",prefix[i].data()));
      h_AK8SDHCorr[i]->SetXTitle("AK8 H-corrected Puppi+Softdrop mass [GeV]");

      h_PR[i] = (TH1F*)h_mass->Clone(Form("h_PR_%s",prefix[i].data()));
      h_PR[i]->SetXTitle("Raw CHS+Pruned mass [GeV]");

      h_PRCorr[i] = (TH1F*)h_mass->Clone(Form("h_PRCorr_%s",prefix[i].data()));
      h_PRCorr[i]->SetXTitle("L2L3-corrected CHS+Pruned mass [GeV]");

      // study the difference with respect to 125 GeV

     
	
	h_diff_AK8SD[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_AK8SD_%s",prefix[i].data()));
      h_diff_AK8SD[i]->SetXTitle("AK8 Raw Puppi+Softdrop (m-125)/125");

	h_diff_AK8SDCorrThea[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_AK8SDCorrThea_%s",prefix[i].data()));
      h_diff_AK8SDCorrThea[i]->SetXTitle("AK8 Thea-corrected Puppi+Softdrop (m-125)/125");
	
	h_diff_AK8SDHCorr[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_AK8SDHCorr_%s",prefix[i].data()));
      h_diff_AK8SDHCorr[i]->SetXTitle("AK8 H-corrected Puppi+Softdrop (m-125)/125");

      h_diff_PR[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_PR_%s",prefix[i].data()));
      h_diff_PR[i]->SetXTitle("Raw CHS+Pruned (m-125)/125");

      h_diff_PRCorr[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_PRCorr_%s",prefix[i].data()));
      h_diff_PRCorr[i]->SetXTitle("L2L3-corrected CHS+Pruned (m-125)/125");

    }


  for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){

  if((jEntry+1)%2)continue;
    if (jEntry % 1000 == 0)
      fprintf(stderr, "Processing event %lli of %lli\n", jEntry + 1, data.GetEntriesFast());
    if(debug && jEntry>10)break;

    data.GetEntry(jEntry);
    nTotal++;

    Int_t nGenPar        = data.GetInt("nGenPar");
    Int_t* genParId      = data.GetPtrInt("genParId");
    Int_t* genParSt      = data.GetPtrInt("genParSt");
    Int_t* genMomParId   = data.GetPtrInt("genMomParId");
    Int_t* genDa1      = data.GetPtrInt("genDa1");
    Int_t* genDa2      = data.GetPtrInt("genDa2");

    int genHIndex[2]={-1,-1};
    int genbIndex[2][2]={{-1,-1},
			 {-1,-1}};		       

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=25)continue;

      if(genHIndex[0]<0)
	{
	  genHIndex[0]=ig;
	  genbIndex[0][0]=genDa1[ig];
	  genbIndex[0][1]=genDa2[ig];
	}

      else if(genHIndex[1]<0)
	{
	  genHIndex[1]=ig;
	  genbIndex[1][0]=genDa1[ig];
	  genbIndex[1][1]=genDa2[ig];
	}

    }    

    if(genHIndex[0]<0 || genHIndex[1]<0)continue;
    if(genbIndex[0][0]<0 || genbIndex[0][1]<0)continue;
    if(genbIndex[1][0]<0 || genbIndex[1][1]<0)continue;

    nPass[0]++;

    if(genHIndex[0]==genHIndex[1])continue;
    nPass[1]++;

    TLorentzVector genH_l4[2];
    TLorentzVector genb_l4[2][2];
    TClonesArray* genParP4 = (TClonesArray*) data.GetPtrTObject("genParP4");

    for(int ih=0; ih<2; ih++)
      {
	genH_l4[ih] = *((TLorentzVector*)genParP4->At(genHIndex[ih]));
	for(int ib=0; ib<2; ib++)
	  {
	    genb_l4[ih][ib] = *((TLorentzVector*)genParP4->At(genbIndex[ih][ib]));
	  }
      }


   
    int nFATJet         = data.GetInt("FATnJet");
    const int nJets=nFATJet;
    TClonesArray* FATjetP4   = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    TClonesArray* AK8PuppijetP4 = (TClonesArray*) data.GetPtrTObject("AK8PuppijetP4");

    // check matching first

    bool findAMatch=false;
    const float dRMax=0.4;
    const float dRbMax=0.8;
    int matchedHJetIndex[2]={-1,-1};
		      
    for(int ij=0; ij<nJets; ij++)
      {
	TLorentzVector* thisJet = (TLorentzVector*)FATjetP4->At(ij);

	for(int jj=0; jj<nJets; jj++)
	  {

	    if(ij==jj)continue;
	    TLorentzVector* thatJet = (TLorentzVector*)FATjetP4->At(jj);
	    
	    if(thisJet->DeltaR(genH_l4[0])<dRMax && 
	       (!matchb || (matchb && 
			    thisJet->DeltaR(genb_l4[0][0])<dRbMax && 
			    thisJet->DeltaR(genb_l4[0][1])<dRbMax)) &&
	       thatJet->DeltaR(genH_l4[1])<dRMax &&
	       (!matchb || (matchb &&
			    thatJet->DeltaR(genb_l4[1][0])<dRbMax &&
			    thatJet->DeltaR(genb_l4[1][1])<dRbMax)))
	      {
		if(debug)
		  {
		    cout << "dRhb00= " <<  thisJet->DeltaR(genb_l4[0][0]) << endl;
		    cout << "dRhb01= " <<  thisJet->DeltaR(genb_l4[0][1]) << endl;
		    cout << "dRhb10= " <<  thatJet->DeltaR(genb_l4[1][0]) << endl;
		    cout << "dRhb11= " <<  thatJet->DeltaR(genb_l4[1][1]) << endl;
		  }
		if(ij<jj){
		  matchedHJetIndex[0]=ij;
		  matchedHJetIndex[1]=jj;
		}
		else
		  {
		    matchedHJetIndex[0]=jj;
		    matchedHJetIndex[1]=ij;
		  }
		findAMatch=true;
		break;
	      }

	    if(findAMatch)break;

	  }	

	if(findAMatch)break;

      }

    if(!findAMatch)continue;
    if(debug)
      cout << matchedHJetIndex[0] << "\t" << matchedHJetIndex[1] << endl;
    nPass[2]++;

    //0. has a good vertex
    Int_t nVtx        = data.GetInt("nVtx");
    if(nVtx<1 && cut)continue;
    nPass[3]++;



    Float_t*  fatjetTau1 = data.GetPtrFloat("FATjetTau1");
    Float_t*  fatjetTau2 = data.GetPtrFloat("FATjetTau2");
    Float_t*  fatjetCISVV2 = data.GetPtrFloat("FATjetCISVV2");
    Float_t*  fatjetPRmass = data.GetPtrFloat("FATjetPRmass");
    Float_t*  fatjetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
    Float_t*  fatjetSDmass = data.GetPtrFloat("FATjetPuppiSDmass");
    Float_t*  fatjetSDmassL2L3Corr = data.GetPtrFloat("FATjetPuppiSDmassL2L3Corr"); 
    Float_t*  AK8PuppijetSDmass = data.GetPtrFloat("AK8PuppijetSDmass");

    vector<bool>    &passFatJetLooseID = *((vector<bool>*) data.GetPtr("FATjetPassIDLoose"));
    
    TLorentzVector recoH_l4[2];
    int nGoodJets=0;
    
    
    
    for(int i=0; i<2; i++)
      {
    	
	int ij = matchedHJetIndex[i];
     	TLorentzVector* thisJet = (TLorentzVector*)FATjetP4->At(ij);
	recoH_l4[i]= (*thisJet);
    	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;
	nGoodJets++;
      }

    if(nGoodJets<2)continue;
    nPass[5]++;
    
    

    float dEta=fabs(recoH_l4[0].Eta()-recoH_l4[1].Eta());
    if(dEta>1.3 && cut)continue;
    nPass[6]++;

    float M=(recoH_l4[0] + recoH_l4[1]).M();
    if(M<800 && cut)continue;
    nPass[7]++;


    int nHP=0;
    int nLP=0;
    for(int i=0; i<2; i++)
      {
    	
	int ij = matchedHJetIndex[i];

	float tau21_i = fatjetTau2[ij]/fatjetTau1[ij];
	bool isHP= (tau21_i < 0.6);
	if(isHP)nHP++;
      }

    if(nHP<2 && cut)continue;
    nPass[8]++;

	double SDMass[2];
	Int_t AK8PuppinJet        = data.GetInt("AK8PuppinJet");
	if(AK8PuppinJet<2)continue;
	bool matchThis=0,matchThat=0;
	//TClonesArray* AK8PuppijetP4 = (TClonesArray*) data.GetPtrTObject("AK8PuppijetP4");
	
	TLorentzVector* thisJet,* thatJet;
			thisJet= (TLorentzVector*)FATjetP4->At(0);
			thatJet= (TLorentzVector*)FATjetP4->At(1);
			for(int i=0;i<AK8PuppinJet;i++){
				TLorentzVector* thisAddJet ;
				thisAddJet= (TLorentzVector*)AK8PuppijetP4->At(i);
				if(!matchThis && thisAddJet->DeltaR(*thisJet)<0.8){
					matchThis=1;
					SDMass[0]=AK8PuppijetSDmass[i];
					continue;
				}
				if(!matchThat && thisAddJet->DeltaR(*thatJet)<0.8){
					matchThat=1;
					SDMass[1]=AK8PuppijetSDmass[i];
				}
				if(matchThis&& matchThat)break;
			}
    
    
    
    
    for(int i=0; i<2;i++)
      {
	
	float thea_corr = getPUPPIweight_o(thisJet->Pt(),thisJet->Eta());
	if(i==1)thea_corr = getPUPPIweight_o(thatJet->Pt(),thatJet->Eta());
	float H_corr= getPUPPIweight(thisJet->Pt(),thisJet->Eta());
	if(i==1)H_corr = getPUPPIweight(thatJet->Pt(),thatJet->Eta());
	
	h_PR[i]->Fill(fatjetPRmass[i]);
	h_PRCorr[i]->Fill(fatjetPRmassL2L3Corr[i]);
	h_AK8SD[i]->Fill(SDMass[i]);
	h_AK8SDCorrThea[i]->Fill(SDMass[i]*thea_corr);
	h_AK8SDHCorr[i]->Fill(SDMass[i]*H_corr);

	h_PR[2]->Fill(fatjetPRmass[i]);
	h_PRCorr[2]->Fill(fatjetPRmassL2L3Corr[i]);
	h_AK8SD[2]->Fill(SDMass[i]);
	h_AK8SDCorrThea[2]->Fill(SDMass[i]*thea_corr);
	h_AK8SDHCorr[2]->Fill(SDMass[i]*H_corr);

	h_diff_PR[i]->Fill((fatjetPRmass[i]-125)/125);
	h_diff_PRCorr[i]->Fill((fatjetPRmassL2L3Corr[i]-125)/125);
	h_diff_AK8SD[i]->Fill((SDMass[i]-125)/125);
	h_diff_AK8SDCorrThea[i]->Fill((SDMass[i]*thea_corr-125)/125);
	h_diff_AK8SDHCorr[i]->Fill((SDMass[i]*H_corr-125)/125);

	h_diff_PR[2]->Fill((fatjetPRmass[i]-125)/125);
	h_diff_PRCorr[2]->Fill((fatjetPRmassL2L3Corr[i]-125)/125);
	h_diff_AK8SD[2]->Fill((SDMass[i]-125)/125);
	h_diff_AK8SDCorrThea[2]->Fill((SDMass[i]*thea_corr-125)/125);
	h_diff_AK8SDHCorr[2]->Fill((SDMass[i]*H_corr-125)/125);
      }
    

  } // end of loop over entries

  std::cout << "nTotal    = " << nTotal << std::endl;
  for(int i=0;i<20;i++)
    if(nPass[i]>0)
      std::cout << "nPass[" << i << "]= " << nPass[i] << std::endl;

  TFile* outFile = new TFile(Form("output/%s",outputFile.Data()),"recreate");

  for(int i=0; i<nHistos; i++)
    {
      h_diff_PR[i]->Write();
      h_diff_PRCorr[i]->Write();
	h_diff_AK8SD[i]->Write();
	h_diff_AK8SDCorrThea[i]->Write();
	h_diff_AK8SDHCorr[i]->Write();
      
      h_PR[i]->Write();
      h_PRCorr[i]->Write();
	h_AK8SD[i]->Write();
	h_AK8SDCorrThea[i]->Write();
	h_AK8SDHCorr[i]->Write();
    }
  outFile->Close();

}
Example #22
0
//////////////////Taking in/out file name as input
void loop(string infile, string outfile, bool REAL=0){
//void loop(bool REAL=0){

const   char* infname;
const   char* outfname;
/////////////////

   if(REAL)
     {
      cout<<"--- REAL DATA ---"<<endl;
      infname = "/net/hidsk0001/d00/scratch/yjlee/bmeson/merged_pPbData_20131114.root";
      outfname = "nt_data.root";
     }
   else
     {
      cout<<"--- MC ---"<<endl;
	  //infname = "/mnt/hadoop/cms/store/user/wangj/HI_Btuple/20140218_PAMuon_HIRun2013_PromptReco_v1/Bfinder_all_100_1_Jrd.root";
      //outfname = "nt_mc.root";

//////////////////
	  infname = infile.c_str();
	  outfname = outfile.c_str();
/////////////////

     }

   //File type
   TFile *f = new TFile(infname);
   TTree *root = (TTree*)f->Get("demo/root");

   //Chain type
   //TChain* root = new TChain("demo/root");
   //root->Add("/mnt/hadoop/cms/store/user/twang/HI_Btuple/20131202_PPMuon_Run2013A-PromptReco-v1_RECO/Bfinder_all_*");

   setBranch(root);
   TFile *outf = new TFile(outfname,"recreate");

   int ifchannel[7];
   ifchannel[0] = 1; //jpsi+Kp
   ifchannel[1] = 1; //jpsi+pi
   ifchannel[2] = 1; //jpsi+Ks(pi+,pi-)
   ifchannel[3] = 1; //jpsi+K*(K+,pi-)
   ifchannel[4] = 1; //jpsi+K*(K-,pi+)
   ifchannel[5] = 1; //jpsi+phi
   ifchannel[6] = 1; //jpsi+pi pi <= psi', X(3872), Bs->J/psi f0
   bNtuple* b0 = new bNtuple;
   bNtuple* b1 = new bNtuple;
   bNtuple* b2 = new bNtuple;
   bNtuple* b3 = new bNtuple;
   bNtuple* b4 = new bNtuple;
   bNtuple* b5 = new bNtuple;
   bNtuple* b6 = new bNtuple;
      
   TTree* nt0 = new TTree("ntKp","");
   b0->buildBranch(nt0);
   TTree* nt1 = new TTree("ntpi","");
   b1->buildBranch(nt1);
   TTree* nt2 = new TTree("ntKs","");
   b2->buildBranch(nt2);
   TTree* nt3 = new TTree("ntKstar1","");
   b3->buildBranch(nt3);
   TTree* nt4 = new TTree("ntKstar2","");
   b4->buildBranch(nt4);
   TTree* nt5 = new TTree("ntphi","");
   b5->buildBranch(nt5);
   TTree* nt6 = new TTree("ntmix","");
   b6->buildBranch(nt6);

   TNtuple* ntGen = new TNtuple("ntGen","","y:eta:phi:pt:pdgId");

   Long64_t nentries = root->GetEntries();
   Long64_t nbytes = 0;
   TVector3* bP = new TVector3;
   TVector3* bVtx = new TVector3;
   TLorentzVector bGen;
   int type;

   for (Long64_t i=0; i<100;i++) {
//   for (Long64_t i=0; i<nentries;i++) {
      nbytes += root->GetEntry(i);
      if (i%10000==0) cout <<i<<" / "<<nentries<<endl;
      for (int j=0;j<BInfo_size;j++) {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	if(BInfo_type[j]==1)
	  {
	    fillTree(b0,bP,bVtx,j);
	    nt0->Fill();
	  }
	if(BInfo_type[j]==2)
	  {
	    fillTree(b1,bP,bVtx,j);
	    nt1->Fill();
	  }
	if(BInfo_type[j]==3)
	  {
	    fillTree(b2,bP,bVtx,j);
	    nt2->Fill();
	  }
	if(BInfo_type[j]==4)
	  {
	    fillTree(b3,bP,bVtx,j);
	    nt3->Fill();
	  }
	if(BInfo_type[j]==5)
	  {
	    fillTree(b4,bP,bVtx,j);
	    nt4->Fill();
	  }
	if(BInfo_type[j]==6)
	  {
	    fillTree(b5,bP,bVtx,j);
	    nt5->Fill();
	  }
	if(BInfo_type[j]==7)
	  {
	    fillTree(b6,bP,bVtx,j);
	    nt6->Fill();
	  }
      }

      for (int j=0;j<GenInfo_size;j++)
	{
	  for(type=1;type<8;type++)
	    {
	      if(signalGen(type,j))
		{
		  bGen.SetPtEtaPhiM(GenInfo_pt[j],GenInfo_eta[j],GenInfo_phi[j],GenInfo_mass[j]);
		  ntGen->Fill(bGen.Rapidity(),bGen.Eta(),bGen.Phi(),bGen.Pt(),GenInfo_pdgId[j]);
		  break;
		}
	    }
	}
   }

  outf->Write();
  outf->Close();
}
int main( int argc, char* argv[] ) {


    std::string filename;
    if( use76 )
        filename = "dcap://t3se01.psi.ch:22125//pnfs/psi.ch/cms/trivcat/store/user/mschoene/MT2production/76X/Spring15/PostProcessed/12Feb2016_ZGammaMC/ZGTo2LG_post.root";
    else
        filename = "dcap://t3se01.psi.ch:22125//pnfs/psi.ch/cms/trivcat/store/user/mmasciov/MT2production/74X/Spring15/PostProcessed/20Dec2015_forGunther/ZGTo2LG_post.root";
    TFile* file = TFile::Open(filename.c_str());
    TTree* tree = (TTree*)file->Get("mt2");

    std::cout << "-> Opened file: " << filename << std::endl;



    TFile* puFile_data = TFile::Open("puData.root");
    TH1D* h1_nVert_data = (TH1D*)puFile_data->Get("nVert");

    TFile* puFile_mc = TFile::Open("puMC.root");
    TH1D* h1_nVert_mc = (TH1D*)puFile_mc->Get("nVert");


    ZGTree myTree;
    myTree.loadGenStuff = true;
    myTree.Init(tree);



    TFile* outFile;
    if( use76 )
        outFile = TFile::Open("genEfficiency76.root", "recreate");
    else
        outFile = TFile::Open("genEfficiency.root", "recreate");
    outFile->cd();

    int nBins = 8;
    Double_t bins[nBins+1];
    bins[0] = 300.;
    bins[1] = 350.;
    bins[2] = 400.;
    bins[3] = 450.;
    bins[4] = 500.;
    bins[5] = 600.;
    bins[6] = 700.;
    bins[7] = 800.;
    bins[8] = 950.;

    TH1D* h1_eff_denom = new TH1D( "eff_denom", "", nBins, bins );
    h1_eff_denom->Sumw2();
    TH1D* h1_eff_denom_ee = new TH1D( "eff_denom_ee", "", nBins, bins );
    h1_eff_denom_ee->Sumw2();
    TH1D* h1_eff_denom_mm = new TH1D( "eff_denom_mm", "", nBins, bins );
    h1_eff_denom_mm->Sumw2();

    TH1D* h1_eff_all_num = new TH1D( "eff_all_num", "", nBins, bins );
    h1_eff_all_num->Sumw2();
    TH1D* h1_eff_ee_num = new TH1D( "eff_ee_num", "", nBins, bins );
    h1_eff_ee_num->Sumw2();
    TH1D* h1_eff_mm_num = new TH1D( "eff_mm_num", "", nBins, bins );
    h1_eff_mm_num->Sumw2();
    TH1D* h1_eff_noHLT_num = new TH1D( "eff_noHLT_num", "", nBins, bins );
    h1_eff_noHLT_num->Sumw2();
    TH1D* h1_eff_noIso_num = new TH1D( "eff_noIso_num", "", nBins, bins );
    h1_eff_noIso_num->Sumw2();

    TH1D* h1_massBias = new TH1D( "massBias", "", nBins, bins );
    h1_massBias->Sumw2();
    TH1D* h1_massReso = new TH1D( "massReso", "", nBins, bins );
    h1_massReso->Sumw2();

    TH1D* h1_massBias_ee = new TH1D( "massBias_ee", "", nBins, bins );
    h1_massBias_ee->Sumw2();
    TH1D* h1_massReso_ee = new TH1D( "massReso_ee", "", nBins, bins );
    h1_massReso_ee->Sumw2();

    TH1D* h1_massBias_mm = new TH1D( "massBias_mm", "", nBins, bins );
    h1_massBias_mm->Sumw2();
    TH1D* h1_massReso_mm = new TH1D( "massReso_mm", "", nBins, bins );
    h1_massReso_mm->Sumw2();

    std::vector<TH1D*> vh1_massReso, vh1_massReso_ee, vh1_massReso_mm;

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

        TH1D* h1_tmp = new TH1D( Form("reso_%d", i), "", 40, -0.2, 0.2);
        h1_tmp->Sumw2();
        vh1_massReso.push_back( h1_tmp );

        TH1D* h1_tmp_ee = new TH1D( Form("reso_ee_%d", i), "", 40, -0.2, 0.2);
        h1_tmp_ee->Sumw2();
        vh1_massReso_ee.push_back( h1_tmp_ee );

        TH1D* h1_tmp_mm = new TH1D( Form("reso_mm_%d", i), "", 40, -0.2, 0.2);
        h1_tmp_mm->Sumw2();
        vh1_massReso_mm.push_back( h1_tmp_mm );

    }

    rochcor2015 *rmcor = new rochcor2015();


    TTree* outtree = new TTree("genTree", "");

    int leptType;
    outtree->Branch( "leptType", &leptType, "leptType/I" );

    float gammaReco_pt;
    outtree->Branch( "gammaReco_pt", &gammaReco_pt, "gammaReco_pt/F" );
    float gammaReco_eta;
    outtree->Branch( "gammaReco_eta", &gammaReco_eta, "gammaReco_eta/F" );
    float gammaReco_phi;
    outtree->Branch( "gammaReco_phi", &gammaReco_phi, "gammaReco_phi/F" );
    float gammaReco_mass;
    outtree->Branch( "gammaReco_mass", &gammaReco_mass, "gammaReco_mass/F" );

    float lept0Reco_pt;
    outtree->Branch( "lept0Reco_pt", &lept0Reco_pt, "lept0Reco_pt/F" );
    float lept0Reco_eta;
    outtree->Branch( "lept0Reco_eta", &lept0Reco_eta, "lept0Reco_eta/F" );
    float lept0Reco_phi;
    outtree->Branch( "lept0Reco_phi", &lept0Reco_phi, "lept0Reco_phi/F" );
    float lept0Reco_mass;
    outtree->Branch( "lept0Reco_mass", &lept0Reco_mass, "lept0Reco_mass/F" );

    float lept1Reco_pt;
    outtree->Branch( "lept1Reco_pt", &lept1Reco_pt, "lept1Reco_pt/F" );
    float lept1Reco_eta;
    outtree->Branch( "lept1Reco_eta", &lept1Reco_eta, "lept1Reco_eta/F" );
    float lept1Reco_phi;
    outtree->Branch( "lept1Reco_phi", &lept1Reco_phi, "lept1Reco_phi/F" );
    float lept1Reco_mass;
    outtree->Branch( "lept1Reco_mass", &lept1Reco_mass, "lept1Reco_mass/F" );

    float zReco_pt;
    outtree->Branch( "zReco_pt", &zReco_pt, "zReco_pt/F" );
    float zReco_eta;
    outtree->Branch( "zReco_eta", &zReco_eta, "zReco_eta/F" );
    float zReco_phi;
    outtree->Branch( "zReco_phi", &zReco_phi, "zReco_phi/F" );
    float zReco_mass;
    outtree->Branch( "zReco_mass", &zReco_mass, "zReco_mass/F" );

    float bossReco_pt;
    outtree->Branch( "bossReco_pt", &bossReco_pt, "bossReco_pt/F" );
    float bossReco_eta;
    outtree->Branch( "bossReco_eta", &bossReco_eta, "bossReco_eta/F" );
    float bossReco_phi;
    outtree->Branch( "bossReco_phi", &bossReco_phi, "bossReco_phi/F" );
    float bossReco_mass;
    outtree->Branch( "bossReco_mass", &bossReco_mass, "bossReco_mass/F" );

    float gammaGen_pt;
    outtree->Branch( "gammaGen_pt", &gammaGen_pt, "gammaGen_pt/F" );
    float gammaGen_eta;
    outtree->Branch( "gammaGen_eta", &gammaGen_eta, "gammaGen_eta/F" );
    float gammaGen_phi;
    outtree->Branch( "gammaGen_phi", &gammaGen_phi, "gammaGen_phi/F" );
    float gammaGen_mass;
    outtree->Branch( "gammaGen_mass", &gammaGen_mass, "gammaGen_mass/F" );

    float lept0Gen_pt;
    outtree->Branch( "lept0Gen_pt", &lept0Gen_pt, "lept0Gen_pt/F" );
    float lept0Gen_eta;
    outtree->Branch( "lept0Gen_eta", &lept0Gen_eta, "lept0Gen_eta/F" );
    float lept0Gen_phi;
    outtree->Branch( "lept0Gen_phi", &lept0Gen_phi, "lept0Gen_phi/F" );
    float lept0Gen_mass;
    outtree->Branch( "lept0Gen_mass", &lept0Gen_mass, "lept0Gen_mass/F" );

    float lept1Gen_pt;
    outtree->Branch( "lept1Gen_pt", &lept1Gen_pt, "lept1Gen_pt/F" );
    float lept1Gen_eta;
    outtree->Branch( "lept1Gen_eta", &lept1Gen_eta, "lept1Gen_eta/F" );
    float lept1Gen_phi;
    outtree->Branch( "lept1Gen_phi", &lept1Gen_phi, "lept1Gen_phi/F" );
    float lept1Gen_mass;
    outtree->Branch( "lept1Gen_mass", &lept1Gen_mass, "lept1Gen_mass/F" );

    float zGen_pt;
    outtree->Branch( "zGen_pt", &zGen_pt, "zGen_pt/F" );
    float zGen_eta;
    outtree->Branch( "zGen_eta", &zGen_eta, "zGen_eta/F" );
    float zGen_phi;
    outtree->Branch( "zGen_phi", &zGen_phi, "zGen_phi/F" );
    float zGen_mass;
    outtree->Branch( "zGen_mass", &zGen_mass, "zGen_mass/F" );

    float bossGen_pt;
    outtree->Branch( "bossGen_pt", &bossGen_pt, "bossGen_pt/F" );
    float bossGen_eta;
    outtree->Branch( "bossGen_eta", &bossGen_eta, "bossGen_eta/F" );
    float bossGen_phi;
    outtree->Branch( "bossGen_phi", &bossGen_phi, "bossGen_phi/F" );
    float bossGen_mass;
    outtree->Branch( "bossGen_mass", &bossGen_mass, "bossGen_mass/F" );



    int nentries = tree->GetEntries();

    for( int iEntry=0; iEntry<nentries; ++iEntry ) {

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

        myTree.GetEntry(iEntry);

        float weight = (myTree.isData) ? 1. : myTree.evt_scale1fb;
        // pu reweighting:
        if( !myTree.isData ) {
            //weight *= myTree.puWeight;
        }


        // first find leptons
        //if( myTree.ngenLep!=2 ) continue;
        //TLorentzVector genLep0, genLep1;
        //genLep0.SetPtEtaPhiM( myTree.genLep_pt[0], myTree.genLep_eta[0], myTree.genLep_phi[0], myTree.genLep_mass[0] );
        //genLep1.SetPtEtaPhiM( myTree.genLep_pt[1], myTree.genLep_eta[1], myTree.genLep_phi[1], myTree.genLep_mass[1] );

        std::vector<TLorentzVector> genLeptons;
        int genLeptType = 0;
        for( int iGen=0; iGen<myTree.ngenPart && genLeptons.size()<2; ++iGen ) {

            if( myTree.genPart_pt[iGen]<1. ) continue;
            if( myTree.genPart_status[iGen]!=1 ) continue;
            if( abs(myTree.genPart_pdgId[iGen])!=11 && abs(myTree.genPart_pdgId[iGen])!=13 ) continue;
            if( myTree.genPart_motherId[iGen]!=myTree.genPart_pdgId[iGen] ) continue;
            TLorentzVector tmpLep;
            tmpLep.SetPtEtaPhiM( myTree.genPart_pt[iGen], myTree.genPart_eta[iGen], myTree.genPart_phi[iGen], myTree.genPart_mass[iGen] );
            genLeptons.push_back(tmpLep);
            genLeptType = abs(myTree.genPart_pdgId[iGen]);

        }

        if( genLeptType!=11 && genLeptType!=13 ) continue;
        if( genLeptons.size()<2 ) continue;

        TLorentzVector genLep0, genLep1;
        genLep0 = genLeptons[0];
        genLep1 = genLeptons[1];

        float maxPt = TMath::Max( genLep0.Pt(), genLep1.Pt() );
        float minPt = TMath::Min( genLep0.Pt(), genLep1.Pt() );
        if( maxPt<25. ) continue;
        if( minPt<20. ) continue;

        if( fabs(genLep0.Eta()) > 2.4 ) continue;
        if( fabs(genLep1.Eta()) > 2.4 ) continue;

        TLorentzVector genZ = genLep0 + genLep1;
        if( genZ.M()<50. ) continue;
        //if( genZ.M()<50. || genZ.M()>130. ) continue;


        TLorentzVector genPhoton;
        bool foundGenPhoton = false;

        for( int iGen=0; iGen<myTree.ngenPart && !foundGenPhoton; ++iGen ) {

            if( myTree.genPart_pdgId[iGen]!=22 ) continue;
            if( myTree.genPart_status[iGen]!=1 ) continue;
            if( myTree.genPart_pt[iGen]<40. ) continue;
            if( fabs(myTree.genPart_eta[iGen])>2.5 ) continue;

            TLorentzVector photon_temp;
            photon_temp.SetPtEtaPhiM( myTree.genPart_pt[iGen], myTree.genPart_eta[iGen], myTree.genPart_phi[iGen], myTree.genPart_mass[iGen] );

            float deltaRmin_part = 999.;
            // look for closest parton
            for( int jGen=0; jGen<myTree.ngenPart && iGen!=jGen; ++jGen ) {

                if( myTree.genPart_pt[jGen]<1. ) continue;
                if( myTree.genPart_status[jGen]<=21 ) continue;
                bool isParton = ( myTree.genPart_pdgId[jGen]==21 || abs(myTree.genPart_pdgId[jGen])<7 );
                if( !isParton ) continue;

                TLorentzVector thisparton;
                thisparton.SetPtEtaPhiM( myTree.genPart_pt[jGen], myTree.genPart_eta[jGen], myTree.genPart_phi[jGen], myTree.genPart_mass[jGen] );

                float thisDeltaR = thisparton.DeltaR(photon_temp);
                if( thisDeltaR<deltaRmin_part ) {
                    deltaRmin_part = thisDeltaR;
                }

            }

            // far away from partons
            if( deltaRmin_part<0.4 ) continue;


            // far away from leptons
            if( photon_temp.DeltaR( genLep0 ) > 0.4 && photon_temp.DeltaR( genLep1 ) > 0.4 ) {
                genPhoton.SetPtEtaPhiM( myTree.genPart_pt[iGen], myTree.genPart_eta[iGen], myTree.genPart_phi[iGen], myTree.genPart_mass[iGen] );
                foundGenPhoton = true;
            }

        }


        if( !foundGenPhoton ) continue;
        if( genPhoton.Pt()<40. ) continue;
        if( fabs(genPhoton.Eta())>2.5 ) continue;
        if( fabs(genPhoton.Eta())>1.44 && fabs(genPhoton.Eta())<1.57 ) continue;


        TLorentzVector genBoss = genZ + genPhoton;
        float genMass = genBoss.M();
        if( genMass<200. ) continue;

        h1_eff_denom->Fill( genMass, weight );
        if( genLeptType==11 )
            h1_eff_denom_ee->Fill( genMass, weight );
        else
            h1_eff_denom_mm->Fill( genMass, weight );


        // and now reco!

        if( myTree.nVert==0 ) continue;


        if( myTree.nlep!=2 ) continue; // two leptons
        if( myTree.lep_pdgId[0] != -myTree.lep_pdgId[1] ) continue; // same flavour, opposite sign

        leptType = abs(myTree.lep_pdgId[0]);
        if( leptType!=11 && leptType!=13 ) continue; // just in case


        TLorentzVector lept0;
        lept0.SetPtEtaPhiM( myTree.lep_pt[0], myTree.lep_eta[0], myTree.lep_phi[0], myTree.lep_mass[0] );
        TLorentzVector lept1;
        lept1.SetPtEtaPhiM( myTree.lep_pt[1], myTree.lep_eta[1], myTree.lep_phi[1], myTree.lep_mass[1] );

        if( lept0.Pt()<25. ) continue;
        if( lept1.Pt()<20. ) continue;

        if( leptType==11 ) { //electrons
            if( myTree.lep_tightId[0]==0 || myTree.lep_tightId[1]==0 ) continue; // loose electron ID
        } else { // muons
            float qter = 1.0;
            rmcor->momcor_mc(lept0, myTree.lep_pdgId[0]/(abs(myTree.lep_pdgId[0])), 0, qter);
            rmcor->momcor_mc(lept1, myTree.lep_pdgId[1]/(abs(myTree.lep_pdgId[1])), 0, qter);
            //if( myTree.lep_tightId[0]==0 && myTree.lep_tightId[1]==0 ) continue; // tight muon ID on one leg
        }


        TLorentzVector zBoson = lept0+lept1;
        if( zBoson.M()<50. ) continue;
        //if( zBoson.M()<50. || zBoson.M()>130. ) continue;


        if( myTree.ngamma==0 ) continue; // photon

        bool foundPhoton = false;
        TLorentzVector photon;

        for( int iPhot=0; iPhot<myTree.ngamma && !foundPhoton; ++iPhot ) {

            TLorentzVector tmp_photon;
            tmp_photon.SetPtEtaPhiM( myTree.gamma_pt[iPhot], myTree.gamma_eta[iPhot], myTree.gamma_phi[iPhot], myTree.gamma_mass[iPhot] );

            if( tmp_photon.Pt()<40. ) continue;
            if( fabs(tmp_photon.Eta())>1.44 && fabs(tmp_photon.Eta())<1.57 ) continue;
            if( fabs(tmp_photon.Eta())>2.5 ) continue;
            if( myTree.gamma_idCutBased[iPhot]==0 ) continue;
            //if( fabs(myTree.gamma_eta[iPhot])<1.44 ) {
            //  if( myTree.gamma_sigmaIetaIeta[iPhot]>0.0102 ) continue;
            //} else {
            //  if( myTree.gamma_sigmaIetaIeta[iPhot]>0.0274 ) continue;
            //}
            float deltaR_thresh = 0.4;
            if( tmp_photon.DeltaR(lept0)<deltaR_thresh || tmp_photon.DeltaR(lept1)<deltaR_thresh ) continue;

            photon.SetPtEtaPhiM( myTree.gamma_pt[iPhot], myTree.gamma_eta[iPhot], myTree.gamma_phi[iPhot], myTree.gamma_mass[iPhot] );
            foundPhoton = true;

        }

        if( !foundPhoton ) continue;

        smearEmEnergy( photon );

        TLorentzVector boss = zBoson + photon;
        float recoMass = boss.M();
        if( recoMass<200. ) continue;

        h1_eff_noHLT_num->Fill( genMass, weight );

        if( !( myTree.HLT_DoubleEl || myTree.HLT_DoubleMu || myTree.HLT_DoubleEl33 || myTree.HLT_SingleMu ) ) continue;

        h1_eff_noIso_num->Fill( genMass, weight );

        if( myTree.gamma_chHadIso[0]>2.5 ) continue;

        h1_eff_all_num->Fill( genMass, weight );
        if( leptType==11 ) h1_eff_ee_num->Fill( genMass, weight );
        else               h1_eff_mm_num->Fill( genMass, weight );

        int iBin = h1_eff_all_num->FindBin( genMass ) - 1;

        if( iBin>=0 && iBin<vh1_massReso.size() ) {
            vh1_massReso[iBin]->Fill( (recoMass-genMass)/genMass, weight );
            if( leptType==11 ) {
                vh1_massReso_ee[iBin]->Fill( (recoMass-genMass)/genMass, weight );
            } else {
                vh1_massReso_mm[iBin]->Fill( (recoMass-genMass)/genMass, weight );
            }
        }

        // set tree branches and fill tree
        gammaReco_pt   = photon.Pt();
        gammaReco_eta  = photon.Eta();
        gammaReco_phi  = photon.Phi();
        gammaReco_mass = photon.M();

        lept0Reco_pt   = lept0.Pt();
        lept0Reco_eta  = lept0.Eta();
        lept0Reco_phi  = lept0.Phi();
        lept0Reco_mass = lept0.M();

        lept1Reco_pt   = lept1.Pt();
        lept1Reco_eta  = lept1.Eta();
        lept1Reco_phi  = lept1.Phi();
        lept1Reco_mass = lept1.M();

        zReco_pt   = zBoson.Pt();
        zReco_eta  = zBoson.Eta();
        zReco_phi  = zBoson.Phi();
        zReco_mass = zBoson.M();

        bossReco_pt   = boss.Pt();
        bossReco_eta  = boss.Eta();
        bossReco_phi  = boss.Phi();
        bossReco_mass = boss.M();

        gammaGen_pt   = genPhoton.Pt();
        gammaGen_eta  = genPhoton.Eta();
        gammaGen_phi  = genPhoton.Phi();
        gammaGen_mass = genPhoton.M();

        lept0Gen_pt   = genLep0.Pt();
        lept0Gen_eta  = genLep0.Eta();
        lept0Gen_phi  = genLep0.Phi();
        lept0Gen_mass = genLep0.M();

        lept1Gen_pt   = genLep1.Pt();
        lept1Gen_eta  = genLep1.Eta();
        lept1Gen_phi  = genLep1.Phi();
        lept1Gen_mass = genLep1.M();

        zGen_pt   = genZ.Pt();
        zGen_eta  = genZ.Eta();
        zGen_phi  = genZ.Phi();
        zGen_mass = genZ.M();

        bossGen_pt   = genBoss.Pt();
        bossGen_eta  = genBoss.Eta();
        bossGen_phi  = genBoss.Phi();
        bossGen_mass = genBoss.M();

        outtree->Fill();

    } // for entries


    outFile->cd();

    h1_eff_denom->Write();
    h1_eff_denom_ee->Write();
    h1_eff_denom_mm->Write();
    h1_eff_all_num->Write();
    h1_eff_ee_num->Write();
    h1_eff_mm_num->Write();
    h1_eff_noHLT_num->Write();
    h1_eff_noIso_num->Write();

    TEfficiency* eff_all = new TEfficiency( *h1_eff_all_num, *h1_eff_denom);
    eff_all->SetName( "eff_all" );
    eff_all->Write();

    TEfficiency* eff_ee = new TEfficiency( *h1_eff_ee_num, *h1_eff_denom_ee);
    eff_ee->SetName( "eff_ee" );
    eff_ee->Write();

    TEfficiency* eff_mm = new TEfficiency( *h1_eff_mm_num, *h1_eff_denom_mm);
    eff_mm->SetName( "eff_mm" );
    eff_mm->Write();

    TEfficiency* eff_noHLT = new TEfficiency( *h1_eff_noHLT_num, *h1_eff_denom);
    eff_noHLT->SetName( "eff_noHLT" );
    eff_noHLT->Write();

    TEfficiency* eff_noIso = new TEfficiency( *h1_eff_noIso_num, *h1_eff_denom);
    eff_noIso->SetName( "eff_noIso" );
    eff_noIso->Write();


    for( unsigned i=0; i<vh1_massReso.size(); ++i ) {

        h1_massBias->SetBinContent( i+1, vh1_massReso[i]->GetMean() );
        h1_massReso->SetBinContent( i+1, vh1_massReso[i]->GetRMS() );
        h1_massBias->SetBinError  ( i+1, vh1_massReso[i]->GetMeanError() );
        h1_massReso->SetBinError  ( i+1, vh1_massReso[i]->GetRMSError() );

        h1_massBias_ee->SetBinContent( i+1, vh1_massReso_ee[i]->GetMean() );
        h1_massReso_ee->SetBinContent( i+1, vh1_massReso_ee[i]->GetRMS() );
        h1_massBias_ee->SetBinError  ( i+1, vh1_massReso_ee[i]->GetMeanError() );
        h1_massReso_ee->SetBinError  ( i+1, vh1_massReso_ee[i]->GetRMSError() );

        h1_massBias_mm->SetBinContent( i+1, vh1_massReso_mm[i]->GetMean() );
        h1_massReso_mm->SetBinContent( i+1, vh1_massReso_mm[i]->GetRMS() );
        h1_massBias_mm->SetBinError  ( i+1, vh1_massReso_mm[i]->GetMeanError() );
        h1_massReso_mm->SetBinError  ( i+1, vh1_massReso_mm[i]->GetRMSError() );

        vh1_massReso[i]->Write();
        vh1_massReso_ee[i]->Write();
        vh1_massReso_mm[i]->Write();

    }

    h1_massReso->Write();
    h1_massBias->Write();
    h1_massReso_ee->Write();
    h1_massBias_ee->Write();
    h1_massReso_mm->Write();
    h1_massBias_mm->Write();

    outtree->Write();

    outFile->Close();

    return 0;

}
void HH4bCategoryBase_80(int wMs,int wM, string st,string st2,string option=""){	

	//1=signal ,0=QCD ,2=data
	int nameRoot=1;
	if(st2.find("QCD")!= std::string::npos)nameRoot=0;
	if(st2.find("data")!= std::string::npos)nameRoot=2;
	cout<<"nameRoot = "<<nameRoot<<endl;
	
	//option-----------------------------------------------------------
	
	int JESOption=0;
	if(option.find("JESUp")!= std::string::npos)JESOption=1;
	if(option.find("JESDown")!= std::string::npos)JESOption=2;
	cout<<"JESOption = "<<JESOption<<endl;
	
	
	//using for Btag Eff -----------------------------------------------------------------------------
	string btagsystematicsType="central";
	if(JESOption==3)btagsystematicsType="up";
	else if(JESOption==4)btagsystematicsType="down";
	BTagCalibration calib("CSVv2L", "subjet_CSVv2_ichep.csv");
	BTagCalibrationReader LF(BTagEntry::OP_LOOSE,"central", {"up", "down"});  
	BTagCalibrationReader HFC(BTagEntry::OP_LOOSE, "central", {"up", "down"});      // other sys types
	BTagCalibrationReader HF(BTagEntry::OP_LOOSE,"central",{"up", "down"});      // other sys types
	LF.load(calib, BTagEntry::FLAV_UDSG,    // btag flavour
            "incl");               // measurement type
	HFC.load(calib, BTagEntry::FLAV_C,    // btag flavour
            "lt");               // measurement type
	HF.load(calib, BTagEntry::FLAV_B,    // btag flavour
            "lt");               // measurement type
	
	TFile *f1;
	if(nameRoot==2)f1=TFile::Open("btagEffSource/data.root");
	else if (nameRoot!=2 && (JESOption==0||JESOption==3||JESOption==4||JESOption==5||JESOption==6))f1=TFile::Open(Form("btagEffSource/%s.root",st2.data()));
	else if (nameRoot!=2 && JESOption==1)f1=TFile::Open(Form("btagEffSource/%s_JESUp.root",st2.data()));
	else if (nameRoot!=2 && JESOption==2)f1=TFile::Open(Form("btagEffSource/%s_JESDown.root",st2.data()));
	TH1D* th1[6];
	string btaggingEff[6]={"effD_b","effN_b","effD_c","effN_c","effD_l","effN_l"};
	for(int i=0;i<6;i++){
		th1[i]=(TH1D*)f1->FindObjectAny(Form("%s_1d",btaggingEff[i].data()));
		if(i==1||i==3||i==5)th1[i]->Divide(th1[i-1]);
	}
	
	standalone_LumiReWeighting LumiWeights_central(0),LumiWeights_up(1),LumiWeights_down(-1);
	
	TFile *f;
	TTree *tree;
	int nPass[20]={0};
	int total=0;
	double fixScaleNum[2]={0};
	double xBinsForHeavyFlavor[5]={30,140,180,240,3000};
	double xBinsForLightFlavor[11]={20,100,200,300,400,500,600,700,800,900,3000};
	
	TH1D* th5[3];
	th5[0]=new TH1D("cat0","cat0",4000,1000,5000);
	th5[1]=new TH1D("cat1","cat1",4000,1000,5000);
	th5[2]=new TH1D("cat2","cat2",4000,1000,5000);

	for(int i=0;i<3;i++){
		th5[i]->Sumw2();
	}
	
	//---------------------------------
	
	for (int w=wMs;w<wM;w++){
		if(w%20==0)cout<<w<<endl;
		
		if (nameRoot!=1)f = TFile::Open(Form("%s%d.root",st.data(),w));
		else f = TFile::Open(st.data());
		if (!f || !f->IsOpen())continue;
		
		TDirectory * dir;
		if (nameRoot!=1)dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
		else dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));
		
		dir->GetObject("treeMaker",tree);
		TreeReader data(tree);
		total+=data.GetEntriesFast();
		for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){
			data.GetEntry(jEntry);
			
			
			double PU_weight[3]={1,1,1};
			Float_t ntrue= data.GetFloat("pu_nTrueInt");
			if(nameRoot!=2){
				if(ntrue<51){
					PU_weight[0] = LumiWeights_central.weight(ntrue);
					PU_weight[1]= LumiWeights_up.weight(ntrue);
					PU_weight[2] = LumiWeights_down.weight(ntrue);
				}
				else {
					PU_weight[0] = LumiWeights_central.weight(50);
					PU_weight[1] = LumiWeights_up.weight(50);
					PU_weight[2]= LumiWeights_down.weight(50);
				}
			}
			fixScaleNum[0]+=PU_weight[0];
			
			Int_t nVtx        = data.GetInt("nVtx");
			//0. has a good vertex
			if(nVtx<1)continue;
			nPass[0]++;
			
			//1.trigger
			std::string* trigName = data.GetPtrString("hlt_trigName");
		 	vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
			bool passTrigger=false;
			for(int it=0; it< data.GetPtrStringSize();it++){
				std::string thisTrig= trigName[it];
				bool results = trigResult[it];
				if( ((thisTrig.find("HLT_PFHT800")!= std::string::npos||
						thisTrig.find("HLT_PFHT650_WideJetMJJ900DEtaJJ1p5_v")!= std::string::npos||
						thisTrig.find("HLT_PFHT650_WideJetMJJ950DEtaJJ1p5_v")!= std::string::npos||
						thisTrig.find("HLT_AK8PFJet360_TrimMass30_v")!= std::string::npos||
						thisTrig.find("HLT_AK8PFHT700_TrimR0p1PT0p03Mass50_v")!= std::string::npos
						) && results==1)){
					passTrigger=true;
					break;
				}
			}
			if(!passTrigger && nameRoot==2)continue;
			nPass[1]++;

			const int nFATJet=data.GetInt("FATnJet");
			//2.nJets
			if(nFATJet<2)continue;nPass[2]++;
			TClonesArray* fatjetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
			float*  FATjetCorrUncUp = data.GetPtrFloat("FATjetCorrUncUp"); 
			float*  FATjetCorrUncDown = data.GetPtrFloat("FATjetCorrUncDown"); 
			TLorentzVector* thisJet ,* thatJet;
			if(JESOption==0){
				thisJet=(TLorentzVector*)fatjetP4->At(0);
				thatJet=(TLorentzVector*)fatjetP4->At(1);
			}
			else if (JESOption==1){
				TLorentzVector thisJetScaleUp= (*((TLorentzVector*)fatjetP4->At(0)))*(1+FATjetCorrUncUp[0]);
				TLorentzVector thatJetScaleUp= (*((TLorentzVector*)fatjetP4->At(1)))*(1+FATjetCorrUncUp[1]);
				thisJet= &thisJetScaleUp;
				thatJet= &thatJetScaleUp;
			}
			else if (JESOption==2){
				TLorentzVector thisJetScaleDown= (*((TLorentzVector*)fatjetP4->At(0)))*(1-FATjetCorrUncDown[0]);
				TLorentzVector thatJetScaleDown= (*((TLorentzVector*)fatjetP4->At(1)))*(1-FATjetCorrUncDown[1]);
				thisJet= &thisJetScaleDown;
				thatJet= &thatJetScaleDown;
			}
			
			//3. Pt 
			if(thisJet->Pt()<200)continue;
			if(thatJet->Pt()<200)continue;
			nPass[3]++;
			//4tightId-----------------------------------------
			vector<bool>    &FATjetPassIDTight = *((vector<bool>*) data.GetPtr("FATjetPassIDTight"));
			if(FATjetPassIDTight[0]==0)continue;
			if(FATjetPassIDTight[1]==0)continue;
			Float_t*  FATjetCEmEF = data.GetPtrFloat("FATjetCEmEF");
			Float_t*  FATjetMuEF = data.GetPtrFloat("FATjetMuEF");
			if(FATjetMuEF[0]>0.8)continue;
			if(FATjetCEmEF[0]>0.9)continue;
			if(FATjetMuEF[1]>0.8)continue;
			if(FATjetCEmEF[1]>0.9)continue;
			nPass[4]++;
			//5. Eta-----------------------------------------
			if(fabs(thisJet->Eta())>2.4)continue;
			if(fabs(thatJet->Eta())>2.4)continue;
			nPass[5]++;
			//6. DEta-----------------------------------------
			float dEta = fabs(thisJet->Eta()-thatJet->Eta());
			if(dEta>1.3)continue;
			nPass[6]++;
			//7. Mjj-----------------------------------------
			float mjjRed = (*thisJet+*thatJet).M()+250-thisJet->M()-thatJet->M();
			if(mjjRed<1000)continue;
			nPass[7]++;
			//8. fatjetPRmassL2L3Corr-----------------------------------------
			Float_t*  fatjetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
			if(fatjetPRmassL2L3Corr[0]<105||fatjetPRmassL2L3Corr[0]>135)continue;
			if(fatjetPRmassL2L3Corr[1]<105||fatjetPRmassL2L3Corr[1]>135)continue;
			nPass[8]++;
			//9.-----------------------------------------
			Float_t*  fatjetTau1 = data.GetPtrFloat("FATjetTau1");
			Float_t*  fatjetTau2 = data.GetPtrFloat("FATjetTau2");
			double tau21_1=(fatjetTau2[0]/fatjetTau1[0]),tau21_2=(fatjetTau2[1]/fatjetTau1[1]);
			//10.btag
			vector<float>   *subjetSDCSV =  data.GetPtrVectorFloat("FATsubjetSDCSV");
			int nbtag=0;
			if(subjetSDCSV[0][0]>0.46)nbtag++;
			if(subjetSDCSV[0][1]>0.46)nbtag++;
			if(subjetSDCSV[1][0]>0.46)nbtag++;
			if(subjetSDCSV[1][1]>0.46)nbtag++;
			
			vector<float>   *subjetSDPx  =  data.GetPtrVectorFloat("FATsubjetSDPx");
			vector<float>   *subjetSDPy  =  data.GetPtrVectorFloat("FATsubjetSDPy");
			vector<float>   *subjetSDPz  =  data.GetPtrVectorFloat("FATsubjetSDPz");
			vector<float>   *subjetSDE   =  data.GetPtrVectorFloat("FATsubjetSDE");
			vector<Int_t>   *FATsubjetSDHadronFlavor =  data.GetPtrVectorInt("FATsubjetSDHadronFlavor");
			
			double sf[2][2],subjetPt[2][2],subjetEta[2][2],eff[2][2],btaggingscaleFactor=1;
			TLorentzVector* subjetP4[2][2];
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					sf[i][j]=1;
					subjetP4[i][j]=new TLorentzVector(0,0,0,0);
					subjetP4[i][j]->SetPxPyPzE(subjetSDPx[i][j],subjetSDPy[i][j],subjetSDPz[i][j],subjetSDE[i][j]);
					subjetPt[i][j]=subjetP4[i][j]->Pt();
					subjetEta[i][j]=subjetP4[i][j]->Eta();
				}
			}
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					
					//get btagging eff------------------------------------------------------------
					int getPtBin=1;
					if(subjetPt[i][j]<140)getPtBin=1;
					else if (140<=subjetPt[i][j] && subjetPt[i][j]<180)getPtBin=2;
					else if (180<=subjetPt[i][j] && subjetPt[i][j]<240)getPtBin=3;
					else getPtBin=4;
					if(FATsubjetSDHadronFlavor[i][j]==5)eff[i][j]=th1[1]->GetBinContent(getPtBin);
					else if(FATsubjetSDHadronFlavor[i][j]==4)eff[i][j]=th1[3]->GetBinContent(getPtBin);
					else {
						int temp=0;
						if(subjetPt[i][j]>=900)temp=10;
						else temp=ceil(subjetPt[i][j]/100);
						
						bool checkBinContentIfZero=0;
						while(checkBinContentIfZero==0){
							if(th1[4]->GetBinContent(temp)==0){
								temp--;
							}
							else checkBinContentIfZero=1;
						}
						eff[i][j]=th1[5]->GetBinContent(temp);
					}
					//Get SF from csv------------------------------------------------------------
					if(FATsubjetSDHadronFlavor[i][j]==5){
						sf[i][j]=HF.eval_auto_bounds("central",BTagEntry::FLAV_B, subjetEta[i][j],subjetPt[i][j]); 
					}
					else if(FATsubjetSDHadronFlavor[i][j]==4){
						sf[i][j]=HFC.eval_auto_bounds("central",BTagEntry::FLAV_C, subjetEta[i][j],subjetPt[i][j]); 
					}
					else {
						sf[i][j]=LF.eval_auto_bounds("central",BTagEntry::FLAV_UDSG, subjetEta[i][j],subjetPt[i][j]); 
					}
					//get tot. btagging SF
					if(subjetSDCSV[i][j]>=0.46)btaggingscaleFactor*=sf[i][j];
					else btaggingscaleFactor*=((1-eff[i][j]*sf[i][j])/(1-eff[i][j]));
					
				}
			}
			
			//if(tau21_1>0.75 || tau21_2>0.75) continue;
			
			//if(nbtag==3 && ((tau21_1>0.6 && tau21_2<0.6)||(tau21_1<0.6 && tau21_2>0.6)))th1[2]->Fill(mjjRed);
			
			if(tau21_1>0.6 || tau21_2>0.6) continue;
			if(nbtag==4)th5[0]->Fill(mjjRed,btaggingscaleFactor*PU_weight[0]);
			if(nbtag==3)th5[1]->Fill(mjjRed,btaggingscaleFactor*PU_weight[0]);
			if(nbtag==2)th5[2]->Fill(mjjRed,btaggingscaleFactor*PU_weight[0]);
			nPass[9]++;
			
			 fixScaleNum[1]+=PU_weight[0];
			
			
			
		}
	}	
	cout<<"entries="<<total<<endl;	
	for(int i=0;i<9;i++)cout<<"nPass["<<i<<"]="<<nPass[i]<<endl;
	
	
	TH1D * fixScale=new TH1D("fixScale","fixScale",2,-0.5,1.5);
	fixScale->SetBinContent(1,fixScaleNum[0]);
	fixScale->SetBinContent(2,fixScaleNum[1]);
	
	TFile* outFile ;
	if(JESOption==0)outFile= new TFile(Form("category/%s.root",st2.data()),"recreate");
	else if(JESOption==1)outFile= new TFile(Form("category/%s_JESUp.root",st2.data()),"recreate");
	else if(JESOption==2)outFile= new TFile(Form("category/%s_JESDown.root",st2.data()),"recreate");
	fixScale->Write();
	for(int i=0;i<3;i++){
		th5[i]->Write();
	}
	outFile->Close();
}
Example #25
0
void fitSingleMass( const std::string& basedir, float mass, const std::string&  width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) {


  std::string outdir = "genSignalShapes";
  system( Form("mkdir -p %s", outdir.c_str()) );


  std::string dataset( Form( "GluGluSpin0ToZGamma_ZToLL_W_%s_M_%.0f_TuneCUEP8M1_13TeV_pythia8", width.c_str(), mass ) );
  std::cout << "-> Starting: " << dataset << std::endl;

  system( Form("ls %s/%s/crab_%s/*/0000/genAna_1.root >> toBeAdded.txt", basedir.c_str(), dataset.c_str(), dataset.c_str() ) );
  TChain* tree = new TChain("mt2");
  ifstream ifs("toBeAdded.txt");
  while( ifs.good() ) {
    std::string fileName;
    ifs >> fileName;
    TString fileName_tstr(fileName);
    if( !fileName_tstr.Contains("pnfs") ) continue;
    tree->Add(Form("$DCAP/%s/mt2", fileName.c_str()) );
  }
  system( "rm toBeAdded.txt" );

  if( tree->GetEntries()==0 ) return;

  int ngenPart;
  tree->SetBranchAddress( "ngenPart", &ngenPart );
  float genPart_pt[100];
  tree->SetBranchAddress( "genPart_pt", genPart_pt );
  float genPart_eta[100];
  tree->SetBranchAddress( "genPart_eta", genPart_eta );
  float genPart_phi[100];
  tree->SetBranchAddress( "genPart_phi", genPart_phi );
  float genPart_mass[100];
  tree->SetBranchAddress( "genPart_mass", genPart_mass );
  int genPart_pdgId[100];
  tree->SetBranchAddress( "genPart_pdgId", genPart_pdgId );
  int genPart_motherId[100];
  tree->SetBranchAddress( "genPart_motherId", genPart_motherId );
  int genPart_status[100];
  tree->SetBranchAddress( "genPart_status", genPart_status );



  RooRealVar* x = new RooRealVar("boss_mass", "boss_mass", mass, 0.5*mass, 1.5*mass );

  RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(*x) );



  int nentries = tree->GetEntries();


  for( int iEntry = 0; iEntry<nentries; ++iEntry ) {

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

    tree->GetEntry(iEntry);

    TLorentzVector leptPlus;
    TLorentzVector leptMinus;
    TLorentzVector photon;
    bool foundLeptPlus = false;
    bool foundLeptMinus = false;
    bool foundPhoton = false;
    bool tauEvent = false;

    for( int iPart=0; iPart<ngenPart; ++iPart ) {

      if( genPart_status[iPart]!=1 ) continue;

      if( abs(genPart_pdgId[iPart])==15 ) {
        tauEvent = true;
        break;
      }

      if( (genPart_pdgId[iPart]==+11 || genPart_pdgId[iPart]==+13) && genPart_motherId[iPart]==23 ) {
        leptMinus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptMinus = true;
      }
      if( (genPart_pdgId[iPart]==-11 || genPart_pdgId[iPart]==-13) && genPart_motherId[iPart]==23 ) {
        leptPlus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptPlus = true;
      }
      if( genPart_pdgId[iPart]==22 && genPart_motherId[iPart]==25 ) {
        photon.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundPhoton = true;
      }

    } // for genparts

    if( tauEvent ) continue;
    if( !foundLeptPlus || !foundLeptMinus || !foundPhoton ) continue;


    if( photon.Pt() < 40. ) continue;
    float ptMax = TMath::Max( leptPlus.Pt(), leptMinus.Pt() );
    float ptMin = TMath::Min( leptPlus.Pt(), leptMinus.Pt() );
    if( ptMax<25. ) continue;
    if( ptMin<20. ) continue;
    if( fabs( photon.Eta() ) > 2.5 ) continue;
    if( fabs( photon.Eta())>1.44 && fabs( photon.Eta())<1.57 ) continue;
    if( fabs( leptPlus.Eta() ) > 2.4 ) continue;
    if( fabs( leptMinus.Eta() ) > 2.4 ) continue;
    if( photon.DeltaR( leptPlus  ) < 0.4 ) continue;
    if( photon.DeltaR( leptMinus ) < 0.4 ) continue;

    TLorentzVector zBoson = leptPlus + leptMinus;
    if( zBoson.M() < 50. ) continue;

    TLorentzVector boss = zBoson + photon;
    if( boss.M() < 200. ) continue;

    if( photon.Pt()/boss.M()< 40./150. ) continue;

    x->setVal(boss.M());

    data->add(RooArgSet(*x));

  }


  //RooRealVar* bw_mean  = new RooRealVar( "bw_mean", "Breit-Wigner Mean" , mass, 0.2*mass, 1.8*mass );
  //RooRealVar* bw_gamma = new RooRealVar( "bw_gamma", "Breit-Wigner Width", 0.01*mass, 0., 0.3*mass );
  //RooBreitWigner* model = new RooBreitWigner( "bw", "Breit-Wigner", *x, *bw_mean, *bw_gamma);

  // Crystal-Ball
  RooRealVar mean( "mean", "mean", mass, 0.9*mass, 1.1*mass );
  RooRealVar sigma( "sigma", "sigma", 0.015*mass, 0., 0.07*mass );
  RooRealVar alpha1( "alpha1", "alpha1", 1.2, 0., 2.5 );
  RooRealVar n1( "n1", "n1", 3., 0., 5. );
  RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 );
  RooRealVar n2( "n2", "n2", 3., 0., 10. );
  RooDoubleCBShape* model = new RooDoubleCBShape( "cb", "cb", *x, mean, sigma, alpha1, n1, alpha2, n2 );

  model->fitTo( *data );

  int npoints = gr_mean->GetN();
  gr_mean  ->SetPoint( npoints, mass, mean.getVal() );
  gr_sigma ->SetPoint( npoints, mass, sigma.getVal() );
  gr_width ->SetPoint( npoints, mass, sigma.getVal()/mean.getVal() );
  gr_alpha1->SetPoint( npoints, mass, alpha1.getVal() );
  gr_alpha2->SetPoint( npoints, mass, alpha2.getVal() );
  gr_n1    ->SetPoint( npoints, mass, n1.getVal() );
  gr_n2    ->SetPoint( npoints, mass, n2.getVal() );

  gr_mean  ->SetPointError( npoints, 0., mean.getError() );
  gr_sigma ->SetPointError( npoints, 0., sigma.getError() );
  gr_width ->SetPointError( npoints, 0., sigma.getError()/mean.getVal() );
  gr_alpha1->SetPointError( npoints, 0., alpha1.getError() );
  gr_alpha2->SetPointError( npoints, 0., alpha2.getError() );
  gr_n1    ->SetPointError( npoints, 0., n1.getError() );
  gr_n2    ->SetPointError( npoints, 0., n2.getError() );

  //gr_mean ->SetPoint     ( npoints, mass, bw_mean->getVal() );
  //gr_gamma->SetPoint     ( npoints, mass, bw_gamma->getVal() );
  //gr_width->SetPoint     ( npoints, mass, bw_gamma->getVal()/bw_mean->getVal() );
  //gr_mean ->SetPointError( npoints,   0., bw_mean->getError() );
  //gr_gamma->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );
  //gr_width->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );

  RooPlot* plot = x->frame();
  data->plotOn(plot);
  model->plotOn(plot);

  TCanvas* c1 = new TCanvas( "c1", "", 600, 600 );
  c1->cd();

  plot->Draw();
    
  c1->SaveAs( Form("%s/fit_m%.0f_%s.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s.pdf", outdir.c_str(), mass, width.c_str()) );

  c1->SetLogy();

  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.pdf", outdir.c_str(), mass, width.c_str()) );


  //delete bw_mean;
  //delete bw_gamma;

  delete c1;
  delete data;
  delete model;
  delete plot;
  delete x;

}
Example #26
0
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  
void xAna_hh_massResolution(std::string inputFile, bool matchb=false, bool debug=false, bool cut=false){

  TString outputFile;
  outputFile=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; echo \"massHisto_${test}\"",inputFile.data()));
  cout << "output file name = " << outputFile.Data() << endl;


  //get TTree from file ...
  TreeReader data(inputFile.data());
  
  Long64_t nTotal=0;
  Long64_t nPass[20]={0};

  const int nHistos=3;

  TH1F* h_massDiff = new TH1F("h_massDiff","",100,-0.5,0.5);
  //TH1F* h_mass     = new TH1F("h_mass","",100,0,200);
  TH1F* h_mass     = new TH1F("h_mass","",100,62.5,187.5);

  TH1F* h_SD[nHistos];
  TH1F* h_SDCorr[nHistos];
  TH1F* h_SDCorrThea[nHistos];
  
  TH1F* h_AK8SD[nHistos];
  TH1F* h_AK8SDCorrThea[nHistos];
  
  TH1F* h_PR[nHistos];
  TH1F* h_PRCorr[nHistos];

  TH1F* h_diff_SD[nHistos];
  TH1F* h_diff_SDCorr[nHistos];
  TH1F* h_diff_SDCorrThea[nHistos];
  TH1F* h_diff_PR[nHistos];
  TH1F* h_diff_PRCorr[nHistos];
  
  TH1F* h_diff_AK8SD[nHistos];
  TH1F* h_diff_AK8SDCorrThea[nHistos];

  std::string prefix[]={"leading","subleading","both"};
  for(int i=0; i<nHistos; i++)
    {

      h_SD[i] = (TH1F*)h_mass->Clone(Form("h_SD_%s",prefix[i].data()));
      h_SD[i]->SetXTitle("Raw Puppi+Softdrop mass [GeV]");
	
	h_AK8SD[i] = (TH1F*)h_mass->Clone(Form("h_AK8SD_%s",prefix[i].data()));
      h_AK8SD[i]->SetXTitle("AK8 Raw Puppi+Softdrop mass [GeV]");

      h_SDCorr[i] = (TH1F*)h_mass->Clone(Form("h_SDCorr_%s",prefix[i].data()));
      h_SDCorr[i]->SetXTitle("L2L3-corrected Puppi+Softdrop mass [GeV]");

      h_SDCorrThea[i] = (TH1F*)h_mass->Clone(Form("h_SDCorrThea_%s",prefix[i].data()));
      h_SDCorrThea[i]->SetXTitle("Thea-corrected Puppi+Softdrop mass [GeV]");
	
	h_AK8SDCorrThea[i] = (TH1F*)h_mass->Clone(Form("h_AK8SDCorrThea_%s",prefix[i].data()));
      h_AK8SDCorrThea[i]->SetXTitle("AK8 Thea-corrected Puppi+Softdrop mass [GeV]");

      h_PR[i] = (TH1F*)h_mass->Clone(Form("h_PR_%s",prefix[i].data()));
      h_PR[i]->SetXTitle("Raw CHS+Pruned mass [GeV]");

      h_PRCorr[i] = (TH1F*)h_mass->Clone(Form("h_PRCorr_%s",prefix[i].data()));
      h_PRCorr[i]->SetXTitle("L2L3-corrected CHS+Pruned mass [GeV]");

      // study the difference with respect to 125 GeV

      h_diff_SD[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_SD_%s",prefix[i].data()));
      h_diff_SD[i]->SetXTitle("Raw Puppi+Softdrop (m-125)/125");
	
	h_diff_AK8SD[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_AK8SD_%s",prefix[i].data()));
      h_diff_AK8SD[i]->SetXTitle("AK8 Raw Puppi+Softdrop (m-125)/125");

      h_diff_SDCorr[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_SDCorr_%s",prefix[i].data()));
      h_diff_SDCorr[i]->SetXTitle("L2L3-corrected Puppi+Softdrop (m-125)/125");

      h_diff_SDCorrThea[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_SDCorrThea_%s",prefix[i].data()));
      h_diff_SDCorrThea[i]->SetXTitle("Thea-corrected Puppi+Softdrop (m-125)/125");
	
	h_diff_AK8SDCorrThea[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_AK8SDCorrThea_%s",prefix[i].data()));
      h_diff_AK8SDCorrThea[i]->SetXTitle("AK8 Thea-corrected Puppi+Softdrop (m-125)/125");

      h_diff_PR[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_PR_%s",prefix[i].data()));
      h_diff_PR[i]->SetXTitle("Raw CHS+Pruned (m-125)/125");

      h_diff_PRCorr[i] = (TH1F*)h_massDiff->Clone(Form("h_diff_PRCorr_%s",prefix[i].data()));
      h_diff_PRCorr[i]->SetXTitle("L2L3-corrected CHS+Pruned (m-125)/125");

    }


  for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){

    if (jEntry % 1000 == 0)
      fprintf(stderr, "Processing event %lli of %lli\n", jEntry + 1, data.GetEntriesFast());


    if(debug && jEntry>10)break;

    data.GetEntry(jEntry);
    nTotal++;

    //2. pass electron or muon trigger                                                                                                                                          
    std::string* trigName = data.GetPtrString("hlt_trigName");
    vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
    const Int_t nsize = data.GetPtrStringSize();

    bool passTrigger=false;
    for(int it=0; it< nsize; it++)
      {
	std::string thisTrig= trigName[it];
        bool results = trigResult[it];

        // std::cout << thisTrig << " : " << results << std::endl;                                                                                                              

        if( (thisTrig.find("HLT_PFHT900_v")!= std::string::npos && results==1)
            )
          {
            passTrigger=true;
            break;
          }


      }

    if(!passTrigger && cut)continue;
    nPass[4]++;



    Int_t nGenPar        = data.GetInt("nGenPar");
    Int_t* genParId      = data.GetPtrInt("genParId");
    Int_t* genParSt      = data.GetPtrInt("genParSt");
    Int_t* genMomParId   = data.GetPtrInt("genMomParId");
    Int_t* genDa1      = data.GetPtrInt("genDa1");
    Int_t* genDa2      = data.GetPtrInt("genDa2");

    int genHIndex[2]={-1,-1};
    int genbIndex[2][2]={{-1,-1},
			 {-1,-1}};		       

    for(int ig=0; ig < nGenPar; ig++){

      if(genParId[ig]!=25)continue;

      if(genHIndex[0]<0)
	{
	  genHIndex[0]=ig;
	  genbIndex[0][0]=genDa1[ig];
	  genbIndex[0][1]=genDa2[ig];
	}

      else if(genHIndex[1]<0)
	{
	  genHIndex[1]=ig;
	  genbIndex[1][0]=genDa1[ig];
	  genbIndex[1][1]=genDa2[ig];
	}

    }    

    if(genHIndex[0]<0 || genHIndex[1]<0)continue;
    if(genbIndex[0][0]<0 || genbIndex[0][1]<0)continue;
    if(genbIndex[1][0]<0 || genbIndex[1][1]<0)continue;

    nPass[0]++;

    if(genHIndex[0]==genHIndex[1])continue;
    nPass[1]++;

    TLorentzVector genH_l4[2];
    TLorentzVector genb_l4[2][2];
    TClonesArray* genParP4 = (TClonesArray*) data.GetPtrTObject("genParP4");

    for(int ih=0; ih<2; ih++)
      {
	genH_l4[ih] = *((TLorentzVector*)genParP4->At(genHIndex[ih]));
	for(int ib=0; ib<2; ib++)
	  {
	    genb_l4[ih][ib] = *((TLorentzVector*)genParP4->At(genbIndex[ih][ib]));
	  }
      }


    if(debug){
      cout << genHIndex[0] << "\t" << genHIndex[1] << endl;
      genH_l4[0].Print();
      genH_l4[1].Print();

      cout << genbIndex[0][0] << "\t" << genbIndex[0][1] << "\t" 
	   << genbIndex[1][0] << "\t" << genbIndex[1][1] << endl;
      genH_l4[0].Print();
      genH_l4[1].Print();
      genb_l4[0][0].Print();
      genb_l4[0][1].Print();
      genb_l4[1][0].Print();
      genb_l4[1][1].Print();

    }
    int nFATJet         = data.GetInt("FATnJet");
    const int nJets=nFATJet;
    TClonesArray* fatjetP4   = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    TClonesArray* puppijetP4 = (TClonesArray*) data.GetPtrTObject("FATjetPuppiP4");
    TClonesArray* AK8PuppijetP4 = (TClonesArray*) data.GetPtrTObject("AK8PuppijetP4");

    // check matching first

    bool findAMatch=false;
    const float dRMax=0.4;
    const float dRbMax=0.8;
    int matchedHJetIndex[2]={-1,-1};
		      
    for(int ij=0; ij<nJets; ij++)
      {
	TLorentzVector* thisJet = (TLorentzVector*)fatjetP4->At(ij);

	for(int jj=0; jj<nJets; jj++)
	  {

	    if(ij==jj)continue;
	    TLorentzVector* thatJet = (TLorentzVector*)fatjetP4->At(jj);
	    
	    if(thisJet->DeltaR(genH_l4[0])<dRMax && 
	       (!matchb || (matchb && 
			    thisJet->DeltaR(genb_l4[0][0])<dRbMax && 
			    thisJet->DeltaR(genb_l4[0][1])<dRbMax)) &&
	       thatJet->DeltaR(genH_l4[1])<dRMax &&
	       (!matchb || (matchb &&
			    thatJet->DeltaR(genb_l4[1][0])<dRbMax &&
			    thatJet->DeltaR(genb_l4[1][1])<dRbMax)))
	      {
		if(debug)
		  {
		    cout << "dRhb00= " <<  thisJet->DeltaR(genb_l4[0][0]) << endl;
		    cout << "dRhb01= " <<  thisJet->DeltaR(genb_l4[0][1]) << endl;
		    cout << "dRhb10= " <<  thatJet->DeltaR(genb_l4[1][0]) << endl;
		    cout << "dRhb11= " <<  thatJet->DeltaR(genb_l4[1][1]) << endl;
		  }
		if(ij<jj){
		  matchedHJetIndex[0]=ij;
		  matchedHJetIndex[1]=jj;
		}
		else
		  {
		    matchedHJetIndex[0]=jj;
		    matchedHJetIndex[1]=ij;
		  }
		findAMatch=true;
		break;
	      }

	    if(findAMatch)break;

	  }	

	if(findAMatch)break;

      }

    if(!findAMatch)continue;
    if(debug)
      cout << matchedHJetIndex[0] << "\t" << matchedHJetIndex[1] << endl;
    nPass[2]++;

    
    bool findAK8Match=false;
    //const float dRMax=0.4;
    //const float dRbMax=0.8;
    int matchedHAK8JetIndex[2]={-1,-1};
		      int AK8nJet=data.GetInt("AK8PuppinJet");
    for(int ij=0; ij<AK8nJet; ij++)
      {
	TLorentzVector* thisJet = (TLorentzVector*)AK8PuppijetP4->At(ij);

	for(int jj=0; jj<AK8nJet; jj++)
	  {

	    if(ij==jj)continue;
	    TLorentzVector* thatJet = (TLorentzVector*)AK8PuppijetP4->At(jj);
	    
	    if(thisJet->DeltaR(genH_l4[0])<dRMax && 
	       (!matchb || (matchb && 
			    thisJet->DeltaR(genb_l4[0][0])<dRbMax && 
			    thisJet->DeltaR(genb_l4[0][1])<dRbMax)) &&
	       thatJet->DeltaR(genH_l4[1])<dRMax &&
	       (!matchb || (matchb &&
			    thatJet->DeltaR(genb_l4[1][0])<dRbMax &&
			    thatJet->DeltaR(genb_l4[1][1])<dRbMax)))
	      {
		if(debug)
		  {
		    cout << "dRhb00= " <<  thisJet->DeltaR(genb_l4[0][0]) << endl;
		    cout << "dRhb01= " <<  thisJet->DeltaR(genb_l4[0][1]) << endl;
		    cout << "dRhb10= " <<  thatJet->DeltaR(genb_l4[1][0]) << endl;
		    cout << "dRhb11= " <<  thatJet->DeltaR(genb_l4[1][1]) << endl;
		  }
		if(ij<jj){
		  matchedHAK8JetIndex[0]=ij;
		  matchedHAK8JetIndex[1]=jj;
		}
		else
		  {
		    matchedHAK8JetIndex[0]=jj;
		    matchedHAK8JetIndex[1]=ij;
		  }
		findAK8Match=true;
		break;
	      }

	    if(findAK8Match)break;

	  }	

	if(findAK8Match)break;

      }

    if(!findAK8Match)continue;
   
    
    
    //0. has a good vertex
    Int_t nVtx        = data.GetInt("nVtx");
    if(nVtx<1 && cut)continue;
    nPass[3]++;



    Float_t*  fatjetTau1 = data.GetPtrFloat("FATjetTau1");
    Float_t*  fatjetTau2 = data.GetPtrFloat("FATjetTau2");
    Float_t*  fatjetCISVV2 = data.GetPtrFloat("FATjetCISVV2");
    Float_t*  fatjetPRmass = data.GetPtrFloat("FATjetPRmass");
    Float_t*  fatjetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
    Float_t*  fatjetSDmass = data.GetPtrFloat("FATjetPuppiSDmass");
    Float_t*  fatjetSDmassL2L3Corr = data.GetPtrFloat("FATjetPuppiSDmassL2L3Corr"); 
    Float_t*  AK8PuppijetSDmass = data.GetPtrFloat("AK8PuppijetSDmass");

    vector<bool>    &passFatJetLooseID = *((vector<bool>*) data.GetPtr("FATjetPassIDLoose"));
    
    TLorentzVector recoH_l4[2];
    int nGoodJets=0;
    
    
    
    for(int i=0; i<2; i++)
      {
    	
	int ij = matchedHJetIndex[i];
     	TLorentzVector* thisJet = (TLorentzVector*)fatjetP4->At(ij);
	recoH_l4[i]= (*thisJet);
    	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;
	nGoodJets++;
      }

    if(nGoodJets<2)continue;
    nPass[5]++;
    
    if(debug)
      {
	recoH_l4[0].Print();
	recoH_l4[1].Print();
      }

    float dEta=fabs(recoH_l4[0].Eta()-recoH_l4[1].Eta());
    if(dEta>1.3 && cut)continue;
    nPass[6]++;

    float M=(recoH_l4[0] + recoH_l4[1]).M();
    if(M<800 && cut)continue;
    nPass[7]++;


    int nHP=0;
    int nLP=0;
    for(int i=0; i<2; i++)
      {
    	
	int ij = matchedHJetIndex[i];

	float tau21_i = fatjetTau2[ij]/fatjetTau1[ij];
	bool isHP= (tau21_i < 0.6);
	if(isHP)nHP++;
      }

    if(nHP<2 && cut)continue;
    nPass[8]++;

	long eventId=data.GetLong64("eventId");
	
	if(AK8nJet<2)continue;
    // now plot mass
    for(int i=0; i<2;i++)
      {
		
		//cout<< eventId<<endl;
	int jet=matchedHJetIndex[i];
	int AK8jet=matchedHAK8JetIndex[i];
	TLorentzVector* thisJet = (TLorentzVector*)puppijetP4->At(jet);
	float thea_corr = getPUPPIweight(thisJet->Pt(),thisJet->Eta());
	float thea_mass = fatjetSDmass[jet]*thea_corr;
	
	//if(jet>AK8nJet-1)break;
	if(thisJet->Pt()>99998)break;
	//cout<< eventId<<endl;
	
	TLorentzVector* thisAK8Jet = (TLorentzVector*)AK8PuppijetP4->At(AK8jet);
	thea_corr = getPUPPIweight(thisAK8Jet->Pt(),thisAK8Jet->Eta());

	if(debug)
	  cout << thisJet->Pt() << "\t" << thisJet->Eta() << "\t" << thea_corr << endl;
	
	h_SD[i]->Fill(fatjetSDmass[jet]);
	h_SDCorr[i]->Fill(fatjetSDmassL2L3Corr[jet]);
	h_SDCorrThea[i]->Fill(thea_mass);
	h_PR[i]->Fill(fatjetPRmass[jet]);
	h_PRCorr[i]->Fill(fatjetPRmassL2L3Corr[jet]);
	
	h_AK8SD[i]->Fill(AK8PuppijetSDmass[AK8jet]);
	h_AK8SDCorrThea[i]->Fill(AK8PuppijetSDmass[AK8jet]*thea_corr);

	h_SD[2]->Fill(fatjetSDmass[jet]);
	h_SDCorr[2]->Fill(fatjetSDmassL2L3Corr[jet]);
	h_SDCorrThea[2]->Fill(thea_mass);
	h_PR[2]->Fill(fatjetPRmass[jet]);
	h_PRCorr[2]->Fill(fatjetPRmassL2L3Corr[jet]);
	
	h_AK8SD[2]->Fill(AK8PuppijetSDmass[AK8jet]);
	h_AK8SDCorrThea[2]->Fill(AK8PuppijetSDmass[AK8jet]*thea_corr);


	h_diff_SD[i]->Fill((fatjetSDmass[jet]-125)/125);
	h_diff_SDCorr[i]->Fill((fatjetSDmassL2L3Corr[jet]-125)/125);
	h_diff_SDCorrThea[i]->Fill((thea_mass-125)/125);
	h_diff_PR[i]->Fill((fatjetPRmass[jet]-125)/125);
	h_diff_PRCorr[i]->Fill((fatjetPRmassL2L3Corr[jet]-125)/125);
	
	h_diff_AK8SD[i]->Fill((AK8PuppijetSDmass[AK8jet]-125)/125);
	h_diff_AK8SDCorrThea[i]->Fill((AK8PuppijetSDmass[AK8jet]*thea_corr-125)/125);

	h_diff_SD[2]->Fill((fatjetSDmass[jet]-125)/125);
	h_diff_SDCorr[2]->Fill((fatjetSDmassL2L3Corr[jet]-125)/125);
	h_diff_SDCorrThea[2]->Fill((thea_mass-125)/125);
	h_diff_PR[2]->Fill((fatjetPRmass[jet]-125)/125);
	h_diff_PRCorr[2]->Fill((fatjetPRmassL2L3Corr[jet]-125)/125);
	
	h_diff_AK8SD[2]->Fill((AK8PuppijetSDmass[AK8jet]-125)/125);
	h_diff_AK8SDCorrThea[2]->Fill((AK8PuppijetSDmass[AK8jet]*thea_corr-125)/125);

      }
    

  } // end of loop over entries

  std::cout << "nTotal    = " << nTotal << std::endl;
  for(int i=0;i<20;i++)
    if(nPass[i]>0)
      std::cout << "nPass[" << i << "]= " << nPass[i] << std::endl;

  TFile* outFile = new TFile(outputFile.Data(),"recreate");

  for(int i=0; i<nHistos; i++)
    {
      h_diff_SD[i]->Write();
      h_diff_SDCorr[i]->Write();
      h_diff_SDCorrThea[i]->Write();
      h_diff_PR[i]->Write();
      h_diff_PRCorr[i]->Write();

      h_SD[i]->Write();
      h_SDCorr[i]->Write();
      h_SDCorrThea[i]->Write();
      h_PR[i]->Write();
      h_PRCorr[i]->Write();
	
	h_AK8SD[i]->Write();
	h_AK8SDCorrThea[i]->Write();
	
	h_diff_AK8SD[i]->Write();
	h_diff_AK8SDCorrThea[i]->Write();
    }

  outFile->Close();


}
Example #28
0
void testPhiSRvsDetPhi(){


	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________
	
	
	
	TH2D* hPhiSRvPhi_Up = new TH2D("hPhiSRvPhi_Up","hPhiSRvPhi_Up",16,-3.14159,3.14159,16,-3.14159,3.14159);
	TH2D* hPhiSRvPhi_Down = new TH2D("hPhiSRvPhi_Down","hPhiSRvPhi_Down",16,-3.14159,3.14159,16,-3.14159,3.14159);
	
	
	
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");
	
	string outFileName = "./resultsNew_4_22/yellowEtaGT0_pairs_4_2.root"; 
	
	
	
  //______________________________
	
	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	
	for (int iPair = 0; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		if (iPair == 1000000){break;}
		
		pairTree->GetEntry(iPair);
		
		
		if (pair1->withinRadius(0.05, 0.3))
		{
			
			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;
			
			StTriggerId trigId = pair1->triggerIds();
			
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.


				if (sumB.Pt() >= 3 && sumB.Pt() <= 50 && sumB.M() >= 0 && sumB.M() <= 100 && sumB.Eta() >= -1.4 && sumB.Eta() <= 1.4)
				{
					passInitialCut_B = true;
				}
			
				if (passInitialCut_B && (pair1->spinBit() == 9 || pair1->spinBit() == 10))
				{
					
					cout << pair1->phiSR('b') << "  " << sumB.Phi() << endl;
					
					hPhiSRvPhi_Up->Fill(pair1->phiSR('b'), sumB.Phi());
					
				}
				
				if (passInitialCut_B && (pair1->spinBit() == 5 || pair1->spinBit() == 6))
				{
					hPhiSRvPhi_Down->Fill(pair1->phiSR('b'), sumB.Phi());
				}
				
				
				
				
			}
				
			
			
			
			
		}
		
		
		
		
	}
	
	
	TCanvas* cUp = new TCanvas();
	hPhiSRvPhi_Up->Draw("colz");
			
	TCanvas* cDown = new TCanvas();
	hPhiSRvPhi_Down->Draw("colz");
			
			
			
}
void TMVARegressionApplication( int wMs,int wM, string st,string st2,string option="",TString myMethodList = "" ) 
{
   //---------------------------------------------------------------
   // This loads the library
   TMVA::Tools::Instance();

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

   // --- Mutidimensional likelihood and Nearest-Neighbour methods
   Use["PDERS"]           = 0;
   Use["PDEFoam"]         = 0; 
   Use["KNN"]             = 0;
   // 
   // --- Linear Discriminant Analysis
   Use["LD"]		        = 0;
   // 
   // --- Function Discriminant analysis
   Use["FDA_GA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   // 
   // --- Neural Network
   Use["MLP"]             = 0; 
   // 
   // --- Support Vector Machine 
   Use["SVM"]             = 0;
   // 
   // --- Boosted Decision Trees
   Use["BDT"]             = 0;
   Use["BDTG"]            = 1;
   // ---------------------------------------------------------------

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

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

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

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

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

   // --- Create the Reader object

   TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

   // Create a set of variables and declare them to the reader
   // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
   //Float_t var1, var2;
   //reader->AddVariable( "var1", &var1 );
   //reader->AddVariable( "var2", &var2 );
   Float_t pt_AK8MatchedToHbb,eta_AK8MatchedToHbb,nsv_AK8MatchedToHbb,sv0mass_AK8MatchedToHbb,sv1mass_AK8MatchedToHbb,
   nch_AK8MatchedToHbb,nmu_AK8MatchedToHbb,nel_AK8MatchedToHbb,muenfr_AK8MatchedToHbb,emenfr_AK8MatchedToHbb;
   reader->AddVariable( "pt_AK8MatchedToHbb", &pt_AK8MatchedToHbb );
   reader->AddVariable( "eta_AK8MatchedToHbb", &eta_AK8MatchedToHbb );
   reader->AddVariable( "nsv_AK8MatchedToHbb", &nsv_AK8MatchedToHbb );
   reader->AddVariable( "sv0mass_AK8MatchedToHbb", &sv0mass_AK8MatchedToHbb );
   reader->AddVariable( "sv1mass_AK8MatchedToHbb", &sv1mass_AK8MatchedToHbb );
   reader->AddVariable( "nch_AK8MatchedToHbb", &nch_AK8MatchedToHbb );
   reader->AddVariable( "nmu_AK8MatchedToHbb", &nmu_AK8MatchedToHbb );
   reader->AddVariable( "nel_AK8MatchedToHbb", &nel_AK8MatchedToHbb );
   reader->AddVariable( "muenfr_AK8MatchedToHbb", &muenfr_AK8MatchedToHbb );
   reader->AddVariable( "emenfr_AK8MatchedToHbb", &emenfr_AK8MatchedToHbb );

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

   // --- Book the MVA methods

   TString dir    = "weights/";
   TString prefix = "TMVARegression";

   // Book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = it->first + " method";
         TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
         reader->BookMVA( methodName, weightfile ); 
      }
   }
   
     TH1* hists[100];
   Int_t nhists = -1;
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
         TH1* h = new TH1F( it->first.c_str(), TString(it->first) + " method", 100, -100, 600 );
         if (it->second) hists[++nhists] = h;
      }
      nhists++;
   
  //1=signal ,0=QCD ,2=data
	int nameRoot=1;
	if((st2.find("QCD")!= std::string::npos)||
	(st2.find("bGen")!= std::string::npos)||
	(st2.find("bEnriched")!= std::string::npos))nameRoot=0;
	if(st2.find("data")!= std::string::npos)nameRoot=2;
	cout<<"nameRoot = "<<nameRoot<<endl;
	
	//option-----------------------------------------------------------
	
	int JESOption=0;
	
   
   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.
   //   
   TFile *f;
	TTree *tree;
	int nPass[20]={0};
	int total=0;
	double fixScaleNum[2]={0};
	
	TH1D* th1=new TH1D("a","a",150,50,200);	
	
	string massName[nMass]={"Thea","HCorr","Reg"};
	string catName[nCat]={"PP","PF","FP","FF"};
	string tau21Name[2]={"withTau21","woTau21"};
	
	string catNameShort[nCat]={"P","F"};
	string looseTight[2]={"loose","tight"};
	TF1 *fa[nMass][2][2][2];
	
	for(int i=0;i<nMass;i++){
		for(int j=0;j<2;j++){
			for(int k=0;k<2;k++){
				for(int w=0;w<2;w++){
					fa[i][j][k][w] = new TF1("fa","[0]+[1]*x+[2]*x*x+[3]*pow(x,3)",-3,3);
					ifstream myfile (Form("PFRatio/%s_%s_%s_%s.txt",looseTight[w].data(),massName[i].data(),catNameShort[j].data(),tau21Name[k].data()));
					double para[4];
					for(int m=0;m<4;m++){
						myfile>>para[m];
					}
					fa[i][j][k][w]->SetParameters(para[0],para[1],para[2],para[3]);
				}
			}
		}
	}
	
	/*
	TH1D* th2[nMass][nCat][2];
	TH1D* th3[nMass][nCat][2];
	for(int i=0;i<nMass;i++){
		for(int j=0;j<nCat;j++){
			for(int k=0;k<2;k++){
				th2[i][j][k]=(TH1D*)th1->Clone(Form("loose_%s_%s_%s",massName[i].data(),catName[j].data(),tau21Name[k].data()));
				th3[i][j][k]=(TH1D*)th1->Clone(Form("tight_%s_%s_%s",massName[i].data(),catName[j].data(),tau21Name[k].data()));
				
				th2[i][j][k]->Sumw2();
				th3[i][j][k]->Sumw2();
			}
		}
	}
	*/
	TH1D* th2d[14];
	
	th2d[0]=new TH1D("0a","0a",4000,1000,5000);	
	th2d[1]=new TH1D("0c","0c",4000,1000,5000);
	th2d[2]=new TH1D("1a","1a",4000,1000,5000);	
	th2d[3]=new TH1D("1c","1c",4000,1000,5000);	
	th2d[4]=new TH1D("2a","2a",4000,1000,5000);	
	th2d[5]=new TH1D("2b","2b",4000,1000,5000);	
	th2d[6]=new TH1D("2d","2d",4000,1000,5000);	
	
	
	th2d[7]=new TH1D("0aL","0aL",4000,1000,5000);		
	th2d[8]=new TH1D("0cL","0cL",4000,1000,5000);		
	th2d[9]=new TH1D("1aL","1aL",4000,1000,5000);		
	th2d[10]=new TH1D("1cL","1cL",4000,1000,5000);		
	th2d[11]=new TH1D("2aL","2aL",4000,1000,5000);	
	th2d[12]=new TH1D("2bL","2bL",4000,1000,5000);	
	th2d[13]=new TH1D("2dL","2dL",4000,1000,5000);	
		
	
		
	
	//int nWidth=5,nBmin=11;
	 int width [nWidth]={25,30,35,40};
	 int bmin[nBmin]={100,105,110,115};
	 
	
	 TH1D* th3d[14][nWidth][nBmin][2];
	 TH1D* th3f[14][nWidth][nBmin][2];
	 TH1D* th3v[14][nWidth][nBmin][2];
	 
	 for(int i=0;i<nWidth;i++){
		 for(int j=0;j<nBmin;j++){
			 for(int k=0;k<2;k++){
				  for(int l=0;l<14;l++){
					  th3d[l][i][j][k]=(TH1D*) th2d[l]->Clone(Form("%s_%d_%d_%s",th2d[l]->GetTitle(),bmin[j],width[i]+bmin[j],tau21Name[k].data()));
					  th3f[l][i][j][k]=(TH1D*) th2d[l]->Clone(Form("fill_%s_%d_%d_%s",th2d[l]->GetTitle(),bmin[j],width[i]+bmin[j],tau21Name[k].data()));
					  th3v[l][i][j][k]=(TH1D*) th2d[l]->Clone(Form("valid_%s_%d_%d_%s",th2d[l]->GetTitle(),bmin[j],width[i]+bmin[j],tau21Name[k].data()));
					   
					  th3d[l][i][j][k]->Sumw2();
					  th3f[l][i][j][k]->Sumw2();
					  th3v[l][i][j][k]->Sumw2();
				  }
			 }
		 }
	 }
   
   for (int w=wMs;w<wM;w++){
		if(w%20==0)cout<<w<<endl;
		
		if (nameRoot!=1)f = TFile::Open(Form("%s%d.root",st.data(),w));
		else f = TFile::Open(st.data());
		if (!f || !f->IsOpen())continue;
		
		TDirectory * dir;
		if (nameRoot!=1)dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
		else dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));
		
		dir->GetObject("treeMaker",tree);
		
		//tree=(TTree*)f->Get("treeMaker");
		TreeReader data(tree);
		total+=data.GetEntriesFast();
		for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){
			data.GetEntry(jEntry);
			
			
			
			Int_t nVtx        = data.GetInt("nVtx");
			//0. has a good vertex
			if(nVtx<1)continue;
			nPass[0]++;
			
			//1.trigger
			std::string* trigName = data.GetPtrString("hlt_trigName");
		 	vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
			bool passTrigger=false;
			for(int it=0; it< data.GetPtrStringSize();it++){
				std::string thisTrig= trigName[it];
				bool results = trigResult[it];
				if( ((thisTrig.find("HLT_PFHT800")!= std::string::npos||
					thisTrig.find("HLT_AK8DiPFJet300_200_TrimMass30_BTagCSV_p20")!= std::string::npos
						) && results==1)){
					passTrigger=true;
					break;
				}
			}
			if(!passTrigger && nameRoot==2)continue;
			nPass[1]++;

			const int nAK8Jet=data.GetInt("AK8PuppinJet");
			//2.nJets
			if(nAK8Jet<2)continue;nPass[2]++;
			int* AK8PuppinSubSDJet=data.GetPtrInt("AK8PuppinSubSDJet");
			if(AK8PuppinSubSDJet[0]!=2||AK8PuppinSubSDJet[1]!=2)continue;
			TClonesArray* AK8PuppijetP4 = (TClonesArray*) data.GetPtrTObject("AK8PuppijetP4");
			float*  AK8PuppijetCorrUncUp = data.GetPtrFloat("AK8PuppijetCorrUncUp"); 
			float*  AK8PuppijetCorrUncDown = data.GetPtrFloat("AK8PuppijetCorrUncDown"); 
			TLorentzVector* thisJet ,* thatJet;
			
			
			thisJet=(TLorentzVector*)AK8PuppijetP4->At(0);
			thatJet=(TLorentzVector*)AK8PuppijetP4->At(1);
			
			//3. Pt 
			if(thisJet->Pt()>99998 ||thatJet->Pt()>99998 )continue;
			if(thisJet->Pt()<300)continue;
			if(thatJet->Pt()<300)continue;
			nPass[3]++;
			//4tightId-----------------------------------------
			vector<bool>    &AK8PuppijetPassIDTight = *((vector<bool>*) data.GetPtr("AK8PuppijetPassIDTight"));
			if(AK8PuppijetPassIDTight[0]==0)continue;
			if(AK8PuppijetPassIDTight[1]==0)continue;
			Float_t*  AK8PuppijetCEmEF = data.GetPtrFloat("AK8PuppijetCEmEF");
			Float_t*  AK8PuppijetMuoEF = data.GetPtrFloat("AK8PuppijetMuoEF");
			if(AK8PuppijetMuoEF[0]>0.8)continue;
			if(AK8PuppijetCEmEF[0]>0.9)continue;
			if(AK8PuppijetMuoEF[1]>0.8)continue;
			if(AK8PuppijetCEmEF[1]>0.9)continue;
			nPass[4]++;
			//5. Eta-----------------------------------------
			if(fabs(thisJet->Eta())>2.4)continue;
			if(fabs(thatJet->Eta())>2.4)continue;
			nPass[5]++;
			//6. DEta-----------------------------------------
			float dEta = fabs(thisJet->Eta()-thatJet->Eta());
			if(dEta>1.3)continue;
			nPass[6]++;
			//7. Mjj-----------------------------------------
			//float mjjRed = (*thisJet+*thatJet).M()+250-thisJet->M()-thatJet->M();
			//if(mjjRed<1000)continue;
			nPass[7]++;
			//8. fatjetPRmassL2L3Corr-----------------------------------------
			nPass[8]++;
			//9.-----------------------------------------
		
			
    
			Float_t*  AK8Puppijet_DoubleSV = data.GetPtrFloat("AK8Puppijet_DoubleSV");
			
			
			int looseStat=-1;
			int tightStat=-1;
			
			if(AK8Puppijet_DoubleSV[0]>0.3 && AK8Puppijet_DoubleSV[1]>0.3)looseStat=0;
			else if(AK8Puppijet_DoubleSV[0]>0.3 && AK8Puppijet_DoubleSV[1]<0.3)looseStat=1;
			else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]>0.3)looseStat=2;
			else looseStat=3;
			
			if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]>0.8)tightStat=0;
			else if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]<0.8)tightStat=1;
			else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]>0.8)tightStat=2;
			else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]<0.8)tightStat=3;
			else tightStat=-1;
			
			
			double varTemp[2];
			
			Float_t*  AK8PuppijetSDmass = data.GetPtrFloat("AK8PuppijetSDmass");
			
			if(AK8PuppijetSDmass[0]<50||AK8PuppijetSDmass[1]<50)continue;
			
			Int_t* AK8Puppijet_nSV=data.GetPtrInt("AK8Puppijet_nSV");
			vector<float>   *AK8Puppijet_SVMass  =  data.GetPtrVectorFloat("AK8Puppijet_SVMass");
			int nEle= data.GetInt("nEle");
			int nMu=data.GetInt("nMu");
			Float_t*  AK8PuppijetEleEF = data.GetPtrFloat("AK8PuppijetEleEF");
			//Float_t*  AK8PuppijetMuoEF = data.GetPtrFloat("AK8PuppijetMuoEF");
			Int_t* AK8PuppijetCMulti=data.GetPtrInt("AK8PuppijetCMulti");
			Int_t* AK8PuppijetEleMulti=data.GetPtrInt("AK8PuppijetEleMulti");
			Int_t* AK8PuppijetMuoMulti=data.GetPtrInt("AK8PuppijetMuoMulti");
			
			for(int i=0; i<2;i++){
		
				TLorentzVector* thisAK8Jet ;
				
				if(i==1)thisAK8Jet=thatJet;
				else thisAK8Jet=thisJet;
				
				
				pt_AK8MatchedToHbb=thisAK8Jet->Pt();
				eta_AK8MatchedToHbb=thisAK8Jet->Eta();
				nsv_AK8MatchedToHbb=AK8Puppijet_nSV[i];
				sv0mass_AK8MatchedToHbb=AK8Puppijet_SVMass[i][0];
				sv1mass_AK8MatchedToHbb=AK8Puppijet_SVMass[i][1];
				nmu_AK8MatchedToHbb=AK8PuppijetMuoMulti[i];
				nel_AK8MatchedToHbb=AK8PuppijetEleMulti[i];
				muenfr_AK8MatchedToHbb=AK8PuppijetMuoEF[i];
				nch_AK8MatchedToHbb=AK8PuppijetCMulti[i];
				emenfr_AK8MatchedToHbb=AK8PuppijetEleEF[i];
				spec1=nVtx;
				spec2=AK8PuppijetSDmass[i];
				Float_t val ;
				for (Int_t ih=0; ih<nhists; ih++) {
				TString title = hists[ih]->GetTitle();
				val= (reader->EvaluateRegression( title ))[0];
				}
				varTemp[i]=val;
			}
			
			double PUPPIweight[2]={0};
			PUPPIweight[0]=getPUPPIweight(thisJet->Pt(),thisJet->Eta());
			PUPPIweight[1]=getPUPPIweight(thatJet->Pt(),thatJet->Eta());
			
			double PUPPIweightThea[2]={0};
			PUPPIweightThea[0]=getPUPPIweight_o(thisJet->Pt(),thisJet->Eta());
			PUPPIweightThea[1]=getPUPPIweight_o(thatJet->Pt(),thatJet->Eta());
	
			double Mjja= ((*thisJet)+(*thatJet)).M()+250
									-((*thisJet)).M()-((*thatJet)).M();
									
			TLorentzVector  thisJetReg, thatJetReg;
			thisJetReg=(*thisJet)*varTemp[0];
			thatJetReg=(*thatJet)*varTemp[1];
			
			double Mjjb= (thisJetReg+thatJetReg).M()+250
									-(thisJetReg).M()-(thatJetReg).M();
			
			double PUPPIweightOnRegressed[2]={0};			
			PUPPIweightOnRegressed[0]=getPUPPIweightOnRegressed(thisJetReg.Pt(),thisJetReg.Eta());
			PUPPIweightOnRegressed[1]=getPUPPIweightOnRegressed(thatJetReg.Pt(),thatJetReg.Eta());
			
			vector<float>   *subjetSDPx  =  data.GetPtrVectorFloat("AK8PuppisubjetSDPx");
			vector<float>   *subjetSDPy  =  data.GetPtrVectorFloat("AK8PuppisubjetSDPy");
			vector<float>   *subjetSDPz  =  data.GetPtrVectorFloat("AK8PuppisubjetSDPz");
			vector<float>   *subjetSDE   =  data.GetPtrVectorFloat("AK8PuppisubjetSDE");
			vector<float>   *AK8PuppisubjetSDRawFactor =  data.GetPtrVectorFloat("AK8PuppisubjetSDRawFactor");
			
			TLorentzVector thisSDJet, thatSDJet;
			TLorentzVector* subjetP4[2][2];
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					subjetP4[i][j]=new TLorentzVector(0,0,0,0);
					subjetP4[i][j]->SetPxPyPzE(subjetSDPx[i][j],subjetSDPy[i][j],subjetSDPz[i][j],subjetSDE[i][j]);
				//	subjetP4[i][j]*=AK8PuppisubjetSDRawFactor[i][j];
				}
			}
			thisSDJet=(*subjetP4[0][0])*AK8PuppisubjetSDRawFactor[0][0]+(*subjetP4[0][1])*AK8PuppisubjetSDRawFactor[0][1];
			thatSDJet=(*subjetP4[1][0])*AK8PuppisubjetSDRawFactor[1][0]+(*subjetP4[1][1])*AK8PuppisubjetSDRawFactor[1][1];
			//thatSDJet=(*subjetP4[1][0])+(*subjetP4[1][1]);
			TLorentzVector thisSDJetReg, thatSDJetReg;			
			thisSDJetReg=	thisSDJet*varTemp[0]*PUPPIweightOnRegressed[0];			
			thatSDJetReg=	thatSDJet*varTemp[1]*PUPPIweightOnRegressed[1];			
			
			
			//double Mjjc= ((thisSDJet)+(thatSDJet)).M()+250
			//						-((thisSDJet)).M()-((thatSDJet)).M();
			
			
			double Mjjd= ((thisSDJet)+(thatSDJet)).M()+250
									-((thisSDJet)).M()-((thatSDJet)).M();
			
			
			Float_t*  AK8PuppijetTau1 = data.GetPtrFloat("AK8PuppijetTau1");
			Float_t*  AK8PuppijetTau2 = data.GetPtrFloat("AK8PuppijetTau2");
			double puppiTau21[2];
			puppiTau21[0]=(AK8PuppijetTau2[0]/AK8PuppijetTau1[0]),puppiTau21[1]=(AK8PuppijetTau2[1]/AK8PuppijetTau1[1]);
			
			double mass_j0,mass_j1,MjjLoop;
			int massCat;
			for(int k=0;k<7;k++){
				
				if(k==0||k==2||k==4){
					if(thisJet->Pt()<300)continue;
					if(thatJet->Pt()<300)continue;
				}
				else if (k==1){
					if((thisSDJet*PUPPIweightThea[0]).Pt()<300)continue;
					if((thatSDJet*PUPPIweightThea[1]).Pt()<300)continue;
				}
				else if (k==3){
					if((thisSDJet*PUPPIweight[0]).Pt()<300)continue;
					if((thatSDJet*PUPPIweight[1]).Pt()<300)continue;
				}
				else if (k==5){
					if(thisJetReg.Pt()<300)continue;
					if(thatJetReg.Pt()<300)continue;
				}
				else{
					if(thisSDJetReg.Pt()<300)continue;
					if(thatSDJetReg.Pt()<300)continue;
				}
				
				
				if(k==0||k==1){
					mass_j0=AK8PuppijetSDmass[0]*PUPPIweightThea[0];
					mass_j1=AK8PuppijetSDmass[1]*PUPPIweightThea[1];
					massCat=0;
				}
				else if (k==2||k==3){
					mass_j0=AK8PuppijetSDmass[0]*PUPPIweight[0];
					mass_j1=AK8PuppijetSDmass[1]*PUPPIweight[1];
					massCat=1;
				}
				
				else{
					mass_j0=AK8PuppijetSDmass[0]*varTemp[0]*PUPPIweightOnRegressed[0];
					mass_j1=AK8PuppijetSDmass[1]*varTemp[1]*PUPPIweightOnRegressed[1];
					massCat=2;
				} 
				
				
				
				if(k==0||k==2||k==4)MjjLoop=Mjja;
				else if (k==1)MjjLoop=((thisSDJet)*PUPPIweightThea[0]+(thatSDJet)*PUPPIweightThea[1]).M()+250-((thisSDJet)*PUPPIweightThea[0]).M()-((thatSDJet)*PUPPIweightThea[1]).M();
				else if (k==3)MjjLoop=((thisSDJet)*PUPPIweight[0]+(thatSDJet)*PUPPIweight[1]).M()+250-((thisSDJet)*PUPPIweight[0]).M()-((thatSDJet)*PUPPIweight[1]).M();
				else if (k==5)MjjLoop=Mjjb;
				else MjjLoop=Mjjd;
				
				
				//cout<<mass_j0<<","<<mass_j1<<",k="<<k<<endl;
				for(int i=0;i<nWidth;i++){
					for(int j=0;j<nBmin;j++){
						if(mass_j0<bmin[j] ||mass_j0>width[i]+bmin[j]
						||mass_j1<bmin[j] ||mass_j1>width[i]+bmin[j] )continue;
						
						for(int m=0;m<2;m++){
							if(m==0 && (puppiTau21[0]>0.6 || puppiTau21[1]>0.6))continue;
							double tightPFRatio=0,loosePFRatio=0;
							tightPFRatio=fa[massCat][0][m][1]->Eval(mass_j0);
							loosePFRatio=fa[massCat][0][m][0]->Eval(mass_j0);
							if(tightStat==0){
								th3d[k][i][j][m]->Fill(MjjLoop);
							}
							else if (tightStat==1){
								th3f[k][i][j][m]->Fill(MjjLoop);
							}
							else if(tightStat==3){
								tightPFRatio=fa[massCat][1][m][1]->Eval(mass_j0);
								th3v[k][i][j][m]->Fill(MjjLoop,tightPFRatio);
							}
							
							if(looseStat==0 && tightStat!=0){
								th3d[k+7][i][j][m]->Fill(MjjLoop);
							}
							else if (looseStat==1){
								th3f[k+7][i][j][m]->Fill(MjjLoop);
							}
							else if(looseStat==3){
								loosePFRatio=fa[massCat][1][m][0]->Eval(mass_j0);
								th3v[k+7][i][j][m]->Fill(MjjLoop,loosePFRatio);
							}
						}
						
					}
				}
			}
			
			
			
		}
	}	
	
	for(int i=0;i<10;i++)cout<<"npass["<<i<<"]="<<nPass[i]<<endl;
   

	TFile* outFile;//= new TFile(Form("PFRatio/%s.root",st2.data()),"recreate");
	outFile= new TFile(Form("MjjVC/%s.root",st2.data()),"recreate");
	for(int i=0;i<nWidth;i++){
		 for(int j=0;j<nBmin;j++){
			 for(int k=0;k<2;k++){
				  for(int l=0;l<14;l++){
					  th3d[l][i][j][k]->Write();
					  th3f[l][i][j][k]->Write();
					  th3v[l][i][j][k]->Write();
					  
				  }
			 }
		 }
	 }
	outFile->Close();
	
	for(int i=0;i<nWidth;i++){
		 for(int j=0;j<nBmin;j++){
			 for(int k=0;k<2;k++){
				  for(int l=0;l<14;l++){
					  delete th3d[l][i][j][k];
					  delete th3f[l][i][j][k];
					  delete th3v[l][i][j][k];
					  
				  }
			 }
		 }
	 }
  
   delete reader;
    
   
}
void test_JVBF(int erg_tev=8, float mSample=0, bool isggH=false){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "SelectedTree";

  //	TVar::VerbosityLevel verbosity = TVar::INFO;

  Mela mela(erg_tev, mPOLE);

  TFile* foutput;
  if (!isggH){
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_H%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_HAll_%iTeV.root", erg_tev), "recreate");
  }
  else{
    if (mSample>0) foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggH%.0f_%iTeV.root", mSample, erg_tev), "recreate");
    else foutput = new TFile(Form("HZZ4lTree_jvbfMELA_ggHAll_%iTeV.root", erg_tev), "recreate");
  }
  TLorentzVector nullFourVector(0, 0, 0, 0);

  float MC_weight_noxsec;

  float pjvbf_VAJHU;
  float pjvbf_VAJHU_first;
  float pjvbf_VAJHU_second;
  float phj_VAJHU_first;
  float phj_VAJHU_second;
  float pAux_vbf;
  float pAux_vbf_first;
  float pAux_vbf_second;

  float jet1Pt, jet2Pt;
  float jet1Eta, jet2Eta;
  float jet1Phi, jet2Phi;
  float jet1E, jet2E;
  float jet1Pt_Fake, jet2Pt_Fake;
  float jet1Eta_Fake, jet2Eta_Fake;
  float jet1Phi_Fake, jet2Phi_Fake;
  float jet1E_Fake, jet2E_Fake;
  float jet1px, jet1py, jet1pz;
  float jet2px, jet2py, jet2pz;
  float ZZPx, ZZPy, ZZPz, ZZE, dR;
  short NJets30;
  std::vector<double> * JetPt=0;
  std::vector<double> * JetEta=0;
  std::vector<double> * JetPhi=0;
  std::vector<double> * JetMass=0;
  std::vector<double> myJetPt;
  std::vector<double> myJetCosTheta;
  std::vector<double> myJetEta;
  std::vector<double> myJetPhi;
  std::vector<double> myJetMass;
  TBranch* bJetPt=0;
  TBranch* bJetEta=0;
  TBranch* bJetPhi=0;
  TBranch* bJetMass=0;

  float ZZMass, ZZPt, ZZPhi, ZZEta;

  int GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;

  TChain* tree = new TChain(TREE_NAME);
  char* user_folder[3]={ "4mu", "4e", "2mu2e" };
  TString cinput_main = "/scratch0/hep/ianderso/CJLST/140519/PRODFSR";
  if (erg_tev==8) cinput_main.Append("_8TeV");

//  TString cinput_main = "/afs/cern.ch/work/u/usarica/HZZ4l-125p6-FullAnalysis/LHC_";
//  cinput_main.Append(Form("%iTeV", erg_tev));

  for (int ff=0; ff<3; ff++){
    if (!isggH){
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_VBFH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_VBFH*.root", cinput_main.Data(), user_folder[ff]));
    }
    else{
      if (mSample>0) tree->Add(Form("%s/%s/HZZ4lTree_minloH%.0f.root", cinput_main.Data(), user_folder[ff], mSample));
      else tree->Add(Form("%s/%s/HZZ4lTree_minloH*.root", cinput_main.Data(), user_folder[ff]));
    }
  }
  tree->SetBranchAddress("MC_weight_noxsec", &MC_weight_noxsec);
  tree->SetBranchAddress("NJets30", &NJets30);
  tree->SetBranchAddress("JetPt", &JetPt, &bJetPt);
  tree->SetBranchAddress("JetEta", &JetEta, &bJetEta);
  tree->SetBranchAddress("JetPhi", &JetPhi, &bJetPhi);
  tree->SetBranchAddress("JetMass", &JetMass, &bJetMass);
  tree->SetBranchAddress("ZZMass", &ZZMass);
  tree->SetBranchAddress("ZZPt", &ZZPt);
  tree->SetBranchAddress("ZZEta", &ZZEta);
  tree->SetBranchAddress("ZZPhi", &ZZPhi);

  TTree* newtree = new TTree("TestTree", "");
  newtree->Branch("MC_weight_noxsec", &MC_weight_noxsec);
  newtree->Branch("ZZMass", &ZZMass);
  newtree->Branch("pAux_vbf", &pAux_vbf);
  newtree->Branch("pAux_vbf_first", &pAux_vbf_first);
  newtree->Branch("pAux_vbf_second", &pAux_vbf_second);
  newtree->Branch("pjvbf_VAJHU", &pjvbf_VAJHU);
  newtree->Branch("pjvbf_VAJHU_first", &pjvbf_VAJHU_first);
  newtree->Branch("pjvbf_VAJHU_second", &pjvbf_VAJHU_second);
  newtree->Branch("phj_VAJHU_first", &phj_VAJHU_first);
  newtree->Branch("phj_VAJHU_second", &phj_VAJHU_second);
  newtree->Branch("NJets30", &NJets30);
  newtree->Branch("jet1Pt", &jet1Pt);
  newtree->Branch("jet1Eta", &jet1Eta);
  newtree->Branch("jet1Phi", &jet1Phi);
  newtree->Branch("jet1E", &jet1E);
  newtree->Branch("jet2Pt", &jet2Pt);
  newtree->Branch("jet2Eta", &jet2Eta);
  newtree->Branch("jet2Phi", &jet2Phi);
  newtree->Branch("jet2E", &jet2E);
  newtree->Branch("jet1_Fake_Pt", &jet1Pt_Fake);
  newtree->Branch("jet1_Fake_Eta", &jet1Eta_Fake);
  newtree->Branch("jet1_Fake_Phi", &jet1Phi_Fake);
  newtree->Branch("jet1_Fake_E", &jet1E_Fake);
  newtree->Branch("jet2_Fake_Pt", &jet2Pt_Fake);
  newtree->Branch("jet2_Fake_Eta", &jet2Eta_Fake);
  newtree->Branch("jet2_Fake_Phi", &jet2Phi_Fake);
  newtree->Branch("jet2_Fake_E", &jet2E_Fake);
  newtree->Branch("JetPt", &myJetPt);
//  newtree->Branch("JetCosTheta", &myJetCosTheta);
  newtree->Branch("JetPhi", &myJetPhi);
  newtree->Branch("JetMass", &myJetMass);


  int nEntries = tree->GetEntries();
  double selfDHggcoupl[SIZE_HGG][2] ={ { 0 } };
  double selfDHvvcoupl[SIZE_HVV_VBF][2] ={ { 0 } };
  double selfDHwwcoupl[SIZE_HWW_VBF][2] ={ { 0 } };
  double ggvvcoupl[2]={ 0, 0 };
  mela.setProcess(TVar::SelfDefine_spin0, TVar::JHUGen, TVar::ZZGG);
  int recorded=0;
  for (int ev = 0; ev < nEntries; ev++){
    pjvbf_VAJHU=-1;
    pjvbf_VAJHU_first=-1;
    pjvbf_VAJHU_second=-1;
    jet1Pt=-1;
    jet2Pt=-1;
    jet1Eta=0;
    jet2Eta=0;

    tree->GetEntry(ev);
    GenLep1Id=11;
    GenLep2Id=-11;
    GenLep3Id=11;
    GenLep4Id=-11;

    myJetPt.clear();
    myJetEta.clear();
    myJetPhi.clear();
    myJetMass.clear();
    myJetCosTheta.clear();

    TLorentzVector jet1(0, 0, 1e-3, 1e-3), jet2(0, 0, 1e-3, 1e-3), higgs(0, 0, 0, 0);
    TLorentzVector p4[3], jets[2];
    higgs.SetPtEtaPhiM(ZZPt, ZZEta, ZZPhi, ZZMass);
    for (int i = 0; i < NJets30; i++){
      myJetPt.push_back(JetPt->at(i));
      myJetEta.push_back(JetEta->at(i));
      myJetPhi.push_back(JetPhi->at(i));
      myJetMass.push_back(JetMass->at(i));
      myJetCosTheta.push_back(eta_to_costheta(JetEta->at(i)));
    }

    int filled = 0;
    if (myJetPt.size()>=1){

      jets[0].SetPxPyPzE(0, 0, 0, 1);
      jets[1].SetPxPyPzE(0, 0, 0, 1);
      for (int i = 0; i < myJetPt.size(); i++){
        jets[filled].SetPtEtaPhiM(myJetPt[i], myJetEta[i], myJetPhi[i], myJetMass[i]);

        if (filled==0){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet1.SetPxPyPzE(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet1Pt = jet1.Pt();
          jet1Eta = jet1.Eta();
          jet1Phi = jet1.Phi();
          jet1E = jet1.E();
          jet2.SetXYZT(0, 0, 0, 0);
        }
        else if(filled==1){
          double jetE = jets[filled].Energy();
          double jetP = jets[filled].P();
          double ratio = (jetP>0 ? jetE/jetP : 1);
          ratio = 1.;
          jet2.SetXYZT(jets[filled].Px()*ratio, jets[filled].Py()*ratio, jets[filled].Pz()*ratio, jetE);
          filled++;
          jet2Pt = jet2.Pt();
          jet2Eta = jet2.Eta();
          jet2Phi = jet2.Phi();
          jet2E = jet2.E();
        }
        else continue;

/*
        if (filled == 0){
          if (jets[filled].Pt()>jet1.Pt()){
            jet1.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet1Pt = jet1.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
            i = 0;
          }
        }
        else{
          if (jets[filled].Pt()<jet1.Pt() && jets[filled].Pt()>jet2.Pt()){
            jet2.SetPxPyPzE(jets[filled].Px(), jets[filled].Py(), jets[filled].Pz(), jetE);
            jet2Pt = jet2.Pt();
          }
          if (i == myJetPt.size() - 1){
            filled++;
          }
        }
        if (filled == 2) break;
*/
      }
//cos(atan(exp(-jet2Eta))*2)

      if (filled == 2){
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);

        TLorentzVector pTotal;
        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_first);
        mela.get_PAux(pAux_vbf_first);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, pTotal, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, pTotal);
        jet2Pt_Fake = pTotal.Pt();
        jet2Eta_Fake = pTotal.Eta();
        jet2Phi_Fake = pTotal.Phi();
        jet2E_Fake = pTotal.E();

        pTotal.SetXYZT(0, 0, 0, 0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU_second);
        mela.get_PAux(pAux_vbf_second);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(pTotal, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_second);
        mela::computeFakeJet(jet2, higgs, pTotal);
        jet1Pt_Fake = pTotal.Pt();
        jet1Eta_Fake = pTotal.Eta();
        jet1Phi_Fake = pTotal.Phi();
        jet1E_Fake = pTotal.E();

        newtree->Fill();
      }
      else if (filled == 1){
/*
        TLorentzVector pTotal = higgs+jet1;
        pTotal.SetVect(-pTotal.Vect());
        pTotal.SetE(pTotal.P());
        jet2 = pTotal;

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();


        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();

        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
*/
//
        jet2.SetXYZT(0,0,0,0);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJVBF);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, pjvbf_VAJHU);
        mela.get_PAux(pAux_vbf);
        mela.setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JH);
        mela.computeProdP(jet1, 2, jet2, 2, higgs, 25, nullFourVector, 0, phj_VAJHU_first);
        mela::computeFakeJet(jet1, higgs, jet2);
/*
        cout << "TEST:"
          << " Higgs Pz: " <<  higgs.Pz()
          << " Higgs P: " <<  higgs.P()
          << " Higgs E: " <<  higgs.T()
          << " Jet 1 Pz: " <<  jet1.Pz()
          << " Jet 1 P: " <<  jet1.P()
          << " Jet 1 E: " <<  jet1.T()
          << " Jet 2 Pz: " <<  jet2.Pz()
          << " Jet 2 P: " <<  jet2.P()
          << " Jet 2 E: " <<  jet2.T() << '\n' << endl;
*/

        jet2Pt = jet2.Pt();
        jet2Eta = jet2.Eta();
        jet2Phi = jet2.Phi();
        jet2E = jet2.E();

        jet1Pt_Fake = jet1.Pt();
        jet1Eta_Fake = jet1.Eta();
        jet1Phi_Fake = jet1.Phi();
        jet1E_Fake = jet1.E();
        jet2Pt_Fake = jet2.Pt();
        jet2Eta_Fake = jet2.Eta();
        jet2Phi_Fake = jet2.Phi();
        jet2E_Fake = jet2.E();
//
        pjvbf_VAJHU_first = pjvbf_VAJHU;
        pjvbf_VAJHU_second = pjvbf_VAJHU;
        pAux_vbf_first = pAux_vbf;
        pAux_vbf_second = pAux_vbf;
        phj_VAJHU_second = phj_VAJHU_first;

        newtree->Fill();
      }
    }
  }


  foutput->WriteTObject(newtree);
  delete newtree;
  foutput->Close();
  delete tree;
}