void MomScaleCorrection (
  rochcor2012* rmcor, TLorentzVector& muMinus, TLorentzVector& muPlus,
  double rpx1, double rpy1, double rpz1, int charge1, 
  double rpx2, double rpy2, double rpz2, int charge2,
  float qter, int runOpt = 0, bool isData = true) {

  double mu_mass = 0.105658;
  double rp1 = rpx1*rpx1 + rpy1*rpy1 + rpz1*rpz1;
  double rp2 = rpx2*rpx2 + rpy2*rpy2 + rpz2*rpz2;
  double re1 = sqrt(mu_mass*mu_mass + rp1);
  double re2 = sqrt(mu_mass*mu_mass + rp2);

  if( charge1 > 0 ) {
    muPlus.SetPxPyPzE(rpx1, rpy1, rpz1, re1);
    muMinus.SetPxPyPzE(rpx2, rpy2, rpz2, re2);
  }
  else {
    muPlus.SetPxPyPzE(rpx2, rpy2, rpz2, re2);
    muMinus.SetPxPyPzE(rpx1, rpy1, rpz1, re1);
  }

  if( isData ) {
    rmcor->momcor_data(muPlus, 1, runOpt,qter);
    rmcor->momcor_data(muMinus, -1, runOpt,qter);
  }
  else {
    rmcor->momcor_mc(muPlus, 1, runOpt,qter);
    rmcor->momcor_mc(muMinus, -1, runOpt,qter);
  }
  //cout << "Muon = " << muPlus.Pt() << " " << muMinus.Pt() << endl;
}
Beispiel #2
0
 TLorentzVector GenLeptonPair::get4v(){
   TLorentzVector v;
   if(this->type == "ee") v.SetPxPyPzE((this->l1->px+this->l2->px),(this->l1->py+this->l2->py),(this->l1->pz+this->l2->pz),(sqrt(pow(this->l1->px,2)+pow(this->l1->py,2)+pow(this->l1->pz,2)+pow(MASS_EL,2))+sqrt(pow(this->l2->px,2)+pow(this->l2->py,2)+pow(this->l2->pz,2)+pow(MASS_EL,2))));
   if(this->type == "em") v.SetPxPyPzE((this->l1->px+this->l2->px),(this->l1->py+this->l2->py),(this->l1->pz+this->l2->pz),(sqrt(pow(this->l1->px,2)+pow(this->l1->py,2)+pow(this->l1->pz,2)+pow(MASS_EL,2))+sqrt(pow(this->l2->px,2)+pow(this->l2->py,2)+pow(this->l2->pz,2)+pow(MASS_MU,2))));
   if(this->type == "me") v.SetPxPyPzE((this->l1->px+this->l2->px),(this->l1->py+this->l2->py),(this->l1->pz+this->l2->pz),(sqrt(pow(this->l1->px,2)+pow(this->l1->py,2)+pow(this->l1->pz,2)+pow(MASS_EL,2))+sqrt(pow(this->l1->px,2)+pow(this->l1->py,2)+pow(this->l1->pz,2)+pow(MASS_EL,2))));
   if(this->type == "mm") v.SetPxPyPzE((this->l1->px+this->l2->px),(this->l1->py+this->l2->py),(this->l1->pz+this->l2->pz),(sqrt(pow(this->l1->px,2)+pow(this->l1->py,2)+pow(this->l1->pz,2)+pow(MASS_EL,2))+sqrt(pow(this->l2->px,2)+pow(this->l2->py,2)+pow(this->l2->pz,2)+pow(MASS_MU,2))));
   return v;
 }
