Exemple #1
0
void rochcor2012::musclefit_data( TLorentzVector& mu, TLorentzVector& mubar){

  float dpar1 = 0.0;
  float dpar2 = 0.0;
  float epar1 = 0.0;
  float epar2 = 0.0;
  
  if(fabs(mu.PseudoRapidity())<=0.9){
    dpar1 = d0par;
    epar1 = e0par;
  }else if(mu.PseudoRapidity()>0.9){
    dpar1 = d1par;
    epar1 = e1par;
  }else if(mu.PseudoRapidity()<-0.9){
    dpar1 = d2par;
    epar1 = e2par;
  }

  if(fabs(mubar.PseudoRapidity())<=0.9){
    dpar2 = d0par;
    epar2 = e0par;
  }else if(mubar.PseudoRapidity()>0.9){
    dpar2 = d1par;
    epar2 = e1par;
  }else if(mubar.PseudoRapidity()<-0.9){
    dpar2 = d2par;
    epar2 = e2par;
  }

  float corr1 = 1.0 + bpar*mu.Pt() + (-1.0)*cpar*mu.Pt()*TMath::Sign(float(1.0),float(mu.PseudoRapidity()))*TMath::Power(mu.PseudoRapidity(),2)
    + (-1.0)*dpar1*mu.Pt()*sin(mu.Phi() + epar1);
  float corr2 = 1.0 + bpar*mubar.Pt() + (1.0)*cpar*mubar.Pt()*TMath::Sign(float(1.0),float(mubar.PseudoRapidity()))*TMath::Power(mubar.PseudoRapidity(),2)
    + (1.0)*dpar2*mubar.Pt()*sin(mubar.Phi() + epar2);
  
  float px1 = mu.Px();
  float py1 = mu.Py();
  float pz1 = mu.Pz();
  float e1 = mu.E();
  
  float px2 = mubar.Px();
  float py2 = mubar.Py();
  float pz2 = mubar.Pz();
  float e2 = mubar.E();

  px1 *= corr1;
  py1 *= corr1;
  pz1 *= corr1;
  e1 *= corr1;
  
  px2 *= corr2;
  py2 *= corr2;
  pz2 *= corr2;
  e2 *= corr2;
  
  mu.SetPxPyPzE(px1,py1,pz1,e1);
  mubar.SetPxPyPzE(px2,py2,pz2,e2);

}
HHKinFit2::HHKinFitMasterSingleHiggs::HHKinFitMasterSingleHiggs(TLorentzVector const& tauvis1,
                                                                TLorentzVector const& tauvis2,
                                                                TVector2 const& met, 
                                                                TMatrixD const& met_cov, 
                                                                bool istruth,
                                                                TLorentzVector const& higgsgen)
:m_MET_COV(TMatrixD(4,4))
{
  
  m_tauvis1 = HHLorentzVector(tauvis1.Px(), tauvis1.Py(), tauvis1.Pz(), tauvis1.E());  
  m_tauvis2 = HHLorentzVector(tauvis2.Px(), tauvis2.Py(), tauvis2.Pz(), tauvis2.E());
 
  m_tauvis1.SetMkeepE(1.77682);
  m_tauvis2.SetMkeepE(1.77682);
   
  m_MET = met;
  m_MET_COV = met_cov;

  m_chi2_best = pow(10,10);
  m_bestHypo = 0;

  //  if (istruth){
  //    TRandom3 r(0);
  //
  //    HHLorentzVector recoil;
  //    if(heavyhiggsgen != NULL){
  //       Double_t pxRecoil = r.Gaus(-(heavyhiggsgen->Px() ), 10.0);
  //       Double_t pyRecoil = r.Gaus(-(heavyhiggsgen->Py() ), 10.0);
  //
  //       recoil = HHLorentzVector(pxRecoil, pyRecoil, 0,
  //				sqrt(pxRecoil*pxRecoil+pyRecoil*pyRecoil));
  //    }
  //    else{
  //      recoil = HHLorentzVector(0,0,0,0);
  //      std::cout << "WARNING! Truthinput mode active but no Heavy Higgs gen-information given! Setting Recoil to Zero!" << std::endl;
  //    }
  //
  //    TMatrixD recoilCov(2,2);
  //    recoilCov(0,0)=100;  recoilCov(0,1)=0;
  //    recoilCov(1,0)=0;    recoilCov(1,1)=100;
  //
  //    HHLorentzVector recoHH = m_bjet1 + m_bjet2 + m_tauvis1 + m_tauvis2 + recoil;
  //    m_MET = TVector2(-recoHH.Px(), -recoHH.Py() );
  //
  //    m_MET_COV = TMatrixD(2,2);
  //    m_MET_COV = recoilCov + bjet1Cov + bjet2Cov;
  //
  //  }
}
double cosRestFrame(TLorentzVector boost, TLorentzVector vect) {

  double bx = -boost.Px()/boost.E();
  double by = -boost.Py()/boost.E();
  double bz = -boost.Pz()/boost.E();

  vect.Boost(bx,by,bz);
  double prod = -vect.Px()*bx-vect.Py()*by-vect.Pz()*bz;
  double modBeta = TMath::Sqrt(bx*bx+by*by+bz*bz); 
  double modVect = TMath::Sqrt(vect.Px()*vect.Px()+vect.Py()*vect.Py()+vect.Pz()*vect.Pz());
  
  double cosinus = prod/(modBeta*modVect);

  return cosinus;

}
Exemple #4
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);
  
}
Exemple #5
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);
  
}
Exemple #6
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);
  
}
Exemple #7
0
inline float kinematics::betaiSystem( TLorentzVector* pa, TLorentzVector* pb, int i)
{
	TLorentzVector pTmp = (*pa)+(*pb);
	float E = pTmp.E();
	if(E<=0.) return -99999999.;

	if     (i==1) return pTmp.Px()/E;
	else if(i==2) return pTmp.Py()/E;
	else if(i==3) return pTmp.Pz()/E;
	else _WARNING("i needs to be 1,2,3 (x,y,z), returning -99999999.");
	return -99999999.;
}
///------------------------------------------------------------------------
/// MEKD::computeKD - compute KD and MEs for the input processes A and B
///------------------------------------------------------------------------
int MEKD::computeKD( TString processA, TString processB,
                     TLorentzVector lept1P, int lept1Id, TLorentzVector lept2P, int lept2Id,
                     TLorentzVector lept3P, int lept3Id, TLorentzVector lept4P, int lept4Id,
                     double& kd, double& me2processA, double& me2processB )
{
	/// Prepare 4-momenta in the required format
	lept1P_i[0] = lept1P.E();
	lept1P_i[1] = lept1P.Px();
	lept1P_i[2] = lept1P.Py();
	lept1P_i[3] = lept1P.Pz();
	
	lept2P_i[0] = lept2P.E();
	lept2P_i[1] = lept2P.Px();
	lept2P_i[2] = lept2P.Py();
	lept2P_i[3] = lept2P.Pz();
	
	lept3P_i[0] = lept3P.E();
	lept3P_i[1] = lept3P.Px();
	lept3P_i[2] = lept3P.Py();
	lept3P_i[3] = lept3P.Pz();
	
	lept4P_i[0] = lept4P.E();
	lept4P_i[1] = lept4P.Px();
	lept4P_i[2] = lept4P.Py();
	lept4P_i[3] = lept4P.Pz();
	
	/// Load internal containers
	four_particle_Ps_i[0] = lept1P_i;
	four_particle_Ps_i[1] = lept2P_i;
	four_particle_Ps_i[2] = lept3P_i;
	four_particle_Ps_i[3] = lept4P_i;
	
	four_particle_IDs_i[0] = lept1Id;
	four_particle_IDs_i[1] = lept2Id;
	four_particle_IDs_i[2] = lept3Id;
	four_particle_IDs_i[3] = lept4Id;
	
	return computeKD( (string) processA.Data(), (string) processB.Data(), four_particle_Ps_i, four_particle_IDs_i, kd, me2processA, me2processB );
}
float GetWeightWjetsPolarizationF0(TLorentzVector _p4W, TLorentzVector _p4lepton,float PercentVariation, bool isWplus){

  LorentzVector p4W, p4lepton;
  p4W.SetPx(_p4W.Px());
  p4W.SetPy(_p4W.Py());
  p4W.SetPz(_p4W.Pz());
  p4W.SetE(_p4W.E());
  p4lepton.SetPx(_p4lepton.Px());
  p4lepton.SetPy(_p4lepton.Py());
  p4lepton.SetPz(_p4lepton.Pz());
  p4lepton.SetE(_p4lepton.E());

  float final_weight=1;

  float cos_theta = WjetPolarizationAngle(p4W,p4lepton);
  //  final_weight  = GetWeight( cos_theta,PercentVariation );
  //final_weight  = GetWeightFLminusFR( cos_theta,PercentVariation,p4W, isWplus );
  final_weight  = GetWeightF0( cos_theta,PercentVariation,p4W,isWplus );
  
  return final_weight;
  
  
}//end of function
///------------------------------------------------------------------------
/// MEKD::computeMEs - compute MEs for a multiple reuse
///------------------------------------------------------------------------
int MEKD::computeMEs( TLorentzVector lept1P, int lept1Id, TLorentzVector lept2P, int lept2Id,
					TLorentzVector lept3P, int lept3Id, TLorentzVector lept4P, int lept4Id )
{
	/// Prepare 4-momenta in the required format
	lept1P_i[0] = lept1P.E();
	lept1P_i[1] = lept1P.Px();
	lept1P_i[2] = lept1P.Py();
	lept1P_i[3] = lept1P.Pz();
	
	lept2P_i[0] = lept2P.E();
	lept2P_i[1] = lept2P.Px();
	lept2P_i[2] = lept2P.Py();
	lept2P_i[3] = lept2P.Pz();
	
	lept3P_i[0] = lept3P.E();
	lept3P_i[1] = lept3P.Px();
	lept3P_i[2] = lept3P.Py();
	lept3P_i[3] = lept3P.Pz();
	
	lept4P_i[0] = lept4P.E();
	lept4P_i[1] = lept4P.Px();
	lept4P_i[2] = lept4P.Py();
	lept4P_i[3] = lept4P.Pz();
	
	/// Load internal containers
	four_particle_Ps_i[0] = lept1P_i;
	four_particle_Ps_i[1] = lept2P_i;
	four_particle_Ps_i[2] = lept3P_i;
	four_particle_Ps_i[3] = lept4P_i;
	
	four_particle_IDs_i[0] = lept1Id;
	four_particle_IDs_i[1] = lept2Id;
	four_particle_IDs_i[2] = lept3Id;
	four_particle_IDs_i[3] = lept4Id;
	
	return computeMEs( four_particle_Ps_i, four_particle_IDs_i );
}
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);
  
}
Exemple #12
0
int main(int argc, char* argv[])
{ 
  //Upload the file with the data
  TFile* file = TFile::Open("/Users/Fer/Documents/traajo/samples/NeroNtuples_9.root"); // TFile::Open() instead of a constructor since it works over xrootd etc.
  //Upload the tree with the event data
  TTree *tree=(TTree*)file->Get("nero/events");

  //Create the vector to store all the particle identifiers
  std::vector<Int_t> * lepPdgId;

  //Create a variable to store all the lepton event data
  TClonesArray *leptondata = new TClonesArray("leptondata");

  //Specify where all the lepton event data will be stores
  tree->SetBranchAddress("lepP4", &leptondata);
  //Specify where all the lepton identifiers will be stored
  tree->SetBranchAddress("lepPdgId", &lepPdgId);

  //Get how many events we have to loop through
  int nentries = tree->GetEntries();

  //Loop through all the events
  for(int ientry = 0; ientry < nentries; ientry++) 
  {
    //Reset the lepton data 
    leptondata->Clear();
    //This line stores the proper data both in "leptondata" and in "lepPdgId"
    tree->GetEntry(ientry);
    
    //Only if "leptondata" is not empty continue, this is to avoid segmentation errors
    if(leptondata->GetSize() == 0) continue;

    //Loop through all the entries in the current event 
    for(int j=0; j<leptondata->GetEntriesFast()-1; j++) 
    {
        //Only if the identifier of the particle is + or - 11 (electron or antielectron) store the data in electrondata
        if(abs(lepPdgId->at(j))==11) continue;
        //Store all the data of the electron in this variable
        TLorentzVector *electrondata = (TLorentzVector *)leptondata->At(j);
        //Get some specific property such as momentum, position or energy
        cout << electrondata->E() << endl;
    }
  }
  return 0; 
}
TLorentzVector doCalEnergy(double BeamEnergy,
                           TLorentzVector Particle1,
                           TLorentzVector Particle2,
                           double nucleusMass,
                           double Particle2Mass,
                           double Particle3Mass)
{
    double E_Particle1   = Particle1.E();
    double p_Particle1_x = Particle1.Px();
    double p_Particle1_y = Particle1.Py();
    double p_Particle1_z = Particle1.Pz();
    double p_Particle1   = sqrt(TMath::Power(p_Particle1_x,2.0) +
                                    TMath::Power(p_Particle1_y,2.0) +
                                    TMath::Power(p_Particle1_z,2.0));
    double phi   = Particle2.Phi();
    double theta = Particle2.Theta();
    double b     = 2.0 * ( p_Particle1_x * cos(phi) * sin(theta) +
                           p_Particle1_y * sin(phi) * sin(theta) +
                           p_Particle1_z * cos(theta) -
                           BeamEnergy * cos(theta)
                         );
    double c     = p_Particle1 * p_Particle1 + BeamEnergy * BeamEnergy - 2.0 * BeamEnergy * p_Particle1_z;
    double d     = BeamEnergy + nucleusMass - E_Particle1;
    double e     = TMath::Power(Particle3Mass,2.0) - TMath::Power(Particle2Mass,2.0) - d * d + c;
    double Delta = 16.0 * TMath::Power(d,2.0) * (TMath::Power(e,2.0) +
                                                 TMath::Power(b * Particle2Mass,2.0) -
                                                 TMath::Power(d * Particle2Mass * 2.0,2.0));
    
    TLorentzVector NewParticle(0.0,0.0,0.0,0.0);
    if(Delta>0.)
    {
       double sol2     = (2.0 * e * b + sqrt(Delta)) / (2.0 * (4.0 * TMath::Power(d,2.0) - TMath::Power(b,2.0)));
       double newpxcal = sol2 * cos(phi) * sin(theta);
       double newpycal = sol2 * sin(phi) * sin(theta);
       double newpzcal = sol2 * cos(theta);
       double energy   = sqrt(TMath::Power(sol2,2.0) + TMath::Power(Particle2Mass,2.0));
      
       TLorentzVector NewParticle2(newpxcal,newpycal,newpzcal,energy);
       NewParticle = NewParticle2;
    }
  
    return NewParticle;
}
Exemple #14
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);
  
}
Exemple #15
0
void countDoubles(RhoCandList &l, int &n1, int &n2, int &n3)
{
	int n_smc  = 0;
	int n_strk = 0;
	int n_both = 0;
	double d = 0.00001;
	
	for (int i=0;i<l.GetLength()-1;++i)
	{
		for (int j=i+1;j<l.GetLength();++j)
		{
			TLorentzVector dl = l[i]->P4() - l[j]->P4();
		
			bool chkmc = (l[i]->GetMcTruth()==l[j]->GetMcTruth());
			bool chktrk = (fabs(dl.X())<d) && (fabs(dl.Y())<d) && (fabs(dl.Z())<d) && (fabs(dl.E())<d);
			if (chkmc) n_smc++;
			if (chktrk) n_strk++;
			if (chktrk && chkmc) n_both++;
		}	
	}
	n1 = n_strk;
	n2 = n_smc;
	n3 = n_both;
}
Exemple #16
0
// Copied from http://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/CMSSW/TopQuarkAnalysis/SingleTop/src/TopProducer.cc?revision=1.9&view=markup
TLorentzVector getNu4Momentum(const TLorentzVector& TLepton, const TLorentzVector& TMET)
{
  const math::XYZTLorentzVector Lepton(TLepton.Px(), TLepton.Py(), TLepton.Pz(), TLepton.E());
  const math::XYZTLorentzVector MET(TMET.Px(), TMET.Py(), 0., TMET.E());

  double  mW = 80.38;

  //std::vector<math::XYZTLorentzVector> result;
  std::vector<TLorentzVector> result;

  //  double Wmt = sqrt(pow(Lepton.et()+MET.pt(),2) - pow(Lepton.px()+MET.px(),2) - pow(Lepton.py()+MET.py(),2) );
    
  double MisET2 = (MET.px()*MET.px() + MET.py()*MET.py());
  double mu = (mW*mW)/2 + MET.px()*Lepton.px() + MET.py()*Lepton.py();
  double a  = (mu*Lepton.pz())/(Lepton.energy()*Lepton.energy() - Lepton.pz()*Lepton.pz());
  double a2 = TMath::Power(a,2);
  double b  = (TMath::Power(Lepton.energy(),2.)*(MisET2) - TMath::Power(mu,2.))/(TMath::Power(Lepton.energy(),2) - TMath::Power(Lepton.pz(),2));
  double pz1(0),pz2(0),pznu(0);
  int nNuSol(0);

  //math::XYZTLorentzVector p4nu_rec;
  TLorentzVector p4nu_rec;
  math::XYZTLorentzVector p4W_rec;
  math::XYZTLorentzVector p4b_rec;
  math::XYZTLorentzVector p4Top_rec;
  math::XYZTLorentzVector p4lep_rec;

  p4lep_rec.SetPxPyPzE(Lepton.px(),Lepton.py(),Lepton.pz(),Lepton.energy());
  
  //math::XYZTLorentzVector p40_rec(0,0,0,0);

  if(a2-b > 0 ){
    //if(!usePositiveDeltaSolutions_)
    //  {
    //    result.push_back(p40_rec);
    //    return result;
    //  }
    double root = sqrt(a2-b);
    pz1 = a + root;
    pz2 = a - root;
    nNuSol = 2;

    //if(usePzPlusSolutions_)pznu = pz1;    
    //if(usePzMinusSolutions_)pznu = pz2;
    //if(usePzAbsValMinimumSolutions_){
      pznu = pz1;
      if(fabs(pz1)>fabs(pz2)) pznu = pz2;
    //}

    double Enu = sqrt(MisET2 + pznu*pznu);

    p4nu_rec.SetPxPyPzE(MET.px(), MET.py(), pznu, Enu);

    result.push_back(p4nu_rec);

  }
  else{
    //if(!useNegativeDeltaSolutions_){
    //  result.push_back(p40_rec);
    //  return result;
    //}
    //    double xprime = sqrt(mW;

    double ptlep = Lepton.pt(),pxlep=Lepton.px(),pylep=Lepton.py(),metpx=MET.px(),metpy=MET.py();

    double EquationA = 1;
    double EquationB = -3*pylep*mW/(ptlep);
    double EquationC = mW*mW*(2*pylep*pylep)/(ptlep*ptlep)+mW*mW-4*pxlep*pxlep*pxlep*metpx/(ptlep*ptlep)-4*pxlep*pxlep*pylep*metpy/(ptlep*ptlep);
    double EquationD = 4*pxlep*pxlep*mW*metpy/(ptlep)-pylep*mW*mW*mW/ptlep;

    std::vector<long double> solutions = EquationSolve<long double>((long double)EquationA,(long double)EquationB,(long double)EquationC,(long double)EquationD);

    std::vector<long double> solutions2 = EquationSolve<long double>((long double)EquationA,-(long double)EquationB,(long double)EquationC,-(long double)EquationD);

    double deltaMin = 14000*14000;
    double zeroValue = -mW*mW/(4*pxlep); 
    double minPx=0;
    double minPy=0;

    //    std::cout<<"a "<<EquationA << " b " << EquationB  <<" c "<< EquationC <<" d "<< EquationD << std::endl; 
      
    //if(usePxMinusSolutions_){
      for( int i =0; i< (int)solutions.size();++i){
      if(solutions[i]<0 ) continue;
      double p_x = (solutions[i]*solutions[i]-mW*mW)/(4*pxlep); 
      double p_y = ( mW*mW*pylep + 2*pxlep*pylep*p_x -mW*ptlep*solutions[i])/(2*pxlep*pxlep);
      double Delta2 = (p_x-metpx)*(p_x-metpx)+(p_y-metpy)*(p_y-metpy); 

      //      std::cout<<"intermediate solution1 met x "<<metpx << " min px " << p_x  <<" met y "<<metpy <<" min py "<< p_y << std::endl; 

      if(Delta2< deltaMin && Delta2 > 0){deltaMin = Delta2;
      minPx=p_x;
      minPy=p_y;}
      //     std::cout<<"solution1 met x "<<metpx << " min px " << minPx  <<" met y "<<metpy <<" min py "<< minPy << std::endl; 
      }
    //}

    //if(usePxPlusSolutions_){
      for( int i =0; i< (int)solutions2.size();++i){
        if(solutions2[i]<0 ) continue;
        double p_x = (solutions2[i]*solutions2[i]-mW*mW)/(4*pxlep); 
        double p_y = ( mW*mW*pylep + 2*pxlep*pylep*p_x +mW*ptlep*solutions2[i])/(2*pxlep*pxlep);
        double Delta2 = (p_x-metpx)*(p_x-metpx)+(p_y-metpy)*(p_y-metpy); 
        //  std::cout<<"intermediate solution2 met x "<<metpx << " min px " << minPx  <<" met y "<<metpy <<" min py "<< minPy << std::endl; 
        if(Delta2< deltaMin && Delta2 > 0){deltaMin = Delta2;
          minPx=p_x;
          minPy=p_y;
        }
        //        std::cout<<"solution2 met x "<<metpx << " min px " << minPx  <<" met y "<<metpy <<" min py "<< minPy << std::endl; 
      }
    //}

    double pyZeroValue= ( mW*mW*pxlep + 2*pxlep*pylep*zeroValue);
    double delta2ZeroValue= (zeroValue-metpx)*(zeroValue-metpx) + (pyZeroValue-metpy)*(pyZeroValue-metpy);

    if(deltaMin==14000*14000) return TLorentzVector(0,0,0,0);
    //if(deltaMin==14000*14000) return result.front();
    //    else std::cout << " test " << std::endl;

    if(delta2ZeroValue < deltaMin){
      deltaMin = delta2ZeroValue;
      minPx=zeroValue;
      minPy=pyZeroValue;}

    //    std::cout<<" MtW2 from min py and min px "<< sqrt((minPy*minPy+minPx*minPx))*ptlep*2 -2*(pxlep*minPx + pylep*minPy)  <<std::endl;
    ///    ////Y part   

    double mu_Minimum = (mW*mW)/2 + minPx*pxlep + minPy*pylep;
    double a_Minimum  = (mu_Minimum*Lepton.pz())/(Lepton.energy()*Lepton.energy() - Lepton.pz()*Lepton.pz());
    pznu = a_Minimum;

    //if(!useMetForNegativeSolutions_){
      double Enu = sqrt(minPx*minPx+minPy*minPy + pznu*pznu);
      p4nu_rec.SetPxPyPzE(minPx, minPy, pznu , Enu);
    //}
    //else{
    //  pznu = a;
    //  double Enu = sqrt(metpx*metpx+metpy*metpy + pznu*pznu);
    //  p4nu_rec.SetPxPyPzE(metpx, metpy, pznu , Enu);
    //}
    result.push_back(p4nu_rec);
  }
  return result.front();
}
Exemple #17
0
int main(int argc, char * argv[])
{
	// load silly ROOT thing
	gROOT->ProcessLine("#include <vector>");
	gROOT->ProcessLine(".L loader.C+");

	// output
	TFile * output_file = new TFile("output_file.root", "RECREATE");

	TTree * jet_tree = new TTree("jet_tree", "jet_tree");
	float jet_pt = 0;
	float jet_eta = 0;
	float jet_phi = 0;
	float jet_m = 0;
	jet_tree->Branch("jet_pt", &jet_pt);
	jet_tree->Branch("jet_eta", &jet_eta);
	jet_tree->Branch("jet_phi", &jet_phi);
	jet_tree->Branch("jet_m", &jet_m);

	TTree * event_tree = new TTree("event_tree", "event_tree");
	int n = 0;
	int us = 0;
	event_tree->Branch("n", &n);
	event_tree->Branch("us", &us);

	// input tracks
	TChain * tree = new TChain("tree");
	tree->Add("mc15_13TeV.301523.RS_G_hh_bbbb_c20_M2000.track_ntuple.root");
	int number_of_events = tree->GetEntries();

	int track_number = 0;
	vector<float> * track_pt = 0;
	vector<float> * track_eta = 0;
	vector<float> * track_phi = 0;
	tree->SetBranchAddress("track_number", &track_number);
	tree->SetBranchAddress("track_pt", &track_pt);
	tree->SetBranchAddress("track_eta", &track_eta);
	tree->SetBranchAddress("track_phi", &track_phi);

	vector<PseudoJet> particles;

	// variables for timing
	struct timeval start;
	struct timeval end;
	struct timeval duration;
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
//	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 10000);
//	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(10000));
	TH2F * h_timing = new TH2F("timing", "timing; # Tracks; #mus", 1000, 0, 1000, 100, 1, 5000);						// N2Tiled
	TH2F * h_log_timing = new TH2F("log_timing", "log_timing; # Tracks; log_{10}(#mus)", 1000, 0, 1000, 100, log10(1), log10(5000));	// N2Tiled

	for (int event = 0; event < number_of_events; event++)
	{
		// print a sexy load bar
		loadBar(event, number_of_events, 100, 50);

		tree->GetEntry(event);

		for (int track = 0; track < track_number; track++)
		{
			TLorentzVector trackLorentzVector;
			trackLorentzVector.SetPtEtaPhiM(track_pt->at(track) / 1000.0, track_eta->at(track), track_phi->at(track), 0);
			particles.push_back(PseudoJet(trackLorentzVector.Px(), trackLorentzVector.Py(), trackLorentzVector.Pz(), trackLorentzVector.E()));
		}

		// get the start time
		gettimeofday(&start, NULL);

		// not vrplugin
		double R = 0.4;
//		JetDefinition jet_def(antikt_vr, R, N3Dumb, E_scheme, 1, 60);
//		JetDefinition jet_def(antikt_vr, R, N2Plain, E_scheme, 1, 60);
		JetDefinition jet_def(antikt_vr, R, N2Tiled, E_scheme, 1, 60);
		ClusterSequence cs(particles, jet_def);
		vector<PseudoJet> jets = sorted_by_pt(cs.inclusive_jets());

		// vrplugin
//		double rho = 60;
//		double min_r = 0;
//		double max_r = 0.4;
//		VariableRPlugin vrplugin(rho, min_r, max_r, VariableRPlugin::AKTLIKE);
//		JetDefinition jet_def_vrplugin(&vrplugin);
//		ClusterSequence cs_vrplugin(particles, jet_def_vrplugin);
//		vector<fastjet::PseudoJet> jets = sorted_by_pt(cs_vrplugin.inclusive_jets());

		// get the final time
		gettimeofday(&end, NULL);

		// get the duration
		timersub(&end, &start, &duration);
		h_timing->Fill(track_number, (long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec);
		h_log_timing->Fill(track_number, log10((long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec));

		n = track_number;
		us = (long int) duration.tv_sec * 1000000 + (long int) duration.tv_usec;

		event_tree->Fill();

		for (int jet = 0; jet < jets.size(); jet++)
		{
//			printf("jets[jet].pt() = %f\n", jets[jet].pt());
//			printf("jets[jet].eta() = %f\n", jets[jet].eta());
//			printf("jets[jet].phi() = %f\n", jets[jet].phi());
//			printf("jets[jet].m() = %f\n", jets[jet].m());
			jet_pt = jets[jet].pt();
			jet_eta = jets[jet].eta();
			jet_phi = jets[jet].phi();
			jet_m = jets[jet].m();

			jet_tree->Fill();
		}

		particles.clear();
	}

	TProfile * pr_timing = h_timing->ProfileX();
	TF1 * f_timing_n2 = new TF1("f_timing_n2", "pol2", 0, 1000);
	TF1 * f_timing_n3 = new TF1("f_timing_n3", "pol3", 0, 1000);
	pr_timing->Fit(f_timing_n2);
	pr_timing->Fit(f_timing_n3);

	TProfile * pr_log_timing = h_log_timing->ProfileX();
	TF1 * f_log_timing = new TF1("f_log_timing", "pol1", 0, 1000);
	pr_log_timing->Fit(f_log_timing);

	output_file->Write();

	h_timing->Write();
	pr_timing->Write();
	f_timing_n2->Write();
	f_timing_n3->Write();

	h_log_timing->Write();
	pr_log_timing->Write();
	f_log_timing->Write();

	delete(jet_tree);
	delete(event_tree);

	return 0;
}
PseudoJet::PseudoJet(TLorentzVector const& vector) :
    fastjet::PseudoJet(vector.Px(), vector.Py(), vector.Pz(), vector.E())
{
    INFO(vector.Px(), px(), vector.Py(), py());
}
Exemple #19
0
void PlotTheta( TString inputfilename, TString outputfilename = "output.root"){
//    infile= new TFile("../PATGrid.SM.10k.root","READ");
    infile = new TFile(inputfilename, "READ");
    tree = (TTree*)infile->Get("Event");
    outputFile = new TFile(outputfilename, "RECREATE");
    outTree = new TTree("MyTree","Untersuchung der RekoObjekte");

    //TH2::SetDefaultSumw2();

    histogram__CosThetaDiff = new TH1D("histogram__CosThetaDiff", "Differenz CosTheta gen-reko", 400, -2, 2);
    histogram__CosTheta_GenReko = new TH2D("histogram__CosTheta_GenReko", "Reko-cos(theta) gegen Gen-cos(theta)", 50, -1, 1, 50, -1, 1);

    histogram__gen_A = new TH2D("histogram__gen_A", "histogram__gen_A", 5, -1, 1, 5, -1, 1);
    histogram__gen_N = new TH2D("histogram__gen_N", "histogram__gen_N", 5, -1, 1, 5, -1, 1);

    histogram__gen_LL = new TH2D("histogram__gen_LL", "histogram__gen_LL", 5, -1, 1, 5, -1, 1);
    histogram__gen_LR = new TH2D("histogram__gen_LR", "histogram__gen_LR", 5, -1, 1, 5, -1, 1);
    histogram__gen_RR = new TH2D("histogram__gen_RR", "histogram__gen_RR", 5, -1, 1, 5, -1, 1);
    histogram__gen_RL = new TH2D("histogram__gen_RL", "histogram__gen_RL", 5, -1, 1, 5, -1, 1);

    histogram__gen_Correlation = new TH2D("histogram__gen_Correlation", "histogram__gen_Correlation", 5, -1, 1, 5, -1, 1);

    histogram__A = new TH2D("histogram__A", "histogram__A", 5, -1, 1, 5, -1, 1);
    histogram__N = new TH2D("histogram__N", "histogram__N", 5, -1, 1, 5, -1, 1);

    histogram__Correlation = new TH2D("histogram__Correlation", "histogram__Correlation", 5, -1, 1, 5, -1, 1);
    histogram__Correlation_L15_B50_T1 = new TH2D("histogram__Correlation_L15_B50_T1", "histogram__Correlation_L15_B50_T1", 5, -1, 1, 5, -1, 1);
    histogram__A_L15_B50_T1 = new TH2D("histogram__A_L15_B50_T1", "histogram__A_L15_B50_T1", 5, -1, 1, 5, -1, 1);
    histogram__N_L15_B50_T1 = new TH2D("histogram__N_L15_B50_T1", "histogram__N_L15_B50_T1", 5, -1, 1, 5, -1, 1);
    histogram__Correlation_L20 = new TH2D("histogram__Correlation_L20", "histogram__Correlation_L20", 5, -1, 1, 5, -1, 1);
    histogram__A_L20 = new TH2D("histogram__A_L20", "histogram__A_L20", 5, -1, 1, 5, -1, 1);
    histogram__N_L20 = new TH2D("histogram__N_L20", "histogram__N_L20", 5, -1, 1, 5, -1, 1);
    histogram__Correlation_L20_B40 = new TH2D("histogram__Correlation_L20_B40", "histogram__Correlation_L20_B40", 5, -1, 1, 5, -1, 1);
    histogram__A_L20_B40 = new TH2D("histogram__A_L20_B40", "histogram__A_L20_B40", 5, -1, 1, 5, -1, 1);
    histogram__N_L20_B40 = new TH2D("histogram__N_L20_B40", "histogram__N_L20_B40", 5, -1, 1, 5, -1, 1);
    
    histogram__Correlation_L20_B30_T1 = new TH2D("histogram__Correlation_L20_B30_T1", "histogram__Correlation_L20_B30_T1", 5, -1, 1, 5, -1, 1);
    histogram__A_L20_B30_T1 = new TH2D("histogram__A_L20_B30_T1", "histogram__A_L20_B30_T1", 5, -1, 1, 5, -1, 1);
    histogram__N_L20_B30_T1 = new TH2D("histogram__N_L20_B30_T1", "histogram__N_L20_B30_T1", 5, -1, 1, 5, -1, 1);

    histogram__Correlation_L20_B40_T1 = new TH2D("histogram__Correlation_L20_B40_T1", "histogram__Correlation_L20_B40_T1", 5, -1, 1, 5, -1, 1);
    histogram__A_L20_B40_T1 = new TH2D("histogram__A_L20_B40_T1", "histogram__A_L20_B40_T1", 5, -1, 1, 5, -1, 1);
    histogram__N_L20_B40_T1 = new TH2D("histogram__N_L20_B40_T1", "histogram__N_L20_B40_T1", 5, -1, 1, 5, -1, 1);
    histogram__Correlation_T1 = new TH2D("histogram__Correlation_T1", "histogram__Correlation_T1", 5, -1, 1, 5, -1, 1);
    histogram__A_T1 = new TH2D("histogram__A_T1", "histogram__A_T1", 5, -1, 1, 5, -1, 1);
    histogram__N_T1 = new TH2D("histogram__N_T1", "histogram__N_T1", 5, -1, 1, 5, -1, 1);



    histogram__CosThetaDiff_TTbarPt = new TH2D("histogram__CosThetaDiff_TTbarPt", "histogram__CosThetaDiff_TTbarPt", 100, 0, 1000, 400, -2, 2);


    histogram__LeptonRelIso = new TH1D("histogram__LeptonRelIso", "histogram__LeptonRelIso", 101, 0, 1.01);


    histogram__semilepton_BLeptonMinus = new TH1D("histogram__semilepton_BLeptonMinus","histogram__semilepton_BLeptonMinus", 200, -1, 1);
    histogram__semilepton_BLeptonPlus = new TH1D("histogram__semilepton_BLeptonPlus","histogram__semilepton_BLeptonPlus", 200, -1, 1);



    histogram_nupx_gen_reco = new TH2D(" histogram_nupx_gen_reco", " histogram_nupx_gen_reco", 600, -300, 300, 600, -300, 300);
    histogram_nupy_gen_reco = new TH2D(" histogram_nupy_gen_reco", " histogram_nupy_gen_reco", 600, -300, 300, 600, -300, 300);
    histogram_nupz_gen_reco = new TH2D(" histogram_nupz_gen_reco", " histogram_nupz_gen_reco", 600, -300, 300, 600, -300, 300);

    histogram_nubpx_gen_reco = new TH2D(" histogram_nubpx_gen_reco", " histogram_nubpx_gen_reco", 600, -300, 300, 600, -300, 300);
    histogram_nubpy_gen_reco = new TH2D(" histogram_nubpy_gen_reco", " histogram_nubpy_gen_reco", 600, -300, 300, 600, -300, 300);
    histogram_nubpz_gen_reco = new TH2D(" histogram_nubpz_gen_reco", " histogram_nubpz_gen_reco", 600, -300, 300, 600, -300, 300);

    outTree->Branch("EventIsGood", &EventIsGood, "Event ist rekonstruiert/I");
    outTree->Branch("numberOfJets", &numberOfJets, "Anzahl der Jets/I");
    outTree->Branch("numberOfGoodJets", &numberOfGoodJets, "Anzahl der guten Jets/I");

    outTree->Branch("CosThetaDiff" ,&CosThetaDiff ,"Differenz im cosTheta Reko zu Gen/D");
    outTree->Branch("CosThetaPlus" ,&CosThetaPlus ,"cosTheta LeptonPlus/D");
    outTree->Branch("CosThetaMinus" ,&CosThetaMinus ,"cosTheta LeptonMinus/D");
    outTree->Branch("RekoCosThetaPlus" ,&RekoCosThetaPlus ,"cosTheta RekoLeptonPlus/D");
    outTree->Branch("RekoCosThetaMinus" ,&RekoCosThetaMinus ,"cosTheta RekoLeptonMinus/D");

    outTree->Branch("CosLeptonAngleD", &CosLeptonAngleD, "CosinusLeptonWinkel D/D");
    outTree->Branch("CosRekoLeptonAngleD", &CosRekoLeptonAngleD, "CosinusRekoLeptonWinkel D/D");

    outTree->Branch("TTbar_Pt", &TTbar_Pt, "Pt des TTbarsystems Generator/D");
    outTree->Branch("RekoTTbar_Pt", &RekoTTbar_Pt, "Pt des TTbarsystems Reko/D");
    outTree->Branch("TTbar_M", &TTbar_M, "Masse des TTbarsystems Generator/D");
    outTree->Branch("RekoTTbar_M", &RekoTTbar_M, "Masse des TTbarsystems Reko/D");
    outTree->Branch("Top_Pt", &Top_Pt, "Pt des Tops Generator/D");
    outTree->Branch("Top_M", &Top_M, "M des Tops Generator/D");
    outTree->Branch("AntiTop_Pt", &AntiTop_Pt, "Pt des AntiTops Generator/D");
    outTree->Branch("AntiTop_M", &AntiTop_M, "M des AntiTops Generator/D");
    outTree->Branch("RekoTop_Pt", &RekoTop_Pt, "Pt des Tops Reko/D");
    outTree->Branch("RekoAntiTop_Pt", &RekoAntiTop_Pt, "Pt des AntiTops Reko/D");
    outTree->Branch("RekoTop_M", &RekoTop_M, "M des Tops Reko/D");
    outTree->Branch("RekoAntiTop_M", &RekoAntiTop_M, "M des AntiTops Reko/D");
    outTree->Branch("Nu_Px", &Nu_Px, "Px des Neutrinos Generator/D");
    outTree->Branch("Nu_Py", &Nu_Py, "Py des Neutrinos Generator/D");
    outTree->Branch("Nu_Pz", &Nu_Pz, "Pz des Neutrinos Generator/D");
    outTree->Branch("AntiNu_Px", &AntiNu_Px, "Px des AntiNeutrinos Generator/D");
    outTree->Branch("AntiNu_Py", &AntiNu_Py, "Py des AntiNeutrinos Generator/D");
    outTree->Branch("AntiNu_Pz", &AntiNu_Pz, "Pz des AntiNeutrinos Generator/D");
    outTree->Branch("RekoNu_Px", &RekoNu_Px, "Px des Neutrinos Reko/D");
    outTree->Branch("RekoNu_Py", &RekoNu_Py, "Py des Neutrinos Reko/D");
    outTree->Branch("RekoNu_Pz", &RekoNu_Pz, "Pz des Neutrinos Reko/D");
    outTree->Branch("RekoAntiNu_Px", &RekoAntiNu_Px, "Px des AntiNeutrinos Reko/D");
    outTree->Branch("RekoAntiNu_Py", &RekoAntiNu_Py, "Py des AntiNeutrinos Reko/D");
    outTree->Branch("RekoAntiNu_Pz", &RekoAntiNu_Pz, "Pz des AntiNeutrinos Reko/D");

    outTree->Branch("BestNu_Px", &BestNu_Px, "Px des Neutrinos Best/D");
    outTree->Branch("BestNu_Py", &BestNu_Py, "Py des Neutrinos Best/D");
    outTree->Branch("BestNu_Pz", &BestNu_Pz, "Pz des Neutrinos Best/D");
    outTree->Branch("BestAntiNu_Px", &BestAntiNu_Px, "Px des AntiNeutrinos Best/D");
    outTree->Branch("BestAntiNu_Py", &BestAntiNu_Py, "Py des AntiNeutrinos Best/D");
    outTree->Branch("BestAntiNu_Pz", &BestAntiNu_Pz, "Pz des AntiNeutrinos Best/D");

    outTree->Branch("Lepton_Pt", &Lepton_Pt, "kleineres Pt der beiden gewaehlten Leptonen/D");
    outTree->Branch("BJet_Et", &BJet_Et,"niedrigieres Et der BJets/D");
    outTree->Branch("BJet_Tag_TrkCount", &BJet_Tag_TrkCount,"niedrigierer BTag der BJets/D");
    outTree->Branch("BJet_Tag_SVsimple", &BJet_Tag_SVsimple,"niedrigierer BTag der BJets/D");
    outTree->Branch("BJet_Tag_SVcomb", &BJet_Tag_SVcomb,"niedrigierer BTag der BJets/D");
    outTree->Branch("BJet_Disc", &BJet_Disc,"niedrigierer Discriminator der BJets/D");
    outTree->Branch("Lepton1_Id", &Lepton1_Id, "PdgId des ersten Leptons/I");
    outTree->Branch("Lepton2_Id", &Lepton2_Id, "PdgId des zweiten Leptons/I");
    outTree->Branch("Lepton_Mass", &Lepton_Mass, "inv. Masse der beiden Leptonen/D");

    outTree->Branch("BJet_Angle", &BJet_Angle, "Winkel bJet zu Quark/D");
    outTree->Branch("BbarJet_Angle", &BbarJet_Angle, "Winkel bbarJet zu Quark/D");
    outTree->Branch("LeptonPlus_Angle", &LeptonPlus_Angle, "Winkel LeptonPlus zu Lepton Gen /D");
    outTree->Branch("LeptonMinus_Angle", &LeptonMinus_Angle, "Winkel LeptonMinus zu Lepton Gen /D");
    outTree->Branch("RekoNu_Angle", &RekoNu_Angle, "Winkel RekoNu zu GenNu/D");
    outTree->Branch("RekoAntiNu_Angle", &RekoAntiNu_Angle, "Winkel RekoAntiNu zu GenAntiNu/D");
    outTree->Branch("BestNu_Angle", &BestNu_Angle, "Winkel BestNu zu GenNu/D");
    outTree->Branch("BestAntiNu_Angle", &BestAntiNu_Angle, "Winkel BestAntiNu zu GenAntiNu/D");


    histogram__gen_Correlation->Sumw2();
    histogram__Correlation->Sumw2();
    histogram__gen_A->Sumw2();
    histogram__A->Sumw2();
    histogram__gen_N->Sumw2();
    histogram__N->Sumw2();


    double PatJetsPx[50];
    double PatJetsPy[50];
    double PatJetsPz[50];
    double PatJetsE[50];
    double PatJetsEt[50];

    double PatLeptonsPx[20];
    double PatLeptonsPy[20];
    double PatLeptonsPz[20];
    double PatLeptonsPt[20];
    double PatLeptonsE[20];
    int PatLeptonsCharge[20];
    int PatLeptonsPdgId[20];
    double PatLeptonsTrkIso[20];
    double PatLeptonsCaloIso[20];

    double PatJetsBTag_TrkCount[50];
    double PatJetsBTag_SVsimple[50];
    double PatJetsBTag_SVcomb[50];
    double PatJetsCharge[50];
    double PatJetsBQuarkDeltaR[50];
    double PatJetsBbarQuarkDeltaR[50];
    
    int numberOfPatMuons;
    int numberOfPatElectrons;
    int numberOfPatLeptons;
    int numberOfPatJets;

    int numberOfLeptons;



    TLorentzVector *pTop;           //FROM TREE
    TLorentzVector *pAntiTop;       //FROM TREE
    TLorentzVector *pLeptonPlus;    //FROM TREE
    TLorentzVector *pLeptonMinus;   //FROM TREE
    TLorentzVector *pBQuark;        //FROM TREE
    TLorentzVector *pBbarQuark;     //FROM TREE
    TLorentzVector* pGenNu;         //FROM TREE
    TLorentzVector* pGenAntiNu;     //FROM TREE

    TLorentzVector *pTTbar;
    TLorentzVector *pTopBoosted;
    TLorentzVector *pAntiTopBoosted;
    TLorentzVector *pLeptonPlusBoosted;
    TLorentzVector *pLeptonMinusBoosted;

    TLorentzVector *pJet[50];

    TLorentzVector *pBJet1;
    TLorentzVector *pBJet2;
    TLorentzVector *pRekoNu1;
    TLorentzVector *pRekoAntiNu1;
    TLorentzVector *pRekoNu2;
    TLorentzVector *pRekoAntiNu2;

    TLorentzVector *pRekoLeptonPlus;
    TLorentzVector *pRekoLeptonMinus;
    TLorentzVector *pBJet;
    TLorentzVector *pBbarJet;
    TLorentzVector *pRekoNu;
    TLorentzVector *pRekoAntiNu;

    TLorentzVector *pBestNu;
    TLorentzVector *pBestAntiNu;
    TLorentzVector *pBestNu2;
    TLorentzVector *pBestAntiNu2;

    TLorentzVector *pRekoTop;
    TLorentzVector *pRekoAntiTop;

    TLorentzVector *pRekoTTbar;
    TLorentzVector *pRekoTopBoosted;
    TLorentzVector *pRekoAntiTopBoosted;
    TLorentzVector *pRekoLeptonPlusBoosted;
    TLorentzVector *pRekoLeptonMinusBoosted;

    TLorentzVector *pNu;
    TLorentzVector *pAntiNu;

    TLorentzVector *pBBoosted;
    TLorentzVector *pBbarBoosted;

    pTop = new TLorentzVector(0,0,0,0);
    pAntiTop = new TLorentzVector(0,0,0,0);
    pLeptonPlus = new TLorentzVector(0,0,0,0);
    pLeptonMinus = new TLorentzVector(0,0,0,0);
    pBQuark = new TLorentzVector(0,0,0,0);
    pBbarQuark = new TLorentzVector(0,0,0,0);
    pGenNu = new TLorentzVector(0,0,0,0);
    pGenAntiNu = new TLorentzVector(0,0,0,0);

    pTTbar = new TLorentzVector(0,0,0,0);
    pTopBoosted = new TLorentzVector(0,0,0,0);
    pAntiTopBoosted = new TLorentzVector(0,0,0,0);
    pLeptonPlusBoosted = new TLorentzVector(0,0,0,0);
    pLeptonMinusBoosted = new TLorentzVector(0,0,0,0);

    pRekoTop = new TLorentzVector(0,0,0,0);
    pRekoAntiTop = new TLorentzVector(0,0,0,0);
    pRekoLeptonPlus = new TLorentzVector(0,0,0,0);
    pRekoLeptonMinus = new TLorentzVector(0,0,0,0);
    pRekoNu = new TLorentzVector(0,0,0,0);
    pRekoAntiNu = new TLorentzVector(0,0,0,0);

    pBestNu = new TLorentzVector(0,0,0,0);
    pBestAntiNu = new TLorentzVector(0,0,0,0);
    pBestNu2 = new TLorentzVector(0,0,0,0);
    pBestAntiNu2 = new TLorentzVector(0,0,0,0);

    pRekoTTbar = new TLorentzVector(0,0,0,0);
    pRekoTopBoosted = new TLorentzVector(0,0,0,0);
    pRekoAntiTopBoosted = new TLorentzVector(0,0,0,0);
    pRekoLeptonPlusBoosted = new TLorentzVector(0,0,0,0);
    pRekoLeptonMinusBoosted = new TLorentzVector(0,0,0,0);    

    pNu = new TLorentzVector(0,0,0,0);
    pAntiNu = new TLorentzVector(0,0,0,0);
    pBJet1 = new TLorentzVector(0,0,0,0);
    pBJet2 = new TLorentzVector(0,0,0,0);
    pRekoNu1 = new TLorentzVector(0,0,0,0);
    pRekoAntiNu1 = new TLorentzVector(0,0,0,0);
    pRekoNu2 = new TLorentzVector(0,0,0,0);
    pRekoAntiNu2 = new TLorentzVector(0,0,0,0);
    pBJet = new TLorentzVector(0,0,0,0);
    pBbarJet = new TLorentzVector(0,0,0,0);

    pBBoosted = new TLorentzVector(0,0,0,0);
    pBbarBoosted = new TLorentzVector(0,0,0,0);

    for(int i=0; i<50;i++) pJet[i] = new TLorentzVector(0,0,0,0);

    double mass_a = 170.0;
    double mass_b = 175.0;
    calc Poly(mass_a, mass_b, outputFile);
    

    tree->SetBranchAddress("pTop",                &pTop);
    tree->SetBranchAddress("pAntiTop",            &pAntiTop);
    tree->SetBranchAddress("pLeptonPlus",         &pLeptonPlus);
    tree->SetBranchAddress("pLeptonMinus",        &pLeptonMinus);
    tree->SetBranchAddress("pBQuark",             &pBQuark);
    tree->SetBranchAddress("pBbarQuark",          &pBbarQuark);

    tree->SetBranchAddress("PatLeptonsPx",           PatLeptonsPx);
    tree->SetBranchAddress("PatLeptonsPy",           PatLeptonsPy);
    tree->SetBranchAddress("PatLeptonsPz",           PatLeptonsPz);
    tree->SetBranchAddress("PatLeptonsPt",           PatLeptonsPt);
    tree->SetBranchAddress("PatLeptonsE",            PatLeptonsE);
    tree->SetBranchAddress("PatLeptonsCharge",       PatLeptonsCharge);
    tree->SetBranchAddress("PatLeptonsPdgId",        PatLeptonsPdgId);
    tree->SetBranchAddress("PatLeptonsTrkIso",       PatLeptonsTrkIso);
    tree->SetBranchAddress("PatLeptonsCaloIso",      PatLeptonsCaloIso);

    tree->SetBranchAddress("PatJetsPx",           PatJetsPx);
    tree->SetBranchAddress("PatJetsPy",           PatJetsPy);
    tree->SetBranchAddress("PatJetsPz",           PatJetsPz);
    tree->SetBranchAddress("PatJetsE",            PatJetsE);
    tree->SetBranchAddress("PatJetsEt",           PatJetsEt);
    
    tree->SetBranchAddress("PatJetsCharge", 	        PatJetsCharge);
    tree->SetBranchAddress("PatJetsBTag_TrkCount",	 	PatJetsBTag_TrkCount);
    tree->SetBranchAddress("PatJetsBTag_SVsimple",	 	PatJetsBTag_SVsimple);
    tree->SetBranchAddress("PatJetsBTag_SVcomb",	 	PatJetsBTag_SVcomb);
    tree->SetBranchAddress("PatJetsBQuarkDeltaR",     PatJetsBQuarkDeltaR);
    tree->SetBranchAddress("PatJetsBbarQuarkDeltaR",  PatJetsBbarQuarkDeltaR);
   
    tree->SetBranchAddress("numberOfPatMuons",	        &numberOfPatMuons);
    tree->SetBranchAddress("numberOfPatElectrons",	&numberOfPatElectrons);
    tree->SetBranchAddress("numberOfPatLeptons",	&numberOfPatLeptons);
    tree->SetBranchAddress("numberOfPatJets",	        &numberOfPatJets);

    tree->SetBranchAddress("numberOfLeptons",	&numberOfLeptons);

    tree->SetBranchAddress("pGenNu",          &pGenNu);
    tree->SetBranchAddress("pGenAntiNu",      &pGenAntiNu);
 
    int nEvents = (int)tree->GetEntries();
    //nEvents = 5000;
    int EventCounter = 0;
    cout << "Anzahl Ereignisse: " << nEvents << endl;
    for(int iEvent=1; iEvent<nEvents;iEvent++){

        tree->GetEntry(iEvent);

        EventCounter++;

  
        if(iEvent%10000 == 1)
        {
            cout << "Event " << iEvent << endl;
        }
        
        EventIsGood = 0;
        
// GENERATOR THETA

        w_A = 0;
        w_N = 0;
        
        *pTTbar=(*pTop+*pAntiTop);
        *pTopBoosted = *pTop;
        *pAntiTopBoosted = *pAntiTop;
        *pLeptonPlusBoosted = *pLeptonPlus;
        *pLeptonMinusBoosted = *pLeptonMinus;
        *pBBoosted = *pBQuark;
        *pBbarBoosted = *pBbarQuark;

        pAntiTopBoosted->Boost(-pTTbar->BoostVector());
        pTopBoosted->Boost(-pTTbar->BoostVector());
        pLeptonPlusBoosted->Boost(-pTop->BoostVector());
        pLeptonMinusBoosted->Boost(-pAntiTop->BoostVector());
        CosThetaPlus = cos(pLeptonPlusBoosted->Angle(pTopBoosted->Vect()));
        CosThetaMinus = cos(pLeptonMinusBoosted->Angle(pAntiTopBoosted->Vect()));

        pBBoosted->Boost(-pTop->BoostVector());
        pBbarBoosted->Boost(-pAntiTop->BoostVector());

        CosLeptonAngleD = cos(pLeptonPlusBoosted->Angle(pLeptonMinusBoosted->Vect()));

        double Nenner = 1 - 0.256*CosThetaPlus*CosThetaMinus;
        
        w_A = (-CosThetaPlus*CosThetaMinus)/Nenner;
        w_N = 1./Nenner;
        
        w_LL = (1-CosThetaPlus*CosThetaMinus-CosThetaPlus+CosThetaMinus)/Nenner;
        w_LR = (1+CosThetaPlus*CosThetaMinus-CosThetaPlus-CosThetaMinus)/Nenner;
        w_RR = (1-CosThetaPlus*CosThetaMinus+CosThetaPlus-CosThetaMinus)/Nenner;
        w_RL = (1+CosThetaPlus*CosThetaMinus+CosThetaPlus+CosThetaMinus)/Nenner;
        
        histogram__gen_A->Fill(CosThetaPlus, CosThetaMinus, w_A);
        histogram__gen_N->Fill(CosThetaPlus, CosThetaMinus, w_N);
        
        histogram__gen_LL->Fill(CosThetaPlus, CosThetaMinus, w_LL);
        histogram__gen_LR->Fill(CosThetaPlus, CosThetaMinus, w_LR);
        histogram__gen_RR->Fill(CosThetaPlus, CosThetaMinus, w_RR);
        histogram__gen_RL->Fill(CosThetaPlus, CosThetaMinus, w_RL);
        
        histogram__gen_Correlation->Fill(CosThetaPlus, CosThetaMinus);

        if(numberOfLeptons == 2) 
        {
            if(pLeptonMinus->Px() != 0) histogram__semilepton_BLeptonMinus->Fill( cos(pLeptonMinusBoosted->Angle(pBBoosted->Vect())) );
            if(pLeptonPlus->Px() != 0) histogram__semilepton_BLeptonPlus->Fill( cos(pLeptonPlusBoosted->Angle(pBbarBoosted->Vect())) );
        }

        numberOfJets = numberOfPatJets;
        if(numberOfPatLeptons>=2 && numberOfPatJets >=2)
        {

            RekoNu_Px = -10000;
            RekoNu_Py= -10000;
            RekoNu_Pz= -10000;
        
            RekoAntiNu_Px= -10000;
            RekoAntiNu_Py= -10000;
            RekoAntiNu_Pz= -10000;

            RekoTop_M = -10;
            RekoAntiTop_M = -10;
            RekoTop_Pt = -10;
            RekoAntiTop_Pt = -10;


            
            // REKO THETA 

            pBJet1->SetPxPyPzE(0.,0.,0.,0.);
            pBJet2->SetPxPyPzE(0.,0.,0.,0.);
            pRekoLeptonPlus->SetPxPyPzE(0.,0.,0.,0.);
            pRekoLeptonMinus->SetPxPyPzE(0.,0.,0.,0.);
            pBJet->SetPxPyPzE(0.,0.,0.,0.);
            pBbarJet->SetPxPyPzE(0.,0.,0.,0.);
            pRekoNu->SetPxPyPzE(0.,0.,0.,-10000.);
            pRekoAntiNu->SetPxPyPzE(0.,0.,0.,-10000.);

            pBestNu->SetPxPyPzE(0.,0.,0.,-10000.);
            pBestAntiNu->SetPxPyPzE(0.,0.,0.,-10000.);
            pRekoNu1->SetPxPyPzE(0.,0.,0.,-10000.);
            pRekoAntiNu1->SetPxPyPzE(0.,0.,0.,-10000.);
            pRekoNu2->SetPxPyPzE(0.,0.,0.,-10000.);
            pRekoAntiNu2->SetPxPyPzE(0.,0.,0.,-10000.);

            int LeptonIndex[20];
            int BTagTrkCountIndex[50];
            int BTagSVsimpleIndex[50];
            int BTagSVcombIndex[50];
            int BJetsEIndex[50];
            int BJetDeltaRIndex[50];
            int BbarJetDeltaRIndex[50];
            TMath::Sort(20,PatLeptonsE,LeptonIndex);
            TMath::Sort(50,PatJetsBTag_TrkCount, BTagTrkCountIndex);
            TMath::Sort(50,PatJetsBTag_SVsimple, BTagSVsimpleIndex);
            TMath::Sort(50,PatJetsBTag_SVcomb, BTagSVcombIndex);
            TMath::Sort(50, PatJetsE, BJetsEIndex);
            TMath::Sort(50, PatJetsBQuarkDeltaR, BJetDeltaRIndex);
            TMath::Sort(50, PatJetsBbarQuarkDeltaR, BbarJetDeltaRIndex);


            // Leptonen auswaehlen
            int OtherLepton = -1;
            for(int j=0; PatLeptonsCharge[LeptonIndex[0]]==PatLeptonsCharge[LeptonIndex[j]] && j<20; j++){
                OtherLepton=j+1;
            }
//            if(PatLeptonsCharge[LeptonIndex[OtherLepton]]==0) std::cout<<"Only Leptons of same Charge in Event " << iEvent << "!!"<<std::endl;

            if(PatLeptonsCharge[LeptonIndex[OtherLepton]]!=0){
                // Leptonen zuordnen
                if(PatLeptonsCharge[LeptonIndex[0]]==-1){	
                    pRekoLeptonMinus->SetPxPyPzE(PatLeptonsPx[LeptonIndex[0]], PatLeptonsPy[LeptonIndex[0]], PatLeptonsPz[LeptonIndex[0]], PatLeptonsE[LeptonIndex[0]] );
                }

                if(PatLeptonsCharge[LeptonIndex[0]]==+1){	
                    pRekoLeptonPlus->SetPxPyPzE(PatLeptonsPx[LeptonIndex[0]], PatLeptonsPy[LeptonIndex[0]], PatLeptonsPz[LeptonIndex[0]], PatLeptonsE[LeptonIndex[0]] );
                }
            
                if(PatLeptonsCharge[LeptonIndex[OtherLepton]]==-1){	
                    pRekoLeptonMinus->SetPxPyPzE(PatLeptonsPx[LeptonIndex[OtherLepton]], PatLeptonsPy[LeptonIndex[OtherLepton]], PatLeptonsPz[LeptonIndex[OtherLepton]],PatLeptonsE[LeptonIndex[OtherLepton]] );
                }
           
                if(PatLeptonsCharge[LeptonIndex[OtherLepton]]==+1){	
                    pRekoLeptonPlus->SetPxPyPzE(PatLeptonsPx[LeptonIndex[OtherLepton]], PatLeptonsPy[LeptonIndex[OtherLepton]], PatLeptonsPz[LeptonIndex[OtherLepton]], PatLeptonsE[LeptonIndex[OtherLepton]] );
                }

                //cout << "Leptonen ausgewaehlt" << endl;

                Lepton_Mass = ((*pRekoLeptonPlus) + (*pRekoLeptonMinus)).M();

                if( TMath::Abs( Lepton_Mass - 90.0 ) > 10 || PatLeptonsPdgId[LeptonIndex[0]] + PatLeptonsPdgId[LeptonIndex[OtherLepton]] !=0 )
                {

                    double JetDisc[50];
                    numberOfGoodJets = 0;
                    for(int j=0; j<50; j++){
                        JetDisc[j] = 0.;
                        if(j<numberOfPatJets){
                            //JetDisc[j] = PatJetsBTag_TrkCount[j] * PatJetsEt[j];
                            if(PatJetsBTag_TrkCount[j]>1. && PatJetsEt[j]>20){
                                pJet[j]->SetPxPyPzE(PatJetsPx[j],PatJetsPy[j],  PatJetsPz[j], PatJetsE[j]);
                                if(TMath::Min(pJet[j]->Angle(pRekoLeptonPlus->Vect()), pJet[j]->Angle(pRekoLeptonMinus->Vect())) >0.1){
                                    numberOfGoodJets++;
                                    JetDisc[j] = PatJetsBTag_TrkCount[j] * PatJetsEt[j];
                                }
                            }
                            if(j<numberOfPatLeptons){
                                histogram__LeptonRelIso->Fill(PatLeptonsPt[j]/(PatLeptonsPt[j]+PatLeptonsTrkIso[j]+PatLeptonsCaloIso[j]));
                            }
                        }
                    }
                    int JetDiscIndex[50];
                    TMath::Sort(50, JetDisc, JetDiscIndex);
                        
                    // Jets auswaehlen
                    // verbesserte Auswahl (BTag*ET)
                    pBJet1->SetPxPyPzE(PatJetsPx[JetDiscIndex[0]],PatJetsPy[JetDiscIndex[0]],PatJetsPz[JetDiscIndex[0]],PatJetsE[JetDiscIndex[0]]);
                    pBJet2->SetPxPyPzE(PatJetsPx[JetDiscIndex[1]],PatJetsPy[JetDiscIndex[1]],PatJetsPz[JetDiscIndex[1]],PatJetsE[JetDiscIndex[1]]);

                    //pBJet1->SetPxPyPzE(PatJetsPx[BTagTrkCountIndex[0]],PatJetsPy[BTagTrkCountIndex[0]],PatJetsPz[BTagTrkCountIndex[0]],PatJetsE[BTagTrkCountIndex[0]]);
                    //pBJet2->SetPxPyPzE(PatJetsPx[BTagTrkCountIndex[1]],PatJetsPy[BTagTrkCountIndex[1]],PatJetsPz[BTagTrkCountIndex[1]],PatJetsE[BTagTrkCountIndex[1]]);
                    
                    
                    //cout << "Jets gewaehlt" << endl;
                    
                    
                    // Neutrinos berechnen 
                    
                    //Generator-Werte setzen fuer Vergleich mit Berechnung
                    pNu->SetPxPyPzE(pGenNu->Px(),pGenNu->Py(),pGenNu->Pz(),pGenNu->E());
                    pAntiNu->SetPxPyPzE(pGenAntiNu->Px(),pGenAntiNu->Py(),pGenAntiNu->Pz(),pGenAntiNu->E());
                    
                    
                    
                    Poly.Init(pRekoLeptonPlus, pRekoLeptonMinus, pBJet1, pBJet2, pNu, pAntiNu); // BJet1 = b, BJet2 = bbar
                    Poly.Solve(170.0,171.0 , iEvent, pRekoNu1, pRekoAntiNu1, pBestNu, pBestAntiNu);
                    
                    Poly.Init(pRekoLeptonPlus, pRekoLeptonMinus, pBJet2, pBJet1, pNu, pAntiNu); // BJet1 = bbar, BJet2 = b
                    Poly.Solve(170.0,171.0 , iEvent, pRekoNu2, pRekoAntiNu2, pBestNu2, pBestAntiNu2);
                    
                    //cout << "Neutrinos berechnet" << endl;
                    
                    
// Abfrage, ob Neutrinoloesung ungleich -10000 !!!
                    if(pRekoAntiNu1->Pz() != -10000 && pRekoAntiNu2->Pz() != -10000){
                        
                        if(TMath::Abs( ((*pRekoLeptonPlus)+(*pRekoNu1)+(*pBJet1)).M() + ((*pRekoLeptonMinus)+(*pRekoAntiNu1)+(*pBJet2)).M() - 2*173.2) < TMath::Abs(((*pRekoLeptonPlus)+(*pRekoNu2)+(*pBJet2)).M() + ((*pRekoLeptonMinus)+(*pRekoAntiNu2)+(*pBJet1)).M() - 2*173.2) ){
                            *pBJet = *pBJet1;
                            *pBbarJet = *pBJet2;
                            *pRekoNu = *pRekoNu1;
                            *pRekoAntiNu = *pRekoAntiNu1;
                        }
                        else {
                            *pBJet = *pBJet2;
                            *pBbarJet = *pBJet1;
                            *pRekoNu = *pRekoNu2;
                            *pRekoAntiNu = *pRekoAntiNu2;
                            *pBestNu = *pBestNu2;
                            *pBestAntiNu = *pBestAntiNu2;
                        }
                    }
                    else if(pRekoAntiNu1->Pz() != -10000){
                        *pBJet = *pBJet1;
                        *pBbarJet = *pBJet2;
                        *pRekoNu = *pRekoNu1;
                        *pRekoAntiNu = *pRekoAntiNu1;
                    }
                    else if(pRekoAntiNu2->Pz() != -10000){
                        *pBJet = *pBJet2;
                        *pBbarJet = *pBJet1;
                        *pRekoNu = *pRekoNu2;
                        *pRekoAntiNu = *pRekoAntiNu2;
                        *pBestNu = *pBestNu2;
                        *pBestAntiNu = *pBestAntiNu2;
                    }
                    else{
                        pRekoNu->SetPxPyPzE(0,0,-10000, 10000);
                        pRekoAntiNu->SetPxPyPzE(0,0,-10000, 10000);
                        pBestNu->SetPxPyPzE(0,0,-10000, 10000);
                        pBestAntiNu->SetPxPyPzE(0,0,-10000, 10000);
                        pBJet->SetPxPyPzE(0,0,-10000, 10000);
                        pBbarJet->SetPxPyPzE(0,0,-10000, 10000);
                    }
                    
                    
                    
                    TTbar_Pt = pTTbar->Pt();
                    TTbar_M = pTTbar->M();
                    
                    Top_Pt = pTop->Pt();
                    AntiTop_Pt = pAntiTop->Pt();
                    Top_M = pTop->M();
                    AntiTop_M = pAntiTop->M();
                    
                    Nu_Px = pNu->Px();
                    Nu_Py = pNu->Py();
                    Nu_Pz = pNu->Pz();
                    
                    AntiNu_Px = pAntiNu->Px();
                    AntiNu_Py = pAntiNu->Py();
                    AntiNu_Pz = pAntiNu->Pz();
                    
                    
                    
                    Lepton_Pt = TMath::Min(pRekoLeptonPlus->Pt(), pRekoLeptonMinus->Pt());
                    BJet_Et = TMath::Min(pBJet->Et(), pBbarJet->Et());
                    BJet_Tag_SVsimple = PatJetsBTag_SVsimple[BTagSVsimpleIndex[1]];
                    BJet_Tag_SVcomb = PatJetsBTag_SVcomb[BTagSVcombIndex[1]];
                    BJet_Tag_TrkCount = PatJetsBTag_TrkCount[BTagTrkCountIndex[1]];
                    BJet_Disc = JetDisc[JetDiscIndex[1]];
                    Lepton1_Id = PatLeptonsPdgId[LeptonIndex[0]];
                    Lepton2_Id = PatLeptonsPdgId[LeptonIndex[OtherLepton]];
                    
                    LeptonPlus_Angle = -10.;
                    LeptonMinus_Angle = -10.;
                    BJet_Angle = -10.;
                    BbarJet_Angle = -10.;
                    RekoNu_Angle = -10.;
                    RekoAntiNu_Angle = -10.;
                    BestNu_Angle = -10.;
                    BestAntiNu_Angle = -10.;
                    
                    //cout << "Werte gesetzt" << endl;
                    
                    if(pRekoAntiNu->Pz() > -10000){

                        histogram_nupx_gen_reco->Fill(pGenNu->Px(), pRekoNu->Px());
                        histogram_nubpx_gen_reco->Fill(pGenAntiNu->Px(), pRekoAntiNu->Px());
                        histogram_nupy_gen_reco->Fill(pGenNu->Py(), pRekoNu->Py());
                        histogram_nubpy_gen_reco->Fill(pGenAntiNu->Py(), pRekoAntiNu->Py());
                        histogram_nupz_gen_reco->Fill(pGenNu->Pz(), pRekoNu->Pz());
                        histogram_nubpz_gen_reco->Fill(pGenAntiNu->Pz(), pRekoAntiNu->Pz());
                        
                        if(pLeptonPlus->E() != 0 && pLeptonMinus->E() != 0 && pBQuark->E() != 0 ){
                            BJet_Angle = pBJet->DeltaR(*pBQuark);
                            BbarJet_Angle = pBbarJet->DeltaR(*pBbarQuark);
                            LeptonPlus_Angle = pRekoLeptonPlus->DeltaR(*pLeptonPlus);
                            LeptonMinus_Angle = pRekoLeptonMinus->DeltaR(*pLeptonMinus);
                            RekoNu_Angle = pRekoNu->DeltaR(*pNu);
                            RekoAntiNu_Angle = pRekoAntiNu->DeltaR(*pAntiNu);
                            BestNu_Angle = pBestNu->DeltaR(*pNu);
                            BestAntiNu_Angle = pBestAntiNu->DeltaR(*pAntiNu);
                        }

                        RekoNu_Px = pRekoNu->Px();
                        RekoNu_Py = pRekoNu->Py();
                        RekoNu_Pz = pRekoNu->Pz();
                        
                        RekoAntiNu_Px = pRekoAntiNu->Px();
                        RekoAntiNu_Py = pRekoAntiNu->Py();
                        RekoAntiNu_Pz = pRekoAntiNu->Pz();
                        
                        BestNu_Px = pBestNu->Px();
                        BestNu_Py = pBestNu->Py();
                        BestNu_Pz = pBestNu->Pz();
                        
                        BestAntiNu_Px = pBestAntiNu->Px();
                        BestAntiNu_Py = pBestAntiNu->Py();
                        BestAntiNu_Pz = pBestAntiNu->Pz(); 
                        
                        if(pRekoLeptonPlus->E()!=0 && pRekoLeptonMinus->E()!=0 && pBJet->E()!=0 && pBbarJet->E()!=0){ 
                            
                            EventIsGood = 1;
                            
                            *pRekoTop = (*pRekoLeptonPlus) + (*pBJet) + (*pRekoNu);
                            *pRekoAntiTop = (*pRekoLeptonMinus) + (*pBbarJet) + (*pRekoAntiNu);
                            *pRekoTTbar = (*pRekoTop) + (*pRekoAntiTop);
                            *pRekoTopBoosted = *pRekoTop;
                            *pRekoAntiTopBoosted = *pRekoAntiTop;
                            *pRekoLeptonPlusBoosted = *pRekoLeptonPlus;
                            *pRekoLeptonMinusBoosted = *pRekoLeptonMinus;
                            pRekoAntiTopBoosted->Boost(-pRekoTTbar->BoostVector());
                            pRekoTopBoosted->Boost(-pRekoTTbar->BoostVector());
                            pRekoLeptonPlusBoosted->Boost(-pRekoTop->BoostVector());
                            pRekoLeptonMinusBoosted->Boost(-pRekoAntiTop->BoostVector());
                            
                            RekoCosThetaPlus = cos(pRekoLeptonPlusBoosted->Angle(pRekoTopBoosted->Vect()));
                            RekoCosThetaMinus = cos(pRekoLeptonMinusBoosted->Angle(pRekoAntiTopBoosted->Vect()));
                            //cout << "Cos(Theta) Gen-Reko: " << CosThetaPlus - RekoCosThetaPlus << endl;
                            
                            CosThetaDiff = RekoCosThetaPlus - CosThetaPlus;

                            CosRekoLeptonAngleD = cos(pRekoLeptonPlusBoosted->Angle(pRekoLeptonMinusBoosted->Vect()));
                            
                            RekoTTbar_Pt = pRekoTTbar->Pt();
                            RekoTTbar_M = pRekoTTbar->M();
                            
                            RekoTop_Pt = pRekoTop->Pt();
                            RekoAntiTop_Pt = pRekoAntiTop->Pt();
                            
                            RekoTop_M = pRekoTop->M();
                            RekoAntiTop_M = pRekoAntiTop->M();
                            
                            
                            
                            histogram__A->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                            histogram__N->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);
                            
                            histogram__Correlation->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                            
                            histogram__CosThetaDiff->Fill( CosThetaPlus - RekoCosThetaPlus );
                            histogram__CosThetaDiff->Fill( CosThetaMinus - RekoCosThetaMinus );
                            histogram__CosTheta_GenReko->Fill(CosThetaPlus, RekoCosThetaPlus);
                            
                            histogram__CosThetaDiff_TTbarPt->Fill(pTTbar->Pt(), CosThetaPlus - RekoCosThetaPlus);

                            if(BJet_Tag_TrkCount > 1.0){
                                histogram__Correlation_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                histogram__A_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                histogram__N_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);
                            }


                            if(pRekoLeptonPlus->Pt()>15 && pRekoLeptonMinus->Pt()>15 && pBJet->Et()>50 && pBbarJet->Et()>50 && PatJetsBTag_TrkCount[BTagTrkCountIndex[1]]>1 ){
                                histogram__Correlation_L15_B50_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                histogram__A_L15_B50_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                histogram__N_L15_B50_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);

                            }
                            if(pRekoLeptonPlus->Pt()>20 && pRekoLeptonMinus->Pt()>20){
                                    
                                histogram__Correlation_L20->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                histogram__A_L20->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                histogram__N_L20->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);

                                if(pBJet->Et() > 30 && pBbarJet->Et() > 30 && PatJetsBTag_TrkCount[BTagTrkCountIndex[1]] > 1){
                                    histogram__Correlation_L20_B30_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                    histogram__A_L20_B30_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                    histogram__N_L20_B30_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);
                                }
                                    
                                if(pBJet->Et() > 40 && pBbarJet->Et() > 40){
                                    histogram__Correlation_L20_B40->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                    histogram__A_L20_B40->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                    histogram__N_L20_B40->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);
                                        
                                    if(PatJetsBTag_TrkCount[BTagTrkCountIndex[1]] > 1 ){
                                        histogram__Correlation_L20_B40_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus);
                                        histogram__A_L20_B40_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_A);
                                        histogram__N_L20_B40_T1->Fill(RekoCosThetaPlus, RekoCosThetaMinus, w_N);
                                    }
                                }
                            }
                        } // Leptonen und B != 0
                    } // Neutrino-Pz != -10000
                } // inv. Masse der Leptonen != Z-Masse+-10
            }// abfrage auf 2 Leptonen unterschiedlicher Ladung
            //cout << "Tree wird gefuellt: ";
  
            //cout << " und ist fertig" << endl;
            
        }
        outTree->Fill(); 
    } // EventLoop

    cout << "gezaehlte Ereignisse: " << EventCounter << endl;
    cout << "Rekonstruierte Ereignisse: " << histogram__Correlation->Integral() << endl;
    

    outputFile->cd("");
    outputFile->Write();
    outputFile->Close();
    delete outputFile;
}
void print_vec(TLorentzVector v){
    cout <<"("<< v.Px() << " , " << v.Py() << " , " << v.Pz() << " , " << v.E() << ")" <<endl;
}
Exemple #21
0
int PHSartre::process_event(PHCompositeNode *topNode) {

  if (verbosity > 1) cout << "PHSartre::process_event - event: " << _eventcount << endl;
  
  bool passedTrigger = false;
  Event *event = NULL;

  TLorentzVector *eIn     = NULL;
  TLorentzVector *pIn     = NULL;
  TLorentzVector *eOut    = NULL;
  TLorentzVector *gamma   = NULL;
  TLorentzVector *vm      = NULL;
  TLorentzVector *PomOut  = NULL;
  TLorentzVector *pOut    = NULL;
  TLorentzVector *vmDecay1 = NULL; 
  TLorentzVector *vmDecay2 = NULL; 
  unsigned int preVMDecaySize = 0; 

  while (!passedTrigger) {
    ++_gencount;

    // Generate a Sartre event
    event = _sartre->generateEvent();
        
    //
    //  If Sartre is run in UPC mode, half of the events needs to be
    //  rotated around and axis perpendicular to z:
    //  (only for symmetric events)
    //
    if(settings->UPC() and settings->A()==settings->UPCA()){
      randomlyReverseBeams(event);
    }
	
    // for sPHENIX/RHIC p+Au
    // (see comments in ReverseBeams)
    // reverse when the proton emits the virtual photon
	
    if(settings->UPC() and settings->A()==197){
      ReverseBeams(event);
    }

    // Set pointers to the parts of the event we will need:

    eIn     = &event->particles[0].p;
    pIn     = &event->particles[1].p;
    eOut    = &event->particles[2].p;
    gamma   = &event->particles[3].p;
    vm      = &event->particles[4].p;
    PomOut  = &event->particles[5].p;
    pOut    = &event->particles[6].p;

    // To allow the triggering to work properly, we need to decay the vector meson here

    preVMDecaySize = event->particles.size(); 

    if(doPerformDecay) {

      if( decay->SetDecay(*vm, 2, daughterMasses) ){
	double weight = decay->Generate(); // weight is always 1 here
	if ( (weight-1) > FLT_EPSILON) {
	  cout << "PHSartre: Warning decay weight != 1, weight = " << weight << endl;
	}
	TLorentzVector *vmDaughter1 = decay->GetDecay(0);
	TLorentzVector *vmDaughter2 = decay->GetDecay(1);

	event->particles[4].status = 2; // set VM status

	Particle vmDC1; 
	vmDC1.index = event->particles.size(); 
	vmDC1.pdgId =  daughterID; 
	vmDC1.status = 1; // final state
	vmDC1.p = *vmDaughter1; 
	vmDC1.parents.push_back(4);	
	event->particles.push_back(vmDC1); 
	vmDecay1 = &event->particles[event->particles.size()-1].p;

	Particle vmDC2; 
	vmDC2.index = event->particles.size(); 
	vmDC2.pdgId =  -daughterID; 
	vmDC2.status = 1; // final state
	vmDC2.p = *vmDaughter2; 
	vmDC2.parents.push_back(4);	
	event->particles.push_back(vmDC2); 
	vmDecay2 = &event->particles[event->particles.size()-1].p;

      }
      else {
	cout << "PHSartre: WARNING: Kinematics of Vector Meson does not allow decay!" << endl;
      }

    }

    // test trigger logic
    
    bool andScoreKeeper = true;
    if (verbosity > 2) {
      cout << "PHSartre::process_event - triggersize: " << _registeredTriggers.size() << endl;
    }

    for (unsigned int tr = 0; tr < _registeredTriggers.size(); tr++) { 
      bool trigResult = _registeredTriggers[tr]->Apply(event);

      if (verbosity > 2) {
	cout << "PHSartre::process_event trigger: "
	     << _registeredTriggers[tr]->GetName() << "  " << trigResult << endl;
      }

      if (_triggersOR && trigResult) {
	passedTrigger = true;
	break;
      } else if (_triggersAND) {
	andScoreKeeper &= trigResult;
      }
      
      if (verbosity > 2 && !passedTrigger) {
	cout << "PHSartre::process_event - failed trigger: "
	     << _registeredTriggers[tr]->GetName() <<  endl;
      }
    }

    if ((andScoreKeeper && _triggersAND) || (_registeredTriggers.size() == 0)) {
      passedTrigger = true;
    }

  }

  // fill HepMC object with event
  
  HepMC::GenEvent *genevent = new HepMC::GenEvent(HepMC::Units::GEV, HepMC::Units::MM);

  // add some information to the event
  genevent->set_event_number(_eventcount);

  // Set the PDF information
  HepMC::PdfInfo pdfinfo;
  pdfinfo.set_scalePDF(event->Q2);
  genevent->set_pdf_info(pdfinfo); 

  // We would also like to save:
  //
  // event->t;
  // event->x;
  // event->y;
  // event->s;
  // event->W;
  // event->xpom;
  // (event->polarization == transverse ? 0 : 1);
  // (event->diffractiveMode == coherent ? 0 : 1);
  // 
  // but there doesn't seem to be a good place to do so 
  // within the HepMC event information?
  //
  // t, W and Q^2 form a minial set of good variables for diffractive events
  // Maybe what I do is record the input particles to the event at the HepMC
  // vertices and reconstruct the kinematics from there? 
  
  // Create HepMC vertices and add final state particles to them

  // First, the emitter(electron)-virtual photon vertex:

  HepMC::GenVertex* egammavtx = new HepMC::GenVertex(CLHEP::HepLorentzVector(0.0,0.0,0.0,0.0));
  genevent->add_vertex(egammavtx); 

  egammavtx->add_particle_in( 
			 new HepMC::GenParticle( CLHEP::HepLorentzVector(eIn->Px(),
									 eIn->Py(),
									 eIn->Pz(),
									 eIn->E()), 
						 event->particles[0].pdgId, 
						 3 ) 
			  );

  HepMC::GenParticle *hgamma =  new HepMC::GenParticle( CLHEP::HepLorentzVector(gamma->Px(),
									 gamma->Py(),
									 gamma->Pz(),
									 gamma->E()), 
						event->particles[3].pdgId, 
						3 ); 

  egammavtx->add_particle_out(hgamma);

  egammavtx->add_particle_out( 
			 new HepMC::GenParticle( CLHEP::HepLorentzVector(eOut->Px(),
									 eOut->Py(),
									 eOut->Pz(),
									 eOut->E()), 
						 event->particles[2].pdgId, 
						 1 ) 
			  );

  // Next, the hadron-pomeron vertex:

  HepMC::GenVertex* ppomvtx = new HepMC::GenVertex(CLHEP::HepLorentzVector(0.0,0.0,0.0,0.0));
  genevent->add_vertex(ppomvtx); 


  ppomvtx->add_particle_in( 
			 new HepMC::GenParticle( CLHEP::HepLorentzVector(pIn->Px(),
									 pIn->Py(),
									 pIn->Pz(),
									 pIn->E()), 
						 event->particles[1].pdgId, 
						 3 ) 
			     );

  HepMC::GenParticle *hPomOut = new HepMC::GenParticle( CLHEP::HepLorentzVector(PomOut->Px(),
									 PomOut->Py(),
									 PomOut->Pz(),
									 PomOut->E()), 
						 event->particles[5].pdgId, 
						 3 ); 

  ppomvtx->add_particle_out(hPomOut); 

  // If this is a nuclear breakup, add in the nuclear fragments
  // Otherwise, add in the outgoing hadron
        
  //If the event is incoherent, and nuclear breakup is enabled, fill the remnants to the tree
  if(settings->enableNuclearBreakup() and event->diffractiveMode == incoherent){
    for(unsigned int iParticle=7; iParticle < preVMDecaySize; iParticle++){
      if(event->particles[iParticle].status == 1) {  // Final-state particle
	const Particle& particle = event->particles[iParticle];	  
	ppomvtx->add_particle_out( 
			       new HepMC::GenParticle( CLHEP::HepLorentzVector(particle.p.Px(),
								 particle.p.Py(),
								 particle.p.Pz(),
								 particle.p.E()), 
						particle.pdgId, 
						1 ) 
				);
      }  
    }  
  }
  else{

    ppomvtx->add_particle_out( 
			      new HepMC::GenParticle( CLHEP::HepLorentzVector(pOut->Px(),
									      pOut->Py(),
									      pOut->Pz(),
									      pOut->E()), 
						      event->particles[6].pdgId, 
						      1 ) 
			       );
  }

  // The Pomeron-Photon vertex

  HepMC::GenVertex* gammapomvtx = new HepMC::GenVertex(CLHEP::HepLorentzVector(0.0,0.0,0.0,0.0));
  genevent->add_vertex(gammapomvtx); 
  
  gammapomvtx->add_particle_in(hgamma); 
  gammapomvtx->add_particle_in(hPomOut); 

  int isVMFinal = 1; 
  if(doPerformDecay) isVMFinal = 2; 

  HepMC::GenParticle *hvm = new HepMC::GenParticle( CLHEP::HepLorentzVector(vm->Px(),
									    vm->Py(),
									    vm->Pz(),
									    vm->E()), 
						   event->particles[4].pdgId, 
						   isVMFinal ) ; 

  gammapomvtx->add_particle_out( hvm );
 
  // Add the VM decay to the event

  if(doPerformDecay) {

    if(vmDecay1 && vmDecay2){

      HepMC::GenVertex* fvtx = new HepMC::GenVertex(CLHEP::HepLorentzVector(0.0,0.0,0.0,0.0));
      genevent->add_vertex(fvtx); 

      fvtx->add_particle_in( hvm ); 

      fvtx->add_particle_out( 
			 new HepMC::GenParticle( CLHEP::HepLorentzVector(vmDecay1->Px(),
							   vmDecay1->Py(),
							   vmDecay1->Pz(),
							   vmDecay1->E()), 
					  daughterID, 
					  1 ) 
			  );
      fvtx->add_particle_out( 
			 new HepMC::GenParticle( CLHEP::HepLorentzVector(vmDecay2->Px(),
							   vmDecay2->Py(),
							   vmDecay2->Pz(),
							   vmDecay2->E()), 
					  -daughterID, 
					  1 ) 
			  );

    }
    else {
      cout << "PHSartre: WARNING: Kinematics of Vector Meson does not allow decay!" << endl;
    }

  }

  // pass HepMC to PHNode
  
  PHHepMCGenEvent * success = hepmc_helper . insert_event(genevent);
  if (!success) {
    cout << "PHSartre::process_event - Failed to add event to HepMC record!" << endl;
    return Fun4AllReturnCodes::ABORTRUN;
  }


  // print outs
  
  if (verbosity > 2) cout << "PHSartre::process_event - FINISHED WHOLE EVENT" << endl;

  ++_eventcount;
  return Fun4AllReturnCodes::EVENT_OK;
}
Exemple #22
0
//________________________________________________________________________________
void StarMCHits::Step() {
  //  static Int_t Idevt0 = -1;
  static Double_t Gold = 0;
#if 0
  if (Debug() && gMC->IsA()->InheritsFrom("TGeant3TGeo")) {
    TGeant3TGeo *geant3 = (TGeant3TGeo *)gMC;
    geant3->Gdebug();
  }
#endif
  //  cout << "Call StarMCHits::Step" << endl;
  TGeoNode *nodeT = gGeoManager->GetCurrentNode();
  assert(nodeT);
  TGeoVolume *volT = nodeT->GetVolume();
  assert(volT);
  const TGeoMedium   *med = volT->GetMedium(); 
  /*   fParams[0] = isvol;
       fParams[1] = ifield;
       fParams[2] = fieldm;
       fParams[3] = tmaxfd;
       fParams[4] = stemax;
       fParams[5] = deemax;
       fParams[6] = epsil;
       fParams[7] = stmin; */
  Int_t Isvol = (Int_t) med->GetParam(0);
  fCurrentDetector = 0;
  if (Isvol <= 0) return;
  fCurrentDetector = (StarVMCDetector *) fVolUserInfo->At(volT->GetNumber());
  if (! fCurrentDetector) {
    volT = nodeT->GetMotherVolume();
    fCurrentDetector = (StarVMCDetector *) fVolUserInfo->At(volT->GetNumber());
    if (! fCurrentDetector) {
      TString path(gGeoManager->GetPath());
      TObjArray *obj = path.Tokenize("_/");
      Int_t N = obj->GetEntries();
      for (Int_t i = N-2; i >= 0; i -= 2) {
	TObjString *o = (TObjString  *) obj->At(i);
	const Char_t *name = o->GetName();
	volT = gGeoManager->GetVolume(name);
	assert (volT);
	fCurrentDetector = (StarVMCDetector *) fVolUserInfo->At(volT->GetNumber());
	if (fCurrentDetector) break;
      }
      delete obj;
    }
  }
  if (Isvol && ! fCurrentDetector && Debug()) {
    cout << "Active medium:" << med->GetName() << "\t for volume " << volT->GetName() 
	 << " has no detector description" << endl;
  }
  //  Int_t Idevt =  gMC->CurrentEvent();
  gMC->TrackPosition(fHit.Current.Global.xyzT);
  gMC->TrackMomentum(fHit.Current.Global.pxyzE);
  TGeoHMatrix  *matrixC = gGeoManager->GetCurrentMatrix();
  fHit.Current.Global2Local(matrixC);
  if (gMC->IsTrackEntering()) {
    fHit.Detector= fCurrentDetector;
    fHit.Entry = fHit.Current;
    fHit.Sleng = gMC->TrackLength();
    fHit.Charge = (Int_t) gMC->TrackCharge();
    fHit.Mass = gMC->TrackMass();
    fHit.AdEstep = fHit.AStep = 0;
    return;
  }
  Double_t GeKin = fHit.Current.Global.pxyzE.E() - fHit.Mass;
  fHit.Sleng = gMC->TrackLength();
  if (fHit.Sleng == 0.) Gold = GeKin;
  Double_t dEstep = gMC->Edep();
  Double_t Step = gMC->TrackStep();
  fHit.iPart = gMC->TrackPid();
  fHit.iTrack = StarVMCApplication::Instance()->GetStack()->GetCurrentTrackId(); // GetCurrentTrackNumber() + 1 to be consistent with g2t
  // - - - - - - - - - - - - - energy correction - - - - - - - - - -
  if (gMC->IsTrackStop() && TMath::Abs(fHit.iPart) == kElectron) {
    TArrayI proc;
    Int_t Nproc = gMC->StepProcesses(proc);
    Int_t Mec = 0;
    for (Int_t i = 0; i < Nproc; i++) if (proc[i] == kPAnnihilation || proc[i] == kPStop) Mec = proc[i];
    Int_t Ngkine = gMC->NSecondaries();
    if (fHit.iPart == kElectron && Ngkine == 0 && Mec == kPStop) dEstep = Gold;
    else {
      if (fHit.iPart == kPositron && Ngkine < 2 && Mec == kPAnnihilation) {
	dEstep = Gold + 2*fHit.Mass;
	if (Ngkine == 1) {
	  TLorentzVector x;
	  TLorentzVector p;
	  Int_t IpartSec;
	  gMC->GetSecondary(0,IpartSec,x,p);
	  dEstep -= p.E();
	}
      }
    }
  }
  // - - - - - - - - - - - - - - - - user - - - - - - - - - - - - - - -
  // user step
  // - - - - - - - - - - - - - - - sensitive - - - - - - - - - - - - -
  fHit.AdEstep += dEstep;  
  fHit.AStep   += Step;
  if (fHit.AdEstep == 0) return;
  if (! gMC->IsTrackExiting() && ! gMC->IsTrackStop()) return;
  fHit.Exit     = fHit.Current;
  fHit.Middle   = fHit.Entry;
  fHit.Middle  += fHit.Exit;
  fHit.Middle  *= 0.5;
  if (! fCurrentDetector) return;
  fHit.VolumeId = fCurrentDetector->GetVolumeId(gGeoManager->GetPath());
  FillG2Table();
}
Exemple #23
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  
Exemple #24
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::E_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::E_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
  const double dMass = TDatabasePDG::Instance()->GetParticle(211)->Mass();