Beispiel #3
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);

}
double  METMHTAsys(MissingET* met,vector<Jet> jetvec,vector<Muon> muonvec,vector<Electron> electronvec,vector<Photon> photonvec){
  double Met=-99;
  double METAsys=-99;
  TVector2 PUCorMet, RawMet;
   TLorentzVector allvecsum;
  allvecsum.SetPxPyPzE(0, 0, 0, 0);
  PUCorMet.Set(0., 0.);
  RawMet.Set(0.0, 0.0);
  
  for(int i=0; i<(int)jetvec.size(); i++) {allvecsum += jetvec.at(i).P4();}
  for(int j=0; j<(int)muonvec.size(); j++) {allvecsum += muonvec.at(j).P4();}
  for(int k=0; k<(int)electronvec.size(); k++) {allvecsum += electronvec.at(k).P4();}
  for(int l=0; l<(int)photonvec.size(); l++) {allvecsum += photonvec.at(l).P4();}

  PUCorMet.Set(-allvecsum.Px(),-allvecsum.Py());
  Met= PUCorMet.Mod();
  RawMet.SetMagPhi(met->MET, met->Phi);
  
  METAsys=fabs(Met-(RawMet.Mod()))/(Met+(RawMet.Mod()));//this is funny. RawMet.Mod() must return met->MET. We didn't need to build RawMet to obtain its magnitude :):0
  //cout << "......................RawMet.Mod(): " << RawMet.Mod() << endl;
  //cout << "...................... Met: " << Met << endl; 
  //cout << "...................... METAsys: " << METAsys << endl;
  return METAsys;

}
Beispiel #5
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);
  
}
Beispiel #6
0
double t1pfmetPhiCorr(double t1pfmet, double t1pfmetPhi, double t1pfmetSumEt, bool isData){
Double_t t1pfmetCorrX;
Double_t t1pfmetCorrY;
Double_t t1pfmetCorrE;
 if(isData){
   //t1pfmetCorrX = t1pfmet*cos(t1pfmetPhi) - (-3.56  -0.0228096*t1pfmetSumEt);                                                    
   //t1pfmetCorrY = t1pfmet*sin(t1pfmetPhi) - (3.23  -0.0191691*t1pfmetSumEt);                                                     
   t1pfmetCorrX = t1pfmet*cos(t1pfmetPhi) - (-3.54059 + -0.0243867*t1pfmetSumEt);
   t1pfmetCorrY = t1pfmet*sin(t1pfmetPhi) - (3.25566 + -0.0195691*t1pfmetSumEt);
 }else{
   //t1pfmetCorrX = t1pfmet*cos(t1pfmetPhi) - (-1.34 - 0.0073*t1pfmetSumEt);                                                       
   //t1pfmetCorrY = t1pfmet*sin(t1pfmetPhi) - (0.263249  -0.0045*t1pfmetSumEt);                                                    
   t1pfmetCorrX = t1pfmet*cos(t1pfmetPhi) - (-1.33018 + -0.00738871*t1pfmetSumEt);
   t1pfmetCorrY = t1pfmet*sin(t1pfmetPhi) - (0.275181 + -0.00550282*t1pfmetSumEt);
 }


//std::cout << "px = t1pfmet*cos(t1pfmetPhi) - (" << fMETCorr[0] << " + " << fMETCorr[1] << "*t1pfmetSumEt)" << std::endl;
//std::cout << "py = t1pfmet*sin(t1pfmetPhi) - (" << fMETCorr[2] << " + " << fMETCorr[3] << "*t1pfmetSumEt)" << std::endl;
t1pfmetCorrE = sqrt(t1pfmetCorrX*t1pfmetCorrX + t1pfmetCorrY*t1pfmetCorrY);
TLorentzVector correctedMet;
correctedMet.SetPxPyPzE(t1pfmetCorrX,t1pfmetCorrY,0,t1pfmetCorrE);
Double_t t1pfmetPhiCorrected = correctedMet.Phi(); 
Double_t t1pfmetCorrected = correctedMet.Pt();

return t1pfmetPhiCorrected;
}
void printJet(Jet *jet)
{

  GenParticle *particle;
  Muon *muon;

  Track *track;
  Tower *tower;

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

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

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


      for (Int_t j =0; j<jet->Particles.GetEntries();  j++){
     		GenParticle *p_tmp = (GenParticle*) particlearray.At(j);
		printGenParticle(p_tmp);
	}
}
Beispiel #8
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);
  
}
hades_track gen_track(float b_x, float b_y, float b_z, float v_px, float v_py, float v_pz, float v_e)
{
	TVector3 base(b_x, b_y, b_z);
	TLorentzVector vec;
	vec.SetPxPyPzE(v_px, v_py, v_pz, v_e);

	hades_track ht(base, vec);

	return ht;
}
Beispiel #10
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);
  
}
Beispiel #11
0
TLorentzVector buildP (const LHEF::HEPEUP & event, int iPart)
{
  TLorentzVector dummy ;
  dummy.SetPxPyPzE (
      event.PUP.at (iPart).at (0), // px
      event.PUP.at (iPart).at (1), // py
      event.PUP.at (iPart).at (2), // pz
      event.PUP.at (iPart).at (3) // E
    ) ;
  return dummy ;  
}
void getKinematics(TLorentzVector& b, double const mass)
{
   float const pt = gRandom->Uniform(momentumRange.first, momentumRange.second);
   float const y = gRandom->Uniform(-acceptanceRapidity, acceptanceRapidity);
   float const phi = TMath::TwoPi() * gRandom->Rndm();

   float const mT = sqrt(mass * mass + pt * pt);
   float const pz = mT * sinh(y);
   float const E = mT * cosh(y);

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

  Int_t particle;
  Double_t signPz, cosTheta;

  TLorentzVector momentum;

  TRootLHEFParticle *element;

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

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

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

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

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

    element->LifeTime = hepeup.VTIMUP[particle];
    element->Spin = hepeup.SPINUP[particle];
  }
}
Beispiel #17
0
inline float kinematics::cosThetaBoost( TLorentzVector* pa, float ca,
										TLorentzVector* pb, float cb )
{
	// http://xrootd.slac.stanford.edu/BFROOT/www/doc/workbook_backup_010108/analysis/analysis.html
	// A useful quantity in many analyses is the helicity angle.
	// In the reaction Y -> X -> a + b, the helicity angle of 
	// particle a is the angle measured in the rest frame of the
	//decaying parent particle, X, between the direction of the
	// decay daughter a and the direction of the grandparent particle Y.

	TLorentzVector pTmp = (*pa)+(*pb); // this is the mumu system (Z) 4vector
	TVector3 ZboostVector = pTmp.BoostVector(); // this is the 3vector of the Z
	TLorentzVector p; // this is the muon 4vector
	
	if(ca<0)      p.SetPxPyPzE(pa->Px(),pa->Py(),pa->Pz(),pa->E());
	else if(cb<0) p.SetPxPyPzE(pb->Px(),pb->Py(),pb->Pz(),pb->E());
	p.Boost( -ZboostVector ); // boost p to the dimuon CM (rest) frame
	float cosThetaB = p.Vect()*pTmp.Vect()/(p.P()*pTmp.P());
	//if (ySystem(pa,pb) < 0) cosThetaB *= -1.; // reclassify ???
	return cosThetaB;
}
void fillHistos (ifstream & ifs) 
{
  LHEF::Reader reader (ifs) ;
  TH1F h_deta ("h_deta", "h_deta", 100, 0, 10) ;
  TH1F h_jeta ("h_jeta", "h_jeta", 100, -5, 5) ;
  TH1F h_j1eta ("h_j1eta", "h_j1eta", 100, -5, 5) ;
  TH1F h_j2eta ("h_j2eta", "h_j2eta", 100, -5, 5) ;
  TH1F h_j1pt ("h_j1pt", "h_j1pt", 100, 0, 200) ;
  TH1F h_j2pt ("h_j2pt", "h_j2pt", 100, 0, 200) ;


   //PG histograms
//method 1 hist
// tag Jets
   TH1F h_vbf_jj_pt ("h_vbf_jj_pt", "h_vbf_jj_pt", 100, 0, 500) ;
   TH1F h_vbf_jj_eta ("h_vbf_jj_eta", "h_vbf_jj_eta", 100, -5, 5) ;
   TH1F h_vbf_jj_e ("h_vbf_jj_e", "h_vbf_jj_e", 100, 0, 500) ;
   TH1F h_vbf_jj_phi ("h_vbf_jj_phi", "h_vbf_jj_phi", 100, -3, 3) ;
   TH1F h_vbf_jj_m ("h_vbf_jj_m", "h_vbf_jj_m", 100, 0, 2000) ;


   TH1F h_vbf_aj_pt ("h_vbf_aj_pt", "h_vbf_aj_pt", 100, 0, 500) ;
   TH1F h_vbf_aj_eta ("h_vbf_aj_eta", "h_vbf_aj_eta", 100, -5, 5) ;
   TH1F h_vbf_aj_e ("h_vbf_aj_e", "h_vbf_aj_e", 100, 0, 500) ;
   TH1F h_vbf_aj_phi ("h_vbf_aj_phi", "h_vbf_aj_phi", 100, -3, 3) ;

   TH1F h_vbf_bj_pt ("h_vbf_bj_pt", "h_vbf_bj_pt", 100, 0, 500) ;
   TH1F h_vbf_bj_eta ("h_vbf_bj_eta", "h_vbf_bj_eta", 100, -5, 5) ;
   TH1F h_vbf_bj_e ("h_vbf_bj_e", "h_vbf_bj_e", 100, 0, 500) ;
   TH1F h_vbf_bj_phi ("h_vbf_bj_phi", "h_vbf_bj_phi", 100, -3, 3) ;

   TH1F h_vbf_jj_deta ("h_vbf_jj_deta", "h_vbf_jj_deta", 100, -5, 5) ;
   TH1F h_vbf_jj_dphi ("h_vbf_jj_dphi", "h_vbf_jj_dphi", 100, -3, 3) ;
// W JETS
   TH1F h_vbf_wjj_pt ("h_vbf_wjj_pt", "h_vbf_wjj_pt", 100, 0, 500) ;
   TH1F h_vbf_wjj_eta ("h_vbf_wjj_eta", "h_vbf_wjj_eta", 100, -5, 5) ;
   TH1F h_vbf_wjj_e ("h_vbf_wjj_e", "h_vbf_wjj_e", 100, 0, 500) ;
   TH1F h_vbf_wjj_phi ("h_vbf_wjj_phi", "h_vbf_wjj_phi", 100, -3, 3) ;
   TH1F h_vbf_wjj_m ("h_vbf_wjj_m", "h_vbf_wjj_m", 100, 0, 500) ;

   TH1F h_vbf_waj_pt ("h_vbf_waj_pt", "h_vbf_waj_pt", 100, 0, 500) ;
   TH1F h_vbf_waj_eta ("h_vbf_waj_eta", "h_vbf_waj_eta", 100, -5, 5) ;
   TH1F h_vbf_waj_e ("h_vbf_waj_e", "h_vbf_waj_e", 100, 0, 500) ;
   TH1F h_vbf_waj_phi ("h_vbf_waj_phi", "h_vbf_waj_phi", 100, -3, 3) ;

   TH1F h_vbf_wbj_pt ("h_vbf_wbj_pt", "h_vbf_wbj_pt", 100, 0, 500) ;
   TH1F h_vbf_wbj_eta ("h_vbf_wbj_eta", "h_vbf_wbj_eta", 100, -5, 5) ;
   TH1F h_vbf_wbj_e ("h_vbf_wbj_e", "h_vbf_wbj_e", 100, 0, 500) ;
   TH1F h_vbf_wbj_phi ("h_vbf_wbj_phi", "h_vbf_wbj_phi", 100, -3, 3) ;
   
   TH1F h_vbf_lvjj_pt ("h_vbf_lvjj_pt", "h_vbf_lvjj_pt", 100, 0, 500) ;
   TH1F h_vbf_lvjj_eta ("h_vbf_lvjj_eta", "h_vbf_lvjj_eta", 100, -5, 5) ;
   TH1F h_vbf_lvjj_e ("h_vbf_lvjj_e", "h_vbf_lvjj_e", 100, 0, 500) ;
   TH1F h_vbf_lvj_m ("h_vbf_lvj_m", "h_vbf_lvj_m", 100, 0, 500) ;

   TH1F h_vbf_lvjj_phi ("h_vbf_lvjj_phi", "h_vbf_lvjj_phi", 100, -3, 3) ;
   TH1F h_vbf_lvjj_m ("h_vbf_lvjj_m", "h_vbf_lvjj_m", 100, 0, 1000) ;

   TH1F h_vbf_wjj_deta ("h_vbf_wjj_deta", "h_vbf_wjj_deta", 100, -5, 5) ;
   TH1F h_vbf_wjj_dphi ("h_vbf_wjj_dphi", "h_vbf_wjj_dphi", 100, -3, 3) ;

   TH1F h_vbf_l_pt ("h_vbf_l_pt", "h_vbf_l_pt", 100, 0, 500) ;
   TH1F h_vbf_l_eta ("h_vbf_l_eta", "h_vbf_l_eta", 100, -5, 5) ;
   TH1F h_vbf_l_e ("h_vbf_l_e", "h_vbf_l_e", 100, 0, 500) ;
   TH1F h_vbf_l_phi ("h_vbf_l_phi", "h_vbf_l_phi", 100, -3, 3) ;
   TH1F h_vbf_nu_e ("h_vbf_nu_e", "h_vbf_nu_e", 100, 0, 500) ;

   TH1F h_vbf_l_MET_deltaphi ("h_vbf_l_MET_deltaphi", "h_vbf_l_MET_deltaphi", 100, -3, 3) ;
   TH1F h_vbf_lW_hW_deltaphi ("h_vbf_lW_hW_deltaphi", "h_vbf_lW_hW_deltaphi", 100, -3, 3) ;

   TH1F h_vbf_l_tj1_dR ("vbf_l_tj1_dR", "vbf_l_tj1_dR", 100, 0, 6) ;
   TH1F h_vbf_l_tj2_dR ("vbf_l_tj2_dR", "vbf_l_tj2_dR", 100, 0, 6) ;

   TH1F h_vbf_l_wj1_dR ("vbf_l_wj1_dR", "vbf_l_wj1_dR", 100, 0, 6) ;
   TH1F h_vbf_l_wj2_dR ("vbf_l_wj2_dR", "vbf_l_wj2_dR", 100, 0, 6) ;

   TH1F h_vbf_l_wjj_dR ("vbf_l_wjj_dR", "vbf_l_wjj_dR", 100, 0, 6) ;
   TH1F h_vbf_l_tjj_dR ("vbf_l_tjj_dR", "vbf_l_tjj_dR", 100, 0, 6) ;




	
/*	tmva_t->Branch("vbf_event",&vbf_event, "vbf_event/I");
	tmva_t->Branch("vbf_aj_id",&vbf_aj_id, "vbf_aj_id/I");
	tmva_t->Branch("vbf_bj_id",&vbf_bj_id, "vbf_bj_id/I");
	tmva_t->Branch("vbf_waj_id",&vbf_waj_id, "vbf_waj_id/I");
	tmva_t->Branch("vbf_wbj_id",&vbf_wbj_id, "vbf_wbj_id/I");		
*/


  long ieve = 0 ;
  while ( reader.readEvent() ) 
    {
      if (ieve % 1000 == 0) std::cout << "event " << ieve << "\n" ;
      ++ieve;
      
      std::vector<int> bosons ;      
      vector<pair<int, TLorentzVector> > fs_particles ;  //PG final state particles
      //PG loop over particles in the event
      for (int iPart = 0 ; iPart < reader.hepeup.IDUP.size (); ++iPart)
        {
          //PG outgoing particle          
          if (reader.hepeup.ISTUP.at (iPart) == 1)
            {
              TLorentzVector particle 
                (
                  reader.hepeup.PUP.at (iPart).at (0), //PG px
                  reader.hepeup.PUP.at (iPart).at (1), //PG py
                  reader.hepeup.PUP.at (iPart).at (2), //PG pz
                  reader.hepeup.PUP.at (iPart).at (3) //PG E
                ) ;
//              fs_particles[reader.hepeup.IDUP.at (iPart)] = particle ;            
              fs_particles.push_back (pair<int, TLorentzVector> (reader.hepeup.IDUP.at (iPart), particle)) ;
            } //PG outgoing particle
        } //PG loop over particles in the event

      TLorentzVector Z_cand ;
      TLorentzVector H_cand ;
      vector <TLorentzVector *> Jets ;
      vector <TLorentzVector *> leptons ;
      vector <TLorentzVector *> neutrinos ;
      vector <TLorentzVector *> gluons ;

      for (int iPart = 0 ; iPart < fs_particles.size () ; ++iPart)
	{
//	std::cout<<"  Particle Id  "<<fs_particles.at (iPart).first<<" Pt   "<<(fs_particles.at (iPart).second).Pt()<<std::endl;
	}

      for (int iPart = 0 ; iPart < fs_particles.size () ; ++iPart)
        {
          if (abs (fs_particles.at (iPart).first) < 11) //PG tag Jets
            {
              Jets.push_back (&(fs_particles.at (iPart).second)) ;
              continue ;
            }
          if (abs (fs_particles.at (iPart).first) == 21) //PG gluons
            {
              gluons.push_back (&(fs_particles.at (iPart).second)) ;
              continue ;
            }

          if (abs (fs_particles.at (iPart).first) == 12 ||
              abs (fs_particles.at (iPart).first) == 14)
            {
               neutrinos.push_back (&(fs_particles.at (iPart).second)) ;
            }

          if (abs (fs_particles.at (iPart).first) == 11 ||
              abs (fs_particles.at (iPart).first) == 13)
            {
               leptons.push_back (&(fs_particles.at (iPart).second)) ;
               Z_cand += fs_particles.at (iPart).second ; //PG electron or muon
            }
          H_cand += fs_particles.at (iPart).second ;
        }

      //PG VBF cuts

      sort (Jets.begin (), Jets.end (), mySort ()) ;
      sort (leptons.begin (), leptons.end (), mySort ()) ;
      sort (neutrinos.begin (), neutrinos.end (), mySort ()) ;


	 TLorentzVector vbf_ajp(0,0,0,0), vbf_bjp(0,0,0,0);
         TLorentzVector wjj_ajp(0,0,0,0), wjj_bjp(0,0,0,0); 
         TLorentzVector lep(0,0,0,0), nu(0,0,0,0);

         float best_detatagjj = 0; // float best_mtagjj =0;
         float best_mjj = 0; // float best_mjj =0;

   float vbf_jj_e =-999,   vbf_jj_pt =-999,   vbf_jj_eta=-999,  vbf_jj_phi =-999, vbf_jj_m=-999;   
   float vbf_aj_e =-999,   vbf_aj_pt =-999,   vbf_aj_eta=-999,  vbf_aj_phi =-999;   
   float vbf_bj_e =-999,   vbf_bj_pt =-999,   vbf_bj_eta=-999,  vbf_bj_phi =-999;   
   float vbf_jj_deta=-999; Float_t vbf_jj_dphi=-999; 
    int   vbf_jj_type=0,   vbf_n_excj=0,   vbf_n_exfj=0,   vbf_n_gdjj=0;

   float vbf_wjj_e =-999,   vbf_wjj_pt =-999,   vbf_wjj_eta=-999,  vbf_wjj_phi =-999, vbf_wjj_m=-999;   
   float vbf_waj_e =-999,   vbf_waj_pt =-999,   vbf_waj_eta=-999,  vbf_waj_phi =-999;   
   float vbf_wbj_e =-999,   vbf_wbj_pt =-999,   vbf_wbj_eta=-999,  vbf_wbj_phi =-999;   
   float vbf_wjj_deta=-999; Float_t vbf_wjj_dphi=-999;
   float vbf_lvjj_e =-999,   vbf_lvjj_pt =-999,   vbf_lvjj_eta=-999,  vbf_lvjj_phi =-999, vbf_lvjj_m =-999, vbf_lvj_m=-999;
   float vbf_l_pt =-999,   vbf_l_e =-999,   vbf_l_eta=-999,  vbf_l_phi =-999, vbf_nu_e =-999;

   float vbf_l_MET_deltaphi=-999, vbf_lW_hW_deltaphi=-999,vbf_l_tj1_dR=-999,vbf_l_tj2_dR=-999,vbf_l_wj1_dR=-999,vbf_l_wj2_dR=-999,vbf_l_wjj_dR=-999,vbf_l_tjj_dR=-999;



// 	 float jess 1.0; 
         int   n_excj =0, n_exfj = 0, n_gdjj = 0, jj_type = 0, tag_i_id = -1, tag_j_id = -1, wjj_a_id = -1, wjj_b_id = -1;



         for ( size_t i=0; i < leptons.size(); ++i)
         {
        if ((fabs(leptons.at(i)->Eta()) > 2.5) && (leptons.at(i)->Pt() < 25) ) continue;
            TLorentzVector l;
            l.SetPxPyPzE (leptons.at(i)->Px(), leptons.at(i)->Py(), leptons.at(i)->Pz(), leptons.at(i)->E()
              );
	lep=l;
	}

         for ( size_t i=0; i < neutrinos.size(); ++i)
         {
        if (neutrinos.at(i)->Et() < 25) continue;
            TLorentzVector n;
            n.SetPxPyPzE (neutrinos.at(i)->Px(), neutrinos.at(i)->Py(), neutrinos.at(i)->Pz(), neutrinos.at(i)->E()
              );
	nu=n;
        }



       //method1a A two tag Jets from complete eta region
         for ( size_t i=0; i < Jets.size(); ++i)
         {
        if ((fabs(Jets.at(i)->Eta()) > 4.7 )&& (Jets.at(i)->Pt()<20)) continue;
            TLorentzVector i_p;
            i_p.SetPxPyPzE (Jets.at(i)->Px(), Jets.at(i)->Py(), Jets.at(i)->Pz(), Jets.at(i)->E()
              );
            for (size_t j=i+1; j <Jets.size(); ++j)
            {
        if ((fabs(Jets.at(j)->Eta()) > 4.7) && (Jets.at(i)->Pt()<20))continue;
               TLorentzVector j_p;
            j_p.SetPxPyPzE (Jets.at(j)->Px(), Jets.at(j)->Py(), Jets.at(j)->Pz(), Jets.at(j)->E()
              ) ;
               if ( (Jets.at(i)->Eta()*Jets.at(j)->Eta())>0 )  continue;     // 1.  have to be one forward, one backward
               if ( (fabs(Jets.at(i)->Eta()-Jets.at(j)->Eta())<3.5) || (sqrt ((i_p+j_p).M2()) <500)) continue;// 2.Tag pair delta eta>3.5, Mjj>500
                //cout<<"  "<<sqrt ((i_p+j_p).M2())<<endl;
               // if find more than one combinations
               //if ( (fas(i_Eta-j_Eta)>best_detatagjj) )      // 3   Select best combination with maximum deta Eta
               if ( sqrt((i_p+j_p).M2()) > best_mjj )
               {                          // 3   Select best combination with maximum Mjj because of the bad angular resolution in the HF
                  best_detatagjj = fabs(Jets.at(i)->Eta()-Jets.at(j)->Eta());
                  n_gdjj++;
                  best_mjj = sqrt ((i_p+j_p).M2());
                  tag_i_id = i;
                  tag_j_id = j;
                  vbf_ajp = i_p;
                  vbf_bjp = j_p;
               } //loop to find two tag Jets with highest mjj
           } // over over loop over Nmax-1 reco Jets inside 
       } //loop over Nmax reco Jets 
                if (tag_i_id !=-1 && tag_j_id != -1)
                {
                  vbf_jj_e      = (vbf_ajp+ vbf_bjp).E();
                  vbf_jj_pt     = (vbf_ajp+ vbf_bjp).Pt();
                  vbf_jj_eta    = (vbf_ajp+ vbf_bjp).Eta();
                  vbf_jj_phi    = (vbf_ajp+ vbf_bjp).Phi();
                  vbf_jj_m      = best_mjj;
                  vbf_aj_e      = (vbf_ajp).E();
                  vbf_aj_pt     = (vbf_ajp).Pt();
                  vbf_aj_eta    = (vbf_ajp).Eta();
                  vbf_aj_phi    = (vbf_ajp).Phi();
                  //vbf_aj_m      = (i_p).M();
                  vbf_bj_e      = (vbf_bjp).E();
                  vbf_bj_pt     = (vbf_bjp).Pt();
                  vbf_bj_eta    = (vbf_bjp).Eta();
                  vbf_bj_phi    = (vbf_bjp).Phi();
                 // vbf_bj_m      = (j_p).M();

                  vbf_jj_deta   =vbf_aj_eta-vbf_bj_eta;
                  vbf_jj_dphi   = vbf_aj_phi-vbf_bj_phi;
                  //cout<<"  "<<vbf_jj_dphi<<endl;
        } //loop  
        // method1a B

	if (tag_i_id!=-1&&tag_j_id!=-1) 
	{  
	for ( int k=0; k < (int) Jets.size(); ++k) 
	{ 
        if (fabs(Jets.at(k)->Eta()) > 4.7) continue;
	if ( k!=tag_i_id && k!= tag_j_id && wjj_ajp.Pt()!=0 && wjj_bjp.Pt()==0 ) 
	{
	int Bj = k;  
           wjj_bjp.SetPxPyPzE (Jets.at(Bj)->Px(), Jets.at(Bj)->Py(), Jets.at(Bj)->Pz(), Jets.at(Bj)->E()
              );
         wjj_b_id=Bj;                                                                                       
	}
	if ( k!=tag_i_id&&k!=tag_j_id&&wjj_ajp.Pt()==0 && wjj_bjp.Pt()==0 ) 
	{
	int Aj = k;  
           wjj_ajp.SetPxPyPzE (Jets.at(Aj)->Px(), Jets.at(Aj)->Py(), Jets.at(Aj)->Pz(), Jets.at(Aj)->E()
              );
         wjj_a_id=Aj;                                                                                       
	}
	}// loop over reco Jets upto Nmax                                                     
	} // loop of insuring having allready two tagJets

if ( wjj_a_id!=-1 && wjj_b_id!=-1)
{ 
                    //    two W Jets
                        vbf_wjj_e      = (wjj_ajp+wjj_bjp).E();
                        vbf_wjj_pt     = (wjj_ajp+wjj_bjp).Pt();
                        vbf_wjj_eta    = (wjj_ajp+wjj_bjp).Eta();
                        vbf_wjj_phi    = (wjj_ajp+wjj_bjp).Phi();
                        vbf_wjj_m      = sqrt((wjj_ajp+wjj_bjp).M2());
                        vbf_waj_e      = (wjj_ajp).E();
                        vbf_waj_pt     = (wjj_ajp).Pt();
                        vbf_waj_eta    = (wjj_ajp).Eta();
                        vbf_waj_phi    = (wjj_ajp).Phi();
                        //vbf_waj_m      = (wjj_ajp).M();
                        vbf_wbj_e      = (wjj_bjp).E();
                        vbf_wbj_pt     = (wjj_bjp).Pt();
                        vbf_wbj_eta    = (wjj_bjp).Eta();
                        vbf_wbj_phi    = (wjj_bjp).Phi();
                        vbf_wjj_deta=vbf_waj_eta-vbf_wbj_eta;
                        vbf_wjj_dphi= vbf_waj_phi-vbf_wbj_phi;
}
if (tag_i_id!=-1 && tag_j_id!=-1 && wjj_a_id!=-1 && wjj_b_id!=-1 && lep.Pt()>30.)
	{
        		    vbf_lvjj_e      = (lep+nu+wjj_ajp+wjj_bjp).E();
		            vbf_lvjj_pt     = (lep+nu+wjj_ajp+wjj_bjp).Pt();
        		    vbf_lvjj_eta    = (lep+nu+wjj_ajp+wjj_bjp).Eta();
		            vbf_lvjj_phi    = (lep+nu+wjj_ajp+wjj_bjp).Phi();
		            vbf_lvjj_m      = sqrt((lep+nu+wjj_ajp+wjj_bjp).M2());
                            vbf_lvj_m      = (lep+nu).Mt();
//                            vbf_lvj_m      = sqrt((lep+nu).M2());

                            vbf_l_pt = lep.Pt();
                            vbf_l_eta = lep.Eta();
                            vbf_l_phi = lep.Phi();
                            vbf_l_e = lep.E();

                            vbf_nu_e = nu.Et();

                            vbf_l_MET_deltaphi = getDeltaPhi(vbf_l_phi, nu.Phi());
                            vbf_lW_hW_deltaphi = getDeltaPhi((lep+nu).Phi(), vbf_wjj_phi);

                            vbf_l_tj1_dR = delta_R(vbf_l_eta,vbf_l_phi,vbf_aj_eta,vbf_aj_phi);
                            vbf_l_tj2_dR = delta_R(vbf_l_eta,vbf_l_phi,vbf_bj_eta,vbf_bj_phi);

                            vbf_l_wj1_dR = delta_R(vbf_l_eta,vbf_l_phi,vbf_waj_eta,vbf_waj_phi);
                            vbf_l_wj2_dR = delta_R(vbf_l_eta,vbf_l_phi,vbf_wbj_eta,vbf_wbj_phi);

                            vbf_l_tjj_dR = delta_R(vbf_aj_eta,vbf_aj_phi, vbf_bj_eta,vbf_bj_phi);
                            vbf_l_wjj_dR = delta_R(vbf_waj_eta,vbf_waj_phi, vbf_wbj_eta,vbf_wbj_phi);

	}

      double tj_dEta = fabs (Jets.at (0)->Eta () - Jets.at (1)->Eta ()) ; 
      h_deta.Fill (tj_dEta) ; 
      h_j1eta.Fill (Jets.at (0)->Eta ()) ;
      h_j2eta.Fill (Jets.at (1)->Eta ()) ;
      h_j1pt.Fill (Jets.at (0)->Pt ()) ;
      h_j2pt.Fill (Jets.at (1)->Pt ()) ;

        if (tag_i_id!=-1 && tag_j_id!=-1 && wjj_a_id!=-1 && wjj_b_id!=-1 && vbf_aj_pt>30. && vbf_bj_pt>30. && vbf_waj_pt>30. && vbf_wbj_pt>30 && vbf_wjj_m>30. && vbf_lvj_m>30. && vbf_l_pt>30. && vbf_nu_e >30); 
{
	h_vbf_jj_pt.Fill(vbf_jj_pt);
        h_vbf_jj_eta.Fill(vbf_jj_eta);
        h_vbf_jj_phi.Fill(vbf_jj_phi);
        h_vbf_jj_e.Fill(vbf_jj_e);
        h_vbf_jj_m.Fill(vbf_jj_m);


        h_vbf_aj_pt.Fill(vbf_aj_pt);
        h_vbf_aj_eta.Fill(vbf_aj_eta);
        h_vbf_aj_phi.Fill(vbf_aj_phi);
        h_vbf_aj_e.Fill(vbf_aj_e);

        h_vbf_bj_pt.Fill(vbf_bj_pt);
        h_vbf_bj_eta.Fill(vbf_bj_eta);
        h_vbf_bj_phi.Fill(vbf_bj_phi);
        h_vbf_bj_e.Fill(vbf_bj_e);

        h_vbf_jj_deta.Fill(vbf_jj_deta);
        h_vbf_jj_dphi.Fill(vbf_jj_dphi);

        h_vbf_wjj_pt.Fill(vbf_wjj_pt);
        h_vbf_wjj_eta.Fill(vbf_wjj_eta);
        h_vbf_wjj_phi.Fill(vbf_wjj_phi);
        h_vbf_wjj_e.Fill(vbf_wjj_e);
        h_vbf_wjj_m.Fill(vbf_wjj_m);

        h_vbf_waj_pt.Fill(vbf_waj_pt);
        h_vbf_waj_eta.Fill(vbf_waj_eta);
        h_vbf_waj_phi.Fill(vbf_waj_phi);
        h_vbf_waj_e.Fill(vbf_waj_e);

        h_vbf_wbj_pt.Fill(vbf_wbj_pt);
        h_vbf_wbj_eta.Fill(vbf_wbj_eta);
        h_vbf_wbj_phi.Fill(vbf_wbj_phi);
        h_vbf_wbj_e.Fill(vbf_wbj_e);

        h_vbf_wjj_deta.Fill(vbf_wjj_deta);
        h_vbf_wjj_dphi.Fill(vbf_wjj_dphi);

        h_vbf_lvjj_pt.Fill(vbf_lvjj_pt);
        h_vbf_lvjj_eta.Fill(vbf_lvjj_eta);
        h_vbf_lvjj_phi.Fill(vbf_lvjj_phi);
        h_vbf_lvjj_e.Fill(vbf_lvjj_e);
        h_vbf_lvjj_m.Fill(vbf_lvjj_m);
        h_vbf_lvj_m.Fill(vbf_lvj_m);

        h_vbf_l_pt.Fill(vbf_l_pt);
        h_vbf_l_eta.Fill(vbf_l_eta);
        h_vbf_l_phi.Fill(vbf_l_phi);
        h_vbf_l_e.Fill(vbf_l_e);
        h_vbf_nu_e.Fill(vbf_nu_e);

    h_vbf_l_MET_deltaphi.Fill(vbf_l_MET_deltaphi); 
    h_vbf_lW_hW_deltaphi.Fill(vbf_lW_hW_deltaphi); 
    h_vbf_l_tj1_dR.Fill(vbf_l_tj1_dR); 
    h_vbf_l_tj2_dR.Fill(vbf_l_tj2_dR); 
    h_vbf_l_wj1_dR.Fill(vbf_l_wj1_dR); 
    h_vbf_l_wj1_dR.Fill(vbf_l_wj1_dR); 
    h_vbf_l_wjj_dR.Fill(vbf_l_wjj_dR); 
    h_vbf_l_tjj_dR.Fill(vbf_l_tjj_dR); 


}

      for (int k = 0 ; k < Jets.size () ; ++k) h_jeta.Fill (Jets.at (k)->Eta ()) ;
      if (gluons.size () > 0) h_jeta.Fill (gluons.at (0)->Eta ()) ;
        

    } // Now loop over all events

//  TFile histosFile ("cuts_phantom_lheAnalysis_.root","recreate") ;
  TFile histosFile ("unweighted_500Kevents_VBFcuts.root","recreate") ;

//  TFile histosFile ("cuts_Madgraph_lheAnalysis_.root","recreate") ;
//  TFile histosFile ("cuts_vbfnlo_lheAnalysis_.root","recreate") ;


  histosFile.cd () ;
  h_deta.Write () ;
  h_j1eta.Write () ;
  h_j2eta.Write () ;
  h_jeta.Write () ;
  h_j1pt.Write () ;
  h_j2pt.Write () ;

  h_vbf_jj_pt.Write ();
  h_vbf_jj_eta.Write ();
  h_vbf_jj_phi.Write ();
  h_vbf_jj_e.Write ();
  h_vbf_jj_m.Write ();

  h_vbf_aj_pt.Write ();
  h_vbf_aj_eta.Write ();
  h_vbf_aj_phi.Write ();
  h_vbf_aj_e.Write ();

  h_vbf_bj_pt.Write ();
  h_vbf_bj_eta.Write ();
  h_vbf_bj_phi.Write ();
  h_vbf_bj_e.Write ();

  h_vbf_jj_deta.Write ();
  h_vbf_jj_dphi.Write ();

  h_vbf_wjj_pt.Write ();
  h_vbf_wjj_eta.Write ();
  h_vbf_wjj_phi.Write ();
  h_vbf_wjj_e.Write ();
  h_vbf_wjj_m.Write ();

  h_vbf_waj_pt.Write ();
  h_vbf_waj_eta.Write ();
  h_vbf_waj_phi.Write ();
  h_vbf_waj_e.Write ();

  h_vbf_wbj_pt.Write ();
  h_vbf_wbj_eta.Write ();
  h_vbf_wbj_phi.Write ();
  h_vbf_wbj_e.Write ();

  h_vbf_lvjj_pt.Write ();
  h_vbf_lvjj_eta.Write ();
  h_vbf_lvjj_phi.Write ();
  h_vbf_lvjj_e.Write ();
  h_vbf_lvjj_m.Write ();
  h_vbf_lvj_m.Write ();

  h_vbf_l_pt.Write();
  h_vbf_l_eta.Write();
  h_vbf_l_phi.Write();
  h_vbf_l_e.Write();
  h_vbf_nu_e.Write();
  h_vbf_l_MET_deltaphi.Write();
  h_vbf_lW_hW_deltaphi.Write();
  h_vbf_l_tj1_dR.Write();
  h_vbf_l_tj2_dR.Write();
  h_vbf_l_wj1_dR.Write();
  h_vbf_l_wj1_dR.Write();
  h_vbf_l_wjj_dR.Write();
  h_vbf_l_tjj_dR.Write();

  h_vbf_wjj_deta.Write ();
  h_vbf_wjj_dphi.Write ();


  histosFile.Close () ;

  return ;
}
void UpsilonMassFit_PolWeights(int iSpec = 3, int PutWeight=1)
{

  double PtCut=4;

  //minbias integrated, |y|<1.2 and |y|\in[1.2,2.4], centrality [0,10][10,20][20,100]%,  pt [0,6.5], [6.5, 10] [10,20]

  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(1); // at least most of the time
  gStyle->SetOptStat(1); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(1); // set to 1 only if you want to display fit results

  //==================================== Define Histograms====================================================
  ofstream dataFile(Form("Eff_Upsilon.txt"));
  
  TH1D *diMuonsInvMass_Gen = new TH1D("diMuonsInvMass_Gen","diMuonsInvMass_Gen", 100,8.0,12.0);
  TH1D *diMuonsPt_Gen = new TH1D("diMuonsPt_Gen","diMuonsPt_Gen", 100,0,30);
  //Rapidity Gen
  TH1D *diMuonsRap_Gen0 = new TH1D("diMuonsRap_Gen0","diMuonsRap_Gen0", 100,-5,5);
  TH1D *diMuonsRap_Gen1 = new TH1D("diMuonsRap_Gen1","diMuonsRap_Gen1", 100,-5,5);
  TH1D *diMuonsRap_Gen2 = new TH1D("diMuonsRap_Gen2","diMuonsRap_Gen2", 100,-5,5);
  TH1D *diMuonsRap_Gen3 = new TH1D("diMuonsRap_Gen3","diMuonsRap_Gen3", 100,-5,5);
  TH1D *diMuonsRap_Gen4 = new TH1D("diMuonsRap_Gen4","diMuonsRap_Gen4", 100,-5,5);
  TH1D *diMuonsRap_Gen5 = new TH1D("diMuonsRap_Gen5","diMuonsRap_Gen5", 100,-5,5);
  ////Rapidity Reco
  TH1D *diMuonsRap_Rec0 = new TH1D("diMuonsRap_Rec0","diMuonsRap_Rec0", 100,-5,5);
  diMuonsRap_Rec0->SetLineColor(2);
  TH1D *diMuonsRap_Rec1 = new TH1D("diMuonsRap_Rec1","diMuonsRap_Rec1", 100,-5,5);
  diMuonsRap_Rec1->SetLineColor(2);
  TH1D *diMuonsRap_Rec2 = new TH1D("diMuonsRap_Rec2","diMuonsRap_Rec2", 100,-5,5);
  diMuonsRap_Rec2->SetLineColor(2);
  TH1D *diMuonsRap_Rec3 = new TH1D("diMuonsRap_Rec3","diMuonsRap_Rec3", 100,-5,5);
  diMuonsRap_Rec3->SetLineColor(2);
  TH1D *diMuonsRap_Rec4 = new TH1D("diMuonsRap_Rec4","diMuonsRap_Rec4", 100,-5,5);
  diMuonsRap_Rec4->SetLineColor(2);
  TH1D *diMuonsRap_Rec5 = new TH1D("diMuonsRap_Rec5","diMuonsRap_Rec5", 100,-5,5);
  diMuonsRap_Rec5->SetLineColor(2);
  TH1D *Bin_Gen = new TH1D("Bin_Gen","Bin_Gen", 40,0,40);

  //==============================================Define AccEff Stuff here===========================================
  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  if(iSpec == 1) { 
    Nptbin = 5;
    pt_bound[0] = 0;
    pt_bound[1] = 20.0;
    pt_bound[2] = 0.0;
    pt_bound[3] = 6.5;
    pt_bound[4] = 10.0;
    pt_bound[5] = 20.0;
   

    pt_bound[6] = 30.0;
    pt_bound[7] = 35;
    pt_bound[8] = 40;
    pt_bound[9] = 45;
    pt_bound[10] = 50;
  }
  
  if(iSpec == 2) { 
    Nptbin = 2;
    pt_bound[0] = 0.0; 
    pt_bound[1] = 1.2; 
    pt_bound[2] = 2.4; 
    
    pt_bound[3] = 0.0; 
    pt_bound[4] = 0.8; 
    pt_bound[5] = 1.8; 
    //pt_bound[7] = 2.0; 
    pt_bound[6] = 2.4; 
  
  }
  
  
  if(iSpec == 3) {
    Nptbin = 3;
    //for plots
    pt_bound[0] = 0.0;//0
    pt_bound[1] = 4.0;//10
    pt_bound[2] = 8.0;//20
    pt_bound[3] = 40.0;//100
   

    //pt_bound[4] = 16.0;//50
    //pt_bound[5] = 20.0;//100
    //pt_bound[6] = 24.0;
    //pt_bound[7] = 32.0;
    //pt_bound[8] = 40.0;
    //pt_bound[9] = 40.0;
  }
  //X Axis error on Eff graph 
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  double genError, recError;
  double gen_pt[100]={0}, gen_ptError[100]={0}; 
  double rec_pt[100]={0}, rec_ptError[100]={0}; 
  double Eff_cat_1[100]={0},Err_Eff_cat_1[100]={0};  
  
  // Histogram arrays
  TH1D *diMuonsInvMass_GenA[10][1000];
  TH1D *diMuonsInvMass_RecA[10][1000];
  TH1D *diMuonsPt_GenA[10][1000];
  TH1D *diMuonsPt_RecA[10][1000];
  char nameGen[10][500], nameRec[10][500], nameGenPt[10][500], nameRecPt[10][500];
 
  
  for (int ifile = 0; ifile <= 5; ifile++) {
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      sprintf(nameGen[ifile],"DiMuonMassGen_pt_%d_%d",ih,ifile);
      sprintf(nameRec[ifile],"DiMuonMassRec_pt_%d_%d",ih,ifile);

      sprintf(nameGenPt[ifile],"DiMuonPtGen_pt_%d_%d",ih,ifile);
      sprintf(nameRecPt[ifile],"DiMuonPtRec_pt_%d_%d",ih,ifile);
      
      diMuonsInvMass_GenA[ifile][ih]= new TH1D(nameGen[ifile],nameGen[ifile],  100,8.0,12.0); //for eff Gen;
      diMuonsInvMass_GenA[ifile][ih]->Sumw2();
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerStyle(7);
      diMuonsInvMass_GenA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_GenA[ifile][ih]->SetLineColor(4);

      diMuonsInvMass_RecA[ifile][ih] = new TH1D(nameRec[ifile],nameRec[ifile], 100,8.0,12.0); //for eff Rec;
      diMuonsInvMass_RecA[ifile][ih]->Sumw2();
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerStyle(8);
      diMuonsInvMass_RecA[ifile][ih]->SetMarkerColor(4);
      diMuonsInvMass_RecA[ifile][ih]->SetLineColor(4);


      diMuonsPt_GenA[ifile][ih]= new TH1D(nameGenPt[ifile],nameGenPt[ifile],  100,0,40); //for eff Gen;
      diMuonsPt_RecA[ifile][ih]= new TH1D(nameRecPt[ifile],nameRecPt[ifile],  100,0,40); //for eff Rec;
    }
  }
  
  //===========================================Input Root File============================================================
  char fileName[10][500];
  //0.0380228 	0.0480769 	0.0293255 	0.0125156 	0.00336587 	0.00276319*2/5 = 0.001105276
  //Scales
  double scale[10]={0};  
  scale[0]=(6.8802); // pT [0-3]
  scale[1]=(8.6995); // pT [3-6]
  scale[2]=(5.3065); // pT [6-9]
  scale[3]=(2.2647); // pT [9-12] 
  scale[4]=(3.0453); // pT [12-15] 
  scale[5]=(1.0000); // pT [15-30]
  
  sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03_N.root");
  sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36_N.root");
  sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69_N.root");
  sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912_N.root");
  sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215_N.root");
  sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530_N.root");



  //double scale[10]={0};  
  //scale[0]=(0.0380228/0.001105276);
  //scale[1]=(0.0480769/0.001105276);
  //scale[2]=(0.0293255/0.001105276);
  //scale[3]=(0.0125156/0.001105276);
  //scale[4]=(0.00336587/0.001105276);
  //scale[5]=(0.001105276/0.001105276);
   //34.55 , 43.70 , 26.65 , 11.37 , 3.05 , 1
  //sprintf(fileName[0],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt03.root");
  //sprintf(fileName[1],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt36.root");
  //sprintf(fileName[2],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt69.root");
  //sprintf(fileName[3],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt912.root");
  //sprintf(fileName[4],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1215.root");
  //sprintf(fileName[5],"/home/vineet/HiData/UpsilonData/UpsilonEff/DimuonOnia2Dplots_UpsilonPt1530.root");
  
  TFile *infile;
  TTree *tree;
  TTree *gentree;
  
  //===========File loop ======================
  
  for(int ifile =0; ifile<=5; ifile++){
    
    infile=new TFile(fileName[ifile],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    
    //Event variables
    int eventNb,runNb,lumiBlock, gbin, rbin;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiPx,JpsiPy,JpsiPz,JpsiRap, JpsiCharge,JpsiE;
    Double_t JpsiVprob;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt,muPosP,muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt,muNegP,muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    //Gen Level variables
    //Gen JPsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE;
   
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    
    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPx",&JpsiPx);
    tree->SetBranchAddress("JpsiPy",&JpsiPy);
    tree->SetBranchAddress("JpsiPz",&JpsiPz);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
    tree->SetBranchAddress("rbin",&rbin);
    
    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy",    &muNegPy);
    tree->SetBranchAddress("muNegPz",    &muNegPz);
    tree->SetBranchAddress("muNegEta",    &muNegEta);
     tree->SetBranchAddress("muNegPhi", &muNegPhi);

    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);  
    
    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    



//====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    gentree->SetBranchAddress("gbin",&gbin);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",    &GenmuPosEta);
     gentree->SetBranchAddress("GenmuPosPhi",    &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",    &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",    &GenmuNegPhi);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ========="<<endl;
    //dataFile<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ====="<<endl;
    
    
    for(int i=0; i< nGenEntries; i++)  {	    
      gentree->GetEntry(i);
      
      if(i%1000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl; 
      }
      
      bool GenPosIn=0, GenNegIn=0,GenPosPass=0,GenNegPass=0;

      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 
      
      GenJpsiE= TMath::Sqrt( GenJpsiPx*GenJpsiPx+GenJpsiPy*GenJpsiPy+GenJpsiPz*GenJpsiPz + 9.46*9.46);


      
      //============================ calculate Pol weight ========================================================================================= //
      Float_t w1,w2,w3,w4,w5;
      // this is the beam energy: 2760GeV->/2->1380GeV each beam
      // the mp=0.938272 is the mass of the proton, as we are looking at p+p collisions
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
     
      TLorentzVector genJpsi;    // generated upsilon (mother of the single muons) --> if you look at jpsi-> genJpsi (prompt or non-prompt)
      TLorentzVector genMuPlus,genMuMinus; // generator positive muon (charge=+1)
      
      //int mp;
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable

      // put the coordinates of the parent in a TLorentzVector
      // ATTENTION: the last coordinate is the MASS of the parent, which in this case, since it's about Upsilon, it's 9.46
      // when you'll do this for Jpsi, this value has to change to m_jpsi=3.097
      genJpsi.SetPxPyPzE(GenJpsiPx, GenJpsiPy, GenJpsiPz, GenJpsiE); 
      TLorentzRotation boost(-genJpsi.BoostVector()); // boost it
   
      // put the muon in a LorentzVector
      genMuPlus.SetPtEtaPhiM(GenmuPosPt, GenmuPosEta, GenmuPosPhi, 0.106);
      genMuPlus *= boost; // boost it
      
      //genMuMinus.SetPtEtaPhiM(GenmuNegPt, GenmuNegEta, GenmuNegPhi, 0.106);
      //genMuMinus *= boost; // boost it


      //and get the cosTheta in the helicity frame
      cosThetaStarHel = genMuPlus.Vect().Dot(genJpsi.Vect())/(genMuPlus.Vect().Mag()*genJpsi.Vect().Mag());
     
      //int genMuCharge = 1;
      //int mp = genMuCharge>0 ? 0 : 1;
      //cout << genMuCharge << "     " << mp << endl;


      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      // calculate cosTheta CS

      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = genMuPlus.Vect().Dot(zCS)/genMuPlus.Vect().Mag();

      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      

      //w5=1; 

      // cout<<" gen "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl;

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


    
      diMuonsInvMass_Gen->Fill(GenJpsiMass);
      diMuonsPt_Gen->Fill(GenJpsiPt);
 
      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}
  

    
      if(GenPosIn && GenNegIn ) NAccep++;
      
      if(GenPosIn==1 && GenmuPosPt>PtCut ) {GenPosPass=1;}
      if(GenNegIn==1 && GenmuNegPt>PtCut ) {GenNegPass=1;}

      double GenCenWeight=0,GenWeight=0;
      GenCenWeight=FindCenWeight(gbin);
      Bin_Gen->Fill(gbin);
      GenWeight=GenCenWeight*scale[ifile];
      if(PutWeight==0){GenWeight=1;}

      if(GenPosIn && GenNegIn){
	if(ifile==0){diMuonsRap_Gen0->Fill(GenJpsiRap);}
	if(ifile==1){diMuonsRap_Gen1->Fill(GenJpsiRap);}
	if(ifile==2){diMuonsRap_Gen2->Fill(GenJpsiRap);}
	if(ifile==3){diMuonsRap_Gen3->Fill(GenJpsiRap);}
	if(ifile==4){diMuonsRap_Gen4->Fill(GenJpsiRap);}
	if(ifile==5){diMuonsRap_Gen5->Fill(GenJpsiRap);}
      }
 

      for (Int_t ih = 0; ih < Nptbin; ih++) {
	//adding pT of all pt bins to see diss is cont
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 ) && (GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsPt_GenA[ifile][ih]->Fill(GenJpsiPt,GenWeight*w5);}
	if(iSpec == 1)  if( (GenPosPass==1 && GenNegPass==1) && (TMath::Abs(GenJpsiRap)<2.4 )&&(GenJpsiPt>pt_bound[ih] && GenJpsiPt<=pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 2)  if((GenPosPass==1 && GenNegPass==1) &&  (GenJpsiPt<20.0) && (TMath::Abs(GenJpsiRap) > pt_bound[ih] && TMath::Abs(GenJpsiRap) <=pt_bound[ih+1] )){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
	if(iSpec == 3)  if( (GenPosPass==1 && GenNegPass==1) && (GenJpsiPt < 20.0) &&  (TMath::Abs(GenJpsiRap)<2.4 ) && (gbin>=pt_bound[ih] && gbin<pt_bound[ih+1])){diMuonsInvMass_GenA[ifile][ih]->Fill(GenJpsiMass,GenWeight*w5);}
      

      }

    }//gen loop end
    
    cout<<" accepted no "<< NAccep<<endl;
    //dataFile<<" accepted no "<< NAccep<<endl;
     
    //   new TCanvas;
    //diMuonsInvMass_Gen->Draw();
    //gPad->Print("plots/diMuonsInvMass_Gen.png");
    
    //new TCanvas;
    //diMuonsPt_Gen->Draw();
    //gPad->Print("plots/diMuonsPt_Gen.png");
  
    //new TCanvas;
    //diMuonsRap_Gen0->Draw();
    //sprintf(PlotName,"plots/diMuonsRap_Gen_%d.pdf",ifile);   
    //gPad->Print(PlotName);
    
    //new TCanvas;
    //Bin_Gen->Draw();
    //gPad->Print("plots/Bin_Gen.png");
    
  

    //=============== Rec Tree Loop ==============================================================================
    
    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
    //dataFile<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<<endl;
    
    for(int i=0; i<nRecEntries; i++)  {	    
      tree->GetEntry(i);
      if(i%100000==0){
	cout<<" processing record "<<i<<endl;
	cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
	cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<endl; 
      }
      
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 
    
      
      JpsiE= TMath::Sqrt(JpsiPx*JpsiPx+JpsiPy*JpsiPy+JpsiPz*JpsiPz + JpsiMass*JpsiMass);
      //============================ calculate Pol weight rec ========================================================================================= //
      Float_t w1=0,w2=0,w3=0,w4=0,w5=0;
      double E=1380; double pz = sqrt(E*E - 0.938272*0.938272);
      TLorentzVector h1; // beam 1
      TLorentzVector h2; // beam 2
      
      TLorentzVector Jpsi;    
      TLorentzVector MuPlus;       
      Float_t cosThetaStarHel; // cosTheta in the Helicity frame
      Float_t cosThetaStarCS;  // cosTheta in the Collins-Soper frame
      TVector3 zCS;             // collins-soper variable
      
      Jpsi.SetPxPyPzE(JpsiPx, JpsiPy, JpsiPz, JpsiE); 
      TLorentzRotation boost(-Jpsi.BoostVector()); // boost it
      
      // put the muon in a LorentzVector
      MuPlus.SetPtEtaPhiM(muPosPt, muPosEta, muPosPhi, 0.106);
      MuPlus *= boost; // boost it
      //and get the cosTheta in the helicity frame
      cosThetaStarHel = MuPlus.Vect().Dot(Jpsi.Vect())/(MuPlus.Vect().Mag()*Jpsi.Vect().Mag());
      h1.SetPxPyPzE(0,0,pz,E);  // TLorentzVector for beam 1
      h2.SetPxPyPzE(0,0,-pz,E); //  TLorentzVector for beam 2
      h1*=boost;
      h2*=boost;
      zCS = ( h1.Vect().Unit() - h2.Vect().Unit() ).Unit();
      cosThetaStarCS = MuPlus.Vect().Dot(zCS)/MuPlus.Vect().Mag();
      // setup the weights
      w1 = 1;
      w2 = 1 + cosThetaStarHel*cosThetaStarHel;
      w3 = 1 - cosThetaStarHel*cosThetaStarHel;
      w4 = 1 + cosThetaStarCS*cosThetaStarCS;
      w5 = 1 - cosThetaStarCS*cosThetaStarCS;
      


      //w5=1;
      //cout<<" rec "<<w2<<"   "<<w3<<"  "<<w4<<"  "<<w5<<endl; 
      //================================================== Pol weights  ===============================================================================//
      
      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}



      if(muPos_found > 10 && muPos_pixeLayers > 0 && muPos_nchi2In < 4.0 && muPos_dxy < 3 && muPos_dz < 15 && muPos_nchi2Gl < 20 &&  muPos_arbitrated==1 && muPos_tracker==1){PosPass=1;}	  
      
      if(muNeg_found >10 && muNeg_pixeLayers >0 && muNeg_nchi2In <4.0 && muNeg_dxy < 3 && muNeg_dz < 15 && muNeg_nchi2Gl < 20 && muNeg_arbitrated==1 && muNeg_tracker==1){NegPass=1;}

      // cout<<muPos_matches<<"  "<<muNeg_matches<<endl;
      
      if((muPosPt > PtCut && muNegPt > PtCut) && (muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1 )  &&   (PosPass==1 && NegPass==1)){AllCut=1;}
    
      double RecCenWeight=0,RecWeight=0;
      RecCenWeight=FindCenWeight(rbin);
      RecWeight=RecCenWeight*scale[ifile];
      if(PutWeight==0){RecWeight=1;}
     
      if(i%100000==0){
	cout<<" eff loop for reco "<<endl;
      }
      
      if(AllCut==1){
	if(ifile==0){diMuonsRap_Rec0->Fill(JpsiRap);}
	if(ifile==1){diMuonsRap_Rec1->Fill(JpsiRap);}
	if(ifile==2){diMuonsRap_Rec2->Fill(JpsiRap);}
	if(ifile==3){diMuonsRap_Rec3->Fill(JpsiRap);}
	if(ifile==4){diMuonsRap_Rec4->Fill(JpsiRap);}
	if(ifile==5){diMuonsRap_Rec5->Fill(JpsiRap);}
      }

      //Eff loop for reco
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {
	for (Int_t ih = 0; ih < Nptbin; ih++) {
	  //to see cont reco pT
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap) < 2.4) && (JpsiPt>pt_bound[ih] && JpsiPt<=pt_bound[ih+1])) {diMuonsPt_RecA[ifile][ih]->Fill(JpsiPt,RecWeight*w5);}
	  
	  if(iSpec == 1)if((AllCut==1) && (TMath::Abs(JpsiRap)<2.4 ) && (JpsiPt > pt_bound[ih] && JpsiPt <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass, RecWeight*w5);}
	  if(iSpec == 2) if( (AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) > pt_bound[ih] && TMath::Abs(JpsiRap) <=pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	  if(iSpec == 3) if((AllCut==1) &&  (JpsiPt<20.0) && (TMath::Abs(JpsiRap) < 2.4) && (rbin>=pt_bound[ih] &&  rbin < pt_bound[ih+1])){diMuonsInvMass_RecA[ifile][ih]->Fill(JpsiMass,RecWeight*w5);}
	



	}
      }
    }
  
    /*
    new TCanvas;
    if(ifile==0){diMuonsRap_Gen0->Draw();new TCanvas; diMuonsRap_Rec0->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen0.png");}
    if(ifile==1){diMuonsRap_Gen1->Draw();new TCanvas; diMuonsRap_Rec1->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen1.png");}
    if(ifile==2){diMuonsRap_Gen2->Draw();new TCanvas; diMuonsRap_Rec2->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen2.png");}
    if(ifile==3){diMuonsRap_Gen3->Draw();new TCanvas; diMuonsRap_Rec3->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen3.png");}
    if(ifile==4){diMuonsRap_Gen4->Draw();new TCanvas; diMuonsRap_Rec4->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen4.png");}
    if(ifile==5){diMuonsRap_Gen5->Draw();new TCanvas; diMuonsRap_Rec5->Draw(); gPad->Print("plots/NPdiMuonsRap_Gen5.png");}
    */
  }  // file loop ends 

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

  cout<< " adding "<<endl;
  TH1D *diMuonsInvMass_RecA1[100];
  TH1D *diMuonsInvMass_GenA1[100];
  TH1D *diMuonsPt_GenA1[100];
  TH1D *diMuonsPt_RecA1[100];
  TF1 *backfun_1;
  char namePt_1B[500];//for bkg func
 
  for(Int_t ih = 0; ih < Nptbin; ih++){
    diMuonsInvMass_RecA1[ih] = diMuonsInvMass_RecA[0][ih];
    diMuonsInvMass_GenA1[ih] = diMuonsInvMass_GenA[0][ih];
    diMuonsPt_GenA1[ih] = diMuonsPt_GenA[0][ih];
    diMuonsPt_RecA1[ih] = diMuonsPt_RecA[0][ih];
    
    for (int ifile = 1; ifile <= 5; ifile++) {
      diMuonsInvMass_RecA1[ih]->Add(diMuonsInvMass_RecA[ifile][ih]);
      diMuonsInvMass_GenA1[ih]->Add(diMuonsInvMass_GenA[ifile][ih]);     
      
      diMuonsPt_GenA1[ih]->Add(diMuonsPt_GenA[ifile][ih]); 
      diMuonsPt_RecA1[ih]->Add(diMuonsPt_RecA[ifile][ih]); 
    }
  }
  
  //===========================Fitting===================================================================//
  // Fit ranges
  double mass_low, mass_high;
  double MassUpsilon, WeidthUpsilon;
  
  // Low mass range upsilon width 54 KeV
  MassUpsilon = 9.46; WeidthUpsilon = 0.055;
  //MassUpsilon = 9.46; WeidthUpsilon = 0.068;
  mass_low = 9.0; mass_high = 10.0;  // Fit ranges
  
  // Fit Function crystall ball
  TF1 *GAUSPOL = new TF1("GAUSPOL",CrystalBall,8.0,12.0,6);
  GAUSPOL->SetParNames("Yield (#Upsilon)","BinWidth","Mean","Sigma","#alpha","n");
  GAUSPOL->SetParameter(2, MassUpsilon);
  GAUSPOL->SetParameter(3, WeidthUpsilon);
  //GAUSPOL->SetParLimits(3, 0.1*WeidthUpsilon,2.0*WeidthUpsilon);
  GAUSPOL->SetParameter(4, 1.0);
  GAUSPOL->SetParameter(5, 20.0);
  GAUSPOL->SetLineWidth(2.0);
  GAUSPOL->SetLineColor(2);




  //=====================Loop for eff===========================================================
  double GenNo[100]={0};
  double Eff[100]={0};
  double GenError[100]={0};
  double RecError[100]={0};
  double errEff_cat_S1[100]={0};
  double errEff_cat_S2[100]={0};
  double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
  double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
  char PlotName[500],PlotName1[500], PlotName2[500]; 
  char GPlotName[500],GPlotName1[500], GPlotName2[500];

  for (Int_t ih = 0; ih < Nptbin; ih++) {
   
    cout<<" no of gen dimuons from diMuons Pt histo    "<<diMuonsPt_GenA1[ih]->Integral(1,100)<<endl;
    cout<<" no of gen dimuons from diMuons Mass histo  "<<diMuonsInvMass_GenA1[ih]->Integral(1,100)<<endl;
    

    //from pT histogram
    //gen_pt[ih] =diMuonsPt_GenA1[ih]->IntegralAndError(1,100,genError);
   
    gen_pt[ih] = diMuonsInvMass_GenA1[ih]->IntegralAndError(1,100,genError);
    gen_ptError[ih]= genError;
    
    if(iSpec==1) sprintf(PlotName,"plots/DiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(PlotName,"plots/DiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(PlotName,"plots/DiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(PlotName1,"plots/DiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(PlotName1,"plots/DiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(PlotName1,"plots/DiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(PlotName2,"plots/DiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(PlotName2,"plots/DiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(PlotName2,"plots/DiMuonMass_CentBin_%d.eps",ih);
 

    //giving inetial value for crystall ball fourth parameter 
    diMuonsInvMass_RecA1[ih]->Rebin(2);
    GAUSPOL->SetParameter(0, diMuonsInvMass_RecA1[ih]->Integral(0,50));
    GAUSPOL->FixParameter(1, diMuonsInvMass_RecA1[ih]->GetBinWidth(1));
    
    new TCanvas; 
    diMuonsInvMass_RecA1[ih]->Fit("GAUSPOL","LLMERQ", "", mass_low, mass_high);
   
    double UpsilonMass = GAUSPOL->GetParameter(2);
    double UpsilonWidth = GAUSPOL->GetParameter(3);
   
    double UpsilonYield = GAUSPOL->GetParameter(0);
    double UpsilonYieldError = GAUSPOL->GetParError(0);
 
    double par[20];
    GAUSPOL->GetParameters(par);
    sprintf(namePt_1B,"pt_1B_%d",ih);
    backfun_1 = new TF1(namePt_1B, Pol2, mass_low, mass_high, 3);
    backfun_1->SetParameters(&par[4]);
   

    double MassLow=(UpsilonMass-3*UpsilonWidth);
    double MassHigh=(UpsilonMass+3*UpsilonWidth);
    
    int binlow =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassLow);
    int binhi =diMuonsInvMass_RecA1[ih]->GetXaxis()->FindBin(MassHigh);
    double binwidth=diMuonsInvMass_RecA1[ih]->GetBinWidth(1);
        
    //yield by function 
    //rec_pt[ih] = UpsilonYield;
    //rec_ptError[ih]= UpsilonYieldError;

    cout<<"Rec diMuons from Pt histo "<<diMuonsPt_RecA1[ih]->Integral(1,100)<<endl;  
    cout<<"Rec dimuons from mass "<<diMuonsInvMass_RecA1[ih]->Integral(1,100)<<endl; 
    

      
    //from pT histo
    //rec_pt[ih]=diMuonsPt_RecA1[ih]->IntegralAndError(1, 100,recError);

    //yield by histogram integral
    rec_pt[ih] = diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError);
    rec_ptError[ih]= recError;
  
    //Cal eff 
    Eff_cat_1[ih] = rec_pt[ih]/gen_pt[ih]; 
  
    //calculate error on eff
    GenNo[ih]=gen_pt[ih];
    Eff[ih]= Eff_cat_1[ih];
    GenError[ih]=gen_ptError[ih];
    RecError[ih]=rec_ptError[ih];
    //error    
    errEff_cat_S1_1[ih]= ( (Eff[ih] * Eff[ih]) /(GenNo[ih] * GenNo[ih]) );
    errEff_cat_S1_2[ih]= (RecError[ih] * RecError[ih]);
    errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
   

    errEff_cat_S2_1[ih]= ( (1 - Eff[ih])* (1 - Eff[ih]) ) / ( GenNo[ih] * GenNo[ih]);
    errEff_cat_S2_2[ih]= (GenError[ih] * GenError[ih] ) - ( RecError[ih] * RecError[ih] );


    errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
   

    Err_Eff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
   
    //error for no weights
    //Err_Eff_cat_1[ih]= Eff_cat_1[ih]*TMath::Sqrt(gen_ptError[ih]*gen_ptError[ih]/(gen_pt[ih]*gen_pt[ih]) + rec_ptError[ih]*rec_ptError[ih]/(rec_pt[ih]* rec_pt[ih]));

    cout<<"Upsilon Yield by integral of histo:  "<< diMuonsInvMass_RecA1[ih]->IntegralAndError(binlow, binhi,recError) <<"  error "<< rec_ptError[ih]<<endl; 
    cout<<"UpsilonYield by Gauss yield det:     "<< UpsilonYield << " UpsilonWidth "<< UpsilonWidth<<" UpsilonMass "<<UpsilonMass <<endl;
    cout<<"Upsilon Yield by Function integral:  "<< GAUSPOL->Integral(MassLow,MassHigh)/binwidth <<endl;
    cout<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    //dataFile<<" rec_pt[ih]  "<<  rec_pt[ih] <<" gen_pt[ih] "<<gen_pt[ih]<<endl;
    cout<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    dataFile<<"ih " <<ih<<" eff "<< Eff_cat_1[ih]<<" error "<<Err_Eff_cat_1[ih]<<endl;
    
    if(iSpec==1) sprintf(GPlotName,"plots/GenDiMuonMass_PtBin_%d.png",ih);
    if(iSpec==2) sprintf(GPlotName,"plots/GenDiMuonMass_RapBin_%d.png",ih);
    if(iSpec==3) sprintf(GPlotName,"plots/GenDiMuonMass_CentBin_%d.png",ih);
    
    if(iSpec==1) sprintf(GPlotName1,"plots/GenDiMuonMass_PtBin_%d.pdf",ih);
    if(iSpec==2) sprintf(GPlotName1,"plots/GenDiMuonMass_RapBin_%d.pdf",ih);
    if(iSpec==3) sprintf(GPlotName1,"plots/GenDiMuonMass_CentBin_%d.pdf",ih);
    
    if(iSpec==1) sprintf(GPlotName2,"plots/GenDiMuonMass_PtBin_%d.eps",ih);
    if(iSpec==2) sprintf(GPlotName2,"plots/GenDiMuonMass_RapBin_%d.eps",ih);
    if(iSpec==3) sprintf(GPlotName2,"plots/GenDiMuonMass_CentBin_%d.eps",ih);
       
    backfun_1->SetLineColor(4);
    backfun_1->SetLineWidth(1);
    //backfun_1->Draw("same");
    gPad->Print(PlotName);
    gPad->Print(PlotName1);
    gPad->Print(PlotName2);

    new TCanvas;
    diMuonsInvMass_GenA1[ih]->Draw();
    gPad->Print(GPlotName);
    gPad->Print(GPlotName1);
    gPad->Print(GPlotName2);


    //new TCanvas;
    //diMuonsPt_GenA1[ih]->Draw();
    //new TCanvas;
    //diMuonsPt_RecA1[ih]->Draw();
 
}
  dataFile.close();

  TGraphErrors *Eff_Upsilon = new TGraphErrors(Nptbin, PT, Eff_cat_1, mom_err,Err_Eff_cat_1);
  Eff_Upsilon->SetMarkerStyle(21);
  Eff_Upsilon->SetMarkerColor(2);
  Eff_Upsilon->GetYaxis()->SetTitle("Reco Eff");
 
  if(iSpec==1) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon pT (GeV/c^{2})");
  if(iSpec==2) Eff_Upsilon->GetXaxis()->SetTitle("#Upsilon rapidity");
  if(iSpec==3) Eff_Upsilon->GetXaxis()->SetTitle("bin");
   Eff_Upsilon->GetYaxis()->SetRangeUser(0,1.0);

  TLegend *legend_GP = new TLegend( 0.50,0.79,0.80,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  legend_GP->AddEntry(Eff_Upsilon,"PythiaEvtGen + HydjetBass", "P");
  
  new TCanvas;
  Eff_Upsilon->Draw("AP");
  legend_GP->Draw("Same");
    
  if(iSpec==1){ gPad->Print("plots/Eff_Upsilon_Pt.pdf");gPad->Print("plots/Eff_Upsilon_Pt.png");gPad->Print("plots/Eff_Upsilon_Pt.eps");}
  if(iSpec==2){ gPad->Print("plots/Eff_Upsilon_Rap.pdf");gPad->Print("plots/Eff_Upsilon_Rap.png");  gPad->Print("plots/Eff_Upsilon_Rap.eps");}
  if(iSpec==3){ gPad->Print("plots/Eff_Upsilon_Cent.pdf");gPad->Print("plots/Eff_Upsilon_Cent.png"); gPad->Print("plots/Eff_Upsilon_Cent.eps"); }

}
Beispiel #20
0
void AddHop (){
  cout << "Now we add Hop ! " << endl;
  //TFile * signal_file = new TFile("LeptonU-data-electrons.root", "UPDATE");
  TFile *signal_file = new TFile ("/exp/LHCb/amhis/LeptonU-/tuples/montecarlo/spring16/mars/mc-15154001.root", "UPDATE");
 
  TTree * signalcopy = (TTree*)signal_file->Get("Tuple_Bu2LLK_eeLine2/DecayTree");

  cout << "Number of events in the small tree : " << signalcopy->GetEntries() << endl;
  

ULong64_t eventNumber;


Double_t Lambdab_ENDVERTEX_X ;
Double_t Lambdab_ENDVERTEX_Y ;
Double_t Lambdab_ENDVERTEX_Z ;

Double_t Lambdab_OWNPV_X ;
Double_t Lambdab_OWNPV_Y ;
Double_t Lambdab_OWNPV_Z ;

Double_t Lambdab_FD_OWNPV ;

Double_t Lambdastar_PX ;
Double_t Lambdastar_PY ;
Double_t Lambdastar_PZ ;
Double_t Lambdastar_P ;
Double_t Lambdastar_PE ;

Double_t Jpsi_PX ;
Double_t Jpsi_PY ;
Double_t Jpsi_PZ ;
Double_t Jpsi_P ;

Double_t L1_PX ;
Double_t L1_PY ;
Double_t L1_PZ ;
Double_t L1_P ;

Double_t L2_PX ;
Double_t L2_PY ;
Double_t L2_PZ ;
Double_t L2_P ;



Double_t Proton_PX ;
Double_t Proton_PY ;
Double_t Proton_PZ ;
Double_t Proton_P ;

Double_t Proton_PE ;


Double_t Kaon_PX ;
Double_t Kaon_PY ;
Double_t Kaon_PZ ;
Double_t Kaon_P ;
Double_t Kaon_PE ;


signalcopy->SetBranchAddress("Lambdab_ENDVERTEX_X" ,&Lambdab_ENDVERTEX_X);
signalcopy->SetBranchAddress("Lambdab_ENDVERTEX_Y" ,&Lambdab_ENDVERTEX_Y);
signalcopy->SetBranchAddress("Lambdab_ENDVERTEX_Z" ,&Lambdab_ENDVERTEX_Z);

signalcopy->SetBranchAddress("Lambdab_OWNPV_X" ,&Lambdab_OWNPV_X);
signalcopy->SetBranchAddress("Lambdab_OWNPV_Y" ,&Lambdab_OWNPV_Y);
signalcopy->SetBranchAddress("Lambdab_OWNPV_Z" ,&Lambdab_OWNPV_Z);

signalcopy->SetBranchAddress("Lambdab_FD_OWNPV" ,&Lambdab_FD_OWNPV);

signalcopy->SetBranchAddress("Lambdastar_PX" ,&Lambdastar_PX) ;
signalcopy->SetBranchAddress("Lambdastar_PY" ,&Lambdastar_PY) ;
signalcopy->SetBranchAddress("Lambdastar_PZ" ,&Lambdastar_PZ) ;
signalcopy->SetBranchAddress("Lambdastar_P" ,&Lambdastar_P) ;
signalcopy->SetBranchAddress("Lambdastar_PE" ,&Lambdastar_PE) ;

signalcopy->SetBranchAddress("Jpsi_PX" ,&Jpsi_PX) ;
signalcopy->SetBranchAddress("Jpsi_PY" ,&Jpsi_PY) ;
signalcopy->SetBranchAddress("Jpsi_PZ" ,&Jpsi_PZ) ;
signalcopy->SetBranchAddress("Jpsi_P" ,&Jpsi_P) ;


signalcopy->SetBranchAddress("L1_PX" ,&L1_PX) ;
signalcopy->SetBranchAddress("L1_PY" ,&L1_PY) ;
signalcopy->SetBranchAddress("L1_PZ" ,&L1_PZ) ;
signalcopy->SetBranchAddress("L1_P" ,&L1_P) ;

signalcopy->SetBranchAddress("L2_PX" ,&L2_PX) ;
signalcopy->SetBranchAddress("L2_PY" ,&L2_PY) ;
signalcopy->SetBranchAddress("L2_PZ" ,&L2_PZ) ;
signalcopy->SetBranchAddress("L2_P" ,&L2_P) ;


signalcopy->SetBranchAddress("Kaon_PX" ,&Kaon_PX) ;
signalcopy->SetBranchAddress("Kaon_PY" ,&Kaon_PY) ;
signalcopy->SetBranchAddress("Kaon_PZ" ,&Kaon_PZ) ;
signalcopy->SetBranchAddress("Kaon_P" , &Kaon_P) ;
signalcopy->SetBranchAddress("Kaon_PE" ,&Kaon_PE) ;



signalcopy->SetBranchAddress("Proton_PX" ,&Proton_PX) ;
signalcopy->SetBranchAddress("Proton_PY" ,&Proton_PY) ;
signalcopy->SetBranchAddress("Proton_PZ" ,&Proton_PZ) ;
signalcopy->SetBranchAddress("Proton_P" ,&Proton_P) ;
signalcopy->SetBranchAddress("Proton_PE" ,&Proton_PE) ;






Int_t signumberOfEntries = signalcopy->GetEntries();

const Double_t PDG_e_M = 0.510998910 ;
Float_t Jpsi_SF ;
TLorentzVector KstarMom ;
TLorentzVector ScaledL1Mom ;
TLorentzVector ScaledL2Mom ;
TLorentzVector ScaledJpsiMom ;
TLorentzVector ScaledBMom ;


Float_t val =0.0;
Float_t valMee =0.0;
Float_t HopVal =0.0;

TBranch *newbranch1 = signalcopy->Branch("HOP_Lambdab_MM", &val, "HOP_Lambdab_MM");
TBranch *newbranch2 = signalcopy->Branch("HOP", &HopVal, "HOP") ;
TBranch *newbranch3 = signalcopy->Branch("HOP_Jpsi_MM", &valMee, "HOP_Jpsi_MM");
//TBranch *newbranch4 = signalcopy->Branch("phi_InvMass",&phi_InvMass ,"phi_InvMass");

for (Int_t loopie=0; loopie < signumberOfEntries; ++loopie){
  signalcopy->GetEntry(loopie);


  // compute the pT of the K* wrt to the B line of flight

  Double_t cosThetaKstar = ((Lambdab_ENDVERTEX_X-Lambdab_OWNPV_X)*Lambdastar_PX+(Lambdab_ENDVERTEX_Y-Lambdab_OWNPV_Y)*Lambdastar_PY+(Lambdab_ENDVERTEX_Z-Lambdab_OWNPV_Z)*Lambdastar_PZ)/(Lambdastar_P*Lambdab_FD_OWNPV) ;
  Double_t pTKstar = Lambdastar_P*TMath::Sqrt(1.-cosThetaKstar*cosThetaKstar) ;
  Double_t cosThetaY = ((Lambdab_ENDVERTEX_X-Lambdab_OWNPV_X)*Jpsi_PX+(Lambdab_ENDVERTEX_Y-Lambdab_OWNPV_Y)*Jpsi_PY+ (Lambdab_ENDVERTEX_Z-Lambdab_OWNPV_Z)*Jpsi_PZ)/(Jpsi_P*Lambdab_FD_OWNPV);
  Double_t pTY = Jpsi_P*TMath::Sqrt(1.-cosThetaY*cosThetaY) ;

  Jpsi_SF = pTKstar/pTY;

  HopVal = Jpsi_SF ;

  ScaledL1Mom.SetXYZM( Jpsi_SF*L1_PX, Jpsi_SF*L1_PY, Jpsi_SF*L1_PZ, PDG_e_M );
  ScaledL2Mom.SetXYZM( Jpsi_SF*L2_PX, Jpsi_SF*L2_PY, Jpsi_SF*L2_PZ, PDG_e_M );
  KstarMom.SetPxPyPzE( Lambdastar_PX, Lambdastar_PY, Lambdastar_PZ, Lambdastar_PE );
  ScaledBMom = ScaledL1Mom + ScaledL2Mom + KstarMom  ;
  ScaledJpsiMom = ScaledL1Mom + ScaledL2Mom ;
  val = ScaledBMom.M();
  valMee = ScaledJpsiMom.M();
  newbranch1->Fill();
  newbranch2->Fill();
  newbranch3->Fill();
  //newbranch4->Fill();
}
signal_file->Write();







  return;


}
Beispiel #21
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;
}
Beispiel #22
0
void AnalyseEvents(ExRootTreeReader *treeReader, TestPlots *plots)
{
  TClonesArray *branchParticle = treeReader->UseBranch("Particle");
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchPhoton = treeReader->UseBranch("Photon");
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");

  TClonesArray *branchEFlowTrack = treeReader->UseBranch("EFlowTrack");  // These 3 are used in finding reco jets
  TClonesArray *branchEFlowTower = treeReader->UseBranch("EFlowTower");  // 
  TClonesArray *branchEFlowMuon = treeReader->UseBranch("EFlowMuon");    // 
  TClonesArray *branchJet = treeReader->UseBranch("Jet");

  //  Long64_t allEntries = treeReader->GetEntries();
  Long64_t allEntries = 1000;

  cout << "** Chain contains " << allEntries << " events" << endl;

  GenParticle *particle;
  Electron *electron;
  Photon *photon;
  Muon *muon;

  Track *track;
  Tower *tower;

  Jet *jet;
  TObject *object;

  TLorentzVector momentum;

  Float_t Eem, Ehad;
  Bool_t skip;

  Long64_t entry;

  Int_t i, j, pdgCode;

  // Loop over all events
  for(entry = 0; entry < allEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);

    std::cout << "\n ** NEW ENTRY ** : " << entry << std::endl;

    // Loop over all electrons in event
    for(i = 0; i < branchElectron->GetEntriesFast(); ++i)
    {
      electron = (Electron*) branchElectron->At(i);
      particle = (GenParticle*) electron->Particle.GetObject();

      plots->fElectronDeltaPT->Fill((particle->PT - electron->PT)/particle->PT);
      plots->fElectronDeltaEta->Fill((particle->Eta - electron->Eta)/particle->Eta);
    }

    // Loop over all photons in event
    for(i = 0; i < branchPhoton->GetEntriesFast(); ++i)
    {
      photon = (Photon*) branchPhoton->At(i);

      // skip photons with references to multiple particles
      if(photon->Particles.GetEntriesFast() != 1) continue;

      particle = (GenParticle*) photon->Particles.At(0);

      plots->fPhotonDeltaPT->Fill((particle->PT - photon->PT)/particle->PT);
      plots->fPhotonDeltaEta->Fill((particle->Eta - photon->Eta)/particle->Eta);
      plots->fPhotonDeltaE->Fill((particle->E - photon->E)/particle->E);
    }

    // Loop over all muons in event
    for(i = 0; i < branchMuon->GetEntriesFast(); ++i)
    {
      muon = (Muon*) branchMuon->At(i);
      particle = (GenParticle*) muon->Particle.GetObject();

      plots->fMuonDeltaPT->Fill((particle->PT - muon->PT)/particle->PT);
      plots->fMuonDeltaEta->Fill((particle->Eta - muon->Eta)/particle->Eta);
    }

    // Loop over all tracks in event
    for(i = 0; i < branchEFlowTrack->GetEntriesFast(); ++i)
    {
      track = (Track*) branchEFlowTrack->At(i);
      particle = (GenParticle*) track->Particle.GetObject();

      plots->fTrackDeltaPT->Fill((particle->PT - track->PT)/particle->PT);
      plots->fTrackDeltaEta->Fill((particle->Eta - track->Eta)/particle->Eta);
    }

    // Loop over all towers in event
    for(i = 0; i < branchEFlowTower->GetEntriesFast(); ++i)
    {
      tower = (Tower*) branchEFlowTower->At(i);

      Eem = 0.0;           // Electromagnetic tower energy
      Ehad = 0.0;          // Hadronic tower energy
      skip = kFALSE;
      for(j = 0; j < tower->Particles.GetEntriesFast(); ++j)
      {
        particle = (GenParticle*) tower->Particles.At(j);
        pdgCode = TMath::Abs(particle->PID);

        // skip muons and neutrinos
        if(pdgCode == 12 || pdgCode == 13 || pdgCode == 14 || pdgCode == 16)
        {
          continue;
        }

        // skip K0short and Lambda
        if(pdgCode == 310 || pdgCode == 3122)
        {
          skip = kTRUE;
        }

        if(pdgCode == 11 || pdgCode == 22)         // For electrons and photons
        {
          Eem += particle->E;                      // Sum the electrons/photons energy
        }
        else                                       // Rest detected should be all hadronic
        {
          Ehad += particle->E;                     // Sum hadronic particle energy
        }
      }
      if(skip) continue;
      if(Eem > 0.0 && tower->Eem > 0.0) plots->fTowerDeltaEem->Fill((Eem - tower->Eem)/Eem); // Compare energy of EM particle at tower with EM energy of tower
      if(Ehad > 0.0 && tower->Ehad > 0.0) plots->fTowerDeltaEhad->Fill((Ehad - tower->Ehad)/Ehad);
    }

    // Loop over all jets in event. Up to here successfully returns the PT of ecah jet per event 
    for(i = 0; i < branchJet->GetEntriesFast(); ++i)
    {
      
      std::cout << "\nNew jet" << std::endl;

      jet = (Jet*) branchJet->At(i);

      momentum.SetPxPyPzE(0.0, 0.0, 0.0, 0.0);

      //      std::cout << jet->PT << std::endl;

      // Loop over all jet's constituents
      for(j = 0; j < jet->Constituents.GetEntriesFast(); ++j)
      {
        object = jet->Constituents.At(j);



        // Check if the constituent is accessible, if object exists then continue
        if(object == 0) continue;
	

        if(object->IsA() == GenParticle::Class())
        {
          momentum += ((GenParticle*) object)->P4();
	  std::cout << "momentum:" << momentum.Pt() << std::endl;
	}
        else if(object->IsA() == Track::Class())
        {
          momentum += ((Track*) object)->P4();
	  std::cout << "momentum2: " << momentum.Pt() << std::endl;
        }
        else if(object->IsA() == Tower::Class())
        {
          momentum += ((Tower*) object)->P4();
	  std::cout << "momentum3 :" << momentum.Pt() << std::endl;
        }
        else if(object->IsA() == Muon::Class())
        {
          momentum += ((Muon*) object)->P4();
	  std::cout << "momentum4: " << momentum.Pt() << std::endl;
        }
      }
      std::cout << "Jet PT : " << jet->PT << std::endl;
      plots->fJetDeltaPT->Fill((jet->PT - momentum.Pt())/jet->PT );
    }
  }
}
Beispiel #23
0
void rochcor_42X::momcor_mc( TLorentzVector& mu, float charge, float sysdev, int runopt){
  
  //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 = 0.0;
  float da = 0.0;
  
  if(runopt == 0){
    dm = (mcor_bfA[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfAer[mu_phibin][mu_etabin])/mmavgA[mu_phibin][mu_etabin];
    da = mcor_maA[mu_phibin][mu_etabin] + mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maAer[mu_phibin][mu_etabin];
  }else if(runopt == 1){
    dm = (mcor_bfB[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfBer[mu_phibin][mu_etabin])/mmavgB[mu_phibin][mu_etabin];
    da = mcor_maB[mu_phibin][mu_etabin] + mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maBer[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 recm = 0.0;
  float drecm = 0.0; 
  float delta = 0.0;
  float sf = 0.0;

  float gscler = 0.0;
  float deltaer = 0.0;
  float sfer = 0.0;
  
  if(runopt==0){
    recm = recmA;
    drecm = drecmA;
    
    delta = deltaA;
    sf = sfA;
    
    gscler = TMath::Sqrt( TMath::Power(mgsclA_stat,2) + TMath::Power(mgsclA_syst,2) );
    deltaer = TMath::Sqrt( TMath::Power(deltaA_stat,2) + TMath::Power(deltaA_syst,2) );
    sfer = TMath::Sqrt( TMath::Power(sfA_stat,2) + TMath::Power(sfA_syst,2) );
  }else if(runopt==1){
    recm = recmB;
    drecm = drecmB;
    
    delta = deltaB;
    sf = sfB;
    
    gscler = TMath::Sqrt( TMath::Power(mgsclB_stat,2) + TMath::Power(mgsclB_syst,2) );
    deltaer = TMath::Sqrt( TMath::Power(deltaB_stat,2) + TMath::Power(deltaB_syst,2) );
    sfer = TMath::Sqrt( TMath::Power(sfB_stat,2) + TMath::Power(sfB_syst,2) );
  }
  
  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);   
      
  float gscl = (genm_smr/recm);
  
  px *= (gscl + sysdev*gscler);
  py *= (gscl + sysdev*gscler);
  pz *= (gscl + sysdev*gscler);
  e  *= (gscl + sysdev*gscler);
  
  mu.SetPxPyPzE(px,py,pz,e);
  
}
double get_csv_wgt( vvdouble jets, vdouble jetCSV, vint jetFlavor, int iSys, double &csvWgtHF, double &csvWgtLF, double &csvWgtCF ){

  int iSysHF = 0;
  switch(iSys){
  case 11: iSysHF=1; break;
  case 12: iSysHF=2; break;
  case 17: iSysHF=3; break;
  case 18: iSysHF=4; break;
  case 21: iSysHF=5; break;
  case 22: iSysHF=6; break;
  case 25: iSysHF=7; break;
  case 26: iSysHF=8; break;
  default : iSysHF = 0; break;
  }

  int iSysC = 0;
  switch(iSys){
  case 29: iSysC=1; break;
  case 30: iSysC=2; break;
  case 31: iSysC=3; break;
  case 32: iSysC=4; break;
  default : iSysC = 0; break;
  }

  int iSysLF = 0;
  switch(iSys){
  case 11: iSysLF=1; break;
  case 12: iSysLF=2; break;
  case 19: iSysLF=3; break;
  case 20: iSysLF=4; break;
  case 23: iSysLF=5; break;
  case 24: iSysLF=6; break;
  case 27: iSysLF=7; break;
  case 28: iSysLF=8; break;
  default : iSysLF = 0; break;
  }

  double csvWgthf = 1.;
  double csvWgtC  = 1.;
  double csvWgtlf = 1.;

  for( int iJet=0; iJet<int(jets.size()); iJet++ ){
    TLorentzVector myJet;
    myJet.SetPxPyPzE( jets[iJet][0], jets[iJet][1], jets[iJet][2], jets[iJet][3] );
	  
    double csv = jetCSV[iJet];
    double jetPt = myJet.Pt();
    double jetAbsEta = fabs(myJet.Eta());
    int flavor = jetFlavor[iJet];

    int iPt = -1; int iEta = -1;
    if (jetPt >=19.99 && jetPt<30) iPt = 0;
    else if (jetPt >=30 && jetPt<40) iPt = 1;
    else if (jetPt >=40 && jetPt<60) iPt = 2;
    else if (jetPt >=60 && jetPt<100) iPt = 3;
    else if (jetPt >=100 && jetPt<160) iPt = 4;
    else if (jetPt >=160 && jetPt<10000) iPt = 5;

    if (jetAbsEta >=0 &&  jetAbsEta<0.8 ) iEta = 0;
    else if ( jetAbsEta>=0.8 && jetAbsEta<1.6 )  iEta = 1;
    else if ( jetAbsEta>=1.6 && jetAbsEta<2.41 ) iEta = 2;

    if (iPt < 0 || iEta < 0) std::cout << "Error, couldn't find Pt, Eta bins for this b-flavor jet, jetPt = " << jetPt << ", jetAbsEta = " << jetAbsEta << std::endl;

    if (abs(flavor) == 5 ){
      int useCSVBin = (csv>=0.) ? h_csv_wgt_hf[iSysHF][iPt]->FindBin(csv) : 1;
      double iCSVWgtHF = h_csv_wgt_hf[iSysHF][iPt]->GetBinContent(useCSVBin);
      if( iCSVWgtHF!=0 ) csvWgthf *= iCSVWgtHF;

      // if( iSysHF==0 ) printf(" iJet,\t flavor=%d,\t pt=%.1f,\t eta=%.2f,\t csv=%.3f,\t wgt=%.2f \n",
      // 			     flavor, jetPt, iJet->eta, csv, iCSVWgtHF );
    }
    else if( abs(flavor) == 4 ){
      int useCSVBin = (csv>=0.) ? c_csv_wgt_hf[iSysC][iPt]->FindBin(csv) : 1;
      double iCSVWgtC = c_csv_wgt_hf[iSysC][iPt]->GetBinContent(useCSVBin);
      if( iCSVWgtC!=0 ) csvWgtC *= iCSVWgtC;
      // if( iSysC==0 ) printf(" iJet,\t flavor=%d,\t pt=%.1f,\t eta=%.2f,\t csv=%.3f,\t wgt=%.2f \n",
      //      flavor, jetPt, iJet->eta, csv, iCSVWgtC );
    }
    else {
      if (iPt >=3) iPt=3;       /// [30-40], [40-60] and [60-10000] only 3 Pt bins for lf
      int useCSVBin = (csv>=0.) ? h_csv_wgt_lf[iSysLF][iPt][iEta]->FindBin(csv) : 1;
      double iCSVWgtLF = h_csv_wgt_lf[iSysLF][iPt][iEta]->GetBinContent(useCSVBin);
      if( iCSVWgtLF!=0 ) csvWgtlf *= iCSVWgtLF;

      // if( iSysLF==0 ) printf(" iJet,\t flavor=%d,\t pt=%.1f,\t eta=%.2f,\t csv=%.3f,\t wgt=%.2f \n",
      // 			     flavor, jetPt, iJet->eta, csv, iCSVWgtLF );
    }
  }

  double csvWgtTotal = csvWgthf * csvWgtC * csvWgtlf;

  csvWgtHF = csvWgthf;
  csvWgtLF = csvWgtlf;
  csvWgtCF = csvWgtC;

  return csvWgtTotal;
}
void csvSF_treeReader_13TeV( bool isHF=1, int verNum = 0, int insample=1, int maxNentries=-1, int Njobs=1, int jobN=1, double intLumi=-1 ) {

  std::string inputFileHF = "data/csv_rwt_hf_IT.root";
  std::string inputFileLF = "data/csv_rwt_lf_IT.root";

  if( verNum>0 ){
    inputFileHF = Form("CSVHistoFiles/csv_rwt_fit_hf_v%i.root", verNum-1);
    inputFileLF = Form("CSVHistoFiles/csv_rwt_fit_lf_v%i.root", verNum-1);

    std::cout << "\t inputFileHF = " << inputFileHF << std::endl;
    std::cout << "\t inputFileLF = " << inputFileLF << std::endl;
  }

  TFile* f_CSVwgt_HF = new TFile ((string(getenv("CMSSW_BASE")) + "/src/ttH-LeptonPlusJets/AnalysisCode/" + inputFileHF).c_str());
  TFile* f_CSVwgt_LF = new TFile ((string(getenv("CMSSW_BASE")) + "/src/ttH-LeptonPlusJets/AnalysisCode/" + inputFileLF).c_str());

  fillCSVhistos(f_CSVwgt_HF, f_CSVwgt_LF);

  std::cout << " ###===> iteration version " << verNum << std::endl;

  ////
  std::cout << "   ===> load the root files! " << std::endl;

  std::string sampleType = ( insample>=0 ) ? "mc" : "data";
  std::string str_jobN;
  std::stringstream stream;
  stream << jobN;
  str_jobN = stream.str();

  //https://twiki.cern.ch/twiki/bin/viewauth/CMS/StandardModelCrossSectionsat13TeV
  double mySample_xSec_ = 1.;
  double mySample_nGen_ = 1.;
  std::string mySample_sampleName_ = "delete";
  std::string mySample_inputDir_ = "";
  if( insample==2500 ){
    mySample_xSec_ = 831.76;//https://twiki.cern.ch/twiki/bin/view/LHCPhysics/TtbarNNLO
    mySample_nGen_ = 25446993;
    mySample_sampleName_ = "TTJets";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_005136/0000/";
    //mySample_inputDir_ = "/uscms_data/d2/dpuigh/TTH/miniAOD/CMSSW_7_2_3/src/ttH-LeptonPlusJets/YggdrasilTreeMaker/";
  }
  else if( insample==2300 ){
    mySample_xSec_ = 2008.4; 
    mySample_nGen_ = 2829164;
    mySample_sampleName_ = "DYJetsToLL";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/DYJetsToLL_M-50_13TeV-madgraph-pythia8/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150216_233924/0000/";
  }
  else if( insample==2400 ){
    mySample_xSec_ = 20508.9;  
    mySample_nGen_ = 10017462;
    mySample_sampleName_ = "WJetsToLNu";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_010312/0000/";
  }
  else if( insample==2524 ){
    mySample_xSec_ = 1.152;  
    mySample_nGen_ = 246521;
    mySample_sampleName_ = "TTWJets";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TTWJets_Tune4C_13TeV-madgraph-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_005352/0000/";
  }
  else if( insample==2523 ){
    mySample_xSec_ = 2.232;  
    mySample_nGen_ = 249275;
    mySample_sampleName_ = "TTZJets";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TTZJets_Tune4C_13TeV-madgraph-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_005607/0000/";
  }
  else if( insample==2510 ){
    mySample_xSec_ = 2.232;  
    mySample_nGen_ = 500000;
    mySample_sampleName_ = "TToLeptons_s";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_005853/0000/";
  }
  else if( insample==2511 ){
    mySample_xSec_ = 2.232;  
    mySample_nGen_ = 250000;
    mySample_sampleName_ = "TBarToLeptons_s";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TBarToLeptons_s-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_004555/0000/";
  }
  else if( insample==2512 ){
    mySample_xSec_ = 2.232;  
    mySample_nGen_ = 3991000;
    mySample_sampleName_ = "TToLeptons_t";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TToLeptons_t-channel-CSA14_Tune4C_13TeV-aMCatNLO-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_005929/0000/";
  }
  else if( insample==2513 ){
    mySample_xSec_ = 2.232;  
    mySample_nGen_ = 1999800;
    mySample_sampleName_ = "TBarToLeptons_t";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TBarToLeptons_t-channel_Tune4C_CSA14_13TeV-aMCatNLO-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_004732/0000/";
  }
  else if( insample==2514 ){
    mySample_xSec_ = 35.6;  
    mySample_nGen_ = 986100;
    mySample_sampleName_ = "T_tW_DR";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/T_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_010006/0000/";
  }
  else if( insample==2515 ){
    mySample_xSec_ = 35.6;  
    mySample_nGen_ = 971800;
    mySample_sampleName_ = "Tbar_tW_DR";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/Tbar_tW-channel-DR_Tune4C_13TeV-CSA14-powheg-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1_yggdrasilTree_v1/150217_010035/0000/";
  }
  else if( insample==9125 ){
    mySample_xSec_ = 0.5085 * 1.0;// YR3 * BR(all)  
    mySample_nGen_ = 199700;//199000;
    mySample_sampleName_ = "TTbarH_M-125_13TeV_amcatnlo-pythia8-tauola_PU20bx25_tsg_PHYS14_25_V1-v2";
    mySample_inputDir_ = "/eos/uscms/store/user/puigh/TTbarH_M-125_13TeV_amcatnlo-pythia8-tauola/Phys14DR-PU20bx25_tsg_PHYS14_25_V1-v2_v1_yggdrasilTree_v1/150217_004834/0000/";
  }


  std::string treefilename = mySample_inputDir_ + "yggdrasil_treeMaker*.root";


  std::string s_end = "_histo_" + str_jobN + ".root";
  if( Njobs==1 ) s_end = "_histo.root";


  std::string histofilename = Form("CSVHistoFiles/csv_rwt_hf_%s_v%i%s",mySample_sampleName_.c_str(),verNum, s_end.c_str());
  if( !isHF ) histofilename = Form("CSVHistoFiles/csv_rwt_lf_%s_v%i%s",mySample_sampleName_.c_str(),verNum, s_end.c_str());

  std::cout << "  treefilename  = " << treefilename.c_str() << std::endl;
  std::cout << "  histofilename = " << histofilename.c_str() << std::endl;

  TChain *chain = new TChain("ttHTreeMaker/worldTree");
  chain->Add(treefilename.c_str());


  //////////////////////////////////////////////////////////////////////////
  ///  Tree branches/leaves
  //////////////////////////////////////////////////////////////////////////

  yggdrasilEventVars *eve=0;
  chain->SetBranchAddress("eve.", &eve );

  //////////////////////////////////////////////////////////////////////////
  ///  Histogram making
  //////////////////////////////////////////////////////////////////////////


  TFile histofile(histofilename.c_str(),"recreate");
  histofile.cd();


  bool verbose = false;

  //////////////////////////////////////////////////////////////////////////
  ///  Histograms
  //////////////////////////////////////////////////////////////////////////

  TH1::SetDefaultSumw2();

  TH1D* h_first_jet_pt  = new TH1D("h_first_jet_pt",";first jet p_{T}", 100, 0., 500. );
  TH1D* h_first_jet_eta = new TH1D("h_first_jet_eta",";first jet #eta", 70, -3.5, 3.5 );
  TH1D* h_first_jet_csv = new TH1D("h_first_jet_csv",";first jet CSV", 102, -0.01, 1.01 );
  TH1D* h_first_jet_flavour = new TH1D("h_first_jet_flavour",";first jet flavour", 28, -6, 22 );
  TH1D* h_first_jet_vtxMass = new TH1D("h_first_jet_vtxMass",";first jet vertex mass", 80, 0., 8.0 );
  TH1D* h_first_jet_vtxNtracks = new TH1D("h_first_jet_vtxNtracks",";first jet vertex number of tracks", 14, -0.5, 13.5 );
  TH1D* h_first_jet_vtx3DVal = new TH1D("h_first_jet_vtx3DVal",";first jet vertex 3D value", 141, -0.01, 14.0 );
  TH1D* h_first_jet_vtx3DSig = new TH1D("h_first_jet_vtx3DSig",";first jet vertex 3D significance", 401, -0.01, 400 );
  TH1D* h_first_jet_vtxMass_b = new TH1D("h_first_jet_vtxMass_b",";first jet vertex mass", 80, 0., 8.0 );
  TH1D* h_first_jet_vtxMass_c = new TH1D("h_first_jet_vtxMass_c",";first jet vertex mass", 80, 0., 8.0 );
  TH1D* h_first_jet_vtxMass_l = new TH1D("h_first_jet_vtxMass_l",";first jet vertex mass", 80, 0., 8.0 );
  TH1D* h_first_jet_vtxMass_o = new TH1D("h_first_jet_vtxMass_o",";first jet vertex mass", 80, 0., 8.0 );

  TH1D* h_second_jet_pt  = new TH1D("h_second_jet_pt",";second jet p_{T}", 100, 0., 500. );
  TH1D* h_second_jet_eta = new TH1D("h_second_jet_eta",";second jet #eta", 70, -3.5, 3.5 );
  TH1D* h_second_jet_csv = new TH1D("h_second_jet_csv",";second jet CSV", 102, -0.01, 1.01 );
  TH1D* h_second_jet_flavour = new TH1D("h_second_jet_flavour",";second jet flavour", 28, -6, 22 );
  TH1D* h_second_jet_vtxMass = new TH1D("h_second_jet_vtxMass",";second jet vertex mass", 80, 0., 8.0 );
  TH1D* h_second_jet_vtxNtracks = new TH1D("h_second_jet_vtxNtracks",";second jet vertex number of tracks", 14, -0.5, 13.5 );
  TH1D* h_second_jet_vtx3DVal = new TH1D("h_second_jet_vtx3DVal",";second jet vertex 3D value", 141, -0.01, 14.0 );
  TH1D* h_second_jet_vtx3DSig = new TH1D("h_second_jet_vtx3DSig",";second jet vertex 3D significance", 401, -0.01, 400 );
  TH1D* h_second_jet_vtxMass_b = new TH1D("h_second_jet_vtxMass_b",";second jet vertex mass", 80, 0., 8.0 );
  TH1D* h_second_jet_vtxMass_c = new TH1D("h_second_jet_vtxMass_c",";second jet vertex mass", 80, 0., 8.0 );
  TH1D* h_second_jet_vtxMass_l = new TH1D("h_second_jet_vtxMass_l",";second jet vertex mass", 80, 0., 8.0 );
  TH1D* h_second_jet_vtxMass_o = new TH1D("h_second_jet_vtxMass_o",";second jet vertex mass", 80, 0., 8.0 );



  TH2D* h_first_jet_csv_vtxMass = new TH2D("h_first_jet_csv_vtxMass",";first jet CSV;first jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_first_jet_csv_vtxMass_b = new TH2D("h_first_jet_csv_vtxMass_b",";first jet CSV;first jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_first_jet_csv_vtxMass_c = new TH2D("h_first_jet_csv_vtxMass_c",";first jet CSV;first jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_first_jet_csv_vtxMass_l = new TH2D("h_first_jet_csv_vtxMass_l",";first jet CSV;first jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_first_jet_csv_vtxMass_o = new TH2D("h_first_jet_csv_vtxMass_o",";first jet CSV;first jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );

  TH2D* h_second_jet_csv_vtxMass = new TH2D("h_second_jet_csv_vtxMass",";second jet CSV;second jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_second_jet_csv_vtxMass_b = new TH2D("h_second_jet_csv_vtxMass_b",";second jet CSV;second jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_second_jet_csv_vtxMass_c = new TH2D("h_second_jet_csv_vtxMass_c",";second jet CSV;second jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_second_jet_csv_vtxMass_l = new TH2D("h_second_jet_csv_vtxMass_l",";second jet CSV;second jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );
  TH2D* h_second_jet_csv_vtxMass_o = new TH2D("h_second_jet_csv_vtxMass_o",";second jet CSV;second jet vertex mass", 102, -0.01, 1.01, 80, 0., 8.0 );

  TH1D* h_minDR_lepton_first_jet  = new TH1D("h_minDR_lepton_first_jet",";min #DeltaR(lepton, first jet)", 102, -0.01, 6.01 );
  TH1D* h_minDR_lepton_second_jet = new TH1D("h_minDR_lepton_second_jet",";min #DeltaR(lepton, second jet)", 102, -0.01, 6.01 );

  TH1D* h_second_jet_eta_TwoMuon = new TH1D("h_second_jet_eta_TwoMuon",";second jet #eta", 70, -3.5, 3.5 );
  TH1D* h_second_jet_eta_TwoElectron = new TH1D("h_second_jet_eta_TwoElectron",";second jet #eta", 70, -3.5, 3.5 );
  TH1D* h_second_jet_eta_MuonElectron = new TH1D("h_second_jet_eta_MuonElectron",";second jet #eta", 70, -3.5, 3.5 );

  TH2D* h_second_jet_pt_eta = new TH2D("h_second_jet_pt_eta",";second jet #eta;second jet p_{T}", 70, -3.5, 3.5, 100, 0., 500. );
  TH2D* h_second_jet_flavour_eta = new TH2D("h_second_jet_flavour_eta",";second jet #eta;second flavour", 70, -3.5, 3.5, 28, -6, 22 );

  TH1D* h_mass_lepton_first_jet  = new TH1D("h_mass_lepton_first_jet",";first jet + lepton mass", 100, 0., 200. );
  TH1D* h_mass_lepton_second_jet  = new TH1D("h_mass_lepton_second_jet",";second jet + lepton mass", 100, 0., 200. );
  TH1D* h_mass_tight_lepton_first_jet  = new TH1D("h_mass_tight_lepton_first_jet",";first jet + tight lepton mass", 100, 0., 200. );
  TH1D* h_mass_tight_lepton_second_jet  = new TH1D("h_mass_tight_lepton_second_jet",";second jet + tight lepton mass", 100, 0., 200. );

  TH2D* h_mass_lepton_second_jet_eta  = new TH2D("h_mass_lepton_second_jet_eta",";second jet #eta;second jet + lepton mass", 70, -3.5, 3.5, 100, 0., 200. );


  int NumCutsHF = 10;
  TH1D* h_hf_event_selection  = new TH1D("h_hf_event_selection",";cut", NumCutsHF, 0, NumCutsHF );

  h_hf_event_selection->GetXaxis()->SetBinLabel(1,"All");
  h_hf_event_selection->GetXaxis()->SetBinLabel(2,"==2 jets");
  h_hf_event_selection->GetXaxis()->SetBinLabel(3,"Dilepton trigger");
  h_hf_event_selection->GetXaxis()->SetBinLabel(4,"==2 leptons");
  h_hf_event_selection->GetXaxis()->SetBinLabel(5,"Opposite charge");
  h_hf_event_selection->GetXaxis()->SetBinLabel(6,"#Delta R(lep,lep) > 0.2");
  h_hf_event_selection->GetXaxis()->SetBinLabel(7,"M(lep,lep) > 12");
  h_hf_event_selection->GetXaxis()->SetBinLabel(8,"ZVeto");
  h_hf_event_selection->GetXaxis()->SetBinLabel(9,"MET > 50");
  h_hf_event_selection->GetXaxis()->SetBinLabel(10,"jet passes medium b-tag");

  int NumCutsLF = 10;
  TH1D* h_lf_event_selection  = new TH1D("h_lf_event_selection",";cut", NumCutsLF, 0, NumCutsLF );

  h_lf_event_selection->GetXaxis()->SetBinLabel(1,"All");
  h_lf_event_selection->GetXaxis()->SetBinLabel(2,"==2 jets");
  h_lf_event_selection->GetXaxis()->SetBinLabel(3,"Dilepton trigger");
  h_lf_event_selection->GetXaxis()->SetBinLabel(4,"==2 leptons");
  h_lf_event_selection->GetXaxis()->SetBinLabel(5,"Opposite charge");
  h_lf_event_selection->GetXaxis()->SetBinLabel(6,"#Delta R(lep,lep) > 0.2");
  h_lf_event_selection->GetXaxis()->SetBinLabel(7,"M(lep,lep) > 12");
  h_lf_event_selection->GetXaxis()->SetBinLabel(8,"Zmass window");
  h_lf_event_selection->GetXaxis()->SetBinLabel(9,"MET < 30");
  h_lf_event_selection->GetXaxis()->SetBinLabel(10,"jet fails loose b-tag");

  TH1D* h_numLooseLeptons = new TH1D("h_numLooseLeptons",";number of loose leptons", 5, 0, 5 );

  // single jet specific plots
  int nPt = 6;
  int nEta = 1;
  if ( !isHF ){
    nPt = 4; nEta = 3;
  }


  //////
  TH1D* h_Data_jet_csv[6][3];
  TH1D* h_MC_b_jet_csv[6][3];
  TH1D* h_MC_nonb_jet_csv[6][3];

  TH1D* h_MC_b_jet_vtxMass[6][3];
  TH1D* h_MC_nonb_jet_vtxMass[6][3];

  TH2D* h_MC_b_jet_csv_vtxMass[6][3];
  TH2D* h_MC_nonb_jet_csv_vtxMass[6][3];


  /////
  int nBins = 18; //Number of bins 
  double xBins_hf[19] = {-10.0, 0.0, 0.122, 0.244, 0.331, 0.418, 0.505, 0.592, 0.679, 0.7228, 0.7666, 0.8104, 0.8542, 0.898, 0.9184, 0.9388, 0.9592, 0.9796, 1.01};

  if(!isHF) nBins = 21;
  double xBins_lf[22] = {-10.0, 0.0, 0.04, 0.08, 0.12, 0.16, 0.2, 0.244, 0.331, 0.418, 0.505, 0.592, 0.679, 0.752, 0.825, 0.898, 0.915, 0.932, 0.949, 0.966, 0.983, 1.01};
 


  for ( int iPt=0; iPt<nPt; iPt++){
    for ( int iEta=0; iEta<nEta; iEta++){

      TString h_Data_Name = Form("csv_Data_Pt%i_Eta%i",iPt,iEta);
      TString h_b_Name = Form("csv_MC_bjets_Pt%i_Eta%i",iPt,iEta);
      TString h_nonb_Name = Form("csv_MC_nonbjets_Pt%i_Eta%i",iPt,iEta);

      TString h_vtxMass_b_Name = Form("vtxMass_MC_bjets_Pt%i_Eta%i",iPt,iEta);
      TString h_vtxMass_nonb_Name = Form("vtxMass_MC_nonbjets_Pt%i_Eta%i",iPt,iEta);

      if ( isHF ){
	h_Data_jet_csv[iPt][iEta] = new TH1D(h_Data_Name, h_Data_Name, nBins, xBins_hf); 
	h_MC_b_jet_csv[iPt][iEta] = new TH1D(h_b_Name, h_b_Name, nBins, xBins_hf); 
	h_MC_nonb_jet_csv[iPt][iEta] = new TH1D(h_nonb_Name, h_nonb_Name, nBins, xBins_hf); 

	h_MC_b_jet_vtxMass[iPt][iEta] = new TH1D(h_vtxMass_b_Name, h_vtxMass_b_Name, 16, 0., 8.0); 
	h_MC_nonb_jet_vtxMass[iPt][iEta] = new TH1D(h_vtxMass_nonb_Name, h_vtxMass_nonb_Name, 16, 0., 8.0); 

	h_MC_b_jet_csv_vtxMass[iPt][iEta] = new TH2D("csv_"+h_vtxMass_b_Name, "csv_"+h_vtxMass_b_Name, nBins, xBins_hf, 16, 0., 8.0); 
	h_MC_nonb_jet_csv_vtxMass[iPt][iEta] = new TH2D("csv_"+h_vtxMass_nonb_Name, "csv_"+h_vtxMass_nonb_Name, nBins, xBins_hf, 16, 0., 8.0); 
      }
      else { 
	h_Data_jet_csv[iPt][iEta] = new TH1D(h_Data_Name, h_Data_Name, nBins, xBins_lf); 
	h_MC_b_jet_csv[iPt][iEta] = new TH1D(h_b_Name, h_b_Name, nBins, xBins_lf); 
	h_MC_nonb_jet_csv[iPt][iEta] = new TH1D(h_nonb_Name, h_nonb_Name, nBins, xBins_lf); 

	h_MC_b_jet_vtxMass[iPt][iEta] = new TH1D(h_vtxMass_b_Name, h_vtxMass_b_Name, 16, 0., 8.0); 
	h_MC_nonb_jet_vtxMass[iPt][iEta] = new TH1D(h_vtxMass_nonb_Name, h_vtxMass_nonb_Name, 16, 0., 8.0); 

	h_MC_b_jet_csv_vtxMass[iPt][iEta] = new TH2D("csv_"+h_vtxMass_b_Name, "csv_"+h_vtxMass_b_Name, nBins, xBins_lf, 16, 0., 8.0); 
	h_MC_nonb_jet_csv_vtxMass[iPt][iEta] = new TH2D("csv_"+h_vtxMass_nonb_Name, "csv_"+h_vtxMass_nonb_Name, nBins, xBins_lf, 16, 0., 8.0); 
      }   
    }
  }

  //////////////////////////////////////////////////////////////////////////
  /////
  //////////////////////////////////////////////////////////////////////////
 
  int numEvents_all=0;
  int numEvents_2jets=0;

  int numEvents_lepselection2=0;
  int numEvents_lepselection1a=0;
  int numEvents_lepselection1b=0;
  int numEvents_lepselection1c=0;

  int numEvents_exselection=0;

  int nentries = chain->GetEntries();
  std::cout << "\n\t Number of entries = " << nentries << std::endl;
  std::cout << "\t Max number of entries = " << maxNentries << std::endl;
  std::cout << "\n" << std::endl;

  int use_nentries = std::max( maxNentries, nentries);

  int NeventsPerJob = int( double(use_nentries)/double(Njobs) + 0.000001 ) + 1;

  int firstEvent = (jobN-1)*NeventsPerJob + 1;
  int lastEvent  = firstEvent + NeventsPerJob;
  if( jobN==Njobs ) lastEvent = -1;
  if( jobN==1 ) firstEvent = 0;

  int cnt = 0;
  int nPass = 0;
  std::cout << "========  Starting Event Loop  ========" << std::endl;
  for (Long64_t ievt=0; ievt<chain->GetEntries();ievt++) {    //Long64_t
    cnt++;
    if( ievt<firstEvent ) continue;
    if( ievt==lastEvent ) break;

    if( ievt==1 )        std::cout << "     Event " << ievt << std::endl;
    if( ievt%10000==0 && ievt!=1 ) std::cout << "           " << ievt << "\t" 
					     << int(double(ievt-firstEvent)/double(NeventsPerJob)*100) << "% done" << std::endl;

    //if( ievt==(maxNentries+1) ) break;
    if( ievt==(maxNentries+1) && ievt!=0 ) break;

    chain->GetEntry(ievt);
    numEvents_all++;

    //// --------- various weights: PU, topPt, triggerSF, leptonSF...
    // double  wgt_topPtSF = eve->wgt_topPt_;
    double Xsec = mySample_xSec_;//eve->wgt_xs_;
    double nGen = ( maxNentries>0 ) ? maxNentries : mySample_nGen_;//eve->wgt_nGen_;
    double lumi = ( intLumi > 0 ) ? intLumi : eve->wgt_lumi_ ;

    double wgt_gen = ( insample==9125 || insample==9135 ) ? eve->wgt_generator_ : 1;
    double wgt = wgt_gen * lumi * (Xsec/nGen);//"weight_PU*topPtWgt*osTriggerSF*lepIDAndIsoSF*"; // various weights

    ///////////////////
    ////// selections
    ///////////////////


    h_hf_event_selection->Fill(0.5, wgt);
    h_lf_event_selection->Fill(0.5, wgt);

    int iSys = 0;
    //////------- exactly 2 jets -----
    vvdouble jet_vect_TLV = eve->jet_loose_vect_TLV_[iSys];
    vdouble jet_CSVv2IVf = eve->jet_loose_combinedInclusiveSecondaryVertexV2BJetTags_[iSys];

    int numJets = int(jet_vect_TLV.size()) ;
    if (numJets !=2) continue;
    numEvents_2jets++;

    h_hf_event_selection->Fill(1.5, wgt);
    h_lf_event_selection->Fill(1.5, wgt);

    double jet1_btag = jet_CSVv2IVf[0];
    double jet2_btag = jet_CSVv2IVf[1];

    bool passTightBtag = false;
    bool failLooseBtag = false;
    if( jet1_btag>0.814 || jet2_btag>0.814 ) passTightBtag = true;
    if( jet1_btag<0.423 || jet1_btag<0.423 ) failLooseBtag = true;

    double MHT = eve->MHT_[iSys];

    //////------- two leptons -----
    double met_pt = eve->MET_[iSys];
    //bool PassZmask = eve->PassZmask_ ;
    int TwoMuon = eve->TwoMuon_;
    int TwoElectron = eve->TwoElectron_ ;
    int MuonElectron = eve->MuonElectron_ ;

    double mass_leplep = eve->mass_leplep_;
    double dR_leplep = eve->dR_leplep_;
    int oppositeLepCharge = eve->oppositeLepCharge_;

    vvdouble lepton_vect_TLV = eve->lepton_vect_TLV_;
    vint lepton_isTight = eve->lepton_isTight_;
    vint lepton_isLoose = eve->lepton_isLoose_;
    vint lepton_trkCharge = eve->lepton_trkCharge_;

    int numLooseLeptons=0;
    for( int iLep=0; iLep<int(lepton_vect_TLV.size()); iLep++ ){
      bool isLoose1 = lepton_isLoose[iLep];
      if( !isLoose1 ) continue;
      numLooseLeptons++;

      int charge1 = lepton_trkCharge[iLep];

      TLorentzVector myLep1;
      myLep1.SetPxPyPzE( lepton_vect_TLV[iLep][0], lepton_vect_TLV[iLep][1], lepton_vect_TLV[iLep][2], lepton_vect_TLV[iLep][3] );

      for( int jLep=iLep+1; jLep<int(lepton_vect_TLV.size()); jLep++ ){
	if( iLep==jLep ) continue;
	bool isLoose2 = lepton_isLoose[jLep];
	if( !isLoose2 ) continue;

	int charge2 = lepton_trkCharge[jLep];

	TLorentzVector myLep2;
	myLep2.SetPxPyPzE( lepton_vect_TLV[jLep][0], lepton_vect_TLV[jLep][1], lepton_vect_TLV[jLep][2], lepton_vect_TLV[jLep][3] );

	TLorentzVector sum = myLep1 + myLep2;
	mass_leplep = sum.M();

	dR_leplep = myLep1.DeltaR(myLep2);

	if( (charge1 * charge2)==-1 )     oppositeLepCharge = 1;
	else if( (charge1 * charge2)==1 ) oppositeLepCharge = 0;
	else if( charge1==-99 )           oppositeLepCharge = -1;
	else if( charge2==-99 )           oppositeLepCharge = -2;
	else                              oppositeLepCharge = -3;
      }
    }

    h_numLooseLeptons->Fill(numLooseLeptons,wgt);

    bool PassZmask = ( MuonElectron || 
		       (mass_leplep < (65.5 + 3*MHT/8)) || 
		       (mass_leplep > (108 - MHT/4)) || 
		       (mass_leplep < (79 - 3*MHT/4)) || 
		       (mass_leplep > (99 + MHT/2)) 
		       );

    

    /// triggers 
    bool isDoubleMuTriggerPass = eve->passDoubleMuonTrigger_;//1;
    bool isDoubleElectronTriggerPass = eve->passDoubleElectronTrigger_;//1;
    bool isMuEGTriggerPass = eve->passElectronMuonTrigger_;//1;


    // for different datasets or sub-lep categories
    bool lepselection1a = ( TwoMuon && isDoubleMuTriggerPass && (PassZmask==1) && (met_pt>50) ); //Selection for TwoMuon data events
    bool lepselection1b = ( TwoElectron && isDoubleElectronTriggerPass && (PassZmask==1) && (met_pt>50) ); //Selection for TwoEle data events
    bool lepselection1c = ( MuonElectron && isMuEGTriggerPass ); //Selection for MuonEle data events
    if (!isHF){
      lepselection1a = ( TwoMuon && isDoubleMuTriggerPass && (PassZmask==0) && (met_pt<30) && abs(mass_leplep-91)<10 ); //Selection for TwoMuon data events
      lepselection1b = ( TwoElectron && isDoubleElectronTriggerPass && (PassZmask==0) && (met_pt<30) && abs(mass_leplep-91)<10 ); //Selection for TwoEle data events
      lepselection1c = 0; // ( MuonElectron && isMuEGTriggerPass ); //Selection for MuonEle data events
    }
    // for MC events
    bool lepselection2 = ( lepselection1a || lepselection1b || lepselection1c ) ;
    // if (!isHF) lepselection2 = ( lepselection1a || lepselection1b || lepselection1c ) ;

    if( lepselection1a ) numEvents_lepselection1a++;
    if( lepselection1b ) numEvents_lepselection1b++;
    if( lepselection1c ) numEvents_lepselection1c++;


    bool isCleanEvent = 1;

    bool exselection = ((dR_leplep > 0.2) && (mass_leplep > 12) && (isCleanEvent == 1) && (oppositeLepCharge == 1)); //General dilepton selection   


    // trigger
    if( isDoubleMuTriggerPass || isDoubleElectronTriggerPass || isMuEGTriggerPass ){
      h_hf_event_selection->Fill(2.5, wgt);
      if( TwoMuon || TwoElectron || MuonElectron ){
	h_hf_event_selection->Fill(3.5, wgt);
	if( oppositeLepCharge == 1 ){
	  h_hf_event_selection->Fill(4.5, wgt);
	  if( (dR_leplep > 0.2) ){
	    h_hf_event_selection->Fill(5.5, wgt);
	    if( mass_leplep > 12 ){
	      h_hf_event_selection->Fill(6.5, wgt);
	      if( PassZmask==1 && fabs(mass_leplep-91)>10 ){
		h_hf_event_selection->Fill(7.5, wgt);
		if( met_pt>50 ){
		  h_hf_event_selection->Fill(8.5, wgt);
		  if( passTightBtag ){
		    h_hf_event_selection->Fill(9.5, wgt);
		  }
		}
	      }
	    }
	  }
	}
      }
    }

    if( isDoubleMuTriggerPass || isDoubleElectronTriggerPass ){
      h_lf_event_selection->Fill(2.5, wgt);
      if( TwoMuon || TwoElectron ){
	h_lf_event_selection->Fill(3.5, wgt);
	if( oppositeLepCharge == 1 ){
	  h_lf_event_selection->Fill(4.5, wgt);
	  if( (dR_leplep > 0.2) ){
	    h_lf_event_selection->Fill(5.5, wgt);
	    if( mass_leplep > 12 ){
	      h_lf_event_selection->Fill(6.5, wgt);
	      if( PassZmask==0 && fabs(mass_leplep-91)<10 ){
		h_lf_event_selection->Fill(7.5, wgt);
		if( met_pt<30 ){
		  h_lf_event_selection->Fill(8.5, wgt);
		  if( failLooseBtag ){
		    h_lf_event_selection->Fill(9.5, wgt);
		  }
		}
	      }
	    }
	  }
	}
      }
    }


    if ( !lepselection2 ) continue;
    numEvents_lepselection2++;



    /////------ extra seletions -----
    // double dR_leplep = eve->dR_leplep_;
    // bool isCleanEvent = 1;
    // int oppositeLepCharge = eve->oppositeLepCharge_;

    // bool exselection = ((dR_leplep > 0.2) && (mass_leplep > 12) && (isCleanEvent == 1) && (oppositeLepCharge == 1)); //General dilepton selection   
    // bool exselection = ((dR_leplep > 0.2) && (mass_leplep > 12) && (isCleanEvent == 1)); //General dilepton selection // opposite sign applied in treemaking

    if ( !exselection ) continue;
    numEvents_exselection++;


    nPass++;
    ///// --------jet variables
    //vdouble jet_CSV = eve->jet_loose_CSV_[iSys];
    vdouble jet_vtxMass = eve->jet_loose_vtxMass_[iSys];
    vdouble jet_vtxNtracks = eve->jet_loose_vtxNtracks_[iSys];
    vdouble jet_vtx3DVal = eve->jet_loose_vtx3DVal_[iSys];
    vdouble jet_vtx3DSig = eve->jet_loose_vtx3DSig_[iSys];
    vint jet_flavour = eve->jet_loose_flavour_[iSys];

    double first_jet_pt = -9.;
    double first_jet_eta = -9.;
    double first_jet_csv = -9.;
    double first_jet_vtxMass = -9.;
    double first_jet_vtxNtracks = -9.;
    double first_jet_vtx3DVal = -9.;
    double first_jet_vtx3DSig = -9.;
    int    first_jet_flavour = -9;

    double second_jet_pt = -9.;
    double second_jet_eta = -9.;
    double second_jet_csv = -9.;
    double second_jet_vtxMass = -9.;
    double second_jet_vtxNtracks = -9.;
    double second_jet_vtx3DVal = -9.;
    double second_jet_vtx3DSig = -9.;
    int    second_jet_flavour = -9;

    if( verbose ) std::cout << "--for event  "<< cnt << std::endl;    
    if( verbose ) std::cout << " --number of jets is "<< numJets << std::endl;    

    double minDR_lepton_first_jet = 99, minDR_lepton_second_jet = 99;


    for( int iJet=0; iJet<int(jet_vect_TLV.size()); iJet++ ){
      TLorentzVector myJet;
      myJet.SetPxPyPzE( jet_vect_TLV[iJet][0], jet_vect_TLV[iJet][1], jet_vect_TLV[iJet][2], jet_vect_TLV[iJet][3] );

      double myCSV = jet_CSVv2IVf[iJet];
      double myVtxMass = jet_vtxMass[iJet];
      double myVtxNtracks = jet_vtxNtracks[iJet];
      double myVtx3DVal = jet_vtx3DVal[iJet];
      double myVtx3DSig = jet_vtx3DSig[iJet];

      double myJetPt = myJet.Pt();
      double myJetEta = myJet.Eta();
      int myFlavor = jet_flavour[iJet];
      
      if( iJet==0 ){
	first_jet_pt = myJetPt;
	first_jet_eta = myJetEta;
	first_jet_csv = myCSV;
	first_jet_vtxMass = myVtxMass;
	first_jet_vtxNtracks = myVtxNtracks;
	first_jet_vtx3DVal = myVtx3DVal;
	first_jet_vtx3DSig = myVtx3DSig;
	first_jet_flavour = myFlavor;

	for( int iLep=0; iLep<int(lepton_vect_TLV.size()); iLep++ ){
	  TLorentzVector myLep;
	  myLep.SetPxPyPzE( lepton_vect_TLV[iLep][0], lepton_vect_TLV[iLep][1], lepton_vect_TLV[iLep][2], lepton_vect_TLV[iLep][3] );

	  double dR = myLep.DeltaR(myJet);
	  if( dR<minDR_lepton_first_jet ) minDR_lepton_first_jet = dR;

	  TLorentzVector sum = myLep + myJet;
	  h_mass_lepton_first_jet->Fill(sum.M());
	  if( lepton_isTight[iLep] ) h_mass_tight_lepton_first_jet->Fill(sum.M());
	}
      }
      if( iJet==1 ){
	second_jet_pt = myJetPt;
	second_jet_eta = myJetEta;
	second_jet_csv = myCSV;
	second_jet_vtxMass = myVtxMass;
	second_jet_vtxNtracks = myVtxNtracks;
	second_jet_vtx3DVal = myVtx3DVal;
	second_jet_vtx3DSig = myVtx3DSig;
	second_jet_flavour = myFlavor;

	for( int iLep=0; iLep<int(lepton_vect_TLV.size()); iLep++ ){
	  TLorentzVector myLep;
	  myLep.SetPxPyPzE( lepton_vect_TLV[iLep][0], lepton_vect_TLV[iLep][1], lepton_vect_TLV[iLep][2], lepton_vect_TLV[iLep][3] );

	  double dR = myLep.DeltaR(myJet);
	  if( dR<minDR_lepton_second_jet ) minDR_lepton_second_jet = dR;

	  TLorentzVector sum = myLep + myJet;
	  h_mass_lepton_second_jet->Fill(sum.M());
	  h_mass_lepton_second_jet_eta->Fill(second_jet_eta,sum.M());
	  if( lepton_isTight[iLep] ) h_mass_tight_lepton_second_jet->Fill(sum.M());

	}
      }


    } // end loop over jets
    

    if( verbose ) std::cout << "   -first jet pt, eta is " << first_jet_pt << ";  "<<first_jet_eta << std::endl;
    if( verbose ) std::cout << "   -second jet pt, eta is " << second_jet_pt << ";  "<<second_jet_eta << std::endl;

    h_first_jet_pt->Fill(first_jet_pt);
    h_first_jet_eta->Fill(first_jet_eta);
    h_first_jet_csv->Fill(first_jet_csv);
    h_first_jet_vtxMass->Fill(first_jet_vtxMass);
    h_first_jet_vtxNtracks->Fill(first_jet_vtxNtracks);
    h_first_jet_vtx3DVal->Fill(first_jet_vtx3DVal);
    h_first_jet_vtx3DSig->Fill(first_jet_vtx3DSig);
    h_first_jet_flavour->Fill(first_jet_flavour);
    if( abs(first_jet_flavour)==5 )      h_first_jet_vtxMass_b->Fill(first_jet_vtxMass);
    else if( abs(first_jet_flavour)==4 ) h_first_jet_vtxMass_c->Fill(first_jet_vtxMass);
    else if( abs(first_jet_flavour)==0 ) h_first_jet_vtxMass_o->Fill(first_jet_vtxMass);
    else                                 h_first_jet_vtxMass_l->Fill(first_jet_vtxMass);

    h_first_jet_csv_vtxMass->Fill(first_jet_csv,first_jet_vtxMass);
    if( abs(first_jet_flavour)==5 )      h_first_jet_csv_vtxMass_b->Fill(first_jet_csv,first_jet_vtxMass);
    else if( abs(first_jet_flavour)==4 ) h_first_jet_csv_vtxMass_c->Fill(first_jet_csv,first_jet_vtxMass);
    else if( abs(first_jet_flavour)==0 ) h_first_jet_csv_vtxMass_o->Fill(first_jet_csv,first_jet_vtxMass);
    else                                 h_first_jet_csv_vtxMass_l->Fill(first_jet_csv,first_jet_vtxMass);


    h_second_jet_pt->Fill(second_jet_pt);
    h_second_jet_eta->Fill(second_jet_eta);
    h_second_jet_csv->Fill(second_jet_csv);
    h_second_jet_vtxMass->Fill(second_jet_vtxMass);
    h_second_jet_vtxNtracks->Fill(second_jet_vtxNtracks);
    h_second_jet_vtx3DVal->Fill(second_jet_vtx3DVal);
    h_second_jet_vtx3DSig->Fill(second_jet_vtx3DSig);
    h_second_jet_flavour->Fill(second_jet_flavour);
    if( abs(second_jet_flavour)==5 )      h_second_jet_vtxMass_b->Fill(second_jet_vtxMass);
    else if( abs(second_jet_flavour)==4 ) h_second_jet_vtxMass_c->Fill(second_jet_vtxMass);
    else if( abs(second_jet_flavour)==0 ) h_second_jet_vtxMass_o->Fill(second_jet_vtxMass);
    else                                  h_second_jet_vtxMass_l->Fill(second_jet_vtxMass);

    h_second_jet_csv_vtxMass->Fill(second_jet_csv,second_jet_vtxMass);
    if( abs(second_jet_flavour)==5 )      h_second_jet_csv_vtxMass_b->Fill(second_jet_csv,second_jet_vtxMass);
    else if( abs(second_jet_flavour)==4 ) h_second_jet_csv_vtxMass_c->Fill(second_jet_csv,second_jet_vtxMass);
    else if( abs(second_jet_flavour)==0 ) h_second_jet_csv_vtxMass_o->Fill(second_jet_csv,second_jet_vtxMass);
    else                                  h_second_jet_csv_vtxMass_l->Fill(second_jet_csv,second_jet_vtxMass);

    h_second_jet_pt_eta->Fill(second_jet_eta,second_jet_pt);
    h_second_jet_flavour_eta->Fill(second_jet_eta,second_jet_flavour);

    h_minDR_lepton_first_jet->Fill(minDR_lepton_first_jet);
    h_minDR_lepton_second_jet->Fill(minDR_lepton_second_jet);

    if( TwoMuon ) h_second_jet_eta_TwoMuon->Fill(second_jet_eta);
    if( TwoElectron ) h_second_jet_eta_TwoElectron->Fill(second_jet_eta);
    if( MuonElectron ) h_second_jet_eta_MuonElectron->Fill(second_jet_eta);



    double csvWgtHF, csvWgtLF, csvWgtCF;
    double newCSVwgt = ( insample<0 ) ? 1 : get_csv_wgt(jet_vect_TLV, jet_CSVv2IVf, jet_flavour,iSys, csvWgtHF, csvWgtLF, csvWgtCF);
    double wgtfakeData = wgt*newCSVwgt;
    if( verbose ) std::cout << " HF/LF csv wgts are: " << csvWgtHF << "/"<< csvWgtLF << "\t new CSV wgt = " << newCSVwgt << std::endl; 
    ///// for iteration
    if (verNum !=0 ) {
      if ( isHF ) wgt *= csvWgtLF; // applying lfSFs
      else        wgt *= csvWgtHF; // applying lfSFs
    }


    ///// ------  tag and proble jet selections --------
    // 2nd jet --> tag, 1st jet --> proble
    //bool jetselection2a = (second_jet_csv > 0.679) ? 1:0; //Probe jet being the first_jet
    bool jetselection2a = (second_jet_csv > 0.814) ? 1:0; //Probe jet being the first_jet
    bool firstjetb = ( abs(first_jet_flavour)==5 ) ? 1:0;


    if(!isHF) {
      //jetselection2a = second_jet_csv < 0.244 ? 1:0 ; 
      jetselection2a = second_jet_csv < 0.423 ? 1:0 ; 
      firstjetb = ( abs(first_jet_flavour)==5 || abs(first_jet_flavour)==4 );
    }


    if ( jetselection2a ){
      double jetPt = first_jet_pt;
      double jetAbsEta = fabs(first_jet_eta);

      int iPt = -1; int iEta = -1;
      if (jetPt >=19.99 && jetPt<30) iPt = 0;
      else if (jetPt >=30 && jetPt<40) iPt = 1;
      else if (jetPt >=40 && jetPt<60) iPt = 2;
      else if (jetPt >=60 && jetPt<100) iPt = 3;
      else if (jetPt >=100 && jetPt<160) iPt = 4;
      else if (jetPt >=160 && jetPt<10000) iPt = 5;
      
      if (jetAbsEta >=0 &&  jetAbsEta<0.8 ) iEta = 0;
      else if ( jetAbsEta>=0.8 && jetAbsEta<1.6 )  iEta = 1;
      else if ( jetAbsEta>=1.6 && jetAbsEta<2.41 ) iEta = 2;

      if (isHF && iEta>0) iEta=0;
      if (!isHF && iPt>3) iPt=3;

      ///fake data
      h_Data_jet_csv[iPt][iEta]->Fill(first_jet_csv, wgtfakeData); 

      if( firstjetb ){
	h_MC_b_jet_csv[iPt][iEta]->Fill(first_jet_csv, wgt);
	h_MC_b_jet_vtxMass[iPt][iEta]->Fill(first_jet_vtxMass, wgt);
	h_MC_b_jet_csv_vtxMass[iPt][iEta]->Fill(first_jet_csv, first_jet_vtxMass, wgt);
      }
      else  {
	h_MC_nonb_jet_csv[iPt][iEta]->Fill(first_jet_csv, wgt);
	h_MC_nonb_jet_vtxMass[iPt][iEta]->Fill(first_jet_vtxMass, wgt);
	h_MC_nonb_jet_csv_vtxMass[iPt][iEta]->Fill(first_jet_csv, first_jet_vtxMass, wgt);
      }
    }

    // 1st jet --> tag, 2nd jet --> proble
    //bool jetselection2b = ( first_jet_csv > 0.679) ; //Probe jet being the second_jet
    bool jetselection2b = ( first_jet_csv > 0.814) ; //Probe jet being the second_jet
    bool secondjetb = ( abs(second_jet_flavour)==5 );
    if(!isHF) {
      //jetselection2b = first_jet_csv < 0.244 ? 1:0 ; 
      jetselection2b = first_jet_csv < 0.423 ? 1:0 ; 
      secondjetb = ( abs(second_jet_flavour)==5 || abs(second_jet_flavour)==4 );
    }


    if ( jetselection2b ){
      double jetPt = second_jet_pt;
      double jetAbsEta = fabs(second_jet_eta);

      int iPt = -1; int iEta = -1;
      if (jetPt >=19.99 && jetPt<30) iPt = 0;
      else if (jetPt >=30 && jetPt<40) iPt = 1;
      else if (jetPt >=40 && jetPt<60) iPt = 2;
      else if (jetPt >=60 && jetPt<100) iPt = 3;
      else if (jetPt >=100 && jetPt<160) iPt = 4;
      else if (jetPt >=160 && jetPt<10000) iPt = 5;
      
      if (jetAbsEta >=0 &&  jetAbsEta<0.8 ) iEta = 0;
      else if ( jetAbsEta>=0.8 && jetAbsEta<1.6 )  iEta = 1;
      else if ( jetAbsEta>=1.6 && jetAbsEta<2.41 ) iEta = 2;

      if (isHF && iEta>0) iEta=0;
      if (!isHF && iPt>3) iPt=3;

      ///fake data
      h_Data_jet_csv[iPt][iEta]->Fill(second_jet_csv, wgtfakeData);       

      if( secondjetb ){
	h_MC_b_jet_csv[iPt][iEta]->Fill(second_jet_csv, wgt); 
	h_MC_b_jet_vtxMass[iPt][iEta]->Fill(second_jet_vtxMass, wgt);
	h_MC_b_jet_csv_vtxMass[iPt][iEta]->Fill(second_jet_csv, second_jet_vtxMass, wgt);
      }
      else {
	h_MC_nonb_jet_csv[iPt][iEta]->Fill(second_jet_csv, wgt); 
	h_MC_nonb_jet_vtxMass[iPt][iEta]->Fill(second_jet_vtxMass, wgt);
	h_MC_nonb_jet_csv_vtxMass[iPt][iEta]->Fill(second_jet_csv, second_jet_vtxMass, wgt);
      }
    }

    

  } // end loop over events
  std::cout << "total selected events is " << nPass << std::endl;

  std::cout << "===========================================" << std::endl;
  std::cout << "\t Number of all events = " << numEvents_all << std::endl;
  std::cout << "\t Number of events with ==2 jets = " << numEvents_2jets << std::endl;
  std::cout << "\t Number of events with lepselection2  = " << numEvents_lepselection2 << std::endl;
  std::cout << "\t Number of events with lepselection1a = " << numEvents_lepselection1a << std::endl;
  std::cout << "\t Number of events with lepselection1b = " << numEvents_lepselection1b << std::endl;
  std::cout << "\t Number of events with lepselection1c = " << numEvents_lepselection1c << std::endl;
  std::cout << "\t Number of events with exselection    = " << numEvents_exselection << std::endl;
  std::cout << "===========================================" << std::endl;


  std::cout << " Done! " << std::endl;

  histofile.Write();
  histofile.Close();

}
Beispiel #26
0
int main(int argc, const char* argv[]){

  gErrorIgnoreLevel = kError;

  gSystem->Load("libTree");

  bool   _ttbar_cat = false;
  bool   _syst      = false;
  const char * _output   = 0;
  const char * _input    = 0;
  // TopTrees directory
  const char * _dir      = "../Files_v7-6-3/";
  const char * _syst_var = 0;
  const char * _ttbar_id = "";

  // Arguments used
  //std::set<int> usedargs;
  //Parsing input options
  if(argc == 1){
    display_usage();
    return -1;
  }

  else{
      //Argumet 1 must be a valid input fileName
      for (int i = 1; i < argc; i++){
	if( strcmp(argv[i],"-i") == 0 ){
	  _input = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-d") == 0 ){
	  _dir = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-o") == 0 ){
	  _output= argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-cat") == 0 ){
	  _ttbar_cat = true;
	  _ttbar_id  = argv[i+1];
	  i++;
	}
	if( strcmp(argv[i],"-s") == 0 ){
	  _syst= true;
	  _syst_var = argv[i+1];
	}
	if( strcmp(argv[i],"-h") == 0 ||
	    strcmp(argv[i],"--help") == 0 ){
	  display_usage();
	  return 0;
	}
      }
  }//else
  if( _input ==0 ){
    std::cerr << "\033[1;31mskimfile ERROR:\033[1;m The '-i' option is mandatory!"
	      << std::endl;
    display_usage();
    return -1;
  }
  
  // reassigning
  TString fname(_input);
  TString hname(_output);
  TString fdir(_dir);
  TString ttbar_id(_ttbar_id);
  TString syst_varname(_syst_var);
  
  TChain theTree("ttbbLepJets/gentree"); 
  
  std::cout << "---------------------------------------------------------------------------------" << std::endl;
  std::cout << "Signal: ";
  std::cout << fname + ".root" << std::endl;

  theTree.Add(fdir + fname + ".root");

  int Channel;
  float GENWeight; 
  std::vector<float> *ScaleWeight=0;
  float Lep_pT, Lep_eta;
  std::vector<float> *Jet_px=0, *Jet_py=0, *Jet_pz=0, *Jet_pT=0, *Jet_E=0;
  std::vector<int> *Jet_Mom=0;

  std::vector<int>   *Jet_partonFlavour=0;

  // Categorization
  int  GenCat_ID;
  std::vector<int> *GenConeCat=0; 
 /*********************************
           Tree Branches
  **********************************/
  
  theTree.SetBranchAddress( "genweight",     &GENWeight  );
  theTree.SetBranchAddress( "scaleweight",   &ScaleWeight);
  theTree.SetBranchAddress( "genchannel",    &Channel    );
  theTree.SetBranchAddress( "genhiggscatid", &GenCat_ID  );
  theTree.SetBranchAddress( "genconecatid",  &GenConeCat );


  theTree.SetBranchAddress( "genlepton_pT",  &Lep_pT );
  theTree.SetBranchAddress( "genlepton_eta", &Lep_eta);
  theTree.SetBranchAddress( "genjet_px",     &Jet_px );
  theTree.SetBranchAddress( "genjet_py",     &Jet_py );
  theTree.SetBranchAddress( "genjet_pz",     &Jet_pz );
  theTree.SetBranchAddress( "genjet_E",      &Jet_E  );

  theTree.SetBranchAddress( "genjet_mom",     &Jet_Mom);


  /*********************************
         Output Tree: MVA     
  **********************************/
  float b_pTjj, b_Mjj, b_DRjj, b_DPhijj;    

  TTree *MVASignaltree;
  MVASignaltree = new TTree("MVASignaltree","Dijets from W decay");
  MVASignaltree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVASignaltree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVASignaltree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVASignaltree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  TTree *MVAtree;
  MVAtree = new TTree("MVAtree","All Dijets");
  MVAtree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVAtree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVAtree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVAtree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  TTree *MVABkgtree;
  MVABkgtree = new TTree("MVABkgtree","All Dijets but W decay");
  MVABkgtree->Branch("pTjj",   &b_pTjj,   "pTjj/F");
  MVABkgtree->Branch("Mjj",    &b_Mjj,    "Mjj/F");
  MVABkgtree->Branch("DRjj",   &b_DRjj,   "DRjj/F");
  MVABkgtree->Branch("DPhijj", &b_DPhijj, "DPhijj/F");

  /*********************************
             Histograms
  **********************************/

  //Correct Statistical Uncertainty Treatment
  //TH1::SetDefaultSumw2(kTRUE);  
  
  TH1F *hNJets[2];
  TH1F *hJetMatch[2];
  TH2F *h2DJetMjjID_I[2], *h2DJetMjjID_II[2];

  TH1F *hJetPt[6][2], *hOJetPt[4][2], *hWJetPt[2][2];

  TH1F *hpTJet [5][6][2], *hMassJet [5][6][2], *hDRJet [5][6][2], *hDPhiJet [5][6][2];
  TH1F *hOpTJet[3][4][2], *hOMassJet[3][4][2], *hODRJet[3][4][2], *hODPhiJet[3][4][2];

  TH1F *hpTWjj[2],*hInvMassWjj[2],*hDRWjj[2], *hDPhiWjj[2];
  TH1F *hpTOjj[2],*hInvMassOjj[2],*hDROjj[2], *hDPhiOjj[2];

  TH1F *hpTminjj [2], *hpTmaxjj [2], *hInvMassjj [2], *hDRminjj [2], *hDRmaxjj [2], *hDPhiminjj [2], *hDPhimaxjj [2];
  TH1F *hOpTminjj[2], *hOpTmaxjj[2], *hOInvMassjj[2], *hODRminjj[2], *hODRmaxjj[2], *hODPhiminjj[2], *hODPhimaxjj[2];

  TString namech[2];
  namech[0]="mujets";
  namech[1]="ejets";
  
  TString titlenamech[2];
  titlenamech[0]="#mu+Jets";
  titlenamech[1]="e+Jets";
  
  for(int i=0; i<2; i++){ // Channel
    hNJets[i]      = new TH1F("hNJets_" + namech[i], "Jet multiplicity " + titlenamech[i],9,-0.5,8.5);
    hNJets[i]->GetXaxis()->SetTitle("Number of jets");      
    hNJets[i]->GetXaxis()->SetBinLabel(1,"0");
    hNJets[i]->GetXaxis()->SetBinLabel(2,"1");
    hNJets[i]->GetXaxis()->SetBinLabel(3,"2");
    hNJets[i]->GetXaxis()->SetBinLabel(4,"3");
    hNJets[i]->GetXaxis()->SetBinLabel(5,"4");
    hNJets[i]->GetXaxis()->SetBinLabel(6,"5");
    hNJets[i]->GetXaxis()->SetBinLabel(7,"6");
    hNJets[i]->GetXaxis()->SetBinLabel(8,"7");
    hNJets[i]->GetXaxis()->SetBinLabel(9,"#geq 8");
        

    hJetMatch[i] = new TH1F("hJetMatch_" + namech[i], "W Jet Match " + titlenamech[i],13,0,13);
    hJetMatch[i]->GetXaxis()->SetBinLabel(1,"Total # Evt");
    hJetMatch[i]->GetXaxis()->SetBinLabel(2,"#Delta Mjj is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(3,"Min #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(4,"Max #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(5,"Min #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(6,"Max #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(7,"At least 1 ->");
    hJetMatch[i]->GetXaxis()->SetBinLabel(8, "#Delta Mjj is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(9, "Min #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(10,"Max #Delta R_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(11,"Min #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(12,"Max #Delta #Phi_{jj} is Wjj");
    hJetMatch[i]->GetXaxis()->SetBinLabel(13,"#Delta Mjj && Min #Delta R_{jj} is Wjj");

    h2DJetMjjID_I[i] = new TH2F("h2DJetMjjID1_" + namech[i], "Index ID " + titlenamech[i], 6, 0, 6, 6, 0, 6);
    h2DJetMjjID_I[i]->GetXaxis()->SetTitle("W Index");      
    h2DJetMjjID_I[i]->GetYaxis()->SetTitle("Mjj Index");      

    h2DJetMjjID_II[i] = new TH2F("h2DJetMjjID2_" + namech[i], "Index ID " + titlenamech[i],6, 0, 6, 6, 0, 6);
    h2DJetMjjID_II[i]->GetXaxis()->SetTitle("W Index");      
    h2DJetMjjID_II[i]->GetYaxis()->SetTitle("Mjj Index");      


    TString jetn[6];
    jetn[0]= "Jet-0"; 
    jetn[1]= "Jet-1"; 
    jetn[2]= "Jet-2"; 
    jetn[3]= "Jet-3"; 
    jetn[4]= "Jet-4"; 
    jetn[5]= "Jet-5"; 
    
    for(int ij=0; ij<2; ij++){
      hWJetPt[ij][i] = new TH1F("hWJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hWJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }
    for(int ij=0; ij<6; ij++){
      hJetPt[ij][i] = new TH1F("hJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }
    for(int ij=0; ij<4; ij++){
      hOJetPt[ij][i] = new TH1F("hOJetPt_" + jetn[ij] + "_" + namech[i], "p_{T}^{Jet} " + jetn[ij] + " " + titlenamech[i],40,0,200);
      hOJetPt[ij][i]->GetXaxis()->SetTitle("p_{T}[GeV]");      
    }

    
    TString dijetname[5][6];
    dijetname[0][1] = "Jet01";
    dijetname[0][2] = "Jet02";
    dijetname[0][3] = "Jet03";
    dijetname[0][4] = "Jet04";
    dijetname[0][5] = "Jet05";
    dijetname[1][2] = "Jet12";
    dijetname[1][3] = "Jet13";
    dijetname[1][4] = "Jet14";
    dijetname[1][5] = "Jet15";
    dijetname[2][3] = "Jet23";
    dijetname[2][4] = "Jet24";
    dijetname[2][5] = "Jet25";
    dijetname[3][4] = "Jet34";
    dijetname[3][5] = "Jet35";
    dijetname[4][5] = "Jet45";
    
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++){
	hpTJet[ja][jb][i]   = new TH1F("hpTJet_"   + dijetname[ja][jb] + "_" + namech[i], "transverse pT of Dijets "   + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hMassJet[ja][jb][i] = new TH1F("hMassJet_" + dijetname[ja][jb] + "_" + namech[i], "transverse Mass of Dijets " + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hDRJet[ja][jb][i]   = new TH1F("hDRJet_"   + dijetname[ja][jb] + "_" + namech[i], "#Delta R of Dijets "        + dijetname[ja][jb] + " " + titlenamech[i],50,0,5);
	hDPhiJet[ja][jb][i] = new TH1F("hDPhiJet_" + dijetname[ja][jb] + "_" + namech[i], "#Delta #phi of Dijets "     + dijetname[ja][jb] + " " + titlenamech[i],80,0,4);
      }
    }
    
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++){
	hOpTJet[ja][jb][i]   = new TH1F("hOpTJet_"   + dijetname[ja][jb] + "_" + namech[i], "transverse pT of Dijets "   + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hOMassJet[ja][jb][i] = new TH1F("hOMassJet_" + dijetname[ja][jb] + "_" + namech[i], "transverse Mass of Dijets " + dijetname[ja][jb] + " " + titlenamech[i],80,0,400);
	hODRJet[ja][jb][i]   = new TH1F("hODRJet_"   + dijetname[ja][jb] + "_" + namech[i], "#Delta R of Dijets "        + dijetname[ja][jb] + " " + titlenamech[i],50,0,5);
	hODPhiJet[ja][jb][i] = new TH1F("hODPhiJet_" + dijetname[ja][jb] + "_" + namech[i], "#Delta #phi of Dijets "     + dijetname[ja][jb] + " " + titlenamech[i],80,0,4);
      }
    }
    
    hpTWjj[i]      = new TH1F("hpTWjj_"      + namech[i] ,"pT jets coming from W "                  + titlenamech[i], 80, 0, 400);
    hInvMassWjj[i] = new TH1F("hInvMassWjj_" + namech[i] ,"Inv. Mass of jets coming from W "        + titlenamech[i], 80, 0, 400);
    hDRWjj[i]      = new TH1F("hDRWjj_"      + namech[i] ,"#Delta R_{jj} of jets coming from W "    + titlenamech[i], 50, 0, 5);
    hDPhiWjj[i]    = new TH1F("hDPhiWjj_"    + namech[i] ,"#Delta #phi_{jj} of jets coming from W " + titlenamech[i], 80, 0, 4);

    hpTOjj[i]      = new TH1F("hpTOjj_"      + namech[i] ,"pT jets coming from W "                  + titlenamech[i], 80, 0, 400);
    hInvMassOjj[i] = new TH1F("hInvMassOjj_" + namech[i] ,"Inv. Mass of jets coming from W "        + titlenamech[i], 80, 0, 400);
    hDROjj[i]      = new TH1F("hDROjj_"      + namech[i] ,"#Delta R_{jj} of jets coming from W "    + titlenamech[i], 50, 0, 5);
    hDPhiOjj[i]    = new TH1F("hDPhiOjj_"    + namech[i] ,"#Delta #phi_{jj} of jets coming from W " + titlenamech[i], 80, 0, 4);
    
    hpTminjj[i]   = new TH1F("hpTminjj_"      + namech[i] ,"Minimum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hpTmaxjj[i]   = new TH1F("hpTmaxjj_"      + namech[i] ,"Maximum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hInvMassjj[i] = new TH1F("hInvMassjj_" + namech[i] ,"Compatible Inv. Mass "     + titlenamech[i], 80, 0, 400);
    hDRminjj[i]   = new TH1F("hDRminjj_"   + namech[i] ,"Minimum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hDRmaxjj[i]   = new TH1F("hDRmaxjj_"   + namech[i] ,"Maximum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hDPhiminjj[i] = new TH1F("hDPhiminjj_" + namech[i] ,"Minimum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    hDPhimaxjj[i] = new TH1F("hDPhimaxjj_" + namech[i] ,"Maximum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    
    hOpTminjj[i]   = new TH1F("hOpTminjj_"   + namech[i] ,"Minimum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hOpTmaxjj[i]   = new TH1F("hOpTmaxjj_"   + namech[i] ,"Maximum pT^{jj} "          + titlenamech[i], 80, 0, 400);
    hOInvMassjj[i] = new TH1F("hOInvMassjj_" + namech[i] ,"Compatible Inv. Mass "     + titlenamech[i], 80, 0, 400);
    hODRminjj[i]   = new TH1F("hODRminjj_"   + namech[i] ,"Minimum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hODRmaxjj[i]   = new TH1F("hODRmaxjj_"   + namech[i] ,"Maximum #Delta R_{jj} "    + titlenamech[i], 50, 0, 5);
    hODPhiminjj[i] = new TH1F("hODPhiminjj_" + namech[i] ,"Minimum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);
    hODPhimaxjj[i] = new TH1F("hODPhimaxjj_" + namech[i] ,"Maximum #Delta #Phi_{jj} " + titlenamech[i], 80, 0, 4);

  }//for(i)
  
  
  TStopwatch sw;
  sw.Start(kTRUE);

  ///////////////////////////////////////
  // Please, IGNORE. Temporal solution //
  ///////////////////////////////////////
  TCanvas *mydummycanvas=new TCanvas();// 
  ///////////////////////////////////////
  // Number de events for acceptance
  //          [Channel]
  float fAccEvent_full_ttbb[2] = {0.0,0.0};
  float fAccEvent_full_ttjj[2] = {0.0,0.0};  
  float fAccEvent_vis_ttbb [2] = {0.0,0.0};
  float fAccEvent_vis_ttjj [2] = {0.0,0.0};

  int AccEvent_full_ttbb[2] = {0,0};
  int AccEvent_full_ttjj[2] = {0,0};
  int AccEvent_vis_ttbb [2] = {0,0};
  int AccEvent_vis_ttjj [2] = {0,0};

  // Uncertainties file name
  if(_syst) fname += "_SYS_" + syst_varname;

  /********************************
             Event Loop
  ********************************/
  std::cout << "--- Processing: " << theTree.GetEntries() << " events" << std::endl;
  
  for (Long64_t ievt=0; ievt<theTree.GetEntries();ievt++) {
    
    theTree.GetEntry(ievt);  
    print_progress(theTree.GetEntries(), ievt);
    
    // Jets 
    int NJets;
    NJets     = 0;    
    std::vector<TLorentzVector> vjets, vOjets, vWjets, vTjets;
    std::vector<int> vIndex, vWIndex, vOIndex, vTIndex;

    for(int ijet=0; ijet < Jet_px->size(); ijet++){
      
      TLorentzVector gjet;
      gjet.SetPxPyPzE((*Jet_px)[ijet], (*Jet_py)[ijet], (*Jet_pz)[ijet], (*Jet_E)[ijet]);

      if(gjet.Pt()>25 && std::abs(gjet.Eta())<2.5){

	vjets.push_back(gjet); // All Jets
	vIndex.push_back(ijet);

	if ((*Jet_Mom)[ijet] == 24){
	  vWjets.push_back(gjet); // Jets coming from W	
	  vWIndex.push_back(ijet);	  
	}	
	else if ((*Jet_Mom)[ijet] == 6){
	  vTjets.push_back(gjet); // Jets coming from W	
	  vTIndex.push_back(ijet);	  
	}	
	else{
	  vOjets.push_back(gjet); // Other Jets
	  vOIndex.push_back(ijet);
	}
      } // if(jet.pT > 25)
    }// for(jets)
    
        
    /***************************
       Categorization GenTop
    ***************************/

    int cone_channel = (*GenConeCat)[0];

    // Visible Phase Space:
    // pT(jet) > 20GeV && |eta(Jet)| < 2.5
    int cone_NJets  = (*GenConeCat)[1];
    int cone_NbJets = (*GenConeCat)[2];
    int cone_NcJets = (*GenConeCat)[3];
    
    int cone_NbJetsNoTop = (*GenConeCat)[4];
    
    // Full Phase Space:
    // pT(jet) > 20GeV && |eta(Jet)| < 2.5
    int cone_NaddJets  = (*GenConeCat)[5];
    int cone_NaddbJets = (*GenConeCat)[6];

    /*******************************************
          Categorization to use W Jets 
    *******************************************/

  TString CatEvt = "";
  // if (_ttbar_cat){
  if (cone_NaddJets == 0 && ttbar_category("tt", GenCat_ID) && vWjets.size() == 2){
    if      (ttbar_Wjjcategory(GenCat_ID).Contains("bb_") && vTjets.size() == 2) CatEvt = "bbWjj"; // Two b-jets from top inside acceptance
    else if (ttbar_Wjjcategory(GenCat_ID).Contains("b_" ) && vTjets.size() == 1) CatEvt = "bWbjj"; // One b-jet  from top inside acceptance
    else if ((ttbar_Wjjcategory(GenCat_ID) == "_LF" || ttbar_Wjjcategory(GenCat_ID) == "_c") && vTjets.size() == 0) CatEvt = "Wjj";   // No b-jets  from top inside acceptance
	
  }
  // }
  /*******************************************
             Dijet Invariant Mass 
  *******************************************/
    
  if (vWjets.size() == 2 && 
      (CatEvt == "bbWjj" || CatEvt == "bWjj" || CatEvt == "Wjj")){
  // if (vWjets.size() == 2 && vjets.size() == 6 && vTjets.size() == 2 && cone_NaddJets == 2){
      
      NJets = vjets.size();
      
      float pTWjj, MWjj, DRWjj, DPhiWjj;
      
      // Jets from W
      if(vWjets.size() == 2){
	TLorentzVector jet_WI  = vWjets[0];
	TLorentzVector jet_WII = vWjets[1];
	hWJetPt[0][Channel]->Fill(jet_WI.Pt());
	hWJetPt[1][Channel]->Fill(jet_WII.Pt());
	
	pTWjj   = (vWjets.at(0) + vWjets.at(1)).Pt();
	MWjj    = (vWjets.at(0) + vWjets.at(1)).M();
	DRWjj   = vWjets.at(0).DeltaR(vWjets.at(1));
	DPhiWjj = std::abs(vWjets.at(0).DeltaPhi(vWjets.at(1)));
	
	hpTWjj[Channel]     ->Fill(pTWjj); 
	hInvMassWjj[Channel]->Fill(MWjj); 
	hDRWjj[Channel]     ->Fill(DRWjj);   
	hDPhiWjj[Channel]   ->Fill(DPhiWjj);   

 	// MVA Bkg TREE
	b_pTjj   = pTWjj;
	b_Mjj    = MWjj;
	b_DRjj   = DRWjj;
	b_DPhijj = DPhiWjj;
	
	MVASignaltree->Fill();	

      }

    std::vector<TLorentzVector> seljets;
      
      for(int coljet = 0; coljet < 2; coljet++){
	
	if(coljet == 0) seljets = vjets; 
	else seljets = vOjets; 
	
	// Estimation of all the the paramenters of the dijet
	int pTminIndex[2], pTmaxIndex[2], InvMassIndex[2], DRminIndex[2], DRmaxIndex[2], DPhiminIndex[2], DPhimaxIndex[2];
	float minpTjj = 9999., maxpTjj = 0., Mjj = 0., minDeltaMjj = 9999.,  minDeltaRjj = 9999., maxDeltaRjj = 0., minDeltaPhijj = 9999., maxDeltaPhijj = 0.;
	
	// Loop over the first Jet
	for(int ijet=0; ijet < seljets.size(); ijet++){
	  
	  TLorentzVector jet_i = seljets[ijet];
	  
	  // Loop over the second Jet
	  for(int jjet=ijet+1; jjet < seljets.size(); jjet++){
	    
	    TLorentzVector jet_j = seljets[jjet];
	    
	    float DijetpT = (jet_i+jet_j).Pt(); 
	    
	    if(minpTjj > DijetpT){
	      minpTjj = DijetpT;
	      pTminIndex[0] = vIndex[ijet];
	      pTminIndex[1] = vIndex[jjet];
	    }
	    
	    if(maxpTjj < DijetpT){
	      maxpTjj = DijetpT;
	      pTmaxIndex[0] = vIndex[ijet]; pTmaxIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetInvMass = (jet_i+jet_j).M(); 
	    float DeltaMjj = std::abs(DijetInvMass-80.3);
	    
	    if(minDeltaMjj > DeltaMjj){
	      minDeltaMjj = DeltaMjj;
	      Mjj = DijetInvMass;
	      InvMassIndex[0] = vIndex[ijet]; InvMassIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetDeltaR  = jet_i.DeltaR(jet_j); 
	    
	    if(minDeltaRjj > DijetDeltaR){
	      minDeltaRjj = DijetDeltaR;
	      DRminIndex[0] = ijet; DRminIndex[1] = jjet;
	    }
	    
	    if(maxDeltaRjj < DijetDeltaR){
	      maxDeltaRjj = DijetDeltaR;
	      DRmaxIndex[0] = vIndex[ijet]; DRmaxIndex[1] = vIndex[jjet];
	    }
	    
	    float DijetDeltaPhi  = std::abs(jet_i.DeltaPhi(jet_j)); 
	    
	    if(minDeltaPhijj > DijetDeltaPhi){
	      minDeltaPhijj = DijetDeltaPhi;
	      DPhiminIndex[0] = vIndex[ijet]; DPhiminIndex[1] = vIndex[jjet];
	    }
	    
	    if(maxDeltaPhijj < DijetDeltaPhi){
	      maxDeltaPhijj = DijetDeltaPhi;
	      DPhimaxIndex[0] = vIndex[ijet]; DPhimaxIndex[1] = vIndex[jjet];
	    }
	    
	    // Dijet Variables
	    if(coljet == 0){
	      hpTJet   [ijet][jjet][Channel]->Fill(DijetpT);
	      hMassJet [ijet][jjet][Channel]->Fill(DijetInvMass);  
	      hDRJet   [ijet][jjet][Channel]->Fill(DijetDeltaR);
	      hDPhiJet [ijet][jjet][Channel]->Fill(DijetDeltaPhi);

	      // MVA TREE
	      b_pTjj   = DijetpT;
	      b_Mjj    = DijetInvMass;
	      b_DRjj   = DijetDeltaR;
	      b_DPhijj = DijetDeltaPhi;

	      MVAtree->Fill();
	    }
	    else{
	      hOpTJet   [ijet][jjet][Channel]->Fill(DijetpT);
	      hOMassJet [ijet][jjet][Channel]->Fill(DijetInvMass);  
	      hODRJet   [ijet][jjet][Channel]->Fill(DijetDeltaR);
	      hODPhiJet [ijet][jjet][Channel]->Fill(DijetDeltaPhi);	  


	      hpTOjj[Channel]     ->Fill(DijetpT); 
	      hInvMassOjj[Channel]->Fill(DijetInvMass); 
	      hDROjj[Channel]     ->Fill(DijetDeltaR);   
	      hDPhiOjj[Channel]   ->Fill(DijetDeltaPhi);   

	      // MVA Bkg TREE
	      b_pTjj   = DijetpT;
	      b_Mjj    = DijetInvMass;
	      b_DRjj   = DijetDeltaR;
	      b_DPhijj = DijetDeltaPhi;

	      MVABkgtree->Fill();
	    }
	  }// for(jjets)

	  if(coljet == 0) hJetPt[ijet][Channel]->Fill(jet_i.Pt());
	  else hOJetPt[ijet][Channel]->Fill(jet_i.Pt());
	}// for(ijet)
	
	
	if(coljet == 0){
	  hpTminjj[Channel]  ->Fill(minpTjj);   
	  hpTmaxjj[Channel]  ->Fill(maxpTjj);   
	  hInvMassjj[Channel]->Fill(Mjj); 
	  hDRminjj[Channel]  ->Fill(minDeltaRjj);   
	  hDRmaxjj[Channel]  ->Fill(maxDeltaRjj);   
	  hDPhiminjj[Channel]->Fill(minDeltaPhijj);   
	  hDPhimaxjj[Channel]->Fill(maxDeltaPhijj);   
	}
	else{
	  hOpTminjj[Channel]  ->Fill(minpTjj);   
	  hOpTmaxjj[Channel]  ->Fill(maxpTjj);   
	  hOInvMassjj[Channel]->Fill(Mjj); 
	  hODRminjj[Channel]  ->Fill(minDeltaRjj);   
	  hODRmaxjj[Channel]  ->Fill(maxDeltaRjj);   
	  hODPhiminjj[Channel]->Fill(minDeltaPhijj);   
	  hODPhimaxjj[Channel]->Fill(maxDeltaPhijj);   
	}
      }// for(coljet)
      hNJets[Channel]->Fill(NJets); 
    }// if(vWjets.size() == 0)
    
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------

    /******************
      Scale Weights
    ******************/
    int scaleSysPar;
    if     (_syst && syst_varname.Contains("ScaleRnF_Up"))   scaleSysPar = 0; // muR=Nom,  muF=Up
    else if(_syst && syst_varname.Contains("ScaleRnF_Down")) scaleSysPar = 1; // muR=Nom,  muF=Down
    else if(_syst && syst_varname.Contains("ScaleRuF_Nom"))  scaleSysPar = 2; // muR=Up,   muF=Nom
    else if(_syst && syst_varname.Contains("ScaleRuF_Up"))   scaleSysPar = 3; // muR=Up,   muF=Up
    else if(_syst && syst_varname.Contains("ScaleRdF_Nom"))  scaleSysPar = 4; // muR=Down, muF=Nom
    else if(_syst && syst_varname.Contains("ScaleRdF_Down")) scaleSysPar = 5; // muR=Down, muF=Down

    float EvtStep = GENWeight;
    
    if (_syst && syst_varname.Contains("ScaleR"))
      EvtStep = EvtStep*(*ScaleWeight)[scaleSysPar];

     /******************
         Acceptace
    ******************/
    if(cone_NaddJets  > 1) fAccEvent_full_ttjj[Channel]+=EvtStep;
    if(cone_NaddbJets > 1) fAccEvent_full_ttbb[Channel]+=EvtStep;

    if(Lep_pT > 30 && abs(Lep_eta) < 2.4){
      if(cone_NbJets > 1 && cone_NJets > 5) fAccEvent_vis_ttjj[Channel]+=EvtStep;
      if(cone_NbJets > 3 && cone_NJets > 5) fAccEvent_vis_ttbb[Channel]+=EvtStep;    
    }
    

    /******************
        Histograms
    ******************/
  
  }//for(events)

  AccEvent_full_ttjj[0] = fAccEvent_full_ttjj[0];
  AccEvent_full_ttbb[0] = fAccEvent_full_ttbb[0];

  AccEvent_vis_ttjj[0] = fAccEvent_vis_ttjj[0];
  AccEvent_vis_ttbb[0] = fAccEvent_vis_ttbb[0];

  AccEvent_full_ttjj[1] = fAccEvent_full_ttjj[1];
  AccEvent_full_ttbb[1] = fAccEvent_full_ttbb[1];

  AccEvent_vis_ttjj[1] = fAccEvent_vis_ttjj[1];
  AccEvent_vis_ttbb[1] = fAccEvent_vis_ttbb[1];
  
  // Get elapsed time
  sw.Stop();
  std::cout << "==================================================] 100% " << std::endl;
  std::cout << "--- End of event loop: "; sw.Print();
  
  
  //Acceptance-Efficiency
  std::cout << "--------  Acceptace Full Ph-Sp  --------" << std::endl;
  std::cout << "Number of RAW-mu+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[0] << std::endl;
  std::cout << "ttbb Acceptance Full Ph-Sp: " << AccEvent_full_ttbb[0] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*AccEvent_full_ttbb[0]/AccEvent_full_ttjj[0] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-e+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance: Full Ph-Sp: " << AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*AccEvent_full_ttbb[1]/AccEvent_full_ttjj[1] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-l+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Full Ph-Sp: " << AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance Full Ph-Sp: " << AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Full Ph-Sp: " << 1.0*(AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1])/(AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1]) << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "--------  Acceptace Visible Ph-Sp  --------" << std::endl;
  std::cout << "Number of RAW-mu+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[0] << std::endl;
  std::cout << "ttbb Acceptance Visible Ph-Sp: " << AccEvent_vis_ttbb[0] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*AccEvent_vis_ttbb[0]/AccEvent_vis_ttjj[0] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-e+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance: Visible Ph-Sp: " << AccEvent_vis_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*AccEvent_vis_ttbb[1]/AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "Number of RAW-l+Jets events:" << std::endl;
  std::cout << "ttjj Acceptance Visible Ph-Sp: " << AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1] << std::endl;
  std::cout << "ttbb Acceptance Visible Ph-Sp: " << AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1] << std::endl;
  std::cout << "ttbb/ttjj Visible Ph-Sp: " << 1.0*(AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1])/(AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1]) << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "-----------------------------" << std::endl;
  std::cout << "--------  ttbb Acceptace  --------" << std::endl;
  std::cout << "ttbb Acceptance (mu+Jets): " << 1.0*AccEvent_vis_ttbb[0]/AccEvent_full_ttbb[0] << std::endl;
  std::cout << "ttbb Acceptance (e+Jets): "  << 1.0*AccEvent_vis_ttbb[1]/AccEvent_full_ttbb[1] << std::endl;
  std::cout << "ttbb Acceptance (l+Jets): "  << 1.0*(AccEvent_vis_ttbb[0] + AccEvent_vis_ttbb[1])/(AccEvent_full_ttbb[0] + AccEvent_full_ttbb[1]) << std::endl;
  std::cout << "--------  ttjj Acceptace  --------" << std::endl;
  std::cout << "ttjj Acceptance (mu+Jets): " << 1.0*AccEvent_vis_ttjj[0]/AccEvent_full_ttjj[0] << std::endl;
  std::cout << "ttjj Acceptance (e+Jets): "  << 1.0*AccEvent_vis_ttjj[1]/AccEvent_full_ttjj[1] << std::endl;
  std::cout << "ttjj Acceptance (l+Jets): "  << 1.0*(AccEvent_vis_ttjj[0] + AccEvent_vis_ttjj[1])/(AccEvent_full_ttjj[0] + AccEvent_full_ttjj[1]) << std::endl;

  //Output Dir
  TString dirname="TopResults";   
  // make a dir if it does not exist!!
  struct stat st;
  if(stat(dirname,&st) != 0) system("mkdir " + dirname);
  

  // Sample name identification
  TString samplename="";
  bool matchsamplename=false;
  
  for(int i=0; i<fname.Sizeof(); i++){
    if (i>2){
      if (fname[i-3]=='-' && 
	  fname[i-2]=='1' && 
	  fname[i-1]=='_') matchsamplename=true;
    }
    if (matchsamplename) samplename.Append(fname[i]);
  }
    
  // --- Write histograms
  TString outfname=dirname + "/hAcc-" + hname + "_" + fname  + ".root";
  //TString outfname=dirname + "/hAcc-" + hname + "_" + fname + ttbar_id + ".root";
  TFile *target  = new TFile(outfname,"RECREATE" );  
  
  for(int i=0; i<2; i++){    
    hNJets[i]->Write();

    // pT for EACH jet 
    for(int ij=0; ij<2; ij++) hWJetPt[ij][i]->Write();
    for(int ij=0; ij<6; ij++) hJetPt[ij][i] ->Write();
    for(int ij=0; ij<4; ij++) hOJetPt[ij][i]->Write();
    
    
    // pT for EACH dijet 
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hpTJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hMassJet[ja][jb][i]->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hDRJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<5; ja++){
      for(int jb=ja+1; jb<6; jb++) hDPhiJet[ja][jb][i]->Write();
    }      
    
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hOpTJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hOMassJet[ja][jb][i]->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hODRJet[ja][jb][i]  ->Write();
    }      
    for(int ja=0; ja<3; ja++){
      for(int jb=ja+1; jb<4; jb++) hODPhiJet[ja][jb][i]->Write();
    }      
    
    // MAX and MIN parameter per event
    hpTWjj[i]     ->Write(); 
    hInvMassWjj[i]->Write(); 
    hDRWjj[i]     ->Write();   
    hDPhiWjj[i]   ->Write();   
    
    hpTminjj[i]  ->Write();
    hpTmaxjj[i]  ->Write();
    hInvMassjj[i]->Write();
    hDRminjj[i]  ->Write();
    hDRmaxjj[i]  ->Write();
    hDPhiminjj[i]->Write();
    hDPhimaxjj[i]->Write();
    
    hpTOjj[i]     ->Write(); 
    hInvMassOjj[i]->Write(); 
    hDROjj[i]     ->Write();   
    hDPhiOjj[i]   ->Write();   

    hOpTminjj[i]  ->Write();
    hOpTmaxjj[i]  ->Write();
    hOInvMassjj[i]->Write();
    hODRminjj[i]  ->Write();
    hODRmaxjj[i]  ->Write();
    hODPhiminjj[i]->Write();
    hODPhimaxjj[i]->Write();
    
    hJetMatch[i] ->Write();
    
    h2DJetMjjID_I [i] ->Write();
    h2DJetMjjID_II[i] ->Write();
  }//for(i)

  MVASignaltree->Write();
  MVAtree      ->Write();
  MVABkgtree   ->Write();
  
  target->Close();

  std::cout << "File saved as " << outfname << std::endl;
  
}
void skim(std::string var, TTree *fullTree, TTree *newTree, std::string cutstr, bool isWeighted , bool reweighted, bool addDiMuSel, bool addMuSel, bool addPhoSel){


  std::cout << fullTree->GetName() << " -> " <<  newTree->GetName() << " " << cutstr.c_str() << std::endl;
  fullTree->Draw(">>cutlist",cutstr.c_str());
  TEventList *keep_points = (TEventList*)gDirectory->Get("cutlist");
  int nEntries = fullTree->GetEntries();

  float x,x_orig;
  float mvametPhi, metRaw;
  float mvametPhiCor ;// corected phis for deltaPhi(met,jet) cut (// NOT to be used in calculation of MT!)
  float weight, weight_wpt, weight_in, weight_in_pu; 
  float catvar1,catvar2,catvar3,catvar4,catvar5,catvar6;   // These are empty, do as we want with them 
  float tau1,tau2;
  float dimuM, mt;	// used for the W/Z selection
  int passVBF;
  unsigned int njets;
  unsigned int nphotons;
  float phopt, phoeta;
  // Why do we use these?
  float metBasicPhi, metBasic;

 
  // Used for reweighting if needed
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *genZ  = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();
  TBranch *brgenZ ;

  // W/Z selection for leptions
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *lepV   = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *lep2V  = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();

  TBranch *brlep   = fullTree->GetBranch("lep1");
  TBranch *brlep_2 = fullTree->GetBranch("lep2");
  brlep->SetAddress(&lepV);
  brlep_2->SetAddress(&lep2V);

  // Check VBF selection 
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *jetV   = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *jet2V  = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();

  // Also need these for second jet veto 
  TBranch *brjet   = fullTree->GetBranch("jet1");
  TBranch *brjet_2 = fullTree->GetBranch("jet2");
  brjet->SetAddress(&jetV);
  brjet_2->SetAddress(&jet2V);


  // if addPhoSel add the two photons
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *pho1V  = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();
  ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > *pho2V  = new ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> >();
  TBranch *brpho_1 ;
  TBranch *brpho_2 ;
  if (addPhoSel){
    brpho_1 = fullTree->GetBranch("pho1");
    brpho_2 = fullTree->GetBranch("pho2");    
    brpho_1->SetAddress(&pho1V);
    brpho_2->SetAddress(&pho2V);
  }


  // mu/dimu ?
  std::string origVar = var;
  if (addMuSel)   var+="CorW";
  if (addDiMuSel) var+="CorZ";

  // Add Output branches to our very skimmed down tree.
  //TTree *newTree = new TTree(newname.c_str(),newname.c_str());

  newTree->Branch("mvamet",&x,"mvamet/Float_t");
  newTree->Branch("mvamet_orig",&x_orig,"mvamet_orig/Float_t");
  newTree->Branch("weight",&weight,"weight/Float_t");
  newTree->Branch("weight_wpt",&weight_wpt,"weight_wpt/Float_t");
  newTree->Branch("metRaw",&metRaw,"metRaw/Float_t"); // useful to keep this
  newTree->Branch("jet1mprune",&catvar1,"jet1mprume/Float_t");
  newTree->Branch("jet1mtrim",&catvar2,"jet1mtrim/Float_t");
  newTree->Branch("jet1tau2o1",&catvar3,"jet1tau12o1/Float_t");
  newTree->Branch("jpt",&catvar4,"jpt/Float_t");
  newTree->Branch("jet1eta",&catvar6,"jet1eta/Float_t");
  newTree->Branch("jet1QGtag",&catvar5,"jet1QGtag/Float_t");
  newTree->Branch("passVBF",&passVBF,"passVBF/Int_t");
  newTree->Branch("njets",&njets,"njets/Int_t");

  if (addDiMuSel) {	
    newTree->Branch("dimu_m",&dimuM,"dimu_m/Float_t");
  }
  if (addMuSel) {	
    newTree->Branch("mt",&mt,"mt/Float_t");
  }
  if (addPhoSel) {	
    newTree->Branch("phopt",&phopt,"phopt/Float_t");
    newTree->Branch("phoeta",&phoeta,"phoeta/Float_t");
  }

  fullTree->SetBranchAddress(var.c_str(),&x);
  if (addDiMuSel || addMuSel) fullTree->SetBranchAddress(origVar.c_str(),&x_orig);
  fullTree->SetBranchAddress(Form("%sPhi",var.c_str()),&mvametPhiCor);
  if (addDiMuSel || addMuSel) fullTree->SetBranchAddress(Form("%sPhi",origVar.c_str()),&mvametPhi);
  if (isWeighted) fullTree->SetBranchAddress("weight",&weight_in);
  fullTree->SetBranchAddress("metRaw",&metRaw);
  fullTree->SetBranchAddress("njets",&njets);
  fullTree->SetBranchAddress("nphotons",&nphotons);


  if (isWeighted) fullTree->SetBranchAddress("puWeight",&weight_in_pu);
  //fullTree->SetBranchAddress("jet1mprune",&catvar1);
  //fullTree->SetBranchAddress("jet1mtrim" ,&catvar2);
  //fullTree->SetBranchAddress("jet1tau2" ,&tau2);
  //fullTree->SetBranchAddress("jet1tau1" ,&tau1);
  //fullTree->SetBranchAddress("jet1QGtag",&catvar5);
  //fullTree->SetBranchAddress("jet1"     ,&jet);
   
  if ( reweighted){

    	std::cout << "Reweighting For Photon Efficiency! " << std::endl;
  }

  std::cout << " Filling Skim tree " << newTree->GetName() << std::endl;

  for (int evt=0;evt<nEntries;evt++){
    if ( !(keep_points->Contains(evt)) ) continue;

    fullTree->GetEntry(evt);

    TLorentzVector jet, jet2;
    jet.SetPtEtaPhiM(jetV->Pt(),jetV->Eta(),jetV->Phi(),jetV->M());
    jet2.SetPtEtaPhiM(jet2V->Pt(),jet2V->Eta(),jet2V->Phi(),jet2V->M());
 
    if (addDiMuSel){
      TLorentzVector lep, lep2;
      lep.SetPxPyPzE(lepV->Px(),lepV->Py(),lepV->Pz(),lepV->E());
      lep2.SetPxPyPzE(lep2V->Px(),lep2V->Py(),lep2V->Pz(),lep2V->E());
      dimuM = TMath::Sqrt(2*(lep.E()*lep2.E()-(lep.Px()*lep2.Px()+lep.Py()*lep2.Py()+lep.Pz()*lep2.Pz()))); 
      if ( dimuM < 61 || dimuM > 121 ) continue;     
    }

    if (addMuSel){
      TLorentzVector lep;
      lep.SetPxPyPzE(lepV->Px(),lepV->Py(),lepV->Pz(),lepV->E());
      mt = TMath::Sqrt(2*x_orig*lep.Pt()*(1-TMath::Cos(deltaphi(mvametPhi,lep.Phi()))));  // used original metphi and met to calculate mt
      if ( mt < 50 || mt > 100 ) continue;     
    }

    if (addPhoSel){
      double pho2eta = TMath::Abs(pho2V->Eta());
      if (nphotons>1 && pho2V->Pt() > 100 && (pho2eta<1.4442 || ( pho2eta > 1.566 && pho2eta<2.5))) continue;
      TLorentzVector pho;
      pho.SetPxPyPzE(pho1V->Px(),pho1V->Py(),pho1V->Pz(),pho1V->E());
      x_orig = x;
      double metphocor = computeMET(x,mvametPhiCor,pho);  
      double metphophicor = computeMETPhi(x,mvametPhiCor,pho);  
      x = metphocor;    // Set the variables to the corrected ones now
      mvametPhiCor = metphophicor;
      phopt = pho.Pt();
      phoeta = pho.Eta();
    }
    // Back to regular selection
    // Add MET and second Jet balance cuts !!!
    if (jet2.Pt() > 30){
      if  (deltaphi(jet.Phi(),jet2.Phi()) >= 2) continue;
    }
    if ( deltaphi(jet.Phi(),mvametPhiCor)<2 ) continue;  // this will always be the corrected Phi 
    
    // Weights/Reweightsi
    if (isWeighted) weight = weight_in*weight_in_pu*luminosity;
    else  weight = 1.;
    if (reweighted && isWeighted) { 
        //float genpt = genZ->Pt();
	double phpt  = phopt;
	double pheta = TMath::Abs(phoeta);
    	if (
	    phpt<reweightpheff->GetXaxis()->GetXmax() && phpt > reweightpheff->GetXaxis()->GetXmin()
  	 && pheta<reweightpheff->GetYaxis()->GetXmax() && pheta > reweightpheff->GetYaxis()->GetXmin() 	
	   ) {
	  weight_wpt = weight*reweightpheff->GetBinContent(reweightpheff->FindBin(phpt,pheta));
	} else {
	  weight_wpt = weight;
	}
    } else {
	weight_wpt = weight;
    }
    catvar3 = tau2/tau1;  // make the sub-structure variable
    catvar4 = jet.Pt();
    catvar6 = jet.Eta();

    // Now check the VBF selection (added as a flag)
    // pt>50, eta <4.7, eta1*eta2 < 0 , delta(Eta) > 4.2, Mjj > 1100, deltaPhi < 1.0
    passVBF=0;
    if (jet2.Pt() > 50 && TMath::Abs(jet2.Eta()) < 4.7 ) {
      double j1eta = jet.Eta();
      double j2eta = jet2.Eta();
      if( j1eta*j2eta <0  && deltaphi(jet.Phi(),jet2.Phi()) < 1.0 && (jet+jet2).M() > 1100 && TMath::Abs(j1eta-j2eta) > 4.2) {
	passVBF=1;
      }
    }
    newTree->Fill();
  }
  std::cout << " Finished skim " << std::endl;
}
Beispiel #28
0
void polGen(double rapdilepton_min = 1,
		double rapdilepton_max = 1,
		double pTdilepton_min = 1,
		double pTdilepton_max = 1,
		double mass_signal_peak  =  1,
		double mass_signal_sigma =  1,
		double n_sigmas_signal = 1,
		int n_events = 50000,
		double f_BG = 0.5,
		double lambda_theta_sig=1,
		double lambda_phi_sig=1,
		double lambda_thetaphi_sig=1,
		double lambda_theta_bkg=1,
		double lambda_phi_bkg=1,
		double lambda_thetaphi_bkg=1,
		int frameSig=1,//CS...1, HX...2, PX...3
		int frameBkg=1,//CS...1, HX...2, PX...3
		int nGen=1,
		Char_t *dirstruct = "ToyDirectory_Default"
){

	char frameSigName[200];
	if(frameSig==1)sprintf(frameSigName,"CS");
	if(frameSig==2)sprintf(frameSigName,"HX");
	if(frameSig==3)sprintf(frameSigName,"PX");
	char frameBkgName[200];
	if(frameBkg==1)sprintf(frameBkgName,"CS");
	if(frameBkg==2)sprintf(frameBkgName,"HX");
	if(frameBkg==3)sprintf(frameBkgName,"PX");


	if(frameSig==2) HX_is_natural_sig=true; if(frameSig==3) PX_is_natural_sig=true; //else CS is the natural frame by default
	if(frameBkg==2) HX_is_natural_bkg=true; if(frameBkg==3) PX_is_natural_bkg=true; //else CS is the natural frame by default

	cout<<"Number of Events to be generated ........... "<<n_events<<endl;
	cout<<"pT min ..................................... "<<pTdilepton_min<<endl;
	cout<<"pT max ..................................... "<<pTdilepton_max<<endl;
	cout<<"Rapidity min ............................... "<<rapdilepton_min<<endl;
	cout<<"Rapidity max ............................... "<<rapdilepton_max<<endl;
	cout<<"Background Fraction ........................ "<<f_BG<<endl;
	cout<<"Injected lambda_theta Signal ............... "<<lambda_theta_sig<<" , in the "<<frameSigName<<" frame"<<endl;
	cout<<"Injected lambda_phi Signal ................. "<<lambda_phi_sig<<" , in the "<<frameSigName<<" frame"<<endl;
	cout<<"Injected lambda_thetaphi Signal ............ "<<lambda_thetaphi_sig<<" , in the "<<frameSigName<<" frame"<<endl;
	cout<<"Injected lambda_theta Background............ "<<lambda_theta_bkg<<" , in the "<<frameBkgName<<" frame"<<endl;
	cout<<"Injected lambda_phi Background ............. "<<lambda_phi_bkg<<" , in the "<<frameBkgName<<" frame"<<endl;
	cout<<"Injected lambda_thetaphi Background ........ "<<lambda_thetaphi_bkg<<" , in the "<<frameBkgName<<" frame"<<endl;
	cout<<"Number of Generation ....................... "<<nGen<<endl;
	cout<<"Directory Structure of Output .............. "<<dirstruct<<endl;


	double mass_min = mass_signal_peak - n_sigmas_signal*mass_signal_sigma;
	double mass_max = mass_signal_peak + n_sigmas_signal*mass_signal_sigma;

	char outfilename [500];
	sprintf(outfilename,"%s/genData.root",dirstruct);

  gROOT->Reset();

  delete gRandom;
  gRandom = new TRandom3(0);

  TF1* pT_distr = new TF1("pT_distr",func_pT_gen,pTdilepton_min,pTdilepton_max,0);
  TF1* rap_distr = new TF1("rap_distr",func_rap_gen,rapdilepton_min,rapdilepton_max,0);

  TFile* hfileout = new TFile(outfilename, "RECREATE", "genData");
  TTree* genData = new TTree("genData","genData");

  // Structure of output ntuple

  TLorentzVector* lepP = new TLorentzVector(0.,0.,0.,0.);
  genData->Branch("lepP","TLorentzVector",&lepP);
  TLorentzVector* lepN = new TLorentzVector(0.,0.,0.,0.);
  genData->Branch("lepN","TLorentzVector",&lepN);

  double costh_CS;  genData->Branch("costh_CS",     &costh_CS,     "costh_CS/D");
  double phi_CS;    genData->Branch("phi_CS",       &phi_CS,       "phi_CS/D"  );
  double phith_CS;  genData->Branch("phith_CS",     &phith_CS,     "phith_CS/D");

  double costh_HX;  genData->Branch("costh_HX",     &costh_HX,     "costh_HX/D");
  double phi_HX;    genData->Branch("phi_HX",       &phi_HX,       "phi_HX/D"  );
  double phith_HX;  genData->Branch("phith_HX",     &phith_HX,     "phith_HX/D");

  double costh_PX;  genData->Branch("costh_PX",     &costh_PX,     "costh_PX/D");
  double phi_PX;    genData->Branch("phi_PX",       &phi_PX,       "phi_PX/D"  );
  double phith_PX;  genData->Branch("phith_PX",     &phith_PX,     "phith_PX/D");

  double cosalpha;  genData->Branch("cosalpha",     &cosalpha,     "cosalpha/D");

  double pT;        genData->Branch("pT",           &pT,           "pT/D"  );
  double rap;       genData->Branch("rap",          &rap,          "rap/D" );
  double mass;      genData->Branch("mass",         &mass,         "mass/D");

  double deltaHXCS; genData->Branch("deltaHXCS",    &deltaHXCS,    "deltaHXCS/D");

  int isBG;         genData->Branch("isBG",         &isBG,         "isBG/I");


  // extremes and binning of lambda_gen extraction histos
  const double l_min = -1;
  const double l_max =  1;
  const double l_step_1D = 0.02;


  TH1D* h_costh2_CS = new TH1D( "h_costh2_CS", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_cos2ph_CS = new TH1D( "h_cos2ph_CS", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_sin2thcosph_CS = new TH1D( "h_sin2thcosph_CS", "", int((l_max-l_min)/l_step_1D), l_min, l_max );

  TH1D* h_costh2_HX = new TH1D( "h_costh2_HX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_cos2ph_HX = new TH1D( "h_cos2ph_HX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_sin2thcosph_HX = new TH1D( "h_sin2thcosph_HX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );

  TH1D* h_costh2_PX = new TH1D( "h_costh2_PX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_cos2ph_PX = new TH1D( "h_cos2ph_PX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );
  TH1D* h_sin2thcosph_PX = new TH1D( "h_sin2thcosph_PX", "", int((l_max-l_min)/l_step_1D), l_min, l_max );

  double costh2;
  double cos2ph;
  double sin2thcosph;
  double Phi;

  const int n_step = n_events/5;
  int n_step_=1;


  cout << endl;
  cout << "Generating " << n_events << " dilepton events"<< endl;
  cout << "------------------------------------------------------------" << endl;
  cout << "Progress: "<<endl;



/////////////////// CYCLE OF EVENTS ////////////////////////
  for(int i_event = 1; i_event <= n_events; i_event++){

	    if (i_event%n_step == 0) {cout << n_step_*20 <<" % "<<endl; n_step_++;}

	    // generation of dilepton in the pp event in the pp CM

    // mass

    isBG = 0;

    if ( gRandom->Uniform() < f_BG ) { mass = gRandom->Uniform(mass_min, mass_max); isBG = 1; }
                                        else { do { mass = gRandom->Gaus(mass_signal_peak, mass_signal_sigma); }
                                               while ( mass < mass_min || mass > mass_max ); }

    // pT:

    pT = pT_distr->GetRandom();

    // pL:

    double rap_sign = gRandom->Uniform(-1., 1.); rap_sign /= TMath::Abs(rap_sign);
    rap = rap_distr->GetRandom() * rap_sign;
    double mT = sqrt( mass*mass + pT*pT );
    double pL1 = 0.5 *mT * exp(rap);
    double pL2 = - 0.5 *mT * exp(-rap);
    double pL = pL1 + pL2;

    // Phi:

    double Phi = 2. * gPI * gRandom->Uniform(1.);

    // 4-vector:

    TLorentzVector dilepton;
    dilepton.SetXYZM( pT * cos(Phi) , pT * sin(Phi), pL, mass );


    // generation of polarization (generic reference frame)

    double lambda_theta    = lambda_theta_sig;
    double lambda_phi      = lambda_phi_sig;
    double lambda_thetaphi = lambda_thetaphi_sig;
    bool HX_is_natural = HX_is_natural_sig;
    bool PX_is_natural = PX_is_natural_sig;

    if ( isBG ) {
       lambda_theta    = lambda_theta_bkg;
       lambda_phi      = lambda_phi_bkg;
       lambda_thetaphi = lambda_thetaphi_bkg;
       HX_is_natural = HX_is_natural_bkg;
       PX_is_natural = PX_is_natural_bkg;
    }


    double costhphidistr_max = 1. + TMath::Abs(lambda_phi) + TMath::Abs(lambda_thetaphi);
    double costhphidistr_rnd;
    double costhphidistr;
    double costh_gen;
    double sinth_gen;
    double phi_gen;

    if ( lambda_theta > 0. ) costhphidistr_max += lambda_theta;

    do { costh_gen = -1. + 2. * gRandom->Uniform(1.);
         phi_gen   = 2. * gPI * gRandom->Uniform(1.);
         sinth_gen = sqrt( 1. - costh_gen*costh_gen );
         costhphidistr_rnd = costhphidistr_max * gRandom->Uniform(1.);
         costhphidistr = 1. + lambda_theta    * costh_gen*costh_gen
                            + lambda_phi      * sinth_gen*sinth_gen * cos(2.*phi_gen)
                            + lambda_thetaphi * 2.* sinth_gen*costh_gen * cos(phi_gen);
       } while ( costhphidistr_rnd > costhphidistr );


    // lepton momentum in the dilepton rest frame:

    double p_lepton_DILEP = sqrt( 0.25*mass*mass - Mlepton*Mlepton );

    TLorentzVector lepton_DILEP;

    lepton_DILEP.SetXYZM( p_lepton_DILEP * sinth_gen * cos(phi_gen),
                          p_lepton_DILEP * sinth_gen * sin(phi_gen),
                          p_lepton_DILEP * costh_gen,
                          Mlepton );


    // reference directions to calculate angles:

    TVector3 lab_to_dilep = -dilepton.BoostVector();

    TLorentzVector beam1_DILEP = beam1_LAB;
    beam1_DILEP.Boost(lab_to_dilep);         // beam1 in the dilepton rest frame
    TLorentzVector beam2_DILEP = beam2_LAB;
    beam2_DILEP.Boost(lab_to_dilep);         // beam2 in the dilepton rest frame

    TVector3 beam1_direction     = beam1_DILEP.Vect().Unit();
    TVector3 beam2_direction     = beam2_DILEP.Vect().Unit();
    TVector3 dilep_direction     = dilepton.Vect().Unit();
    TVector3 beam1_beam2_bisect  = ( beam1_direction - beam2_direction ).Unit();


    deltaHXCS = dilep_direction.Angle(beam1_beam2_bisect) * 180./gPI;

    // all polarization frames have the same Y axis = the normal to the plane formed by
    // the directions of the colliding hadrons

    TVector3 Yaxis = ( beam1_direction.Cross( beam2_direction ) ).Unit();

    // flip of y axis with rapidity

    if ( rap < 0 ) Yaxis = - Yaxis;

    TVector3 perpendicular_to_beam = ( beam1_beam2_bisect.Cross( Yaxis ) ).Unit();


    // step 1: transform (rotation) lepton momentum components from generation frame
    // to the frame with x,y,z axes as in the laboratory

    TVector3 oldZaxis = beam1_beam2_bisect;
    if ( HX_is_natural ) oldZaxis = dilep_direction;
    if ( PX_is_natural ) oldZaxis = perpendicular_to_beam;

    TVector3 oldYaxis = Yaxis;
    TVector3 oldXaxis = oldYaxis.Cross(oldZaxis);

    TRotation rotation;
    rotation.RotateAxes(oldXaxis, oldYaxis, oldZaxis);
                     // transforms coordinates from the "old" frame to the "xyz" frame

    TLorentzVector lepton_DILEP_xyz = lepton_DILEP;

    lepton_DILEP_xyz.Transform(rotation);
                     // lepton_DILEP_xyz is the lepton in the dilepton rest frame
                     // wrt to the lab axes

    // lepton 4-vectors in the LAB frame:

    TVector3 dilep_to_lab = dilepton.BoostVector();

    *lepP = lepton_DILEP_xyz;
    lepP->Boost(dilep_to_lab);
    lepN->SetPxPyPzE(-lepton_DILEP_xyz.Px(),-lepton_DILEP_xyz.Py(),-lepton_DILEP_xyz.Pz(),lepton_DILEP_xyz.E());
    lepN->Boost(dilep_to_lab);


    /////////////////////////////////////////////////////////////////////
    // CS frame


    TVector3 newZaxis = beam1_beam2_bisect;
    TVector3 newYaxis = Yaxis;
    TVector3 newXaxis = newYaxis.Cross( newZaxis );

    rotation.SetToIdentity();
    rotation.RotateAxes( newXaxis, newYaxis, newZaxis );
    rotation.Invert();  // transforms coordinates from the "xyz" frame to the new frame

    TVector3 lepton_DILEP_rotated = lepton_DILEP_xyz.Vect();

    lepton_DILEP_rotated.Transform(rotation);

    costh_CS = lepton_DILEP_rotated.CosTheta();

    phi_CS = lepton_DILEP_rotated.Phi() * 180. / gPI;

    if ( costh_CS < 0. ) phith_CS = phi_CS - 135.;
    if ( costh_CS > 0. ) phith_CS = phi_CS - 45.;

    if ( phith_CS < -180. ) phith_CS = 360. + phith_CS;


    /////////////////////////////////////////////////////////////////////
    // HELICITY frame

    newZaxis = dilep_direction;
    newYaxis = Yaxis;
    newXaxis = newYaxis.Cross( newZaxis );

    rotation.SetToIdentity();
    rotation.RotateAxes( newXaxis, newYaxis, newZaxis );
    rotation.Invert();

    lepton_DILEP_rotated = lepton_DILEP_xyz.Vect();

    lepton_DILEP_rotated.Transform(rotation);

    costh_HX = lepton_DILEP_rotated.CosTheta();

    phi_HX = lepton_DILEP_rotated.Phi() * 180. / gPI;

    if ( costh_HX < 0. ) phith_HX = phi_HX - 135.;
    if ( costh_HX > 0. ) phith_HX = phi_HX - 45.;

    if ( phith_HX < -180. ) phith_HX = 360. + phith_HX;


    /////////////////////////////////////////////////////////////////////
    // PERPENDICULAR HELICITY frame

    newZaxis = perpendicular_to_beam;
    newYaxis = Yaxis;
    newXaxis = newYaxis.Cross( newZaxis );

    rotation.SetToIdentity();
    rotation.RotateAxes( newXaxis, newYaxis, newZaxis );
    rotation.Invert();

    lepton_DILEP_rotated = lepton_DILEP_xyz.Vect();

    lepton_DILEP_rotated.Transform(rotation);

    costh_PX = lepton_DILEP_rotated.CosTheta();

    phi_PX = lepton_DILEP_rotated.Phi() * 180. / gPI;

    if ( costh_PX < 0. ) phith_PX = phi_PX - 135.;
    if ( costh_PX > 0. ) phith_PX = phi_PX - 45.;

    if ( phith_PX < -180. ) phith_PX = 360. + phith_PX;


    /////////////////////////////////////////////////////////////////////
    // invariant polarization angle

    cosalpha = sqrt( 1. - pow(costh_PX, 2.) ) * sin( lepton_DILEP_rotated.Phi() );



////// Filling Histograms of costh2, cos2ph and sin2thcosph for the extraction of the actual generated polarization

    if ( !isBG ){
		costh2=pow(costh_CS,2.);
	    Phi = phi_CS/180. * gPI ;
	    cos2ph = cos(2.*Phi);
	    sin2thcosph= sin(2.*acos(costh_CS))*cos(Phi);
	    h_costh2_CS->Fill( costh2 );
	    h_cos2ph_CS->Fill( cos2ph );
	    h_sin2thcosph_CS->Fill( sin2thcosph );

	    costh2=pow(costh_HX,2.);
	    Phi = phi_HX/180. * gPI ;
	    cos2ph = cos(2.*Phi);
	    sin2thcosph= sin(2.*acos(costh_HX))*cos(Phi);
	    h_costh2_HX->Fill( costh2 );
	    h_cos2ph_HX->Fill( cos2ph );
	    h_sin2thcosph_HX->Fill( sin2thcosph );

	    costh2=pow(costh_PX,2.);
	    Phi = phi_PX/180. * gPI ;
	    cos2ph = cos(2.*Phi);
	    sin2thcosph= sin(2.*acos(costh_PX))*cos(Phi);
	    h_costh2_PX->Fill( costh2 );
	    h_cos2ph_PX->Fill( cos2ph );
	    h_sin2thcosph_PX->Fill( sin2thcosph );
    }


//  filling of the ntuple:

    genData->Fill();


  } // end of external loop (generated events)

  cout << endl;


  double lamth_CS;
  double lamph_CS;
  double lamtp_CS;
  costh2=h_costh2_CS->GetMean();
  lamth_CS = (1. - 3. * costh2 ) / ( costh2 - 3./5. );
  cos2ph=h_cos2ph_CS->GetMean();
  lamph_CS = cos2ph * (3. + lamth_CS);
  sin2thcosph=h_sin2thcosph_CS->GetMean();
  lamtp_CS = sin2thcosph * 5./4. * (3. + lamth_CS);

  double lamth_HX;
  double lamph_HX;
  double lamtp_HX;
  costh2=h_costh2_HX->GetMean();
  lamth_HX = (1. - 3. * costh2 ) / ( costh2 - 3./5. );
  cos2ph=h_cos2ph_HX->GetMean();
  lamph_HX = cos2ph * (3. + lamth_HX);
  sin2thcosph=h_sin2thcosph_HX->GetMean();
  lamtp_HX = sin2thcosph * 5./4. * (3. + lamth_HX);

  double lamth_PX;
  double lamph_PX;
  double lamtp_PX;
  costh2=h_costh2_PX->GetMean();
  lamth_PX = (1. - 3. * costh2 ) / ( costh2 - 3./5. );
  cos2ph=h_cos2ph_PX->GetMean();
  lamph_PX = cos2ph * (3. + lamth_PX);
  sin2thcosph=h_sin2thcosph_PX->GetMean();
  lamtp_PX = sin2thcosph * 5./4. * (3. + lamth_PX);


  char resfilename[200];
  sprintf(resfilename,"%s/GenResults.root",dirstruct);
  TFile* GenResultFile = new TFile(resfilename, "RECREATE", "GenResultFile");

  TTree* GenResults = new TTree("GenResults","GenResults");
  GenResults->Branch("lthCS",         &lamth_CS,         "lthCS/D");
  GenResults->Branch("lphCS",         &lamph_CS,         "lphCS/D");
  GenResults->Branch("ltpCS",         &lamtp_CS,         "ltpCS/D");
  GenResults->Branch("lthHX",         &lamth_HX,         "lthHX/D");
  GenResults->Branch("lphHX",         &lamph_HX,         "lphHX/D");
  GenResults->Branch("ltpHX",         &lamtp_HX,         "ltpHX/D");
  GenResults->Branch("lthPX",         &lamth_PX,         "lthPX/D");
  GenResults->Branch("lphPX",         &lamph_PX,         "lphPX/D");
  GenResults->Branch("ltpPX",         &lamtp_PX,         "ltpPX/D");

  GenResults->Fill();


  GenResultFile->Write();
  GenResultFile->Close();

  hfileout->Write();
  hfileout->Close();

} // end of main
Beispiel #29
0
  bool WTauStudy::processEvent(Event& event)
  {
      TLorentzVector w_vec;
      TLorentzVector el1_vec , el2_vec , nue_vec;
      TLorentzVector tau_vec , nutau1_vec , nutau2_vec;
      int w_id = -100; 
      int el1_id = -100, el2_id = -100, nue_id = -100;
      int tau_id = -100, nutau1_id = -100, nutau2_id = -100;
      vector<TLorentzVector> photon_vecs;

      _ana.wq = 0;
      _ana.mw = -1;
      _ana.wpt = -1;
      _ana.elpt = -1;
      _ana.eleq = 0;
      _ana.nuelept = -1;
      _ana.taupt = -1;
      _ana.tauq = 0;
      _ana.met = -1;

      double metx=0 , mety=0;

      const TMBGlobal * _glob = event.getGlobal();
      _ana.nevt = _glob->evtno();
//       out() << "evtno " << _ana.nevt << endl;
      const TMBMCevtInfo * _mcglob = event.getMCEventInfo();
      _ana.event_weight = _mcglob->weight();
//       out() << "evtwt " << _ana.event_weight << endl;

      int nparts = _mcglob->npart(0);
//       out() << "nparts " << nparts << endl;

//       _ana.event_weight = stat.pointer()->eventWeight();
//       _ana.event_weight = 1.0;
      
//       Collection<TMBMCvtx>  AllMCvtxs  = event.getMCVertices();
//       const TMBMCvtx &PV = AllMCvtxs[0];
      
      cafe::Collection<TMBMCpart> mcparts = event.getMCParticles();
//       out() << "mcparts size " << mcparts.size() << endl;

      TLorentzVector ele , nue , tau , pi;
      int number_of_w = 0;
      for( int i = 0 ; i < nparts ; i++ )
      {
        const TMBMCpart * ptcl = &mcparts[i];
        int absid = ptcl->abspdgid();
        int id = ptcl->pdgid();
        
//         if( ptcl->isStable() != 1 )
//           continue;

        const TMBMCvtx *vtx = ptcl->getDMCvtx();
        
        if( absid != 24 ) continue;
        if( id == 24 ) {
          w_id = 80;
          number_of_w++;
        }
        else if( id == -24 ) {
          w_id = -80;
          number_of_w++;
        }
        else if( id == 23 ) w_id = 90;
        if( !vtx ) continue;
        int ndaughters = vtx->ndaughters();
//         out() << "W ndaughters " << ndaughters << " " << absid << " " << ptcl->isStable() << endl;
        if( ndaughters == 0 ) continue;

        double px = ptcl->Px();
        double py = ptcl->Py();
        double pz = ptcl->Pz();
        double pE = ptcl->E();
        double pT = ptcl->Pt();
        double mass = ptcl->M();
        double eta = ptcl->Eta();

        w_vec.SetPxPyPzE( px , py , pz , pE );

        _ana.mw = mass;
        _ana.wpt = pT;
        _ana.weta = eta;
        _ana.wq = int(ptcl->charge());

        for( int j = 0 ; j < ndaughters ; j++ )
        {
          const TMBMCpart* daught = vtx->getDaughter(j);
          const TMBMCvtx *dvtx = daught->getDMCvtx();
          
//           if( daught->isStable() != 1 )
//             continue;
          
          absid = daught->abspdgid();
          id = daught->pdgid();
          
          px = daught->Px();
          py = daught->Py();
          pz = daught->Pz();
          pE = daught->E();
          pT = daught->Pt();
          eta = daught->Eta();
          
          if( absid == 16 )
          {
            _ana.nutaupt[0] = pT;
            _ana.nutaueta[0] = eta;
            metx -= px;
            mety -= py;
          }
          else if( absid == 15 )
          {
            _ana.taupt = pT;
            _ana.taueta = eta;
            _ana.tauq = int(daught->charge());
            tau.SetPxPyPzE(px,py,pz,pE);
          }

          if( absid != 15 ) continue;
          if( !dvtx ) continue;
          int nddaughters = dvtx->ndaughters();
//           out() << "W ndaughters " << nddaughters << endl;
          if( nddaughters == 0 ) continue;
          for( int k = 0 ; k < nddaughters ; k++ )
          {
            const TMBMCpart* ddaught = dvtx->getDaughter(k);
            
            absid = ddaught->abspdgid();
            id = ddaught->pdgid();
            
            px = ddaught->Px();
            py = ddaught->Py();
            pz = ddaught->Pz();
            pE = ddaught->E();
            pT = ddaught->Pt();
            eta = ddaught->Eta();
            
            if( absid == 11 )
            {
              _ana.elpt = pT;
              _ana.eleta = eta;
              _ana.eleq = int(ddaught->charge());
              ele.SetPxPyPzE(px,py,pz,pE);
            }
            else if( absid == 12 )
            {
              _ana.nuelept = pT;
              _ana.nueleeta = eta;
              metx -= px;
              mety -= py;
              nue.SetPxPyPzE(px,py,pz,pE);
            }
            else if( absid == 16 )
            {
              _ana.nutaupt[1] = pT;
              _ana.nutaueta[1] = eta;
              metx -= px;
              mety -= py;
            }
            else if( absid == 211 )
            {
              pi.SetPxPyPzE(px,py,pz,pE);
            }
          }
          if( _ana.elpt < 0 ) return false;
//           if( !(pi.E() > 0 ) || nddaughters>2 ) return false;
        }
      }
//       cout << " number of w bosons " << number_of_w << endl;
      if( pi.E() > 0 )
      {
        _ewetau->Fill( pi.E()/tau.E() );
        _ptwtau->Fill( pi.Pt() );
      }
      else
      {
        _ewetau->Fill( (ele+nue).E() / tau.E() );
        _ptwtau->Fill( (ele+nue).Pt() );
      }

      _ana.met = TMath::Sqrt( metx*metx + mety*mety );

      _MW_hist->Fill( _ana.mw , _ana.event_weight );
      _WPT_hist->Fill( _ana.wpt , _ana.event_weight );
      _WETA_hist->Fill( _ana.weta , _ana.event_weight );
      _ELPT_hist->Fill( _ana.elpt , _ana.event_weight );
      _ELETA_hist->Fill( _ana.eleta , _ana.event_weight );
      _NUELEPT_hist->Fill( _ana.nuelept , _ana.event_weight );
      _NUELEPT_hist->Fill( _ana.nuelept , _ana.event_weight );
      _NUELETA_hist->Fill( _ana.nueleeta , _ana.event_weight );
      _NUELETA_hist->Fill( _ana.nueleeta , _ana.event_weight );
      _TAUPT_hist->Fill( _ana.taupt , _ana.event_weight );
      _TAUETA_hist->Fill( _ana.taueta , _ana.event_weight );
      _NUTAUPT_hist->Fill( _ana.nutaupt[0] , _ana.event_weight );
      _NUTAUPT_hist->Fill( _ana.nutaupt[1] , _ana.event_weight );
      _NUTAUETA_hist->Fill( _ana.nutaueta[0] , _ana.event_weight );
      _NUTAUETA_hist->Fill( _ana.nutaueta[1] , _ana.event_weight );
      _PIPT_hist->Fill( pi.Pt() , _ana.event_weight );
      _MET_hist->Fill( _ana.met , _ana.event_weight );

//       _ana_tree->Fill();

      return true;

  }
int main(int argc, char * argv[]) {

	// first argument - config file 
	// second argument - filelist

	using namespace std;

	// **** configuration
	Config cfg(argv[1]);

	const bool isData = cfg.get<bool>("IsData");
	const bool applyGoodRunSelection = cfg.get<bool>("ApplyGoodRunSelection");

	// pile up reweighting
	const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");

	//const bool applyPUreweighting = cfg.get<bool>("ApplyPUreweighting");
	const bool applyLeptonSF = cfg.get<bool>("ApplyLeptonSF");

	// kinematic cuts on muons
	const float ptMuonLowCut   = cfg.get<float>("ptMuonLowCut");
	const float ptMuonHighCut  = cfg.get<float>("ptMuonHighCut");
	const float etaMuonHighCut = cfg.get<float>("etaMuonHighCut");
	const float etaMuonLowCut = cfg.get<float>("etaMuonLowCut");
	const double etaMuonCut     = cfg.get<double>("etaMuonCut");
	const float dxyMuonCut     = cfg.get<float>("dxyMuonCut");
	const float dzMuonCut      = cfg.get<float>("dzMuonCut");
	const float isoMuonCut     = cfg.get<float>("isoMuonCut");
	//const bool  applyTauTauSelection = cfg.get<bool>("ApplyTauTauSelection");
	//const bool  selectZToTauTauMuMu = cfg.get<bool>("SelectZToTauTauMuMu");

	// topological cuts

	// trigger
	const bool applyTrigger = cfg.get<bool>("ApplyTrigger");
	const string muonTriggerName  = cfg.get<string>("MuonTriggerName");
	const string muonFilterName   = cfg.get<string>("MuonFilterName");
	const string muon17FilterName = cfg.get<string>("Muon17FilterName"); 
	const string muon8FilterName = cfg.get<string>("Muon8FilterName"); 
	const string singleMuonFilterName = cfg.get<string>("SingleMuonFilterName");
	const float singleMuonTriggerPtCut = cfg.get<float>("SingleMuonTriggerPtCut");
	const float singleMuonTriggerEtaCut = cfg.get<float>("SingleMuonTriggerEtaCut");


	TString MuonTriggerName(muonTriggerName);
	TString MuonFilterName(muonFilterName);

	TString Muon17FilterName(muon17FilterName);
	TString Muon8FilterName(muon8FilterName);
	TString SingleMuonFilterName(singleMuonFilterName);

	const double leadchargedhadrcand_dz = cfg.get<double>("leadchargedhadrcand_dz");
	const double leadchargedhadrcand_dxy = cfg.get<double>("leadchargedhadrcand_dxy");

	const double etaJetCut   = cfg.get<double>("etaJetCut");
	const double ptJetCut   = cfg.get<double>("ptJetCut");


	// topological cuts
	const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
	const float dPhileptonsCut = cfg.get<float>("dPhileptonsCut");
	const float DRTrigMatch    = cfg.get<float>("DRTrigMatch"); 
	const double dRleptonsCutmutau   = cfg.get<double>("dRleptonsCutmutau");
	const double dZetaCut       = cfg.get<double>("dZetaCut");
	const double deltaRTrigMatch = cfg.get<double>("DRTrigMatch");
	const bool oppositeSign    = cfg.get<bool>("oppositeSign");
	const bool isIsoR03 = cfg.get<bool>("IsIsoR03");

	// tau
	const double taupt    = cfg.get<double>("taupt");
	const double taueta    = cfg.get<double>("taueta");
	const double decayModeFinding    = cfg.get<double>("decayModeFinding");
	const double   decayModeFindingNewDMs  = cfg.get<double>("decayModeFindingNewDMs");
	const double   againstElectronVLooseMVA5  = cfg.get<double>("againstElectronVLooseMVA5");
	const double   againstMuonTight3  = cfg.get<double>("againstMuonTight3");
	const double   vertexz =  cfg.get<double>("vertexz");
	const double   byCombinedIsolationDeltaBetaCorrRaw3Hits = cfg.get<double>("byCombinedIsolationDeltaBetaCorrRaw3Hits");




	// vertex cuts
	const float ndofVertexCut  = cfg.get<float>("NdofVertexCut");   
	const float zVertexCut     = cfg.get<float>("ZVertexCut");
	const float dVertexCut     = cfg.get<float>("DVertexCut");

	// jet related cuts
	//const float jetEtaCut      = cfg.get<float>("JetEtaCut");
	//const float jetEtaTrkCut   = cfg.get<float>("JetEtaTrkCut");
	//const float jetPtHighCut   = cfg.get<float>("JetPtHighCut");
	//const float jetPtLowCut    = cfg.get<float>("JetPtLowCut");
	//const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");

	// Run range
	const unsigned int RunRangeMin = cfg.get<unsigned int>("RunRangeMin");
	const unsigned int RunRangeMax = cfg.get<unsigned int>("RunRangeMax");

	//
	const string dataBaseDir = cfg.get<string>("DataBaseDir");

	// vertex distributions filenames and histname
	const string vertDataFileName = cfg.get<string>("VertexDataFileName");
	const string vertMcFileName   = cfg.get<string>("VertexMcFileName");
	const string vertHistName     = cfg.get<string>("VertexHistName");

	// lepton scale factors
	const string muonSfDataBarrel = cfg.get<string>("MuonSfDataBarrel");
	const string muonSfDataEndcap = cfg.get<string>("MuonSfDataEndcap");
	const string muonSfMcBarrel = cfg.get<string>("MuonSfMcBarrel");
	const string muonSfMcEndcap = cfg.get<string>("MuonSfMcEndcap");

	const string jsonFile = cfg.get<string>("jsonFile");
	string TrigLeg  ;
	if (!isData) TrigLeg  = cfg.get<string>("Mu17LegMC");
	if (isData) TrigLeg  = cfg.get<string>("Mu18LegData");
  	const string Region  = cfg.get<string>("Region");
  	const string Sign  = cfg.get<string>("Sign");
	
	TString MainTrigger(TrigLeg);
	// **** end of configuration

	string cmsswBase = (getenv ("CMSSW_BASE"));
	string fullPathToJsonFile = cmsswBase + "/src/DesyTauAnalyses/NTupleMaker/test/json/" + jsonFile;

	// Run-lumi selector
	std::vector<Period> periods;  
	if (isData) { // read the good runs 
		std::fstream inputFileStream(fullPathToJsonFile.c_str(), std::ios::in);
		if (inputFileStream.fail() ) {
			std::cout << "Error: cannot find json file " << fullPathToJsonFile << std::endl;
			std::cout << "please check" << std::endl;
			std::cout << "quitting program" << std::endl;
			exit(-1);
		}

		for(std::string s; std::getline(inputFileStream, s); ) {
			periods.push_back(Period());
			std::stringstream ss(s);
			ss >> periods.back();
		}
	}
	char ff[100];

	sprintf(ff,"%s/%s",argv[3],argv[2]);
	// file name and tree name
	std::string rootFileName(argv[2]);
	std::ifstream fileList(ff);
	std::ifstream fileList0(ff);
	std::string ntupleName("makeroottree/AC1B");

	TString era=argv[3];
  	TString TStrName(rootFileName+"_"+Region+"_"+Sign);
	std::cout <<TStrName <<std::endl;  
  	datasetName = rootFileName.c_str();

	TFile * file ;//= new TFile(era+"/"+TStrName+TString(".root"),"update");
  	if (isData) file = new TFile(era+"/"+TStrName+TString("_DataDriven.root"),"update");
  	if (!isData) file = new TFile(era+"/"+TStrName+TString(".root"),"update");
	file->cd("");
	/*
	// file name and tree name
	std::string rootFileName(argv[2]);
	std::ifstream fileList(argv[2]);
	std::ifstream fileList0(argv[2]);
	std::string ntupleName("makeroottree/AC1B");

	TString TStrName(rootFileName);
	TString era=argv[3];
	std::cout <<TStrName <<std::endl;  

	TFile * file = new TFile(TStrName+TString(".root"),"recreate");
	file->cd("");
	*/
	std::string initNtupleName("initroottree/AC1B");
	TH1D * inputEventsH = new TH1D("inputEventsH","",1,-0.5,0.5);
	TH1D * histWeightsH = new TH1D("histWeightsH","",1,-0.5,0.5);
	TH1D * histWeightsSkimmedH = new TH1D("histWeightsSkimmedH","",1,-0.5,0.5);

	// Histograms after selecting unique dimuon pair
	TH1D * massSelH = new TH1D("massSelH","",200,0,200);
	TH1D * metSelH  = new TH1D("metSelH","",200,0,400);

	TH1D * hDiJetmet = new TH1D("hDiJetmet","",200,0,400);
	TH1D * hDiJetmass = new TH1D("hDiJetmass","",500,0,1000);
	TH1D * hHT_ = new TH1D("hHT_","",800,0,1600);
	TH1D * metAll  = new TH1D("metAll","",200,0,400);

	TH1D * muon1PtH = new TH1D("muon1PtH","",200,0,400);
	TH1D * muon2PtH = new TH1D("muon2PtH","",200,0,400);

	TH1F * NumberOfVerticesH = new TH1F("NumberOfVerticesH","",51,-0.5,50.5);


	//*****  create eta histogram with eta ranges associated to their names (eg. endcap, barrel)   ***** //

	TFile * fileDataNVert = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertDataFileName);
  	TFile * fileMcNVert   = new TFile(TString(cmsswBase)+"/src/"+dataBaseDir+"/"+vertMcFileName);


	TH1D * vertexDataH = (TH1D*)fileDataNVert->Get(TString(vertHistName));
	TH1D * vertexMcH   = (TH1D*)fileMcNVert->Get(TString(vertHistName));

	float normVertexData = vertexDataH->GetSumOfWeights();
	float normVertexMc   = vertexMcH->GetSumOfWeights();

	vertexDataH->Scale(1/normVertexData);
	vertexMcH->Scale(1/normVertexMc);


	PileUp * PUofficial = new PileUp();

	TFile * filePUdistribution_data = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/Data_Pileup_2015D_Nov17.root","read");
	TFile * filePUdistribution_MC = new TFile (TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/PileUpDistrib/MC_Spring15_PU25_Startup.root", "read");
	TH1D * PU_data = (TH1D *)filePUdistribution_data->Get("pileup");
	TH1D * PU_mc = (TH1D *)filePUdistribution_MC->Get("pileup");
	PUofficial->set_h_data(PU_data);
	PUofficial->set_h_MC(PU_mc);


	TFile *f10= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataBarrel);  // mu SF barrel data
	TFile *f11 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfDataEndcap); // mu SF endcap data
	TFile *f12= new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcBarrel);  // mu SF barrel MC
	TFile *f13 = new TFile(TString(cmsswBase)+"/src/DesyTauAnalyses/NTupleMaker/data/"+muonSfMcEndcap); // mu SF endcap MC 

	TGraphAsymmErrors *hEffBarrelData = (TGraphAsymmErrors*)f10->Get("ZMassBarrel");
	TGraphAsymmErrors *hEffEndcapData = (TGraphAsymmErrors*)f11->Get("ZMassEndcap");
	TGraphAsymmErrors *hEffBarrelMC = (TGraphAsymmErrors*)f12->Get("ZMassBarrel");
	TGraphAsymmErrors *hEffEndcapMC = (TGraphAsymmErrors*)f13->Get("ZMassEndcap");

	double * dataEffBarrel = new double[10];
	double * dataEffEndcap = new double[10];
	double * mcEffBarrel = new double[10];
	double * mcEffEndcap = new double[10];

	dataEffBarrel = hEffBarrelData->GetY();
	dataEffEndcap = hEffEndcapData->GetY();
	mcEffBarrel = hEffBarrelMC->GetY();
	mcEffEndcap = hEffEndcapMC->GetY();
	double Weight=0;
	int nTotalFiles = 0;
	int nominator=-1;int denominator = -1;


	file->cd();
	TH1D * hMT = new TH1D("hMT","",20,0,200);
	TH1D * hMass = new TH1D("hMass","",20,0,200);
	TH1D * hRatioSum = new TH1D("hRatioSum","",10,0,1);
	TH1D * hDPhi = new TH1D("hDPhi","",70,0,3.5);

	int nPtBins = 3;
	//float ptBins[6] = {19,25,30,40,60,1000};
	float ptBins[4] = {19,25,40,1000};


/*
	TString PtBins[5] = {"Pt19to25",
		"Pt25to30",
		"Pt30to40",
		"Pt40to60",
		"PtGt60"};//,		       "Pt100to150",		       "Pt150to200",		        "PtGt200"};
*/
	TString PtBins[3] = {"Pt19to25",
		"Pt25to40",
		"PtGt40"};//,		       "Pt100to150",		       "Pt150to200",		        "PtGt200"};


//int nEtaBins = 3;
int nEtaBins = 1;
int nCuts = 4;
//float etaBins[4] = {0,0.9,1.2,2.4}; 
//float etaBins[3] = {0,1.48,2.4}; 
float etaBins[2] = {0,2.4}; 

TString EtaBins[1] = {
	//"EtaLt0p9",
	//"Eta0p9to1p2",
	//"EtaGt1p2"};
	"EtaLt2p4"};

TString Cuts[4] = {"Ratio","mT","DPhi","All"};
/////first stands for the Eta bin, second array for the cut 
TH1D * FakeRatePtIncLoose[1][4];
TH1D * FakeRatePtIncTight[2][4];


//TH1D * FakeRatePt[3][7];
//TH1D * FakeRateNV[3][7];
//TH1D * FakeRateEta[3][7];


TH1D * etaBinsH = new TH1D("etaBinsH", "etaBinsH", nEtaBins, etaBins);
etaBinsH->Draw();
etaBinsH->GetXaxis()->Set(nEtaBins, etaBins);
for (int i=0; i<nEtaBins; i++){ etaBinsH->GetXaxis()->SetBinLabel(i+1, EtaBins[i]);}


for (int iEta=0; iEta<nEtaBins; ++iEta) {
	for (int iCut=0; iCut<nCuts; ++iCut) {
		FakeRatePtIncLoose[iEta][iCut] = new TH1D("FakeRatePtIncLoose"+EtaBins[iEta]+Cuts[iCut],"",nPtBins,ptBins);
		FakeRatePtIncTight[iEta][iCut] = new TH1D("FakeRatePtIncTight"+EtaBins[iEta]+Cuts[iCut],"",nPtBins,ptBins);

	}

	//for (int iPt=0; iPt<nPtBins; ++iPt) {
	//  FakeRatePt[iEta][iPt] = new TH1D("FakeRatePt"+EtaBins[iEta]+PtBins[iPt],"",100,0,1000);
	//  FakeRateNV[iEta][iPt] = new TH1D("FakeRateNV"+EtaBins[iEta]+PtBins[iPt],"",50,0,50);
	//  FakeRateEta[iEta][iPt] = new TH1D("FakeRateEta"+EtaBins[iEta]+PtBins[iPt],"",80,-4,4);
	// }

}





int nFiles = 0;
int nEvents = 0;
int selEventsAllMuons = 0;
int selEventsIdMuons = 0;
int selEventsIsoMuons = 0;


std::string dummy;
// count number of files --->
while (fileList0 >> dummy) nTotalFiles++;

unsigned int RunMin = 9999999;
unsigned int RunMax = 0;
  ifstream ifs("xsecs");
  string line;

  while(std::getline(ifs, line)) // read one line from ifs
    {

      fact=fact2=1;
      istringstream iss(line); // access line as a stream

      // we only need the first two columns
      string dt,st1,st2;st1="stau2_1";st2="stau5_2";
      iss >> dt >> xs >> fact >> fact2;
      //datasetName = dt.c_str();
      //ifs >> dt >> xs; // no need to read further
      //cout<< " "<<dt<<"  "<<endl;
      //cout<< "For sample ========================"<<dt<<" xsecs is "<<xs<<" XSec "<<XSec<<"  "<<fact<<"  "<<fact2<<endl;
      //if (dt==argv[2]) {
      //if (std::string::npos != dt.find(argv[2])) {
      if (  dt == argv[2]) {
	XSec= xs*fact*fact2;
	cout<<" Found the correct cross section "<<xs<<" for Dataset "<<dt<<" XSec "<<XSec<<endl;
      }
      /*
	if ( argv[2] == st1) {ChiMass=100;mIntermediate=200;}
	else if (argv[2] == st2) {ChiMass=200;mIntermediate=500;}
      */
      if (isData) XSec=1.;
      ChiMass=0.0;
    }

  if (XSec<0&& !isData) {cout<<" Something probably wrong with the xsecs...please check  - the input was "<<argv[2]<<endl;return 0;}
	
  xsecs=XSec;

std::vector<unsigned int> allRuns; allRuns.clear();
vector <unsigned int> run_;
vector <unsigned int> lumi_;
vector <unsigned int> event_;
run_.clear();
lumi_.clear();
event_.clear();

std::vector<Event> EventList;
std::ifstream EventsFile;
TString file_events=argv[4]; //eventlist_csc2015.txt
//EventsFile.open("MET_filters/eventlist_"+file_events+".txt");
EventsFile.open(era+"/"+file_events+".txt");
//cout<<"  limits  int -> "<<std::numeric_limits<int>::max()<<"  long int -> "<<std::numeric_limits<long int>::max()<<"  unsigned int -> "<<std::numeric_limits<unsigned int>::max()<<endl;
cout<<" The file that will be used will be "<<era<<"/"<<file_events<<".txt"<<endl;


while (getline(EventsFile, line))
{
	std::vector<std::string> columns = split(line,':');
	run_.push_back(std::stoi(columns[0]));
	lumi_.push_back(std::stoi(columns[1]));
	event_.push_back(std::stoul(columns[2]));
	/*   Event events_;

	     events_.name     = "Test";
	     events_.run     = std::stoi(columns[0]);
	     events_.lumi   = std::stoi(columns[1]);
	     events_.eventrn = std::stof(columns[2]);

	     EventList.push_back(events_);
	     */
}

cout<<" In total there are "<<run_.size()<< " entries for "<<file_events<<" filter "<<endl;
EventsFile.close();
//----Attention----//
//if(XSec!=1) nTotalFiles=20;
//nTotalFiles=5;

if (argv[4] != NULL  && atoi(argv[4])< nTotalFiles) nTotalFiles=atoi(argv[4]);

cout<<" There are in total "<<nTotalFiles<<endl;
for (int iF=0; iF<nTotalFiles; ++iF) {

	std::string filen;
	fileList >> filen;

	std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
	TFile * file_ = TFile::Open(TString(filen));

	TH1D * histoInputEvents = NULL;
	histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
	if (histoInputEvents==NULL) continue;
	int NE = int(histoInputEvents->GetEntries());
	for (int iE=0;iE<NE;++iE)
		inputEventsH->Fill(0.);
	std::cout << "      number of input events         = " << NE << std::endl;

	TTree * _inittree = NULL;
	_inittree = (TTree*)file_->Get(TString(initNtupleName));
	if (_inittree==NULL) continue;
	Float_t genweight;
	if (!isData)
		_inittree->SetBranchAddress("genweight",&genweight);
	Long64_t numberOfEntriesInitTree = _inittree->GetEntries();
	std::cout << "      number of entries in Init Tree = " << numberOfEntriesInitTree << std::endl;
	for (Long64_t iEntry=0; iEntry<numberOfEntriesInitTree; iEntry++) {
		_inittree->GetEntry(iEntry);
		if (isData)
			histWeightsH->Fill(0.,1.);
		else
			histWeightsH->Fill(0.,genweight);
	}

	TTree * _tree = NULL;
	_tree = (TTree*)file_->Get(TString(ntupleName));
	if (_tree==NULL) continue;
	Long64_t numberOfEntries = _tree->GetEntries();
	std::cout << "      number of entries in Tree      = " << numberOfEntries << std::endl;
	AC1B analysisTree(_tree);


	// EVENT LOOP //
	for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) { 

		analysisTree.GetEntry(iEntry);
		nEvents++;

		if (nEvents%50000==0) 
			cout << "      processed " << nEvents << " events" << endl; 

		float weight = 1;

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

		if (!isData) 
			weight *=analysisTree.genweight;

		histWeightsSkimmedH->Fill(float(0),weight);

		if (!isData) {/*
			if (applyPUreweighting_vertices) {
				int binNvert = vertexDataH->FindBin(analysisTree.primvertex_count);
				float_t dataNvert = vertexDataH->GetBinContent(binNvert);
				float_t mcNvert = vertexMcH->GetBinContent(binNvert);
				if (mcNvert < 1e-10){mcNvert=1e-10;}
				float_t vertWeight = dataNvert/mcNvert;
				weight *= vertWeight;
				//	  cout << "NVert = " << analysisTree.primvertex_count << "   weight = " << vertWeight << endl;
			}
*/
			if (applyPUreweighting) {

				double Ninteractions = analysisTree.numtruepileupinteractions;
				double PUweight = PUofficial->get_PUweight(Ninteractions);
				weight *= PUweight;
				//PUweightsOfficialH->Fill(PUweight);

			}
/*
			if (applyTauTauSelection) {
				unsigned int nTaus = 0;
				if (analysisTree.gentau_count>0) {
					//	  cout << "Generated taus present" << endl;
					for (unsigned int itau = 0; itau < analysisTree.gentau_count; ++itau) {
						//	    cout << itau << "  : pt = " 
						//		 << analysisTree.gentau_visible_pt[itau] 
						//		 << "   eta = " <<  analysisTree.gentau_visible_eta[itau]
						//		 << "   mother = " << int(analysisTree.gentau_mother[itau]) << endl;
						if (int(analysisTree.gentau_mother[itau])==3) nTaus++;

					}
				}
				bool notTauTau = nTaus < 2;
				//	  std::cout << "nTaus = " << nTaus << std::endl;

				if (selectZToTauTauMuMu&&notTauTau) { 
					//	    std::cout << "Skipping event..." << std::endl;
					//	    cout << endl;
					continue;
				}
				if (!selectZToTauTauMuMu&&!notTauTau) { 
					//	    std::cout << "Skipping event..." << std::endl;
					//	    cout << endl;
					continue;
				}
				//	  cout << endl;
			}*/
		}

		if (isData && applyGoodRunSelection){


			bool lumi = false;
			int n=analysisTree.event_run;
			int lum = analysisTree.event_luminosityblock;
			int nr = analysisTree.event_nr;

			std::string num = std::to_string(n);
			std::string lnum = std::to_string(lum);
			for(const auto& a : periods)
			{

				if ( num.c_str() ==  a.name ) {
					//std::cout<< " Eureka "<<num<<"  "<<a.name<<" ";
					//     std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;

					for(auto b = a.ranges.begin(); b != std::prev(a.ranges.end()); ++b) {

						//	cout<<b->lower<<"  "<<b->bigger<<endl;
						if (lum  >= b->lower && lum <= b->bigger ) lumi = true;
					}
					auto last = std::prev(a.ranges.end());
					//    std::cout <<"min "<< last->lower << "- max last " << last->bigger << std::endl;
					if (  (lum >=last->lower && lum <= last->bigger )) lumi=true;


				}

			}

			if (!lumi) continue;
			bool runbool=false;
			bool lumibool=false;
			bool eventbool=false;
			runbool= std::find(run_.begin(), run_.end(), n) != run_.end();
			lumibool= std::find(lumi_.begin(), lumi_.end(), lum) != lumi_.end();
			eventbool= std::find(event_.begin(), event_.end(), nr) != event_.end();

			if (runbool && lumibool && eventbool) continue;
			//if (lumi ) cout<<"  =============  Found good run"<<"  "<<n<<"  "<<lum<<endl;
			//std::remove("myinputfile");
		}     
		float metall = sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex+analysisTree.pfmet_ey*analysisTree.pfmet_ey);
		metAll->Fill(metall,weight);

		if (analysisTree.event_run<RunMin)
			RunMin = analysisTree.event_run;

		if (analysisTree.event_run>RunMax)
			RunMax = analysisTree.event_run;

		//std::cout << " Run : " << analysisTree.event_run << std::endl;

		bool isNewRun = true;
		if (allRuns.size()>0) {
			for (unsigned int iR=0; iR<allRuns.size(); ++iR) {
				if (analysisTree.event_run==allRuns.at(iR)) {
					isNewRun = false;
					break;
				}
			}
		}

		if (isNewRun) 
			allRuns.push_back(analysisTree.event_run);
			unsigned int nMainTrigger = 0;
			bool isMainTrigger = false;

		unsigned int nMuonFilter = 0;

			unsigned int nfilters = analysisTree.run_hltfilters->size();
			//  std::cout << "nfiltres = " << nfilters << std::endl;
			for (unsigned int i=0; i<nfilters; ++i) {
				//	std::cout << "HLT Filter : " << i << " = " << analysisTree.run_hltfilters->at(i) << std::endl;
				TString HLTFilter(analysisTree.run_hltfilters->at(i));
				if (HLTFilter==MainTrigger) {
					nMainTrigger = i;
					isMainTrigger = true;
					nMuonFilter = i;
				}



			}

			if (!isMainTrigger) {
				std::cout << "Fail on main HLT Filter " << MainTrigger << " not found" << std::endl;
				return(-1);
			}



/*

		bool isTriggerMuon = false;
		for (std::map<string,int>::iterator it=analysisTree.hltriggerresults->begin(); it!=analysisTree.hltriggerresults->end(); ++it) {
			TString trigName(it->first);
			if (trigName.Contains(MuonTriggerName)) {
				//	  std::cout << it->first << " : " << it->second << std::endl;
				if (it->second==1)
					isTriggerMuon = true;
			}
		}

		if (applyTrigger && !isTriggerMuon) continue;

		unsigned int nMuonFilter = 0;
		bool isMuonFilter = false;

		unsigned int nMuon17Filter = 0;
		bool isMuon17Filter = false;

		unsigned int nMuon8Filter = 0;
		bool isMuon8Filter = false;

		unsigned int nSingleMuonFilter = 0;
		bool isSingleMuonFilter = false;

		unsigned int nfilters = analysisTree.run_hltfilters->size();
		for (unsigned int i=0; i<nfilters; ++i) {
			TString HLTFilter(analysisTree.run_hltfilters->at(i));
			if (HLTFilter==MuonFilterName) {
				nMuonFilter = i;
				isMuonFilter = true;
			}
			if (HLTFilter==Muon17FilterName) {
				nMuon17Filter = i;
				isMuon17Filter = true;
			}
			if (HLTFilter==Muon8FilterName) {
				nMuon8Filter = i;
				isMuon8Filter = true;
			}
			if (HLTFilter==SingleMuonFilterName) {
				nSingleMuonFilter = i;
				isSingleMuonFilter = true;
			}
		}
		if (!isMuonFilter) {
			cout << "Filter " << MuonFilterName << " not found " << endl;
			exit(-1);
		}
		if (!isMuon17Filter) {
			cout << "Filter " << Muon17FilterName << " not found " << endl;
			exit(-1);
		}
		if (!isMuon8Filter) {
			cout << "Filter " << Muon8FilterName << " not found " << endl;
			exit(-1);
		}
		if (!isSingleMuonFilter) {
			cout << "Filter " << SingleMuonFilterName << " not found " << endl;
			exit(-1);
		}
*/
		// vertex cuts

		if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
		if (analysisTree.primvertex_ndof<ndofVertexCut) continue;
		float dVertex = (analysisTree.primvertex_x*analysisTree.primvertex_x+
				analysisTree.primvertex_y*analysisTree.primvertex_y);
		if (dVertex>dVertexCut) continue;

		// muon selection

		vector<unsigned int> allMuons; allMuons.clear();
		vector<unsigned int> idMuons; idMuons.clear();
		vector<unsigned int> isoMuons; isoMuons.clear();
		vector<float> isoMuonsValue; isoMuonsValue.clear();
		vector<bool> isMuonPassedIdIso; isMuonPassedIdIso.clear();
		vector<bool> isMuonMatched23Filter; isMuonMatched23Filter.clear();
		vector<bool> isMuonMatched17Filter; isMuonMatched17Filter.clear();
		vector<bool> isMuonMatched8Filter; isMuonMatched8Filter.clear();
		vector<bool> isMuonMatchedSingleMuFilter; isMuonMatchedSingleMuFilter.clear();

		for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
			allMuons.push_back(im);
			bool muPassed    = true;
			bool mu23Matched = false;
			bool mu17Matched = false;
			bool mu8Matched  = false;
			bool muSingleMatched = false;
			if (analysisTree.muon_pt[im]<5) muPassed = false;
			if (fabs(analysisTree.muon_eta[im])>etaMuonLowCut) muPassed = false;
			if (fabs(analysisTree.muon_dxy[im])>dxyMuonCut) muPassed = false;
			if (fabs(analysisTree.muon_dz[im])>dzMuonCut) muPassed = false;
			if (!analysisTree.muon_isMedium[im]) muPassed = false;
			if (muPassed) idMuons.push_back(im);
			float absIso = analysisTree.muon_r03_sumChargedHadronPt[im];
			float neutralIso = analysisTree.muon_r03_sumNeutralHadronEt[im] + 
				analysisTree.muon_r03_sumPhotonEt[im] - 
				0.5*analysisTree.muon_r03_sumPUPt[im];
			neutralIso = TMath::Max(float(0),neutralIso); 
			absIso += neutralIso;
			float relIso = absIso/analysisTree.muon_pt[im];
			if (relIso>isoMuonCut) muPassed = false;
			if (muPassed && analysisTree.muon_pt[im]>ptMuonLowCut) { 
				isoMuons.push_back(im);
				isoMuonsValue.push_back(relIso);
			}

			isMuonPassedIdIso.push_back(muPassed);


			for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
				if (analysisTree.trigobject_filters[iT][nMainTrigger]) { // Mu17 Leg
					double dRtrig = deltaR(analysisTree.muon_eta[im],analysisTree.muon_phi[im],
							analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
					if (dRtrig>deltaRTrigMatch) continue;
					//if (!isData && analysisTree.trigobject_filters[iT][nMainTrigger] && analysisTree.trigobject_pt[iT]>18) 
					isMainTrigger = true;

				}
			}

			if (!isMainTrigger) continue;


/*
			//	cout << "pt:" << analysisTree.muon_pt[im] << "  passed:" << muPassed << endl;
			for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
				float dRtrig = deltaR(analysisTree.muon_eta[im],analysisTree.muon_phi[im],
						analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
				if (dRtrig>DRTrigMatch) continue;
				if (analysisTree.trigobject_filters[iT][nMuon17Filter] && analysisTree.trigobject_pt[iT]>23.0) 
					mu23Matched = true;
				if (analysisTree.trigobject_filters[iT][nMuon17Filter] && analysisTree.trigobject_pt[iT]>17.0)
					mu17Matched = true;
				if (analysisTree.trigobject_filters[iT][nSingleMuonFilter] && analysisTree.trigobject_pt[iT]>singleMuonTriggerPtCut)
					muSingleMatched = true;
				if (analysisTree.trigobject_filters[iT][nMuon8Filter] && analysisTree.trigobject_pt[iT]>8.0) 
					mu8Matched = true;

			}
			isMuonMatched23Filter.push_back(mu23Matched);
			isMuonMatched17Filter.push_back(mu17Matched);
			isMuonMatched8Filter.push_back(mu8Matched);
			isMuonMatchedSingleMuFilter.push_back(muSingleMatched);*/
		}


		unsigned int indx1 = 0;
		unsigned int indx2 = 0;
		bool isIsoMuonsPair = false;
		float isoMin = 9999;
		if (isoMuons.size()>0) {
			for (unsigned int im1=0; im1<isoMuons.size(); ++im1) {
				unsigned int index1 = isoMuons[im1];
				bool isMu1matched = false;
				for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
					float dRtrig = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
							analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
					if (dRtrig>DRTrigMatch) continue;
					if (analysisTree.trigobject_filters[iT][nMainTrigger] && 
							analysisTree.muon_pt[index1] > ptMuonHighCut &&
							fabs(analysisTree.muon_eta[index1]) < etaMuonHighCut) 
						isMu1matched = true;
				}
				if (isMu1matched) {
					for (unsigned int iMu=0; iMu<allMuons.size(); ++iMu) {
						unsigned int indexProbe = allMuons[iMu];
						if (index1==indexProbe) continue;
						float q1 = analysisTree.muon_charge[index1];
						float q2 = analysisTree.muon_charge[indexProbe];
						if (q1*q2>0) continue;
						float dR = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
								analysisTree.muon_eta[indexProbe],analysisTree.muon_phi[indexProbe]);
						if (dR<dRleptonsCut) continue; 
						float dPhi = dPhiFrom2P(analysisTree.muon_px[index1],analysisTree.muon_py[index1],
								analysisTree.muon_px[indexProbe],analysisTree.muon_py[indexProbe]);
						if (dPhi>dPhileptonsCut) continue;
						TLorentzVector muon1; muon1.SetXYZM(analysisTree.muon_px[index1],
								analysisTree.muon_py[index1],
								analysisTree.muon_pz[index1],
								muonMass);
						TLorentzVector muon2; muon2.SetXYZM(analysisTree.muon_px[indexProbe],
								analysisTree.muon_py[indexProbe],
								analysisTree.muon_pz[indexProbe],
								muonMass);


						float mass = (muon1+muon2).M();
					}
				}
				for (unsigned int im2=im1+1; im2<isoMuons.size(); ++im2) {
					unsigned int index2 = isoMuons[im2];
					float q1 = analysisTree.muon_charge[index1];
					float q2 = analysisTree.muon_charge[index2];
					bool isMu2matched = false;
					for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
						float dRtrig = deltaR(analysisTree.muon_eta[index2],analysisTree.muon_phi[index2],
								analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
						if (dRtrig>DRTrigMatch) continue;
						if (analysisTree.trigobject_filters[iT][nMainTrigger] && 
								analysisTree.muon_pt[index2] > ptMuonHighCut &&
								fabs(analysisTree.muon_eta[index2]) < etaMuonHighCut) 
							isMu2matched = true;
					}
					bool isPairSelected = q1*q2 > 0;
					if (oppositeSign) isPairSelected = q1*q2 < 0;
					bool isTriggerMatch = (isMu1matched || isMu2matched);
					float dRmumu = deltaR(analysisTree.muon_eta[index1],analysisTree.muon_phi[index1],
							analysisTree.muon_eta[index2],analysisTree.muon_phi[index2]);
					if (isTriggerMatch && isPairSelected && dRmumu>dRleptonsCut) {
						bool sumIso = isoMuonsValue[im1]+isoMuonsValue[im2];
						if (sumIso<isoMin) {
							isIsoMuonsPair = true;
							isoMin = sumIso;
							if (analysisTree.muon_pt[index1]>analysisTree.muon_pt[index2]) {
								indx1 = index1;
								indx2 = index2;
							}
							else {
								indx2 = index1;
								indx1 = index2;
							}
						}
					}
				}
			}
		}
		if (isIsoMuonsPair) {      
			//match to genparticles

			double isoTauMin = 999;
			bool tau_iso = false;
			bool isTight = false;
			bool isLoose = false;
			unsigned tau_loose=-1;
			vector<int> tau; tau.clear();


			for (unsigned  int it = 0; it<analysisTree.tau_count; ++it) {

				if (analysisTree.tau_pt[it] < ptMuonLowCut || fabs(analysisTree.tau_eta[it])> etaMuonCut) continue;
				if (analysisTree.tau_decayModeFindingNewDMs[it]<decayModeFindingNewDMs) continue;
				if ( fabs(analysisTree.tau_leadchargedhadrcand_dz[it])> leadchargedhadrcand_dz) continue;
				double  tauIso = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[it];

				isLoose  = true;
				tau_loose = int(it);

				if (analysisTree.tau_byMediumCombinedIsolationDeltaBetaCorr3Hits [it]> 0.5  && analysisTree.tau_againstElectronVLooseMVA5[it]>againstElectronVLooseMVA5 
						&& analysisTree.tau_againstMuonTight3[it]>againstMuonTight3) {isTight = true;	  tau_tight = int(it);}




			}


			if (!isLoose) continue;
			TLorentzVector JetsV;

			JetsMV.clear();
			int countjets=0;
			for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
				float absJetEta = fabs(analysisTree.pfjet_eta[jet]);

				if (analysisTree.pfjet_pt[jet] < 19) continue;
				if (absJetEta > etaJetCut) continue;
				//if (fabs(analysisTree.pfjet_pt[jet])<ptJetCut) continue;
				bool  looseJetID = looseJetiD(analysisTree,jet);
				if (!looseJetID) continue;	  

				double dRmuJet1 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
						analysisTree.muon_eta[indx1],analysisTree.muon_phi[indx1]);

				if (dRmuJet1 < 0.5) continue;
				double dRmuJet2 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
						analysisTree.muon_eta[indx2],analysisTree.muon_phi[indx2]);

				if (dRmuJet2 < 0.5) continue;

				JetsV.SetPxPyPzE(0.,0.,0.,0.);
				JetsV.SetPxPyPzE(analysisTree.pfjet_px[jet], analysisTree.pfjet_py[jet], analysisTree.pfjet_pz[jet], analysisTree.pfjet_e[jet]);
				JetsMV.push_back(JetsV);	
				countjets++;
			}
			sort(JetsMV.begin(), JetsMV.end(),ComparePt);

			if (countjets ==0) continue;



			double dPhi=-1;double MT=-1 ; double RatioSums=-1;


			double met = sqrt ( analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
			// w = mu+MET
			// ptW - ptJ/ptW+ptJ      
			//
			//

			TLorentzVector muon1; muon1.SetXYZM(analysisTree.muon_px[indx1],
					analysisTree.muon_py[indx1],
					analysisTree.muon_pz[indx1],
					muonMass);
			TLorentzVector muon2; muon2.SetXYZM(analysisTree.muon_px[indx2],
					analysisTree.muon_py[indx2],
					analysisTree.muon_pz[indx2],
					muonMass);
			TLorentzVector DiM = muon1+muon2;

			RatioSums = analysisTree.tau_pt[tau_loose]/DiM.Pt();


			TLorentzVector MetV; 
			MetV.SetPx(analysisTree.pfmet_ex); 
			MetV.SetPy(analysisTree.pfmet_ey);

			TLorentzVector tauV;  tauV.SetPtEtaPhiM(analysisTree.tau_pt[tau_loose], analysisTree.tau_eta[tau_loose], analysisTree.tau_phi[tau_loose], tauMass);

			TLorentzVector DiL = DiM  + tauV;

			//dPhi = dPhiFrom2P( DiM.Px(), DiM.Py(), MetV.Px(),  MetV.Py() );
			dPhi = dPhiFrom2P( DiM.Px(), DiM.Py(), analysisTree.tau_px[tau_loose],analysisTree.tau_py[tau_loose]);
			MT = TMath::Sqrt(2*DiM.Pt()*MetV.Pt()*(1-TMath::Cos(dPhi)));


			hRatioSum->Fill(RatioSums,weight);
			hMT->Fill(MT,weight);
			hMass->Fill(DiM.M(),weight);
			hDPhi->Fill(dPhi, weight);


			//if (tau.size()==0 || !tau_iso ) continue;

			//cout<<"  "<<endl;
			if (isLoose) denominator++;
			if (isTight) nominator++;

			if (isLoose){
				float ptProbe = TMath::Min(float(analysisTree.tau_pt[tau_loose]),float(ptBins[nPtBins]-0.1));
				float absEtaProbe = fabs(analysisTree.tau_eta[tau_loose]);
				int ptBin = binNumber(ptProbe,nPtBins,ptBins);
				if (ptBin<0) continue;
				int etaBin = binNumber(absEtaProbe,nEtaBins,etaBins);
				if (etaBin<0) continue;

				//cout<< "filling here  "<<analysisTree.tau_pt[tau_loose]<<"  "<<ptBin<<"  "<<etaBin<<"  "<<weight<<endl;
				//FakeRatePt[etaBin][ptBin]->Fill(analysisTree.tau_pt[tau_loose],weight);

				bool bRatio = (RatioSums < 1.2  && RatioSums > 0.8);
				bool bMass = (DiM.M() < 120 && DiM.M() > 60);
				if (isLoose){
					if (bRatio) FakeRatePtIncLoose[etaBin][0]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass && bRatio) FakeRatePtIncLoose[etaBin][1]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (dPhi > 2.5  && bRatio) FakeRatePtIncLoose[etaBin][2]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && dPhi > 2.5 && bRatio) FakeRatePtIncLoose[etaBin][3]->Fill(analysisTree.tau_pt[tau_loose],weight);

				}

				if (isTight) 

				{	
					if (bRatio) FakeRatePtIncTight[etaBin][0]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && bRatio) FakeRatePtIncTight[etaBin][1]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (dPhi > 2.5 && bRatio) FakeRatePtIncTight[etaBin][2]->Fill(analysisTree.tau_pt[tau_loose],weight);
					if (bMass  && dPhi > 2.5 && bRatio) FakeRatePtIncTight[etaBin][3]->Fill(analysisTree.tau_pt[tau_loose],weight);

				}

				//FakeRateEta[etaBin][ptBin]->Fill(analysisTree.tau_eta[tau_loose],weight);
				//FakeRateNV[etaBin][ptBin]->Fill(analysisTree.tau_vertexz[tau_loose],weight);

			}
		}
	} // end of file processing (loop over events in one file)
	nFiles++;
	delete _tree;
	file_->Close();
	delete file_;
}
std::cout << std::endl;
int allEvents = int(inputEventsH->GetEntries());
std::cout << "Total number of input events                     = " << allEvents << std::endl;
std::cout << "Total number of events in Tree                   = " << nEvents << std::endl;
std::cout << "Total number of selected events (iso muon pairs) = " << selEventsIsoMuons << std::endl;
std::cout << std::endl;
std::cout << "RunMin = " << RunMin << std::endl;
std::cout << "RunMax = " << RunMax << std::endl;

//cout << "weight used:" << weight << std::endl;

// using object as comp
std::sort (allRuns.begin(), allRuns.end(), myobject);
std::cout << "Runs   :";
for (unsigned int iR=0; iR<allRuns.size(); ++iR)
std::cout << " " << allRuns.at(iR);
std::cout << std::endl;

file->cd();
hxsec->Fill(XSec);
hxsec->Write();
inputEventsH->Write();
histWeightsH->Write();
file->Write();
file->Close();
delete file;

}