//=============================================================================

  TList *list = new TList();
  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);

  enum                    {  kJet,   kMje,   kDsz,   kIsm,   kZsm,   kDsr, kVar };
  const TString sHist[] = { "aJet", "aMje", "aDsz", "aIsm", "aZsm", "aDsr" };
  const Int_t      nv[] = {   1000,    150,  120,      150,    150,    500 };
  const Double_t dMin[] = {     0.,     0.,   0.,       0.,     0.,     0. };
  const Double_t dMax[] = {  1000.,   150.,  1.2,     150.,    1.5,     5. };

  THnSparseD *hs = new THnSparseD("hs", "", kVar, nv, dMin, dMax); hs->Sumw2();
  for (Int_t i=0; i<kVar; i++) hs->GetAxis(i)->SetName(sHist[i].Data()); list->Add(hs);
//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInput.resize(0);

    TLorentzVector vPar;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPar.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), dMass);

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInput.push_back(fastjet::PseudoJet(vPar.Px(), vPar.Py(), vPar.Pz(), vPar.E()));
      }
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        }
      }

      if ((d1sj>0.) && (d2sj>0.)) {
        TLorentzVector v1sj; v1sj.SetPtEtaPhiM(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi(), trimmdSj[k1sj].m());
        TLorentzVector v2sj; v2sj.SetPtEtaPhiM(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi(), trimmdSj[k2sj].m());
        TLorentzVector vIsj = v1sj + v2sj;

        Double_t dIsm = vIsj.M();
        Double_t dMje = selectJets[j].m();
        Double_t dVar[] = { dJet, dMje, (d1sj-d2sj)/dJet, dIsm, dIsm/dMje, v1sj.DeltaR(v2sj)/2./dJetR };

        hs->Fill(dVar);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TString sXsec = sFile; sXsec.ReplaceAll("out", "xsecs");
  TFile *file = TFile::Open(Form("%s/xsecs/%s.root",sPath.Data(),sXsec.Data()), "READ");
  TH1D *hPtHat        = (TH1D*)file->Get("hPtHat");        hPtHat->SetDirectory(0);
  TH1D *hWeightSum    = (TH1D*)file->Get("hWeightSum");    hWeightSum->SetDirectory(0);
  TProfile *hSigmaGen = (TProfile*)file->Get("hSigmaGen"); hSigmaGen->SetDirectory(0);
  file->Close();
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const int multiLHC = 3000;
  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

  fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
  fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
  fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
  fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
  fastjet::Selector selectBkg = selectRho * (!(selecHard));
  fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::kt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  TRandom3 *r3 = new TRandom3(0);
  TF1 *fBkg = BackgroundSpec();
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInputVac;
  std::vector<fastjet::PseudoJet> fjInputHyd;
//=============================================================================

  TList *list = new TList();
  TH1D *hWeightSum = new TH1D("hWeightSum", "", 1, 0., 1.); list->Add(hWeightSum);


//=============================================================================

  HepMC::IO_GenEvent ascii_in(Form("%s/%s.hepmc",sPath.Data(),sFile.Data()), std::ios::in);
  HepMC::GenEvent *evt = ascii_in.read_next_event();

  while (evt) {
    fjInputVac.resize(0);
    fjInputHyd.resize(0);

    double dXsect  = evt->cross_section()->cross_section() / 1e9;
    double dWeight = evt->weights().back();
    double dNorm = dWeight * dXsect;
    hWeightSum->Fill(0.5, dWeight);

    int iCount = 0;
    TLorentzVector vPseudo;
    for (HepMC::GenEvent::particle_const_iterator p=evt->particles_begin(); p!=evt->particles_end(); ++p) if ((*p)->status()==1) {
      vPseudo.SetPtEtaPhiM((*p)->momentum().perp(), (*p)->momentum().eta(), (*p)->momentum().phi(), 0.);

      if ((TMath::Abs(vPar.Eta())<dCutEtaMax)) {
        fjInputVac.push_back(fastjet::PseudoJet(vPseudo.Px(), vPseudo.Py(), vPseudo.Pz(), vPseudo.E()));
        fjInputVac.back().set_user_info(new UserInfoTrk(false));
        fjInputVac.back().set_user_index(iCount); iCount+=1;
      }
    }
//=============================================================================

    for (int i=0; i<=multiLHC; i++) {
      double dPt = fBkg->GetRandom(fgkPtBkgMin, fgkPtBkgMax); if (dPt<0.001) continue;

      vPseudo.SetPtEtaPhiM(dPt, r3->Uniform(-1.*dCutEtaMax,dCutEtaMax), r3->Uniform(0.,TMath::TwoPi()), 0.);
      fjInputHyd.push_back(fastjet::PseudoJet(vPseudo.Px(), vPseudo.Py(), vPseudo.Pz(), vPseudo.E()));
      fjInputHyd.back().set_user_info(new UserInfoTrk(true));
      fjInputHyd.back().set_user_index(-10);
    }

    fjInputHyd.insert(fjInputHyd.end(), fjInputVac.begin(),fjInputVac.end());
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInputVac, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJetsPy = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJetsPy = bkgSubtractor(includJetsPy);
    std::vector<fastjet::PseudoJet> selectJetsPy = selectJet(includJetsPy);
//  std::vector<fastjet::PseudoJet> sortedJetsPy = fastjet::sorted_by_pt(selectJetsPy);

    for (int j=0; j<selectJetsPy.size(); j++) {
      SetJetUserInfo(selectJetsPy[j]);
      selectJetsPy[j].set_user_index(j);
    }
//=============================================================================

    bkgsEstimator.set_particles(fjInputHyd);
    double dBkgRhoHd = bkgsEstimator.rho();
    double dBkgRmsHd = bkgsEstimator.sigma();

    fastjet::ClusterSequenceArea clustSeqHd(fjInputHyd, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJetsHd = clustSeqHd.inclusive_jets(dJetsPtMin);
    std::vector<fastjet::PseudoJet> selectJetsHd = selectJet(includJetsHd);

    for (int j=0; j<selectJetsHd.size(); j++) {
      SetJetUserInfo(selectJetsHd[j]);
      selectJetsHd[j].set_user_index(j);
      if (selectJetsHd[j].user_info<UserInfoJet>().IsBkg()) continue;

      for (int i=0; i<selectJetsPy.size(); i++) {
        if (CalcDeltaR(selectJetsHd[j],selectJetsPy[i])>0.8) continue;
        DoTrkMatch(selectJetsHd[j], selectJetsPy[i]);
      }
    }
//=============================================================================

  








    for (int j=0; j<sortedJets.size(); j++) {
      double dJet = sortedJets[j].pt();

      hJet->Fill(dJet, dNorm);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(sortedJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double nIsj = 0.;
      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        hJetIsj->Fill(dJet, dIsj, dNorm);
        hJetIsz->Fill(dJet, dIsj/dJet, dNorm);

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        } nIsj += 1.;
      }

      hJetNsj->Fill(dJet, nIsj, dNorm);
      if (d1sj>0.) { hJet1sj->Fill(dJet, d1sj, dNorm); hJet1sz->Fill(dJet, d1sj/dJet, dNorm); }
      if (d2sj>0.) { hJet2sj->Fill(dJet, d2sj, dNorm); hJet2sz->Fill(dJet, d2sj/dJet, dNorm); }

      if ((d1sj>0.) && (d2sj>0.)) {
        TVector3 v1sj; v1sj.SetPtEtaPhi(d1sj, trimmdSj[k1sj].eta(), trimmdSj[k1sj].phi());
        TVector3 v2sj; v2sj.SetPtEtaPhi(d2sj, trimmdSj[k2sj].eta(), trimmdSj[k2sj].phi());

        double dsj = d1sj - d2sj;
        double dsz = dsj / dJet;
        double dsr = v1sj.DeltaR(v2sj) / 2. / dJetR;

        hJetDsj->Fill(dJet, dsj, dNorm);
        hJetDsz->Fill(dJet, dsz, dNorm);
        hJetDsr->Fill(dJet, dsz, dsr, dNorm);
      }
    }
//=============================================================================

    delete evt;
    ascii_in >> evt;
  }
//=============================================================================

  TFile *file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
  return 0;
}
void print_se(TLorentzVector e_vec, TLorentzVector p_vec){
    double_t se = 2.0 * e_vec.E() * (abs(p_vec.Px()) + p_vec.E()) + deut_mass*deut_mass;
    cout << "se: " << se <<endl;
}
Exemple #27
0
void recursive_inter_with_air(){
	TFile *f1 = new TFile("muon.root", "recreate");
	TCanvas *c1 = new TCanvas("test", "test", 600, 700);

	TH1F * mu_c_1 = new TH1F("mu_c_1", "mu_c_1", 100, 0, 500);
	TH1F * mu_c_2 = new TH1F("mu_c_2", "mu_c_2", 100, 0, 500);
	TH1F * mu_c_3 = new TH1F("mu_c_3", "mu_c_3", 100, 0, 500);

	fn_muon_dxde = new TF1("f1", dxde_muon, M_mu, 1000, 1);
	TNtuple * ntuple = new TNtuple("ntuple", "ntuple", "nobs:detz:theta:press");
	// TNtuple *ntuple = new TNtuple("ntuple", "ntuple", "id:flag:e:px:py:pz:x:y:z");
	r = new TRandom();
	// r ->SetSeed(12232);
	for (int ievertex_nt = 0; ievertex_nt < 500; ievertex_nt++)
	{
		n_particle = 0;

		// init muon conunter
		int mu_counter1 = 0;
		int mu_counter2 = 0;
		int mu_counter3 = 0;

		double E = 1000; // GeV
		double theta = 0;
		// double theta = acos(r->Rndm());
		double phi = r->Rndm()*pi*2;
		double x = 0, y = 0, z = 1.0e10; //infinity
		double vertex_z, vertex_x, vertex_y; //km

		

		Get_Int_Posi(pdg_proton_p, theta, phi, x, y, z, vertex_x, vertex_y, vertex_z);

		Hillas_Split(pdg_proton_p, E, theta, phi, vertex_x, vertex_y, vertex_z);

		double proton_threshold = 10;
		double pion_threshold = 10;
		int i_particle = 0;
		while(i_particle < n_particle){
			int id = Ptcl_bank[i_particle].id;
			int flag = Ptcl_bank[i_particle].flag;
			double e = Ptcl_bank[i_particle].e;
			double x = Ptcl_bank[i_particle].vertex_x;
			double y = Ptcl_bank[i_particle].vertex_y;
			double z = Ptcl_bank[i_particle].vertex_z;
			if (id == pdg_proton_p && flag == 1 && e > proton_threshold)
			{
				Get_Int_Posi(id, theta, phi, x, y, z, vertex_x, vertex_y, vertex_z);
				if (vertex_z > 0)
				{
					Hillas_Split(id, e, theta, phi, vertex_x, vertex_y, vertex_z);
					Ptcl_bank[i_particle].flag = 0;
				}
			}
			if (id == pdg_pion_p &&flag == 1){

				Get_Int_Posi(id, theta, phi, x, y, z, vertex_x, vertex_y, vertex_z)	;			
				double l_to_interaction = sqrt((vertex_x-x)*(vertex_x-x)+(vertex_y-y)*(vertex_y-y)+(vertex_z-z)*(vertex_z-z));
				double l_to_decay = get_decay_length(pdg_pion_p, tau_pion, e);
				
				if (l_to_decay>l_to_interaction){
					if (vertex_z > 0){
						Hillas_Split(id, e, theta, phi, vertex_x, vertex_y, vertex_z);
						Ptcl_bank[i_particle].flag = 0;
					}
				}else{ // pion decay
					Ptcl_bank[i_particle].flag = 0;
					double px = Ptcl_bank[i_particle].px;
					double py = Ptcl_bank[i_particle].py;
					double pz = Ptcl_bank[i_particle].pz; // GeV
					TLorentzVector pion(px, py, pz, e);
					double decay_particle_mass[2] = {M_mu, M_neu};
					TGenPhaseSpace event;
					event.SetDecay(pion, 2, decay_particle_mass);
					event.Generate();
					TLorentzVector Muon = *(event.GetDecay(0));
					TLorentzVector Neu = *(event.GetDecay(1));

					double mu_theta = Muon.Theta();
					double mu_phi = Muon.Phi();
					
					if (mu_theta>pi/2.)	{
						double mu_E = Muon.E();
						double muon_decay_time = r ->Exp(tau_muon);
						double muon_decay_length = get_decay_length(pdg_muon_n, tau_muon, mu_E);

						float det_x = 0;
						float det_y = 0;
						float det_z = 0;
						mu_counter1++;
						double l_mu_vtx_to_det = sqrt(pow(vertex_x-det_x,2)+pow(vertex_y-det_y,2)+pow(vertex_z-det_z,2));
						// cout << "MuE" << mu_E << " Mass" <<M_mu<< " dl" << muon_decay_length << " lvd" << l_mu_vtx_to_det << endl;
						if (muon_decay_length > l_mu_vtx_to_det)	
						{
							mu_counter2++;

							double mu_stop_x;
							double mu_stop_y;
							double mu_stop_z;

							get_muon_stop_position(mu_E, mu_theta, mu_phi, vertex_x, vertex_y, vertex_z, mu_stop_x, mu_stop_y, mu_stop_z);
							double l_muon_stop = sqrt(pow(vertex_x-mu_stop_x,2)+pow(vertex_y-mu_stop_y,2)+pow(vertex_z-mu_stop_z,2));
							// cout << l_muon_stop << " " << l_mu_vtx_to_det <<endl;
							if (l_muon_stop > l_mu_vtx_to_det)
							{
								mu_counter3++;
							}
							
							
						}
					}
				}
			}
			i_particle++;
		}
		mu_c_1 ->Fill(mu_counter1);
		mu_c_2 ->Fill(mu_counter2);
		mu_c_3 ->Fill(mu_counter3);

		// for (int i_particle = 0; i_particle < n_particle; ++i_particle){
		// 	int id = Ptcl_bank[i_particle].id;
		// 	int flag = Ptcl_bank[i_particle].flag;
		// 	double e = Ptcl_bank[i_particle].e;
		// 	double px = Ptcl_bank[i_particle].px;
		// 	double py = Ptcl_bank[i_particle].py;
		// 	double pz = Ptcl_bank[i_particle].pz;
		// 	double x = Ptcl_bank[i_particle].vertex_x;
		// 	double y = Ptcl_bank[i_particle].vertex_y;
		// 	double z = Ptcl_bank[i_particle].vertex_z;
		// 	ntuple->Fill(id, flag, e, px, py, pz, x, y, z);
		// }
	}

	mu_c_3 ->Draw();
	mu_c_2 ->SetLineColor(2);
	mu_c_2 ->Draw("same");
	mu_c_1 ->SetLineColor(4);
	mu_c_1 ->Draw("same");
	// ntuple->Draw("z");
} 
void pgsAnalysis::Loop()
{

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

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

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


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

	vector<TVector3> leptons;

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


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

	if (fChain == 0) return;
	

	int nentries = n;

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


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

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

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

		
		}//end instance loop (particles in an event

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

		fillFlag = false;

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


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

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

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


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


			

		fillFlag = true;
		}



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

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

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

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

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

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

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

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


			}
			eeee++;
		fillFlag = true;
		} 


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

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

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

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

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


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

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

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


			}
		xxxx++;
		fillFlag = true;
		}


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

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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

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

	   	//Filling up histogram for the phi angle distribution

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

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

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



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


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

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

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

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

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

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

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

		
		
	// filling the TTree


	}//end entries loop (events)

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

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




}//end loop void
Exemple #29
0
int xAna::HggTreeWriteLoop(const char* filename, int ijob, 
					  bool correctVertex, bool correctEnergy, 
					  bool setRho0
					  ) {

  //bool invDRtoTrk = false;


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

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

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


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

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

//  mode_ = ijob; //  

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

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

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

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

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


  


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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // 2x. radion analysis

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

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

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

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

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

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

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

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

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

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

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

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

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

      }
    }

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

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

  return nEvts[nEvts.size()-1];
}
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;
}