Ejemplo n.º 1
0
void getKinematics(TLorentzVector& b,double const mass)
{
   float const pt = gRandom->Uniform(momentumRange.first,momentumRange.second);
   float const eta = gRandom->Uniform(-acceptanceEta,acceptanceEta);
   float const phi = TMath::TwoPi() * gRandom->Rndm();

   b.SetXYZM(pt * cos(phi),pt * sin(phi),pt * sinh(eta), mass);
}
Ejemplo n.º 2
0
TLorentzVector leptonic_fitter_algebraic::lv_with_mass( const TMatrixD& mat, double mass )
{
  assert( mat.GetNcols() == 1 || mat.GetNrows() == 1 );
  TLorentzVector lv;
  const double *array = mat.GetMatrixArray();
  lv.SetXYZM( array[0], array[1], array[2], mass );
  return lv;
}
Ejemplo n.º 3
0
TLorentzVector smearMom(TLorentzVector const& b,TF1 const * const fMomResolution)
{
  float const pt = b.Perp();
  float const sPt = gRandom->Gaus(pt,pt*fMomResolution->Eval(pt));

  TLorentzVector sMom;
  sMom.SetXYZM(sPt*cos(b.Phi()),sPt*sin(b.Phi()),sPt*sinh(b.PseudoRapidity()),b.M());
  return sMom;
}
Ejemplo n.º 4
0
    // Reset all private to false/zwwDefault/null vector/etc.
void ZWW::reset(){
        // For checker
    isAllOk_ = false;
    isLepOk_ = false;
    isJetOk_ = false;
    isMETOk_ = false;

        // For setter
    lepPt_. clear();
    lepEta_.clear();
    lepPhi_.clear();
    lepFl_. clear();
    lepCh_. clear();
    lepId_. clear();
    jetPt_. clear();
    jetEta_.clear();
    jetPhi_.clear();
    jetM_.  clear();
    jetTag_.clear();
    met_          = zwwDefault;
    metPhi_       = zwwDefault;
    njet_         = zwwDefault;
    nbjet_        = zwwDefault;
    st_           = zwwDefault;
    minMt_        = zwwDefault;
    minDeltaPhi_  = zwwDefault;

        // Buffer
    lepVec_.clear();
    jetVec_.clear();
//    TLorentzVector metVec_.SetXYZM(0.,0.,0.,0.);
    metVec_.SetXYZM(0.,0.,0.,0.);
    z0LepIdx_[0] = zwwDefault;
    z0LepIdx_[1] = zwwDefault;
    z1LepIdx_[0] = zwwDefault;
    z1LepIdx_[1] = zwwDefault;
    zaLepIdx_[0] = zwwDefault;
    zaLepIdx_[1] = zwwDefault;
    zbLepIdx_[0] = zwwDefault;
    zbLepIdx_[1] = zwwDefault;
    flagZ1SF_    = zwwDefault;

        // All other variables
    outPreSelection_ = false;

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

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

  using namespace std;

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

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

  // electron cuta
  const float ptElectronLowCut   = cfg.get<float>("ptElectronLowCut");
  const float ptElectronHighCut  = cfg.get<float>("ptElectronHighCut");
  const float etaElectronCut     = cfg.get<float>("etaElectronCut");
  const float dxyElectronCut     = cfg.get<float>("dxyElectronCut");
  const float dzElectronCut      = cfg.get<float>("dzElectronCut");
  const float isoElectronLowCut  = cfg.get<float>("isoElectronLowCut");
  const float isoElectronHighCut = cfg.get<float>("isoElectronHighCut");
  const bool applyElectronId     = cfg.get<bool>("ApplyElectronId");

  // tau cuts
  const float ptTauLowCut    = cfg.get<float>("ptTauLowCut");
  const float ptTauHighCut   = cfg.get<float>("ptTauHighCut");  
  const float etaTauCut      = cfg.get<float>("etaTauCut");
  const bool applyTauId      = cfg.get<bool>("ApplyTauId");

  // pair selection
  const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");

  // additional lepton veto
  const float ptDiElectronVeto   = cfg.get<float>("ptDiElectronVeto");  
  const float etaDiElectronVeto  = cfg.get<float>("etaDiElectronVeto");
  
  // topological cuts
  const float dZetaCut       = cfg.get<float>("dZetaCut");
  const bool oppositeSign    = cfg.get<bool>("oppositeSign");

  const float deltaRTrigMatch = cfg.get<float>("DRTrigMatch");
  const bool isIsoR03 = cfg.get<bool>("IsIsoR03");
  
  const float jetEtaCut = cfg.get<float>("JetEtaCut");
  const float jetPtLowCut = cfg.get<float>("JetPtLowCut");
  const float jetPtHighCut = cfg.get<float>("JetPtHighCut");
  const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");
  const bool applyJetPfId = cfg.get<bool>("ApplyJetPfId");
  const bool applyJetPuId = cfg.get<bool>("ApplyJetPuId");

  const float bJetEtaCut = cfg.get<float>("bJetEtaCut");
  const float btagCut = cfg.get<float>("btagCut");

  // check overlap
  const bool checkOverlap = cfg.get<bool>("CheckOverlap");
  const bool debug = cfg.get<bool>("debug");
  
  // **** end of configuration

  // file name and tree name
  TString rootFileName(argv[2]);
  std::ifstream fileList(argv[2]);
  std::ifstream fileList0(argv[2]);
  std::string ntupleName("makeroottree/AC1B");

  
  rootFileName += "_et_Sync.root";
  std::cout <<rootFileName <<std::endl;  

  // output fileName with histograms
  TFile * file = new TFile( rootFileName ,"recreate");
  file->cd("");

  TH1F * inputEventsH = new TH1F("inputEventsH","",1,-0.5,0.5);
  TTree * tree = new TTree("TauCheck","TauCheck");
  
  Spring15Tree *otree = new Spring15Tree(tree);

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

  int nEvents = 0;
  int selEvents = 0;
  int nFiles = 0;
  
  vector<int> runList; runList.clear();
  vector<int> eventList; eventList.clear();

  int nonOverlap = 0;

  std::ifstream fileEvents("overlap.txt");
  int Run, Event, Lumi;
  if (checkOverlap) {
    std::cout << "Non-overlapping events ->" << std::endl;
    while (fileEvents >> Run >> Event >> Lumi) {
      runList.push_back(Run);
      eventList.push_back(Event);
      std::cout << Run << ":" << Event << std::endl;
    }
    std::cout << std::endl;
  }
  std::ofstream fileOutput("overlap.out");


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

    AC1B analysisTree(_tree);
    
    Long64_t numberOfEntries = analysisTree.GetEntries();
    
    std::cout << "      number of entries in Tree = " << numberOfEntries << std::endl;
    
    for (Long64_t iEntry=0; iEntry<numberOfEntries; iEntry++) {       
      analysisTree.GetEntry(iEntry);
      nEvents++;
      
      if (nEvents%10000==0) 
	cout << "      processed " << nEvents << " events" << endl; 

      otree->run = int(analysisTree.event_run);
      otree->lumi = int(analysisTree.event_luminosityblock);
      otree->evt = int(analysisTree.event_nr);

      bool overlapEvent = true;
      for (unsigned int iEvent=0; iEvent<runList.size(); ++iEvent) {
	if (runList.at(iEvent)==otree->run && eventList.at(iEvent)==otree->evt) {
	  overlapEvent = false;	  
	}
      }

      if (overlapEvent&&checkOverlap) continue;
      nonOverlap++;

      if (debug) {
	fileOutput << std::endl;
	fileOutput << "Run = " << otree->run << "   Event = " << otree->evt << std::endl;
      }

      // weights
      otree->mcweight = 0;
      otree->puweight = 0;
      otree->trigweight_1 = 0;
      otree->trigweight_2 = 0;
      otree->idweight_1 = 0;
      otree->idweight_2 = 0;
      otree->isoweight_1 = 0;
      otree->isoweight_2 = 0;
      otree->effweight = 0;
      otree->fakeweight = 0;
      otree->embeddedWeight = 0;
      otree->signalWeight = 0;
      otree->weight = 1;
      
      otree->npv = analysisTree.primvertex_count;
      otree->npu = analysisTree.numpileupinteractions;
      otree->rho = analysisTree.rho;

      // vertex cuts
      if (fabs(analysisTree.primvertex_z)>zVertexCut) continue;
      if (analysisTree.primvertex_ndof<=ndofVertexCut) continue;
      float dVertex = sqrt(analysisTree.primvertex_x*analysisTree.primvertex_x+
			   analysisTree.primvertex_y*analysisTree.primvertex_y);
      if (dVertex>dVertexCut)
	continue;
      
      if (debug)
	fileOutput << "Vertex cuts are passed " << std::endl;

      // electron selection
      vector<int> electrons; electrons.clear();
      if (debug)
	fileOutput << "# electrons = " << analysisTree.electron_count << std::endl;
      for (unsigned int ie = 0; ie<analysisTree.electron_count; ++ie) {
	bool electronMvaId = electronMvaIdTight(analysisTree.electron_superclusterEta[ie],
						analysisTree.electron_mva_id_nontrigPhys14[ie]);
	if (checkOverlap)
	  fileOutput << "  " << ie 
		     << " pt = " << analysisTree.electron_pt[ie] 
		     << " eta = " << analysisTree.electron_eta[ie]
		     << " dxy = " << analysisTree.electron_dxy[ie]
		     << " dz  = " << analysisTree.electron_dz[ie]
		     << " passConv = " << analysisTree.electron_pass_conversion[ie]
		     << " nmisshits = " << int(analysisTree.electron_nmissinginnerhits[ie])
		     << " mvaTight = " << electronMvaId << std::endl;
	if (analysisTree.electron_pt[ie]<ptElectronLowCut) continue;
	if (fabs(analysisTree.electron_eta[ie])>etaElectronCut) continue;
	if (fabs(analysisTree.electron_dxy[ie])>dxyElectronCut) continue;
	if (fabs(analysisTree.electron_dz[ie])>dzElectronCut) continue;
	if (!electronMvaId&&applyElectronId) continue;
	if (!analysisTree.electron_pass_conversion[ie]&&applyElectronId) continue;
	if (analysisTree.electron_nmissinginnerhits[ie]!=0&&applyElectronId) continue;
	electrons.push_back(ie);
      }

      // tau selection
      if (debug)
	fileOutput << "# taus = " << analysisTree.tau_count << std::endl;
      vector<int> taus; taus.clear();
      for (unsigned int it = 0; it<analysisTree.tau_count; ++it) {
	if (debug)
	  fileOutput << "  " << it 
		     << " pt = " << analysisTree.tau_pt[it] 
		     << " eta = " << analysisTree.tau_eta[it]
		     << " decayModeFinding = " << analysisTree.tau_decayModeFinding[it]
		     << " decayModeFindingNewDMs = " << analysisTree.tau_decayModeFindingNewDMs[it]
		     << " tau_vertexz = " << analysisTree.tau_vertexz[it] <<std::endl;
	if (analysisTree.tau_pt[it]<ptTauLowCut) continue;
	if (fabs(analysisTree.tau_eta[it])>etaTauCut) continue;
	if (applyTauId &&
	    analysisTree.tau_decayModeFinding[it] < 0.5 &&
	    analysisTree.tau_decayModeFindingNewDMs[it] < 0.5) continue;
	
	float ctgTheta = analysisTree.tau_pz[it] / sqrt(analysisTree.tau_px[it]*analysisTree.tau_px[it] + analysisTree.tau_py[it]*analysisTree.tau_py[it]);
	float zImpact = analysisTree.tau_vertexz[it] + 130. * ctgTheta;

	if ( zImpact > -1.5 && zImpact < 0.5) continue;
	
	if (analysisTree.tau_vertexz[it]!=analysisTree.primvertex_z) continue;
	taus.push_back(it);
      }

      if (debug) {
	fileOutput << " # selected electron = " << electrons.size() << std::endl;
	fileOutput << " # selected taus = " << taus.size() << std::endl;	
      }
      
      if (electrons.size()==0) continue;
      if (taus.size()==0) continue;

      // selecting muon and tau pair (OS or SS);
      int electronIndex = -1;
      int tauIndex = -1;
      
      float isoEleMin = 1e+10;
      float isoTauMin = 1e+10;      
      for (unsigned int ie=0; ie<electrons.size(); ++ie) {
	bool isTrigEle22 = false;
	bool isTrigEle32 = false;

	unsigned int eIndex  = electrons.at(ie);

	float neutralHadIsoEle = analysisTree.electron_neutralHadIso[ie];
	float photonIsoEle = analysisTree.electron_photonIso[ie];
	float chargedHadIsoEle = analysisTree.electron_chargedHadIso[ie];
	float puIsoEle = analysisTree.electron_puIso[ie];
	if (isIsoR03) {
	  neutralHadIsoEle = analysisTree.electron_r03_sumNeutralHadronEt[ie];
	  photonIsoEle = analysisTree.electron_r03_sumPhotonEt[ie];
	  chargedHadIsoEle = analysisTree.electron_r03_sumChargedHadronPt[ie];
	  puIsoEle = analysisTree.electron_r03_sumPUPt[ie];
	}
	float neutralIsoEle = neutralHadIsoEle + photonIsoEle - 0.5*puIsoEle;
	neutralIsoEle = TMath::Max(float(0),neutralIsoEle); 
	float absIsoEle =  chargedHadIsoEle + neutralIsoEle;
	float relIsoEle = absIsoEle/analysisTree.electron_pt[ie];
	
	if (debug)
	  fileOutput << "Electron " << eIndex << " -> relIso = "<<relIsoEle<<" absIso = "<<absIsoEle<<std::endl;

	for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
	  /*if (analysisTree.trigobject_isElectron[iT] ||
	      !analysisTree.trigobject_isMuon[iT] ||
	      analysisTree.trigobject_isTau[iT]) continue;*/
	  
	  float dRtrig = deltaR(analysisTree.electron_eta[eIndex],analysisTree.electron_phi[eIndex],
				analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);

	  if (dRtrig < deltaRTrigMatch){
	    if (analysisTree.trigobject_filters[iT][7] && analysisTree.trigobject_filters[iT][8]) // Ele22 Leg
	      isTrigEle22 = true;	      
	    if (analysisTree.trigobject_filters[iT][10]) // Ele32 Leg
	      isTrigEle32 = true;
	  }
	}
	  
	if (debug)
	  fileOutput << "Electron " << eIndex << " -> isTrigEle22 = " << isTrigEle22 << " ; isTrigEle32 = " << isTrigEle32 << std::endl;

	if ((!isTrigEle22) && (!isTrigEle32)) continue;
      
	for (unsigned int it=0; it<taus.size(); ++it) {
	  unsigned int tIndex = taus.at(it);
	  float absIsoTau = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[tIndex];
	  float relIsoTau = absIsoTau / analysisTree.tau_pt[tIndex];

	  if (debug)
	    fileOutput << "tau" << tIndex << " -> relIso = "<<relIsoTau<<" absIso = "<<absIsoTau<<std::endl;
	  
	  float dR = deltaR(analysisTree.tau_eta[tIndex],analysisTree.tau_phi[tIndex],
			    analysisTree.electron_eta[eIndex],analysisTree.electron_phi[eIndex]);

	  if (debug)
	    fileOutput << "dR(ele,tau) = " << dR << std::endl;

	  if (dR<dRleptonsCut) continue;
	  
	  bool isTrigTau = false;
	  float dRtrig_min = 9999.;
	  
	  for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
	    if (debug){
	      if (analysisTree.trigobject_isElectron[iT] && analysisTree.trigobject_isMuon[iT])
		fileOutput<<" trigObj "<<iT<<" both e and mu"<<std::endl;
	      
	      if (analysisTree.trigobject_isMuon[iT] && analysisTree.trigobject_isTau[iT])
		fileOutput<<" trigObj "<<iT<<" both mu and tau"<<std::endl;
	      
	      if (analysisTree.trigobject_isElectron[iT] && analysisTree.trigobject_isTau[iT])
		fileOutput<<" trigObj "<<iT<<" both e and tau"<<std::endl;
	    }
	    
	    if (analysisTree.trigobject_isElectron[iT] ||
		analysisTree.trigobject_isMuon[iT] ||
		!analysisTree.trigobject_isTau[iT]) continue;
	    
	    float dRtrig = deltaR(analysisTree.tau_eta[tIndex],analysisTree.tau_phi[tIndex],
				  analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	    
	    if (dRtrig < deltaRTrigMatch){
	      if (analysisTree.trigobject_filters[iT][7] && analysisTree.trigobject_filters[iT][8]){
		isTrigTau = true;
		if (dRtrig < dRtrig_min)
		  dRtrig_min = dRtrig;
	      }
	    }
	  }
	  
	  if (debug)
	    fileOutput << "Tau " << it << " -> isTrigTau = " << isTrigTau << " DR="<<dRtrig_min<<std::endl;

	  bool trigMatch = isTrigEle32 || (isTrigEle22 && isTrigTau);

	  if (isTrigEle32 && analysisTree.hltriggerresults_second[4]==false)
	    if (debug)
	      std::cout<<"IsoEle32 Trigger Mismatch"<<std::endl;

	  
	  if (isTrigEle22 && isTrigTau && analysisTree.hltriggerresults_second[1]==false)
	    if (debug)
	      std::cout<<"xEleTau Trigger Mismatch"<<std::endl;
	      
	  if (!trigMatch) continue;
	  
	  bool isKinematicMatch = false;
	  if (isTrigEle32) {
	    if (analysisTree.electron_pt[eIndex]>ptElectronHighCut)
	      isKinematicMatch = true;
	  }	  
	  if (isTrigEle22 && isTrigTau) {
            if (analysisTree.electron_pt[eIndex]>ptElectronLowCut && analysisTree.tau_pt[tIndex]>ptTauHighCut)
              isKinematicMatch = true;
	  }
	  	  
	  if (!isKinematicMatch) continue;
	  
	  bool changePair =  false;
	  
	  if (relIsoEle<isoEleMin) {
	    changePair = true;
	  }
	  else if (fabs(relIsoEle - isoEleMin) < 1.e-5) {
	    if (analysisTree.electron_pt[eIndex] > analysisTree.electron_pt[electronIndex]) {
	      changePair = true;
	    }	    
	    else if (fabs(analysisTree.electron_pt[eIndex] - analysisTree.electron_pt[electronIndex]) < 1.e-5) {
	      if (absIsoTau < isoTauMin) {
		changePair = true;
	      }
	      else if ((absIsoTau - isoTauMin) < 1.e-5){
		if (analysisTree.tau_pt[tIndex] > analysisTree.tau_pt[tauIndex]) {
		  changePair = true;
		}
	      }
	    }
	  }
	  
	  if (changePair){
	    isoEleMin  = relIsoEle;
	    electronIndex = eIndex;
	    isoTauMin = absIsoTau;
	    tauIndex = tIndex;
	  }
	}
      }
    
      if (electronIndex<0) continue;
      if (tauIndex<0) continue;
      
      // filling electron variables
      otree->pt_1 = analysisTree.electron_pt[electronIndex];
      otree->eta_1 = analysisTree.electron_eta[electronIndex];
      otree->phi_1 = analysisTree.electron_phi[electronIndex];
      otree->m_1 = electronMass;
      otree->q_1 = -1;
      if (analysisTree.electron_charge[electronIndex]>0)
        otree->q_1 = 1;
      otree->iso_1 = isoEleMin;
      otree->mva_1 = analysisTree.electron_mva_id_nontrigPhys14[electronIndex];
      otree->d0_1 = analysisTree.electron_dxy[electronIndex];
      otree->dZ_1 = analysisTree.electron_dz[electronIndex];

      otree->byCombinedIsolationDeltaBetaCorrRaw3Hits_1 = 0;
      otree->againstElectronLooseMVA5_1 = 0;
      otree->againstElectronMediumMVA5_1 = 0;
      otree->againstElectronTightMVA5_1 = 0;
      otree->againstElectronVLooseMVA5_1 = 0;
      otree->againstElectronVTightMVA5_1 = 0;
      otree->againstMuonLoose3_1 = 0;
      otree->againstMuonTight3_1 = 0;
      
      // filling tau variables
      otree->pt_2 = analysisTree.tau_pt[tauIndex];
      otree->eta_2 = analysisTree.tau_eta[tauIndex];
      otree->phi_2 = analysisTree.tau_phi[tauIndex];
      otree->q_2 = -1;
      if (analysisTree.tau_charge[tauIndex]>0)
	otree->q_2 = 1;
      otree->mva_2 = log(0);
      otree->d0_2 = analysisTree.tau_dxy[tauIndex];
      otree->dZ_2 = analysisTree.tau_dz[tauIndex];
      otree->iso_2 = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[tauIndex];
      otree->m_2 = analysisTree.tau_mass[tauIndex];

      otree->byCombinedIsolationDeltaBetaCorrRaw3Hits_2 = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[tauIndex];
      otree->againstElectronLooseMVA5_2 = analysisTree.tau_againstElectronLooseMVA5[tauIndex];
      otree->againstElectronMediumMVA5_2 = analysisTree.tau_againstElectronMediumMVA5[tauIndex];
      otree->againstElectronTightMVA5_2 = analysisTree.tau_againstElectronTightMVA5[tauIndex];
      otree->againstElectronVLooseMVA5_2 = analysisTree.tau_againstElectronVLooseMVA5[tauIndex];
      otree->againstElectronVTightMVA5_2 = analysisTree.tau_againstElectronVTightMVA5[tauIndex];
      otree->againstMuonLoose3_2 = analysisTree.tau_againstMuonLoose3[tauIndex];
      otree->againstMuonTight3_2 = analysisTree.tau_againstMuonTight3[tauIndex];

      // ditau system
      TLorentzVector electronLV; electronLV.SetXYZM(analysisTree.electron_px[electronIndex],
					    analysisTree.electron_py[electronIndex],
					    analysisTree.electron_pz[electronIndex],
					    electronMass);

      TLorentzVector tauLV; tauLV.SetXYZM(analysisTree.tau_px[tauIndex],
					  analysisTree.tau_py[tauIndex],
					  analysisTree.tau_pz[tauIndex],
					  tauMass);

      TLorentzVector dileptonLV = electronLV + tauLV;

      otree->m_vis = dileptonLV.M();
      otree->pt_tt = dileptonLV.Pt();

      // opposite charge
      otree->os = (otree->q_1 * otree->q_2) < 0.;

      // dimuon veto
      otree->dilepton_veto = 0;

      for (unsigned int ie = 0; ie<analysisTree.electron_count; ++ie) {
	if (analysisTree.electron_pt[ie]<ptDiElectronVeto) continue;
	if (fabs(analysisTree.electron_eta[ie])>etaDiElectronVeto) continue;	
	
	if (fabs(analysisTree.electron_dxy[ie])>dxyElectronCut) continue;
	if (fabs(analysisTree.electron_dz[ie])>dzElectronCut) continue;

	if (otree->q_1 * analysisTree.electron_charge[ie] > 0.) continue;

	float neutralHadIsoEle = analysisTree.electron_neutralHadIso[ie];
	float photonIsoEle = analysisTree.electron_photonIso[ie];
	float chargedHadIsoEle = analysisTree.electron_chargedHadIso[ie];
	float puIsoEle = analysisTree.electron_puIso[ie];
	if (isIsoR03) {
	  neutralHadIsoEle = analysisTree.electron_r03_sumNeutralHadronEt[ie];
	  photonIsoEle = analysisTree.electron_r03_sumPhotonEt[ie];
	  chargedHadIsoEle = analysisTree.electron_r03_sumChargedHadronPt[ie];
	  puIsoEle = analysisTree.electron_r03_sumPUPt[ie];
	}
	float neutralIsoEle = neutralHadIsoEle + photonIsoEle - 0.5*puIsoEle;
	neutralIsoEle = TMath::Max(float(0),neutralIsoEle); 
	float absIsoEle =  chargedHadIsoEle + neutralIsoEle;
	float relIsoEle = absIsoEle/analysisTree.electron_pt[ie];
	
	if(relIsoEle > 0.3) continue;

	float dr = deltaR(analysisTree.electron_eta[ie],analysisTree.electron_phi[ie],
			  otree->eta_1,otree->phi_1);
	if(dr<0.15) continue;

	otree->dilepton_veto = 1;
      }
      
      // extra electron veto
      otree->extraelec_veto = 0;

      // extra muon veto
      otree->extramuon_veto = 0;
      
      // svfit variables
      otree->m_sv = -9999;
      otree->pt_sv = -9999;
      otree->eta_sv = -9999;
      otree->phi_sv = -9999;

      // pfmet variables      
      otree->met = TMath::Sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
      otree->metphi = TMath::ATan2(analysisTree.pfmet_ey,analysisTree.pfmet_ex);
      otree->metcov00 = analysisTree.pfmet_sigxx;
      otree->metcov01 = analysisTree.pfmet_sigxy;
      otree->metcov10 = analysisTree.pfmet_sigyx;
      otree->metcov11 = analysisTree.pfmet_sigyy;
      
      // bisector of muon and tau transverse momenta
      float electronUnitX = electronLV.Px()/electronLV.Pt();
      float electronUnitY = electronLV.Py()/electronLV.Pt();
	
      float tauUnitX = tauLV.Px()/tauLV.Pt();
      float tauUnitY = tauLV.Py()/tauLV.Pt();

      float zetaX = electronUnitX + tauUnitX;
      float zetaY = electronUnitY + tauUnitY;
      
      float normZeta = TMath::Sqrt(zetaX*zetaX+zetaY*zetaY);

      zetaX = zetaX/normZeta;
      zetaY = zetaY/normZeta;

      float vectorVisX = electronLV.Px() + tauLV.Px();
      float vectorVisY = electronLV.Py() + tauLV.Py();

      otree->pzetavis  = vectorVisX*zetaX + vectorVisY*zetaY;
      
      // choosing mva met
      unsigned int iMet = 0;
      for (; iMet<analysisTree.mvamet_count; ++iMet) {
	if ((int)analysisTree.mvamet_channel[iMet]==2) break;
      }
      
      if (iMet>=analysisTree.mvamet_count){
	if(debug)
	  fileOutput<<"MVA MET channel ploblems.."<<std::endl;

	otree->mvamet = log(0);
	otree->mvametphi = log(0);
 	otree->mvacov00 = log(0);
	otree->mvacov01 = log(0);
	otree->mvacov10 = log(0);
	otree->mvacov11 = log(0);

	otree->mt_1 = log(0);
	otree->mt_2 = log(0);
	
	otree->pzetamiss = log(0);	
      }
      else {
	float mvamet_x = analysisTree.mvamet_ex[iMet];
	float mvamet_y = analysisTree.mvamet_ey[iMet];
	float mvamet_x2 = mvamet_x * mvamet_x;
	float mvamet_y2 = mvamet_y * mvamet_y;

	otree->mvamet = TMath::Sqrt(mvamet_x2+mvamet_y2);
	otree->mvametphi = TMath::ATan2(mvamet_y,mvamet_x);
	otree->mvacov00 = analysisTree.mvamet_sigxx[iMet];
	otree->mvacov01 = analysisTree.mvamet_sigxy[iMet];
	otree->mvacov10 = analysisTree.mvamet_sigyx[iMet];
	otree->mvacov11 = analysisTree.mvamet_sigyy[iMet];

	// computation of mt
	otree->mt_1 = sqrt(2*otree->pt_1*otree->mvamet*(1.-cos(otree->phi_1-otree->mvametphi)));
	otree->mt_2 = sqrt(2*otree->pt_2*otree->mvamet*(1.-cos(otree->phi_2-otree->mvametphi)));  
	
	// computation of DZeta variable
	otree->pzetamiss = analysisTree.pfmet_ex*zetaX + analysisTree.pfmet_ey*zetaY;
      }

      // counting jets
      vector<unsigned int> jets; jets.clear();
      vector<unsigned int> jetspt20; jetspt20.clear();
      vector<unsigned int> bjets; bjets.clear();

      int indexLeadingJet = -1;
      float ptLeadingJet = -1;

      int indexSubLeadingJet = -1;
      float ptSubLeadingJet = -1;
      
      int indexLeadingBJet = -1;
      float ptLeadingBJet = -1;

      for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {
	float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	if (absJetEta>jetEtaCut) continue;

	float jetPt = analysisTree.pfjet_pt[jet];
	if (jetPt<jetPtLowCut) continue;

	float dR1 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
			   otree->eta_1,otree->phi_1);

	float dR2 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
                           otree->eta_2,otree->phi_2);
	
	// pf jet Id
	float energy = analysisTree.pfjet_e[jet];
        float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
        float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
        float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
        float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
        float chm = analysisTree.pfjet_chargedmulti[jet];
        float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>2.4 || (elf<0.99 && chf>0 && chm>0)); // muon fraction missing

	if(debug)
	  fileOutput<<" jet "<<jet<<": pt="<<analysisTree.pfjet_pt[jet]<<" eta="<<analysisTree.pfjet_eta[jet]
		    <<" dr1="<<dR1<<" dr2="<<dR2<<" npr="<<npr<<" phf="<<phf<<" nhf="<<nhf<<std::endl;

	// apply dR cut
	if (dR1<dRJetLeptonCut) continue;
	if (dR2<dRJetLeptonCut) continue;

	// apply pf jet Id
	if (applyJetPfId&&!isPFJetId) continue;

	// pu jet Id
	if (applyJetPuId&&!puJetIdLoose(analysisTree.pfjet_eta[jet],analysisTree.pfjet_pu_jet_full_mva[jet])) continue;
	
	jetspt20.push_back(jet);

	if (absJetEta<bJetEtaCut && analysisTree.pfjet_btag[jet][6]>btagCut) { // b-jet
	  bjets.push_back(jet);
	  if (jetPt>ptLeadingBJet) {
	    ptLeadingBJet = jetPt;
	    indexLeadingBJet = jet;
	  }
	} 

	if (jetPt<jetPtHighCut) continue;
	
	jets.push_back(jet);

	if(jetPt>ptLeadingJet){
	  ptSubLeadingJet = ptLeadingJet;
	  indexSubLeadingJet = indexLeadingJet;

	  ptLeadingJet = jetPt;
	  indexLeadingJet = jet;
	}
	else if(jetPt>ptSubLeadingJet){
	  ptSubLeadingJet = jetPt;
	  indexSubLeadingJet = jet;
	}	
      }
      
      otree->njets = jets.size();
      otree->njetspt20 = jetspt20.size();
      otree->nbtag = bjets.size();
      
      otree->bpt = -9999;
      otree->beta = -9999;
      otree->bphi = -9999;
      
      if (indexLeadingBJet>=0) {
	otree->bpt = analysisTree.pfjet_pt[indexLeadingBJet];
	otree->beta = analysisTree.pfjet_eta[indexLeadingBJet];
	otree->bphi = analysisTree.pfjet_phi[indexLeadingBJet];
      }
     
      otree->jpt_1 = -9999;
      otree->jeta_1 = -9999;
      otree->jphi_1 = -9999;
      otree->jptraw_1 = -9999;
      otree->jptunc_1 = -9999;
      otree->jmva_1 = -9999;
      otree->jlrm_1 = -9999;
      otree->jctm_1 = -9999;

      if (indexLeadingJet>=0&&indexSubLeadingJet>=0&&indexLeadingJet==indexSubLeadingJet)
	cout << "warning : indexLeadingJet ==indexSubLeadingJet = " << indexSubLeadingJet << endl;

      if (indexLeadingJet>=0) {
	otree->jpt_1 = analysisTree.pfjet_pt[indexLeadingJet];
	otree->jeta_1 = analysisTree.pfjet_eta[indexLeadingJet];
	otree->jphi_1 = analysisTree.pfjet_phi[indexLeadingJet];
	otree->jptraw_1 = analysisTree.pfjet_pt[indexLeadingJet]*analysisTree.pfjet_energycorr[indexLeadingJet];
	otree->jmva_1 = analysisTree.pfjet_pu_jet_full_mva[indexLeadingJet];
      }

      otree->jpt_2 = -9999;
      otree->jeta_2 = -9999;
      otree->jphi_2 = -9999;
      otree->jptraw_2 = -9999;
      otree->jptunc_2 = -9999;
      otree->jmva_2 = -9999;
      otree->jlrm_2 = -9999;
      otree->jctm_2 = -9999;

      if (indexSubLeadingJet>=0) {
	otree->jpt_2 = analysisTree.pfjet_pt[indexSubLeadingJet];
	otree->jeta_2 = analysisTree.pfjet_eta[indexSubLeadingJet];
	otree->jphi_2 = analysisTree.pfjet_phi[indexSubLeadingJet];
	otree->jptraw_2 = analysisTree.pfjet_pt[indexSubLeadingJet]*analysisTree.pfjet_energycorr[indexSubLeadingJet];
	otree->jmva_2 = analysisTree.pfjet_pu_jet_full_mva[indexSubLeadingJet];
      }

      otree->mjj =  -9999;
      otree->jdeta =  -9999;
      otree->njetingap = 0;

      if (indexLeadingJet>=0 && indexSubLeadingJet>=0) {

	TLorentzVector jet1; jet1.SetPxPyPzE(analysisTree.pfjet_px[indexLeadingJet],
					     analysisTree.pfjet_py[indexLeadingJet],
					     analysisTree.pfjet_pz[indexLeadingJet],
					     analysisTree.pfjet_e[indexLeadingJet]);

	TLorentzVector jet2; jet2.SetPxPyPzE(analysisTree.pfjet_px[indexSubLeadingJet],
					     analysisTree.pfjet_py[indexSubLeadingJet],
					     analysisTree.pfjet_pz[indexSubLeadingJet],
					     analysisTree.pfjet_e[indexSubLeadingJet]);

	otree->mjj = (jet1+jet2).M();
	otree->jdeta = abs(analysisTree.pfjet_eta[indexLeadingJet]-
		    analysisTree.pfjet_eta[indexSubLeadingJet]);
 
	float etamax = analysisTree.pfjet_eta[indexLeadingJet];
	float etamin = analysisTree.pfjet_eta[indexSubLeadingJet];
	if (etamax<etamin) {
	  float tmp = etamax;
	  etamax = etamin;
	  etamin = tmp;
	}
	for (unsigned int jet=0; jet<jetspt20.size(); ++jet) {
	  int index = jetspt20.at(jet);
	  float etaX = analysisTree.pfjet_eta[index];
	  if (index!=indexLeadingJet&&index!=indexSubLeadingJet&&etaX>etamin&&etaX<etamax) 
	    otree->njetingap++;
	}
      }
      
      otree->Fill();
      selEvents++;
    } // 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 = " << selEvents << std::endl;
  std::cout << std::endl;
  
  file->cd("");
  file->Write();
  file->Close();
  delete file;
  
}
Ejemplo n.º 6
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
Ejemplo n.º 7
0
void leptonic_fitter_algebraic::update_nu_and_decay_chain( double nu_px, double nu_py, double nu_pz )
{
  TLorentzVector nu;
  nu.SetXYZM( nu_px, nu_py, nu_pz, 0. );
  update_nu_and_decay_chain( nu );
}
int main(int argc, char * argv[]) {

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

  using namespace std;

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

  // kinematic cuts on electrons
  const float ptTauCut   = cfg.get<float>("ptTauCut");
  const float etaTauCut     = cfg.get<float>("etaTauCut");
  const float dzTauCut      = cfg.get<float>("dzTauCut");

  // veto electrons
  const float ptVetoElectronCut   = cfg.get<float>("ptVetoElectronCut");
  const float etaVetoElectronCut  = cfg.get<float>("etaVetoElectronCut");
  const float dxyVetoElectronCut  = cfg.get<float>("dxyVetoElectronCut");
  const float dzVetoElectronCut   = cfg.get<float>("dzVetoElectronCut");
  const float isoVetoElectronCut  = cfg.get<float>("isoVetoElectronCut");
  const bool applyVetoElectronId  = cfg.get<bool>("ApplyVetoElectronId");

  // kinematic cuts on muons
  const float ptMuonCut       = cfg.get<float>("ptMuonCut");
  const float ptMuonHighCut   = cfg.get<float>("ptMuonHighCut");
  const float etaMuonCut      = cfg.get<float>("etaMuonCut");
  const float dxyMuonCut      = cfg.get<float>("dxyMuonCut");
  const float dzMuonCut       = cfg.get<float>("dzMuonCut");
  const float isoMuonLowCut   = cfg.get<float>("isoMuonLowCut");
  const float isoMuonHighCut  = cfg.get<float>("isoMuonHighCut");
  const bool applyMuonId      = cfg.get<bool>("ApplyMuonId");

  // HLT filters
  const string isoMuon24Leg   = cfg.get<string>("IsoMuon24Leg");
  const string muonTauMuonLeg = cfg.get<string>("MuonTauMuonLeg");
  const string muonTauOverlap = cfg.get<string>("MuonTauOverlap");
  const string muonTauTauLeg  = cfg.get<string>("MuonTauTauLeg");

  // veto muons
  const float ptVetoMuonCut   = cfg.get<float>("ptVetoMuonCut");
  const float etaVetoMuonCut  = cfg.get<float>("etaVetoMuonCut");
  const float dxyVetoMuonCut   = cfg.get<float>("dxyVetoMuonCut");
  const float dzVetoMuonCut   = cfg.get<float>("dzVetoMuonCut");
  const float isoVetoMuonCut   = cfg.get<float>("isoVetoMuonCut");
  const bool applyVetoMuonId     = cfg.get<bool>("ApplyVetoMuonId");

  // dileptopn veto
  const float ptDilepVeto   = cfg.get<float>("ptDilepVeto");
  const float etaDilepVeto  = cfg.get<float>("etaDilepVeto");
  const float dxyDilepVeto   = cfg.get<float>("dxyDilepVeto");
  const float dzDilepVeto   = cfg.get<float>("dzDilepVeto");
  const float isoDilepVeto   = cfg.get<float>("isoDilepVeto");
  const float dRDilepVeto   = cfg.get<float>("dRDilepVeto");  
  
  // vertex cuts
  const float ndofVertexCut  = cfg.get<float>("NdofVertexCut");   
  const float zVertexCut     = cfg.get<float>("ZVertexCut");
  const float dVertexCut     = cfg.get<float>("DVertexCut");

  // topological cuts
  const float dRleptonsCut   = cfg.get<float>("dRleptonsCut");
  const bool isIsoR03 = cfg.get<bool>("IsIsoR03");
  const bool applyTriggerMatch = cfg.get<bool>("ApplyTriggerMatch");
  const float deltaRTrigMatch = cfg.get<float>("DRTrigMatch");

  // jets
  const float jetEtaCut = cfg.get<float>("JetEtaCut");
  const float jetPtLowCut = cfg.get<float>("JetPtLowCut");
  const float jetPtHighCut = cfg.get<float>("JetPtHighCut");
  const float dRJetLeptonCut = cfg.get<float>("dRJetLeptonCut");
  const float bJetEtaCut = cfg.get<float>("bJetEtaCut");
  const float btagCut = cfg.get<float>("btagCut");
  const bool applyJetPfId = cfg.get<bool>("ApplyJetPfId");
  const bool applyJetPuId = cfg.get<bool>("ApplyJetPuId");

  // check overlap
  const bool checkOverlap = cfg.get<bool>("CheckOverlap");
  
  TString IsoMuon24Leg(isoMuon24Leg);
  TString MuonTauMuonLeg(muonTauMuonLeg);
  TString MuonTauOverlap(muonTauOverlap);
  TString MuonTauTauLeg(muonTauTauLeg);

  // **** end of configuration

  // 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);
  std::cout <<TStrName <<std::endl;  

  // output fileName with histograms
  TFile * file = new TFile(TStrName+TString(".root"),"recreate");
  file->cd("");

  TH1F * inputEventsH = new TH1F("inputEventsH","",1,-0.5,0.5);
  TTree * tree = new TTree("TauCheck","TauCheck");
   // Declaration of leaf types

  Int_t           run;
  Int_t           lumi;
  Int_t           evt;
  Int_t           npv;
  Int_t           npu;
  Float_t         rho;
  Float_t         mcweight;
  Float_t         puweight;
  Float_t         trigweight_1;
  Float_t         trigweight_2;
  Float_t         idweight_1;
  Float_t         idweight_2;
  Float_t         isoweight_1;
  Float_t         isoweight_2;
  Float_t         effweight;
  Float_t         fakeweight;
  Float_t         embeddedWeight;
  Float_t         signalWeight;
  Float_t         weight;
  Float_t         m_vis;
  Float_t         m_sv;
  Float_t         pt_sv;
  Float_t         eta_sv;
  Float_t         phi_sv;
  Float_t         pt_1;
  Float_t         phi_1;
  Float_t         eta_1;
  Float_t         m_1;
  Int_t           q_1;
  Float_t         iso_1;
  Float_t         mva_1;
  Float_t         d0_1;
  Float_t         dZ_1;
  Float_t         mt_1;
  Float_t         pt_2;
  Float_t         phi_2;
  Float_t         eta_2;
  Float_t         m_2;
  Int_t           q_2;
  Float_t         iso_2;
  Float_t         d0_2;
  Float_t         dZ_2;
  Float_t         mva_2;
  Float_t         mt_2;

  Bool_t          os;
  Bool_t          dilepton_veto;
  Bool_t          extraelec_veto;
  Bool_t          extramuon_veto;

  Float_t         byCombinedIsolationDeltaBetaCorrRaw3Hits_1;
  Float_t         againstElectronLooseMVA5_1;
  Float_t         againstElectronMediumMVA5_1;
  Float_t         againstElectronTightMVA5_1;
  Float_t         againstElectronVLooseMVA5_1;
  Float_t         againstElectronVTightMVA5_1;
  Float_t         againstMuonLoose3_1;
  Float_t         againstMuonTight3_1;
  Float_t         byCombinedIsolationDeltaBetaCorrRaw3Hits_2;
  Float_t         againstElectronLooseMVA5_2;
  Float_t         againstElectronMediumMVA5_2;
  Float_t         againstElectronTightMVA5_2;
  Float_t         againstElectronVLooseMVA5_2;
  Float_t         againstElectronVTightMVA5_2;
  Float_t         againstMuonLoose3_2;
  Float_t         againstMuonTight3_2;

  Float_t         met;
  Float_t         metphi;
  Float_t         metcov00;
  Float_t         metcov01;
  Float_t         metcov10;
  Float_t         metcov11;

  Float_t         mvamet;
  Float_t         mvametphi;
  Float_t         mvacov00;
  Float_t         mvacov01;
  Float_t         mvacov10;
  Float_t         mvacov11;

  Float_t         pt_tt;
  Float_t         pzetavis;
  Float_t         pzetamiss;
  Float_t         mva_gf;

  Int_t           njets;
  Int_t           njetspt20;
  Float_t         jpt_1;
  Float_t         jeta_1;
  Float_t         jphi_1;
  Float_t         jptraw_1;
  Float_t         jptunc_1;
  Float_t         jmva_1;
  Float_t         jlrm_1;
  Int_t           jctm_1;
  Float_t         jpt_2;
  Float_t         jeta_2;
  Float_t         jphi_2;
  Float_t         jptraw_2;
  Float_t         jptunc_2;
  Float_t         jmva_2;
  Float_t         jlrm_2;
  Int_t           jctm_2;
  Float_t         mjj;
  Float_t         jdeta;
  Int_t           njetingap;

  Int_t           nbtag;
  Float_t         bpt;
  Float_t         beta;
  Float_t         bphi;
  

  tree->Branch("run", &run, "run/I");
  tree->Branch("lumi", &lumi, "lumi/I");
  tree->Branch("evt", &evt, "evt/I");
  tree->Branch("npv", &npv, "npv/I");
  tree->Branch("npu", &npu, "npu/I");
  tree->Branch("rho", &rho, "rho/F");

  tree->Branch("mcweight", &mcweight, "mcweight/F");
  tree->Branch("puweight", &puweight, "puweight/F");
  tree->Branch("trigweight_1", &trigweight_1, "trigweight_1/F");
  tree->Branch("trigweight_2", &trigweight_2, "trigweight_2/F");
  tree->Branch("idweight_1", &idweight_1, "idweight_1/F");
  tree->Branch("idweight_2", &idweight_2, "idweight_2/F");
  tree->Branch("isoweight_1", &isoweight_1, "isoweight_1/F");
  tree->Branch("isoweight_2", &isoweight_2, "isoweight_2/F");
  tree->Branch("effweight", &effweight, "effweight/F");
  tree->Branch("fakeweight", &fakeweight, "fakeweight/F");
  tree->Branch("embeddedWeight", &embeddedWeight, "embeddedWeight/F");
  tree->Branch("signalWeight", &signalWeight, "signalWeight/F");
  tree->Branch("weight", &weight, "weight/F");

  tree->Branch("m_vis", &m_vis, "m_vis/F");
  tree->Branch("m_sv", &m_sv, "m_sv/F");
  tree->Branch("pt_sv", &pt_sv, "pt_sv/F");
  tree->Branch("eta_sv", &eta_sv, "eta_sv/F");
  tree->Branch("phi_sv", &phi_sv, "phi_sv/F");

  tree->Branch("pt_1", &pt_1, "pt_1/F");
  tree->Branch("phi_1", &phi_1, "phi_1/F");
  tree->Branch("eta_1", &eta_1, "eta_1/F");
  tree->Branch("m_1", &m_1, "m_1/F");
  tree->Branch("q_1", &q_1, "q_1/I");
  tree->Branch("iso_1", &iso_1, "iso_1/F");
  tree->Branch("mva_1", &mva_1, "mva_1/F");
  tree->Branch("d0_1", &d0_1, "d0_1/F");
  tree->Branch("dZ_1", &dZ_1, "dZ_1/F");
  tree->Branch("mt_1", &mt_1, "mt_1/F");

  tree->Branch("pt_2", &pt_2, "pt_2/F");
  tree->Branch("phi_2", &phi_2, "phi_2/F");
  tree->Branch("eta_2", &eta_2, "eta_2/F");
  tree->Branch("m_2", &m_2, "m_2/F");
  tree->Branch("q_2", &q_2, "q_2/I");
  tree->Branch("iso_2", &iso_2, "iso_2/F");
  tree->Branch("d0_2", &d0_2, "d0_2/F");
  tree->Branch("dZ_2", &dZ_2, "dZ_2/F");
  tree->Branch("mva_2", &mva_2, "mva_2/F");
  tree->Branch("mt_2", &mt_2, "mt_2/F");

  tree->Branch("os", &os, "os/O");
  tree->Branch("dilepton_veto", &dilepton_veto, "dilepton_veto/O");
  tree->Branch("extraelec_veto", &extraelec_veto, "extraelec_veto/O");
  tree->Branch("extramuon_veto", &extramuon_veto, "extramuon_veto/O");

  tree->Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_1", &byCombinedIsolationDeltaBetaCorrRaw3Hits_1, "byCombinedIsolationDeltaBetaCorrRaw3Hits_1/F");
  tree->Branch("againstElectronLooseMVA5_1", &againstElectronLooseMVA5_1, "againstElectronLooseMVA5_1/F");
  tree->Branch("againstElectronMediumMVA5_1", &againstElectronMediumMVA5_1, "againstElectronMediumMVA5_1/F");
  tree->Branch("againstElectronTightMVA5_1", &againstElectronTightMVA5_1, "againstElectronTightMVA5_1/F");
  tree->Branch("againstElectronVLooseMVA5_1", &againstElectronVLooseMVA5_1, "againstElectronVLooseMVA5_1/F");
  tree->Branch("againstElectronVTightMVA5_1", &againstElectronVTightMVA5_1, "againstElectronVTightMVA5_1/F");
  tree->Branch("againstMuonLoose3_1", &againstMuonLoose3_1, "againstMuonLoose3_1/F");
  tree->Branch("againstMuonTight3_1", &againstMuonTight3_1, "againstMuonTight3_1/F");

  tree->Branch("byCombinedIsolationDeltaBetaCorrRaw3Hits_2", &byCombinedIsolationDeltaBetaCorrRaw3Hits_2, "byCombinedIsolationDeltaBetaCorrRaw3Hits_2/F");
  tree->Branch("againstElectronLooseMVA5_2", &againstElectronLooseMVA5_2, "againstElectronLooseMVA5_2/F");
  tree->Branch("againstElectronMediumMVA5_2", &againstElectronMediumMVA5_2, "againstElectronMediumMVA5_2/F");
  tree->Branch("againstElectronTightMVA5_2", &againstElectronTightMVA5_2, "againstElectronTightMVA5_2/F");
  tree->Branch("againstElectronVLooseMVA5_2", &againstElectronVLooseMVA5_2, "againstElectronVLooseMVA5_2/F");
  tree->Branch("againstElectronVTightMVA5_2", &againstElectronVTightMVA5_2, "againstElectronVTightMVA5_2/F");
  tree->Branch("againstMuonLoose3_2", &againstMuonLoose3_2, "againstMuonLoose3_2/F");
  tree->Branch("againstMuonTight3_2", &againstMuonTight3_2, "againstMuonTight3_2/F");

  tree->Branch("met", &met, "met/F");
  tree->Branch("metphi", &metphi, "metphi/F");
  tree->Branch("metcov00", &metcov00, "metcov00/F");
  tree->Branch("metcov01", &metcov01, "metcov01/F");
  tree->Branch("metcov10", &metcov10, "metcov10/F");
  tree->Branch("metcov11", &metcov11, "metcov11/F");

  tree->Branch("mvamet", &mvamet, "mvamet/F");
  tree->Branch("mvametphi", &mvametphi, "mvametphi/F");
  tree->Branch("mvacov00", &mvacov00, "mvacov00/F");
  tree->Branch("mvacov01", &mvacov01, "mvacov01/F");
  tree->Branch("mvacov10", &mvacov10, "mvacov10/F");
  tree->Branch("mvacov11", &mvacov11, "mvacov11/F");

  tree->Branch("pt_tt", &pt_tt, "pt_tt/F");
  tree->Branch("pzetavis", &pzetavis, "pzetavis/F");
  tree->Branch("pzetamiss", &pzetamiss, "pzetamiss/F");
  tree->Branch("mva_gf", &mva_gf, "mva_gf/F");

  tree->Branch("njets", &njets, "njets/I");
  tree->Branch("njetspt20", &njetspt20, "njetspt20/I");

  tree->Branch("jpt_1", &jpt_1, "jpt_1/F");
  tree->Branch("jeta_1", &jeta_1, "jeta_1/F");
  tree->Branch("jphi_1", &jphi_1, "jphi_1/F");
  tree->Branch("jptraw_1", &jptraw_1, "jptraw_1/F");
  tree->Branch("jptunc_1", &jptunc_1, "jptunc_1/F");
  tree->Branch("jmva_1", &jmva_1, "jmva_1/F");
  tree->Branch("jlrm_1", &jlrm_1, "jlrm_1/F");
  tree->Branch("jctm_1", &jctm_1, "jctm_1/I");

  tree->Branch("jpt_2", &jpt_2, "jpt_2/F");
  tree->Branch("jeta_2", &jeta_2, "jeta_2/F");
  tree->Branch("jphi_2", &jphi_2, "jphi_2/F");
  tree->Branch("jptraw_2", &jptraw_2, "jptraw_2/F");
  tree->Branch("jptunc_2", &jptunc_2, "jptunc_2/F");
  tree->Branch("jmva_2", &jmva_2, "jlrm_2/F");
  tree->Branch("jlrm_2", &jlrm_2, "jlrm_2/F");
  tree->Branch("jctm_2", &jctm_2, "jctm_2/I");

  tree->Branch("mjj", &mjj, "mjj/F");
  tree->Branch("jdeta", &jdeta, "jdeta/F");
  tree->Branch("njetingap", &njetingap, "njetingap/I");

  tree->Branch("nbtag", &nbtag, "nbtag/I");
  tree->Branch("bpt", &bpt, "bpt/F");
  tree->Branch("beta", &beta, "beta/F");
  tree->Branch("bphi", &bphi, "bphi/F");
  
  int nTotalFiles = 0;
  std::string dummy;
  // count number of files --->
  while (fileList0 >> dummy) nTotalFiles++;

  int nEvents = 0;
  int selEvents = 0;
  int nFiles = 0;
  
  int nonOverlap = 0;

  vector<int> runList; runList.clear();
  vector<int> eventList; eventList.clear();

  if (checkOverlap) {
    std::ifstream fileEvents("overlap.txt");
    int Run, Event, Lumi;
    std::cout << "Non-overlapping events ->" << std::endl;
    while (fileEvents >> Run >> Event >> Lumi) {
      runList.push_back(Run);
      eventList.push_back(Event);
      std::cout << Run << ":" << Event << std::endl;
    }
    std::cout << std::endl;
  }
  std::ofstream fileOutput("overlap.out");

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

    AC1B analysisTree(_tree);
    
    Long64_t numberOfEntries = analysisTree.GetEntries();
    
    std::cout << "      number of entries in Tree = " << numberOfEntries << std::endl;

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

      analysisTree.GetEntry(iEntry);
      nEvents++;
      
      if (nEvents%10000==0) 
	cout << "      processed " << nEvents << " events" << endl; 

      run = int(analysisTree.event_run);
      lumi = int(analysisTree.event_luminosityblock);
      evt = int(analysisTree.event_nr);

      // weights
      mcweight = analysisTree.genweight;
      puweight = 0;
      trigweight_1 = 0;
      trigweight_2 = 0;
      idweight_1 = 0;
      idweight_2 = 0;
      isoweight_1 = 0;
      isoweight_2 = 0;
      effweight = 0;
      fakeweight = 0;
      embeddedWeight = 0;
      signalWeight = 0;
      weight = 1;
      
      npv = analysisTree.primvertex_count;
      npu = analysisTree.numtruepileupinteractions;// numpileupinteractions;
      rho = analysisTree.rho;
      
      unsigned int nIsoMuon24Leg = 0;
      bool isIsoMuon24Leg = false;

      unsigned int nMuonTauMuonLeg = 0;
      bool isMuonTauMuonLeg = false;
      
      unsigned int nMuonTauOverlap = 0;
      bool isMuonTauOverlap = false;

      unsigned int nMuonTauTauLeg = 0;
      bool isMuonTauTauLeg = false;

      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==IsoMuon24Leg) {
	  nIsoMuon24Leg = i;
	  isIsoMuon24Leg = true;
	}
	if (HLTFilter==MuonTauMuonLeg) {
	  nMuonTauMuonLeg = i;
	  isMuonTauMuonLeg = true;
	}
	if (HLTFilter==MuonTauOverlap) {
	  nMuonTauOverlap = i;
	  isMuonTauOverlap = true;
	}
	if (HLTFilter==MuonTauTauLeg) {
	  nMuonTauTauLeg = i;
	  isMuonTauTauLeg = true;
	}
      }
      if (!isIsoMuon24Leg) {
	std::cout << "HLT filter " << IsoMuon24Leg << " not found" << std::endl;
	exit(-1);
      }
      if (!isMuonTauMuonLeg) {
	std::cout << "HLT filter " << MuonTauMuonLeg << " not found" << std::endl;
	exit(-1);
      }
      if (!isMuonTauOverlap) {
	std::cout << "HLT filter " << MuonTauOverlap << " not found" << std::endl;
	exit(-1);
      }
      if (!isMuonTauTauLeg) {
	std::cout << "HLT filter " << MuonTauTauLeg << " not found" << std::endl;
	exit(-1);
      }
      //      std::cout << "IsoMu24      : " << IsoMuon24Leg << " : " << nIsoMuon24Leg << std::endl;
      //      std::cout << "MuTauMuLeg   : " << MuonTauMuonLeg << " : " << nMuonTauMuonLeg << std::endl;
      //      std::cout << "MuTauTauLeg  : " << MuonTauTauLeg << " : " << nMuonTauTauLeg << std::endl;
      //      std::cout << "MuTauOverlap : " << MuonTauOverlap << " : " << nMuonTauOverlap << std::endl;
      //      std::cout << std::endl;
      //      continue;

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

      // tau selection
      vector<int> taus; taus.clear();
      for (unsigned int it = 0; it<analysisTree.tau_count; ++it) {
	if (analysisTree.tau_decayModeFindingNewDMs[it]<=0.5) continue;
	if (analysisTree.tau_pt[it]<=ptTauCut) continue;
	if (fabs(analysisTree.tau_eta[it])>=etaTauCut) continue;
	if (fabs(analysisTree.tau_leadchargedhadrcand_dz[it])>=dzTauCut) continue;
	if (fabs(analysisTree.tau_charge[it])<0.999||
	    fabs(analysisTree.tau_charge[it])>1.001) continue;
	taus.push_back(it);
      }

      // muon selection
      vector<int> muons; muons.clear();
      for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
	if (analysisTree.muon_pt[im]<=ptMuonCut) continue;
	if (fabs(analysisTree.muon_eta[im])>=etaMuonCut) continue;
	if (fabs(analysisTree.muon_dxy[im])>=dxyMuonCut) continue;
	if (fabs(analysisTree.muon_dz[im])>=dzMuonCut) continue;

	bool goodGlb = analysisTree.muon_isGlobal[im] && analysisTree.muon_normChi2[im]  < 3 &&
		       analysisTree.muon_combQ_chi2LocalPosition[im] < 12 && analysisTree.muon_combQ_trkKink[im] < 20;
	bool isMed = analysisTree.muon_isLoose[im] && analysisTree.muon_validFraction[im] > 0.8 &&
		     analysisTree.muon_segmentComp[im] > (goodGlb ? 0.303 : 0.451);
	if (applyMuonId && !isMed) continue;
	//if (applyMuonId && !analysisTree.muon_isMedium[im]) continue;
	muons.push_back(im);
      }

      if (taus.size()==0) continue;
      if (muons.size()==0) continue;
      
      // selecting muon and electron pair (OS or SS);
      int tauIndex = -1;
      int muonIndex = -1;

      float isoMuMin = 1e+10;
      float isoTauMin = 1e+10;
      float ptMu = 0;
      float ptTau = 0;
      //      if (muons.size()>1||electrons.size()>1)
      //      std::cout << "muons = " << muons.size() << "  taus = " << taus.size() << std::endl;
      for (unsigned int im=0; im<muons.size(); ++im) {
	bool isIsoMuon24LegMatch = false;
	bool isMuonTauMuonLegMatch = false;
	bool isMuonTauOverlapMuonMatch = false;
	unsigned int mIndex  = muons.at(im);
	float neutralHadIsoMu = analysisTree.muon_neutralHadIso[mIndex];
	float photonIsoMu = analysisTree.muon_photonIso[mIndex];
	float chargedHadIsoMu = analysisTree.muon_chargedHadIso[mIndex];
	float puIsoMu = analysisTree.muon_puIso[mIndex];
	if (isIsoR03) {
	  neutralHadIsoMu = analysisTree.muon_r03_sumNeutralHadronEt[mIndex];
	  photonIsoMu = analysisTree.muon_r03_sumPhotonEt[mIndex];
	  chargedHadIsoMu = analysisTree.muon_r03_sumChargedHadronPt[mIndex];
	  puIsoMu = analysisTree.muon_r03_sumPUPt[mIndex];
	}
	float neutralIsoMu = neutralHadIsoMu + photonIsoMu - 0.5*puIsoMu;
	neutralIsoMu = TMath::Max(float(0),neutralIsoMu); 
	float absIsoMu = chargedHadIsoMu + neutralIsoMu;
	float relIsoMu = absIsoMu/analysisTree.muon_pt[mIndex];
	for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
	  if (analysisTree.trigobject_filters[iT][nIsoMuon24Leg]&&analysisTree.muon_pt[mIndex]>ptMuonHighCut) { // IsoMu24 Leg
	    float dRtrig = deltaR(analysisTree.muon_eta[mIndex],analysisTree.muon_phi[mIndex],
				  analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	    if (dRtrig<deltaRTrigMatch) {
	      isIsoMuon24LegMatch = true;
	    }
	  }
	  if (analysisTree.trigobject_filters[iT][nMuonTauMuonLeg]) { // MuonTau Muon Leg
	    float dRtrig = deltaR(analysisTree.muon_eta[mIndex],analysisTree.muon_phi[mIndex],
				  analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	    if (dRtrig<deltaRTrigMatch) {
	      isMuonTauMuonLegMatch = true;
	    }
	  }
	  if (analysisTree.trigobject_filters[iT][nMuonTauOverlap]&&analysisTree.trigobject_isMuon[iT]) { // MuonTau Overlap Muon 
	    float dRtrig = deltaR(analysisTree.muon_eta[mIndex],analysisTree.muon_phi[mIndex],
				  analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	    if (dRtrig<deltaRTrigMatch) {
	      isMuonTauOverlapMuonMatch = true;
	    }
	  }
	}

	for (unsigned int it=0; it<taus.size(); ++it) {

	  unsigned int tIndex = taus.at(it);

	  float dR = deltaR(analysisTree.tau_eta[tIndex],analysisTree.tau_phi[tIndex],
			    analysisTree.muon_eta[mIndex],analysisTree.muon_phi[mIndex]);

	  if (dR<dRleptonsCut) continue;

	  bool isMuonTauOverlapTauMatch = false;
	  bool isMuonTauTauLegMatch = false;

	  for (unsigned int iT=0; iT<analysisTree.trigobject_count; ++iT) {
	    if (analysisTree.trigobject_filters[iT][nMuonTauOverlap]&&analysisTree.trigobject_isTau[iT]) { // MuonTau Overlap Tau
	      float dRtrig = deltaR(analysisTree.tau_eta[tIndex],analysisTree.tau_phi[tIndex],
				    analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	      if (dRtrig<deltaRTrigMatch) {
		isMuonTauOverlapTauMatch = true;
	      }
	    }
	    if (analysisTree.trigobject_filters[iT][nMuonTauTauLeg]) { // MuonTau Tau Leg
	      float dRtrig = deltaR(analysisTree.tau_eta[tIndex],analysisTree.tau_phi[tIndex],
				    analysisTree.trigobject_eta[iT],analysisTree.trigobject_phi[iT]);
	      if (dRtrig<deltaRTrigMatch) {
		isMuonTauTauLegMatch = true;
	      }
	    }
	  }

	  bool trigMatch = 
	    (isIsoMuon24LegMatch) || 
	    (isMuonTauOverlapMuonMatch&&isMuonTauMuonLegMatch&&isMuonTauOverlapTauMatch&&isMuonTauTauLegMatch);
	  //	  std::cout << "Trigger match = " << trigMatch << std::endl;

	  if (applyTriggerMatch && !trigMatch) continue;
	  
	  //	  bool isKinematicMatch = false;
	  //	  if (isMu23&&isEle12) {
	  //	    if (analysisTree.muon_pt[mIndex]>ptMuonHighCut&&analysisTree.electron_pt[eIndex]>ptElectronLowCut)
	  //	      isKinematicMatch = true;
	  //	  }
	  //	  if (isMu8&&isEle23) {
	  //            if (analysisTree.muon_pt[mIndex]>ptMuonLowCut&&analysisTree.electron_pt[eIndex]>ptElectronHighCut)
	  //              isKinematicMatch = true;
	  //          }
	  //	  if (!isKinematicMatch) continue;

	  float isoTau = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[tIndex];

	  if (int(mIndex)!=muonIndex) {
	    if (relIsoMu==isoMuMin) {
	      if (analysisTree.muon_pt[mIndex]>ptMu) {
		isoMuMin  = relIsoMu;
		ptMu = analysisTree.muon_pt[mIndex];
		muonIndex = int(mIndex);
		isoTauMin = isoTau;
		ptTau = analysisTree.tau_pt[tIndex];
		tauIndex = int(tIndex);
	      }
	    }
	    else if (relIsoMu<isoMuMin) {
	      isoMuMin  = relIsoMu;
	      ptMu = analysisTree.muon_pt[mIndex];
	      muonIndex = int(mIndex);
	      isoTauMin = isoTau;
	      ptTau = analysisTree.tau_pt[tIndex];
	      tauIndex = int(tIndex);
	    }
	  }
	  else {
	    if (isoTau==isoTauMin) {
	      if (analysisTree.tau_pt[tIndex]>ptTau) {
		ptTau = analysisTree.tau_pt[tIndex];
		isoTauMin = isoTau;
		tauIndex = int(tIndex);
	      }
	    }
	    else if (isoTau<isoTauMin) {
	      ptTau = analysisTree.tau_pt[tIndex];
	      isoTauMin = isoTau;
	      tauIndex = int(tIndex);
	    }
	  }
	  
	}
      }

      //      std::cout << "mIndex = " << muonIndex << "   eIndex = " << electronIndex << std::endl;

      if (tauIndex<0) continue;
      if (muonIndex<0) continue;
      //      std::cout << "OK " << std::endl;
      //      std::cout << std::endl;

      os = (analysisTree.muon_charge[muonIndex]*analysisTree.tau_charge[tauIndex]) < 0;

      //dilepton veto
      vector<int> dilepveto_muons; dilepveto_muons.clear();
      for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
	if (analysisTree.muon_pt[im]<=ptDilepVeto) continue;
	if (fabs(analysisTree.muon_eta[im])>=etaDilepVeto) continue;
	if (fabs(analysisTree.muon_dxy[im])>=dxyDilepVeto) continue;
	if (fabs(analysisTree.muon_dz[im])>=dzDilepVeto) continue;
	if (!analysisTree.muon_isGlobal[im]) continue;
	if (!analysisTree.muon_isTracker[im]) continue;
	if (!analysisTree.muon_isPF[im]) continue;

	float neutralHadIsoMu = analysisTree.muon_neutralHadIso[im];
	float photonIsoMu = analysisTree.muon_photonIso[im];
	float chargedHadIsoMu = analysisTree.muon_chargedHadIso[im];
	float puIsoMu = analysisTree.muon_puIso[im];
	if (isIsoR03) {
	  neutralHadIsoMu = analysisTree.muon_r03_sumNeutralHadronEt[im];
	  photonIsoMu = analysisTree.muon_r03_sumPhotonEt[im];
	  chargedHadIsoMu = analysisTree.muon_r03_sumChargedHadronPt[im];
	  puIsoMu = analysisTree.muon_r03_sumPUPt[im];
	}
	float neutralIsoMu = neutralHadIsoMu + photonIsoMu - 0.5*puIsoMu;
	neutralIsoMu = TMath::Max(float(0),neutralIsoMu); 
	float absIsoMu = chargedHadIsoMu + neutralIsoMu;
	float relIsoMu = absIsoMu/analysisTree.muon_pt[im];
	if (relIsoMu>=isoDilepVeto) continue;

	dilepveto_muons.push_back(im);
      }

      bool foundDilep = false;
      for (unsigned int im = 0; im<dilepveto_muons.size(); ++im) {
	for (unsigned int jm = im; jm<dilepveto_muons.size(); ++jm) {

	  Float_t dR_dilep = deltaR(analysisTree.muon_eta[dilepveto_muons.at(im)],
				    analysisTree.muon_eta[dilepveto_muons.at(im)],
				    analysisTree.muon_eta[dilepveto_muons.at(jm)],
				    analysisTree.muon_eta[dilepveto_muons.at(jm)]);
	  if (dR_dilep > dRDilepVeto)
	    foundDilep = true;
	}
      }
      
      // looking for extra electron
      bool foundExtraElectron = false;
      for (unsigned int ie = 0; ie<analysisTree.electron_count; ++ie) {
	if (analysisTree.electron_pt[ie]<=ptVetoElectronCut) continue;
	if (fabs(analysisTree.electron_eta[ie])>=etaVetoElectronCut) continue;
	if (fabs(analysisTree.electron_dxy[ie])>=dxyVetoElectronCut) continue;
	if (fabs(analysisTree.electron_dz[ie])>=dzVetoElectronCut) continue;
	bool electronMvaId = electronMvaIdWP90(analysisTree.electron_pt[ie],
					       analysisTree.electron_superclusterEta[ie],
					       analysisTree.electron_mva_id_nontrigPhys14[ie]);
	electronMvaId = analysisTree.electron_mva_tightId_nontrig_Spring15_v1[ie];
	if (!electronMvaId&&applyVetoElectronId) continue;
	if (!analysisTree.electron_pass_conversion[ie]&&applyVetoElectronId) continue;
	if (analysisTree.electron_nmissinginnerhits[ie]>1&&applyVetoElectronId) continue;
	float neutralHadIsoEle = analysisTree.electron_neutralHadIso[ie];
	float photonIsoEle = analysisTree.electron_photonIso[ie];
	float chargedHadIsoEle = analysisTree.electron_chargedHadIso[ie];
	float puIsoEle = analysisTree.electron_puIso[ie];
	if (isIsoR03) {
	  neutralHadIsoEle = analysisTree.electron_r03_sumNeutralHadronEt[ie];
	  photonIsoEle = analysisTree.electron_r03_sumPhotonEt[ie];
	  chargedHadIsoEle = analysisTree.electron_r03_sumChargedHadronPt[ie];
	  puIsoEle = analysisTree.electron_r03_sumPUPt[ie];
	}
	float neutralIsoEle = neutralHadIsoEle + photonIsoEle - 0.5*puIsoEle;
	neutralIsoEle = TMath::Max(float(0),neutralIsoEle); 
	float absIsoEle =  chargedHadIsoEle + neutralIsoEle;
	float relIsoEle = absIsoEle/analysisTree.electron_pt[ie];	
	if (relIsoEle>=isoVetoElectronCut) continue;
	foundExtraElectron = true;
      }

      // looking for extra muon
      bool foundExtraMuon = false;
      for (unsigned int im = 0; im<analysisTree.muon_count; ++im) {
	if (int(im)==muonIndex) continue;
	if (analysisTree.muon_pt[im]<=ptVetoMuonCut) continue;
	if (fabs(analysisTree.muon_eta[im])>=etaVetoMuonCut) continue;
	if (fabs(analysisTree.muon_dxy[im])>=dxyVetoMuonCut) continue;
	if (fabs(analysisTree.muon_dz[im])>=dzVetoMuonCut) continue;
	if (applyVetoMuonId && !analysisTree.muon_isMedium[im]) continue;
	float neutralHadIsoMu = analysisTree.muon_neutralHadIso[im];
	float photonIsoMu = analysisTree.muon_photonIso[im];
	float chargedHadIsoMu = analysisTree.muon_chargedHadIso[im];
	float puIsoMu = analysisTree.muon_puIso[im];
	if (isIsoR03) {
	  neutralHadIsoMu = analysisTree.muon_r03_sumNeutralHadronEt[im];
	  photonIsoMu = analysisTree.muon_r03_sumPhotonEt[im];
	  chargedHadIsoMu = analysisTree.muon_r03_sumChargedHadronPt[im];
	  puIsoMu = analysisTree.muon_r03_sumPUPt[im];
	}
	float neutralIsoMu = neutralHadIsoMu + photonIsoMu - 0.5*puIsoMu;
	neutralIsoMu = TMath::Max(float(0),neutralIsoMu); 
	float absIsoMu = chargedHadIsoMu + neutralIsoMu;
	float relIsoMu = absIsoMu/analysisTree.muon_pt[im];
	if (relIsoMu>isoVetoMuonCut) continue;
	foundExtraMuon = true;
      }

      dilepton_veto = foundDilep;
      extraelec_veto = foundExtraElectron;
      extramuon_veto = foundExtraMuon;

      // met
      met = TMath::Sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey);
      metphi = TMath::ATan2(analysisTree.pfmet_ey,analysisTree.pfmet_ex);
      metcov00 = analysisTree.pfmet_sigxx;
      metcov01 = analysisTree.pfmet_sigxy;
      metcov10 = analysisTree.pfmet_sigyx;
      metcov11 = analysisTree.pfmet_sigyy;


      // filling muon variables
      pt_1 = analysisTree.muon_pt[muonIndex];
      eta_1 = analysisTree.muon_eta[muonIndex];
      phi_1 = analysisTree.muon_phi[muonIndex];
      q_1 = -1;
      if (analysisTree.muon_charge[muonIndex]>0)
	q_1 = 1;
      mva_1 = -9999;
      d0_1 = analysisTree.muon_dxy[muonIndex];
      dZ_1 = analysisTree.muon_dz[muonIndex];
      iso_1 = isoMuMin;
      m_1 = muonMass;
      float dPhiMETMuon = dPhiFrom2P(analysisTree.muon_px[muonIndex],analysisTree.muon_py[muonIndex],
				     analysisTree.pfmet_ex,analysisTree.pfmet_ey);
      mt_1 = TMath::Sqrt(2*met*analysisTree.muon_pt[muonIndex]*(1-TMath::Cos(dPhiMETMuon)));


      // filling tau variables
      pt_2 = analysisTree.tau_pt[tauIndex];
      eta_2 = analysisTree.tau_eta[tauIndex];
      phi_2 = analysisTree.tau_phi[tauIndex];
      q_2 = -1;
      if (analysisTree.tau_charge[tauIndex]>0)
        q_2 = 1;
      mva_2 = -9999;
      d0_2 = analysisTree.tau_leadchargedhadrcand_dxy[tauIndex];
      dZ_2 = analysisTree.tau_leadchargedhadrcand_dz[tauIndex];
      iso_2 = isoTauMin;
      m_2 = analysisTree.tau_mass[tauIndex];
      float dPhiMETTau = dPhiFrom2P(analysisTree.tau_px[tauIndex],analysisTree.tau_py[tauIndex],
				    analysisTree.pfmet_ex,analysisTree.pfmet_ey);
      mt_2 = TMath::Sqrt(2*met*analysisTree.tau_pt[tauIndex]*(1-TMath::Cos(dPhiMETTau)));


      byCombinedIsolationDeltaBetaCorrRaw3Hits_2 = analysisTree.tau_byCombinedIsolationDeltaBetaCorrRaw3Hits[tauIndex];
      againstElectronLooseMVA5_2 = analysisTree.tau_againstElectronLooseMVA5[tauIndex];
      againstElectronMediumMVA5_2 = analysisTree.tau_againstElectronMediumMVA5[tauIndex];
      againstElectronTightMVA5_2 = analysisTree.tau_againstElectronTightMVA5[tauIndex];
      againstElectronVLooseMVA5_2 = analysisTree.tau_againstElectronVLooseMVA5[tauIndex];
      againstElectronVTightMVA5_2 = analysisTree.tau_againstElectronVTightMVA5[tauIndex];
      againstMuonLoose3_2 = analysisTree.tau_againstMuonLoose3[tauIndex];
      againstMuonTight3_2 = analysisTree.tau_againstMuonTight3[tauIndex];

      TLorentzVector muonLV; muonLV.SetXYZM(analysisTree.muon_px[muonIndex],
					    analysisTree.muon_py[muonIndex],
					    analysisTree.muon_pz[muonIndex],
					    muonMass);

      TLorentzVector tauLV; tauLV.SetXYZT(analysisTree.tau_px[tauIndex],
					  analysisTree.tau_py[tauIndex],
					  analysisTree.tau_pz[tauIndex],
					  analysisTree.tau_e[tauIndex]);

      TLorentzVector metLV; metLV.SetXYZT(analysisTree.pfmet_ex,
					  analysisTree.pfmet_ey,
					  0,
					  TMath::Sqrt(analysisTree.pfmet_ex*analysisTree.pfmet_ex + analysisTree.pfmet_ey*analysisTree.pfmet_ey));
      
      TLorentzVector dileptonLV = muonLV + tauLV;

      // visible mass
      m_vis = dileptonLV.M();
      // visible ditau pt 
      pt_tt = (dileptonLV+metLV).Pt();

      // bisector of electron and muon transverse momenta
      float tauUnitX = tauLV.Px()/tauLV.Pt();
      float tauUnitY = tauLV.Py()/tauLV.Pt();
	
      float muonUnitX = muonLV.Px()/muonLV.Pt();
      float muonUnitY = muonLV.Py()/muonLV.Pt();

      float zetaX = tauUnitX + muonUnitX;
      float zetaY = tauUnitY + muonUnitY;
      
      float normZeta = TMath::Sqrt(zetaX*zetaX+zetaY*zetaY);

      zetaX = zetaX/normZeta;
      zetaY = zetaY/normZeta;

      // choosing mva met
      unsigned int iMet = 0;
      for (; iMet<analysisTree.mvamet_count; ++iMet) {
	if (analysisTree.mvamet_channel[iMet]==3){
	  if(analysisTree.mvamet_lep1[iMet]==tauIndex && analysisTree.mvamet_lep2[iMet]==muonIndex)
	    break;
	}
      }

      float mvamet_x = 0;
      float mvamet_y = 0;
      mvacov00 = 0.;
      mvacov01 = 0.;
      mvacov10 = 0.;
      mvacov11 = 0.;
      if(iMet < analysisTree.mvamet_count){
	mvamet_x = analysisTree.mvamet_ex[iMet];
	mvamet_y = analysisTree.mvamet_ey[iMet];
	mvacov00 = analysisTree.mvamet_sigxx[iMet];
	mvacov01 = analysisTree.mvamet_sigxy[iMet];
	mvacov10 = analysisTree.mvamet_sigyx[iMet];
	mvacov11 = analysisTree.mvamet_sigyy[iMet];
      }
      
      float mvamet_x2 = mvamet_x * mvamet_x;
      float mvamet_y2 = mvamet_y * mvamet_y;
      mvamet = TMath::Sqrt(mvamet_x2+mvamet_y2);
      mvametphi = TMath::ATan2(mvamet_y,mvamet_x);

      float vectorX = analysisTree.pfmet_ex + muonLV.Px() + tauLV.Px();
      float vectorY = analysisTree.pfmet_ey + muonLV.Py() + tauLV.Py();
      
      float vectorVisX = muonLV.Px() + tauLV.Px();
      float vectorVisY = muonLV.Py() + tauLV.Py();

      // computation of DZeta variable
      pzetamiss = analysisTree.pfmet_ex*zetaX + analysisTree.pfmet_ey*zetaY;
      pzetavis  = vectorVisX*zetaX + vectorVisY*zetaY;

      // counting jets
      vector<unsigned int> jets; jets.clear();
      vector<unsigned int> jetspt20; jetspt20.clear();
      vector<unsigned int> bjets; bjets.clear();

      int indexLeadingJet = -1;
      float ptLeadingJet = -1;

      int indexSubLeadingJet = -1;
      float ptSubLeadingJet = -1;
      
      int indexLeadingBJet = -1;
      float ptLeadingBJet = -1;

      for (unsigned int jet=0; jet<analysisTree.pfjet_count; ++jet) {

	float absJetEta = fabs(analysisTree.pfjet_eta[jet]);
	if (absJetEta>=jetEtaCut) continue;

	float jetPt = analysisTree.pfjet_pt[jet];
	if (jetPt<=jetPtLowCut) continue;

	float dR1 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
			   eta_1,phi_1);
	if (dR1<=dRJetLeptonCut) continue;

	float dR2 = deltaR(analysisTree.pfjet_eta[jet],analysisTree.pfjet_phi[jet],
                           eta_2,phi_2);
        if (dR2<=dRJetLeptonCut) continue;

	// jetId
	float energy = analysisTree.pfjet_e[jet];
        energy *= analysisTree.pfjet_jecfactor[jet];
        float chf = analysisTree.pfjet_chargedhadronicenergy[jet]/energy;
        float nhf = analysisTree.pfjet_neutralhadronicenergy[jet]/energy;
        float phf = analysisTree.pfjet_neutralemenergy[jet]/energy;
        float elf = analysisTree.pfjet_chargedemenergy[jet]/energy;
	float muf = analysisTree.pfjet_muonenergy[jet]/energy;
        float chm = analysisTree.pfjet_chargedmulti[jet];
	float nm = analysisTree.pfjet_neutralmulti[jet];
        float npr = analysisTree.pfjet_chargedmulti[jet] + analysisTree.pfjet_neutralmulti[jet];
	//bool isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>3.0 || (elf<0.99 && chf>0 && chm>0));
	bool isPFJetId = false;
	if (absJetEta<=3.0)
	  isPFJetId = (nhf < 0.99 && phf < 0.99 && npr > 1) && (absJetEta>2.4 || (chf>0 && chm > 0 && elf < 0.99));
	else
	  isPFJetId = phf < 0.9 && nm > 10;
	//isPFJetId = (npr>1 && phf<0.99 && nhf<0.99 && muf < 0.8) && (absJetEta>3.0 || (elf<0.99 && chf>0 && chm>0));
	//isPFJetId = (npr>1 && phf<0.99 && nhf<0.99) && (absJetEta>3.0 || (elf<0.99 && chf>0 && chm>0));
	
	if (!isPFJetId) continue;

	jetspt20.push_back(jet);

	if (absJetEta<bJetEtaCut && analysisTree.pfjet_btag[jet][6]>btagCut) { // b-jet
	  bjets.push_back(jet);
	  if (jetPt>ptLeadingBJet) {
	    ptLeadingBJet = jetPt;
	    indexLeadingBJet = jet;
	  }
	} 

	if (indexLeadingJet>=0) {
	  if (jetPt<ptLeadingJet&&jetPt>ptSubLeadingJet) {
	    indexSubLeadingJet = jet;
	    ptSubLeadingJet = jetPt;
	  }
	}

	if (jetPt>ptLeadingJet) {
	  indexLeadingJet = jet;
	  ptLeadingJet = jetPt;
	}

	if (jetPt<jetPtHighCut) continue;
	jets.push_back(jet);
      }
	
      njets = jets.size();
      njetspt20 = jetspt20.size();
      nbtag = bjets.size();
      
      bpt = -9999;
      beta = -9999;
      bphi = -9999;
      
      if (indexLeadingBJet>=0) {
	bpt = analysisTree.pfjet_pt[indexLeadingBJet];
	beta = analysisTree.pfjet_eta[indexLeadingBJet];
	bphi = analysisTree.pfjet_phi[indexLeadingBJet];
      }
     
      jpt_1 = -9999;
      jeta_1 = -9999;
      jphi_1 = -9999;
      jptraw_1 = -9999;
      jptunc_1 = -9999;
      jmva_1 = -9999;
      jlrm_1 = -9999;
      jctm_1 = -9999;

      if (indexLeadingJet>=0&&indexSubLeadingJet>=0&&indexLeadingJet==indexSubLeadingJet)
	cout << "warning : indexLeadingJet ==indexSubLeadingJet = " << indexSubLeadingJet << endl;

      if (indexLeadingJet>=0) {
	jpt_1 = analysisTree.pfjet_pt[indexLeadingJet];
	jeta_1 = analysisTree.pfjet_eta[indexLeadingJet];
	jphi_1 = analysisTree.pfjet_phi[indexLeadingJet];
	jptraw_1 = analysisTree.pfjet_pt[indexLeadingJet]*analysisTree.pfjet_energycorr[indexLeadingJet];
	jmva_1 = analysisTree.pfjet_pu_jet_full_mva[indexLeadingJet];
      }

      jpt_2 = -9999;
      jeta_2 = -9999;
      jphi_2 = -9999;
      jptraw_2 = -9999;
      jptunc_2 = -9999;
      jmva_2 = -9999;
      jlrm_2 = -9999;
      jctm_2 = -9999;

      if (indexSubLeadingJet>=0) {
	jpt_2 = analysisTree.pfjet_pt[indexSubLeadingJet];
	jeta_2 = analysisTree.pfjet_eta[indexSubLeadingJet];
	jphi_2 = analysisTree.pfjet_phi[indexSubLeadingJet];
	jptraw_2 = analysisTree.pfjet_pt[indexSubLeadingJet]*analysisTree.pfjet_energycorr[indexSubLeadingJet];
	jmva_2 = analysisTree.pfjet_pu_jet_full_mva[indexSubLeadingJet];
      }

      mjj =  -9999;
      jdeta =  -9999;
      njetingap =-1;

      if (indexLeadingJet>=0 && indexSubLeadingJet>=0) {
	njetingap = 0;
	TLorentzVector jet1; jet1.SetPxPyPzE(analysisTree.pfjet_px[indexLeadingJet],
					     analysisTree.pfjet_py[indexLeadingJet],
					     analysisTree.pfjet_pz[indexLeadingJet],
					     analysisTree.pfjet_e[indexLeadingJet]);

	TLorentzVector jet2; jet2.SetPxPyPzE(analysisTree.pfjet_px[indexSubLeadingJet],
					     analysisTree.pfjet_py[indexSubLeadingJet],
					     analysisTree.pfjet_pz[indexSubLeadingJet],
					     analysisTree.pfjet_e[indexSubLeadingJet]);

	mjj = (jet1+jet2).M();
	jdeta = abs(analysisTree.pfjet_eta[indexLeadingJet]-
		    analysisTree.pfjet_eta[indexSubLeadingJet]);
 
	float etamax = analysisTree.pfjet_eta[indexLeadingJet];
	float etamin = analysisTree.pfjet_eta[indexSubLeadingJet];
	if (etamax<etamin) {
	  float tmp = etamax;
	  etamax = etamin;
	  etamin = tmp;
	}
	for (unsigned int jet=0; jet<jets.size(); ++jet) {
	  int index = jets.at(jet);
	  float etaX = analysisTree.pfjet_eta[index];
	  if (index!=indexLeadingJet&&index!=indexSubLeadingJet&&etaX>etamin&&etaX<etamax) 
	    njetingap++;
	}
      }

      tree->Fill();
      selEvents++;
      
    } // 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 = " << selEvents << std::endl;
  std::cout << std::endl;
  
  file->cd("");
  file->Write();
  file->Close();
  delete file;
  
}
Ejemplo n.º 9
0
void asym2_halfday(const int Trig = 0, const int NBins = 5, const int Roadset = 67, const int Seed = 0, const int SaveOn = 0)
{
  
  //gROOT -> ProcessLine ("~/root/init.C");
  gROOT -> ProcessLine (".L ./my_root_functions.C");
  gROOT -> ProcessLine (".L ./asym_funcs.C");
  gROOT -> ProcessLine (".L ./fit_funcs.C");
  gROOT -> SetStyle("Plain");
  gStyle -> SetPalette (1);
  //gStyle -> SetOptTitle(0);
  gStyle -> SetOptStat(0);
  gStyle -> SetOptFit(1);
  gStyle -> SetCanvasColor(0);
  Float_t PI = 3.141592654;
  //File input/output names
  char inName[64];
  char outName[64];
  char inArm[5];
  char inTrig[5];
  char inBeam[7];
  char inPol[5];
  if(Trig == 0) sprintf (inTrig, "Real");
  //else if(Trig == 2) sprintf (inTrig, "Sim");

  //Beam polarization
  Double_t targetPol = 1.0;
  Double_t targetPolError = 0.02;
  char Beam[6];
  char Poldir[5];
  char LRdir[6];

  TRandom *TRand = new TRandom3(0);
  TRand -> SetSeed(Seed);
  
  //ok, lets make our histograms!
  const Int_t nbins = NBins;//2 for mb, 4 for trig
  Float_t binjump = 3.5;
  if(nbins == 1) binjump = 4.5;
  Int_t mbins = 140;
  Double_t mmin = 0.;
  Double_t mmax = 14;
  const Int_t phibins = 12;
  const Int_t cosbins = 32;
  Double_t phimin = -PI;
  Double_t phimax = +PI;
  char Hname[128];

  //Yield histograms
  TH2F *Yield[2][nbins][2]; // [target][xf][pol]
  TH2F *Yieldmix[2][nbins];
  TH2F *Yield2[2][nbins][2]; // [target][xf][pol]
  TH2F *Yieldmix2[2][nbins];
  TH2F *Yield3[2][nbins]; // [target][xf]
  TH2F *Yieldmix3[2][nbins];
  TH1D *Hmass[2][nbins];
  for (int a = 0; a < 2; a++)
    for (int k = 0; k < nbins; k++){
	for (int j = 0; j < 2; j++){
	  sprintf (Hname, "Yield_target%d_xf%d_p%d", a, k, j);
	  Yield[a][k][j] = new TH2F (Hname, Hname, mbins, mmin, mmax, phibins, phimin, phimax);
	  sprintf (Hname, "Yield2_target%d_xf%d_p%d", a, k, j);
	  Yield2[a][k][j] = new TH2F (Hname, Hname, mbins, mmin, mmax, 2, phimin, phimax);
	}
      sprintf (Hname, "Yield3_target%d_xf%d", a, k);
      Yield3[a][k] = new TH2F (Hname, Hname, mbins, mmin, mmax, cosbins, phimin, phimax);
      sprintf (Hname, "Hmass_target%d_xf%d", a, k);
      Hmass[a][k] = new TH1D (Hname, Hname, mbins, mmin, mmax);
    }

  //mixed event subtraction histograms
  TH1D *tmass;
  TH1D *tmass2;
  TH1D *tmass3;
  TH1D *hmass[phibins][2];
  TH1D *hmass2[2][2];
  TH1D *hmass3;

  //mean xf, pt, eta histos
  TH2F *yxfmass  = new TH2F ("yxfmass",  "yxfmass",  100, 0., 1., 100, 0., 10. );
  TH2F *yxfmass3  = new TH2F ("yxfmass3",  "yxfmass3",  100, 0., 1., 100, 0., 10. );
  TH1F *yeta  = new TH1F ("yeta",  "yeta", 300, 2.0, 5.0 );
  TH3F *yxfmasspt  = new TH3F ("yxfmasspt",  "yxfmasspt",  100, 0., 1., 100, 0., 10., 500, 0., 5. );
  TH3F *yxfmasspt3  = new TH3F ("yxfmasspt3",  "yxfmasspt3",  100, 0., 1., 100, 0., 10., 500, 0., 5. );
  TH3F *yxfmasseta  = new TH3F ("yxfmasseta",  "yxfmasseta",  100, 0., 1., 100, 0., 10., 300, 2., 5. );
  TH3F *yxfmasseta3  = new TH3F ("yxfmasseta3",  "yxfmasseta3",  100, 0., 1., 100, 0., 10., 300, 2., 5. );
  TH1F *xf_mean = new TH1F("xf_mean","xf_mean",10, 0., 1.);
  TH1F *pt_mean = new TH1F("pt_mean","pt_mean",10, 0., 1.);
  TH1F *eta_mean = new TH1F("eta_mean","eta_mean",10, 0., 1.);
  TH1D *txf3;
  TH1D *tpt3;
  TH1D *teta3;
  
  for (int p = 0; p < phibins; p++)
      for (int j = 0; j < 2; j++){
	sprintf (Hname, "mass_%d_%d", p, j);
	hmass[p][j] = new TH1D (Hname, Hname, mbins, mmin, mmax);
	hmass[p][j] -> GetXaxis() -> SetTitle ("m_{#gamma#gamma} (GeV/c^{2})");
	hmass[p][j] -> SetLineColor (1);
	hmass[p][j] -> Sumw2();

      }
  for (int p = 0; p < 2; p++)
      for (int j = 0; j < 2; j++){
	sprintf (Hname, "mass2_%d_%d", p, j);
	hmass2[p][j] = new TH1D (Hname, Hname, mbins, mmin, mmax);
	hmass2[p][j] -> GetXaxis() -> SetTitle ("m_{#gamma#gamma} (GeV/c^{2})");
	hmass2[p][j] -> SetLineColor (1);
	hmass2[p][j] -> Sumw2();

      }

  sprintf (Hname, "mass3");
  hmass3 = new TH1D (Hname, Hname, mbins, mmin, mmax);
  hmass3 -> GetXaxis() -> SetTitle ("m_{#gamma#gamma} (GeV/c^{2})");
  hmass3 -> SetLineColor (1);
  hmass3 -> Sumw2();
  
  //phi histograms to grab mass projections in eta range!
  TH1D *hphi_sub[2][nbins][2];   
  TH1D *hphi_sub2[2][nbins][2]; 
  TH1D *hphi_raw3[2][nbins];  
  TH1D *hphi_sub3[2][nbins];  

  // tmp histograms to get the y-projections of the Yield[k] [j] around the pi0 mass
  TH1D *tphi = new  TH1D ("tphi", "tphi", phibins, phimin, phimax); tphi -> Sumw2();
  TH1D *tphi2 = new  TH1D ("tphi2", "tphi2", 2, phimin, phimax); tphi2 -> Sumw2();
  TH1D *tphi3 = new  TH1D ("tphi3", "tphi3", cosbins, phimin, phimax); tphi3 -> Sumw2();
  TH1D *mphi3 = new  TH1D ("mphi3", "mphi3", cosbins, phimin, phimax); mphi3 -> Sumw2();

  for (int a = 0; a < 2; a++)
    for (int k = 0; k < nbins; k++){
      sprintf (Hname, "phi_raw3_%d_%d", a, k);
      hphi_raw3[a][k] = new TH1D (Hname, Hname, cosbins, phimin, phimax);
      hphi_raw3[a][k] -> SetLineColor (k + 1);
      hphi_raw3[a][k] -> Sumw2();
      sprintf (Hname, "phi_sub3_%d_%d", a, k);
      hphi_sub3[a][k] = new TH1D (Hname, Hname, cosbins, phimin, phimax);
      hphi_sub3[a][k] -> SetLineColor (k + 1);
      hphi_sub3[a][k] -> Sumw2();
      
	for (int j = 0; j < 2; j++){	  
	  sprintf (Hname, "phi_sub_%d_%d_%d", a, k, j);
	  hphi_sub[a][k][j] = new TH1D (Hname, Hname, phibins, phimin, phimax);
	  hphi_sub[a][k][j] -> SetLineColor (2 * j + 1);
	  hphi_sub[a][k][j] -> Sumw2();
	  sprintf (Hname, "phi_sub2_%d_%d_%d", a, k, j);
	  hphi_sub2[a][k][j] = new TH1D (Hname, Hname, 2, phimin, phimax);
	  hphi_sub2[a][k][j] -> SetLineColor (2 * j + 1);
	  hphi_sub2[a][k][j] -> Sumw2();
	}
    }

  // Phi distributions for different polarizations!!
  TH1D *yphi[2][nbins][2];      //[target][xf][pol]
  TH1D *yphi2[2][nbins][2];   
  TH1D *yphi3[2][nbins];   
  for (int a = 0; a < 2; a++)  
    for (int k = 0; k < nbins; k++){
      sprintf (Hname, "yphi3_target%d_xf%d", a, k);
      yphi3[a][k] = new TH1D (Hname, Hname, cosbins, phimin, phimax);
      yphi3[a][k] -> SetLineColor (k + 1);
      yphi3[a][k] -> Sumw2();
 
      for (int d = 0; d < 2; d++) { // down-up
	sprintf (Hname, "yphi_target%d_xf%d_%d", a, k, d);
	yphi[a][k][d] = new TH1D (Hname, Hname, phibins, phimin, phimax);
	yphi[a][k][d] -> SetLineColor (d + 1);
	yphi[a][k][d] -> Sumw2();
	sprintf (Hname, "yphi2_target%d_xf%d_%d", a, k, d);
	yphi2[a][k][d] = new TH1D (Hname, Hname, 2, phimin, phimax);
	yphi2[a][k][d] -> SetLineColor (d + 1);
	yphi2[a][k][d] -> Sumw2();
      }
    }
  
  // ---------------------------------------------------------------------
  // Polarization asymmetries [target][xf]
  TH1D *asymP[2][nbins];
  TH1D *asymP2[2][nbins];
  for (int a = 0; a < 2; a++) 
    for (int k = 0; k < nbins; k++) {
      sprintf (Hname, "asymPol_target%d_xf%d", a, k);
      asymP[a][k] = new TH1D (Hname, Hname, phibins, phimin, phimax); // full detector
      asymP[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymP[a][k] -> GetYaxis() -> SetTitle ("#epsilon_{pol}");
      asymP[a][k] -> SetMarkerStyle (21);
      
      sprintf (Hname, "asymPol3_target%d_xf%d", a, k);
      asymP2[a][k] = new TH1D (Hname, Hname, 1, 0, 1); // only one bin
      asymP2[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymP2[a][k] -> GetYaxis() -> SetTitle ("#epsilon_{pol}");
      asymP2[a][k] -> SetMarkerStyle (21);
    }
 
  TH1D *asymF[2][nbins];  // polarization asymmetries, cleaned from rel.lumi. (fit) !!!
  for (int a = 0; a < 2; a++)  
    for (int k = 0; k < nbins; k++) {
      sprintf (Hname, "asymPol2_target%d_xf%d", a, k);
      asymF[a][k] = new TH1D (Hname, Hname, phibins, phimin, phimax); // full detector
      asymF[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymF[a][k] -> GetYaxis() -> SetTitle ("#epsilon_{pol}");
      asymF[a][k] -> SetMarkerStyle (21);
    }
  
  // ---------------------------------------------------------
  // left right asymmetries !!!
  TH1D *asymL[2][nbins];  // [target][xf]
  for (int a = 0; a < 2; a++)  
    for (int k = 0; k < nbins; k++) {  
      sprintf (Hname, "asymSide_target%d_xf%d", a, k);
      asymL[a][k] = new TH1D (Hname, Hname, phibins, phimin, phimax); // full detector
      asymL[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymL[a][k] -> SetMarkerStyle (21);
    }
  
  // ---------------------------------------------------------
  // Square root asymmetries !!!
  TH1D *asymS[2][nbins];  // [target][xf]
  TH1D *asymS2[2][nbins];  // [target][xf]
  TH1F *anval1[2][nbins];
  TH1F *anval5[2][nbins];

  for (int a = 0; a < 2; a++)  
    for (int k = 0; k < nbins; k++) { 
      sprintf (Hname, "asymSqrt_target%d_xf%d", a, k);
      asymS[a][k] = new TH1D (Hname, Hname, phibins /2, phimin, 0); // only left side 
      asymS[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymS[a][k] -> GetYaxis() -> SetTitle ("#epsilon_{sqrt}");
      asymS[a][k] -> SetMarkerStyle (21);
      sprintf (Hname, "asymSqrt2_target%d_xf%d", a, k);
      asymS2[a][k] = new TH1D (Hname, Hname, phibins / 2, phimin, 0); // only left side 
      asymS2[a][k] -> GetXaxis() -> SetTitle ("#varphi (rad)");
      asymS2[a][k] -> GetYaxis() -> SetTitle ("#epsilon_{sqrt}");
      asymS2[a][k] -> SetMarkerStyle (21);
      
      sprintf(Hname, "anval5_target%d_xf%d", a, k);
      anval5[a][k] = new TH1F(Hname, Hname, 200, -1, 1);
      anval5[a][k] -> GetXaxis() -> SetTitle ("Counts");
      anval5[a][k] -> GetYaxis() -> SetTitle ("A_{N}");

      sprintf(Hname, "anval1_target%d_xf%d", a, k);
      anval1[a][k] = new TH1F(Hname, Hname, 200, -1, 1);
      anval1[a][k] -> GetXaxis() -> SetTitle ("Counts");
      anval1[a][k] -> GetYaxis() -> SetTitle ("A_{N}");
    }

  //functions to fit azimuthal asymmetries!
  TF1 *fitcos  = new TF1 ("an_cos",  an_cos,  -PI, 0., 1); // cosine to sqrt-asymmetry
  TF1 *fitsin  = new TF1 ("an_sin",  an_sin,  -PI, 0., 2); // sine with phase to saqrt-asym
  TF1 *fitcosP = new TF1 ("an_cosP", an_cosP, -PI, PI, 2); // cosine with r.l. to P-asymmetry
  TF1 *fitsinP = new TF1 ("an_sinP", an_sinP, -PI, PI, 3); // sine with phase and r.l. to P-asym
  TF1 *fitcosF = new TF1 ("an_cosF", an_cos,  -PI, PI, 1); // cosine to asymF
  fitcos -> SetLineColor(2);
  fitcosF -> SetLineColor(4);

  double amp_val, amp_err;
  double phi_val, phi_err;
  double rel_val, rel_err;
  double ndf, csq;
  
  // Asymmetries as function of xf !!!
  TH1F *xf_asymfit1[2];
  TH1F *xf_asymfit2[2];
  TH1F *xf_phi0fit2[2];
  TH1F *xf_rellfit3[2];
  TH1F *xf_asymfit3[2];
  TH1F *xf_rellfit4[2];
  TH1F *xf_asymfit4[2];
  TH1F *xf_phi0fit4[2];
  TH1F *xf_asymfit5[2];
 
  TH1F *fit_rndf1[2];
  TH1F *fit_rndf2[2];
  TH1F *fit_rndf3[2];
  TH1F *fit_rndf4[2];
  TH1F *fit_rndf5[2];
  TH1F *xf_an5[2];
  TH1F *xf_an1[2];
  TH1F *xf_an3[2];
  TH1F *xf_an6[2];
  TH1F *xf_an7[2];

  for (int a = 0; a < 2; a++){
    sprintf(Hname, "xf_asymfit1_target%d", a);
    xf_asymfit1[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_asymfit1[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_asymfit1[a] -> GetYaxis() -> SetTitle ("raw asymmetry #epsilon");
    SetHistoStyle (xf_asymfit1[a], 20, 2, 1); 

    sprintf(Hname, "xf_asymfit2_target%d", a);
    xf_asymfit2[a] = new TH1F (Hname, Hname, 10, 0, 1);
    sprintf(Hname, "xf_phi0fit2_target%d", a);
    xf_phi0fit2[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_asymfit2[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_asymfit2[a] -> GetYaxis() -> SetTitle ("raw asymmetry #epsilon");
    xf_phi0fit2[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_phi0fit2[a] -> GetYaxis() -> SetTitle ("#varphi_{0}");
    SetHistoStyle (xf_asymfit2[a], 24, 2, 1);
    SetHistoStyle (xf_phi0fit2[a], 24, 2, 1);
    SetHistoAxes  (xf_phi0fit2[a], -1, 1, -.5 * PI, 1.5 * PI);


    sprintf(Hname, "xf_rellfit3_target%d", a);
    xf_rellfit3[a] = new TH1F (Hname, Hname, 10, 0, 1);
    sprintf(Hname, "xf_asymfit3_target%d", a);
    xf_asymfit3[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_rellfit3[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_rellfit3[a] -> GetYaxis() -> SetTitle ("rel.lumi.");
    xf_asymfit3[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_asymfit3[a] -> GetYaxis() -> SetTitle ("raw asymmetry #epsilon");
    SetHistoStyle (xf_rellfit3[a], 21, 8,  1); 
    SetHistoStyle (xf_asymfit3[a], 21, 8,  1);

    sprintf(Hname, "xf_rellfit4_target%d", a);  
    xf_rellfit4[a] = new TH1F (Hname, Hname, 10, 0, 1);
    sprintf(Hname, "xf_asymfit4_target%d", a);
    xf_asymfit4[a] = new TH1F (Hname, Hname, 10, 0, 1);
    sprintf(Hname, "xf_phi0fit4_target%d", a);
    xf_phi0fit4[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_rellfit4[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_rellfit4[a] -> GetYaxis() -> SetTitle ("rel.lumi.");
    xf_asymfit4[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_asymfit4[a] -> GetYaxis() -> SetTitle ("raw asymmetry #epsilon");
    xf_phi0fit4[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_phi0fit4[a] -> GetYaxis() -> SetTitle ("#varphi_{0}");
    SetHistoStyle (xf_rellfit4[a], 25, 8, 1);
    SetHistoStyle (xf_asymfit4[a], 25, 8, 1);
    SetHistoStyle (xf_phi0fit4[a], 24, 8, 1);
    SetHistoAxes  (xf_phi0fit4[a], -1, 1, -.5 * PI, 1.5 * PI);


    // Yes-yes, this is the final fit: subtract the global rel. luminosity and fit plain cosine !!!
    sprintf(Hname, "xf_asymfit5_target%d", a);  
    xf_asymfit5[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_asymfit5[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_asymfit5[a] -> GetYaxis() -> SetTitle ("raw asymmetry #epsilon");
    SetHistoStyle (xf_asymfit5[a], 21, 4, 1);
      
    sprintf(Hname, "fit_rndf1_target%d", a);  
    fit_rndf1[a] = new TH1F (Hname, Hname, 100, 0., 10.);
    sprintf(Hname, "fit_rndf2_target%d", a);  
    fit_rndf2[a] = new TH1F (Hname, Hname, 100, 0., 10.);
    sprintf(Hname, "fit_rndf3_target%d", a);  
    fit_rndf3[a] = new TH1F (Hname, Hname, 100, 0., 10.);
    sprintf(Hname, "fit_rndf4_target%d", a);  
    fit_rndf4[a] = new TH1F (Hname, Hname, 100, 0., 10.);
    sprintf(Hname, "fit_rndf5_target%d", a);  
    fit_rndf5[a] = new TH1F (Hname, Hname, 100, 0., 10.);
    fit_rndf1[a] -> GetXaxis() -> SetTitle ("#chi^{2} / (n.d.f. - 1)");
    fit_rndf2[a] -> GetXaxis() -> SetTitle ("#chi^{2} / (n.d.f. - 1)");
    fit_rndf3[a] -> GetXaxis() -> SetTitle ("#chi^{2} / (n.d.f. - 1)");
    fit_rndf4[a] -> GetXaxis() -> SetTitle ("#chi^{2} / (n.d.f. - 1)");
    fit_rndf5[a] -> GetXaxis() -> SetTitle ("#chi^{2} / (n.d.f. - 1)");

    // And look: then there is the analyzing power !!!
    sprintf(Hname, "xf_an5_target%d", a);  
    xf_an5[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_an5[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_an5[a] -> GetYaxis() -> SetTitle ("A_{N}");
    SetHistoStyle (xf_an5[a], 21, 4, 1);
    sprintf(Hname, "xf_an1_target%d", a);  
    xf_an1[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_an1[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_an1[a] -> GetYaxis() -> SetTitle ("A_{N}");
    SetHistoStyle (xf_an1[a], 21, 2, 1);
    sprintf(Hname, "xf_an3_target%d", a);  
    xf_an3[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_an3[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_an3[a] -> GetYaxis() -> SetTitle ("A_{N}");
    SetHistoStyle (xf_an3[a], 25, 8, 1);
    sprintf(Hname, "xf_an6_target%d", a);  
    xf_an6[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_an6[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_an6[a] -> GetYaxis() -> SetTitle ("A_{N}");
    SetHistoStyle (xf_an6[a], 25, 2, 1);
    sprintf(Hname, "xf_an7_target%d", a);  
    xf_an7[a] = new TH1F (Hname, Hname, 10, 0, 1);
    xf_an7[a] -> GetXaxis() -> SetTitle ("x_{F}");
    xf_an7[a] -> GetYaxis() -> SetTitle ("A_{N}");
    SetHistoStyle (xf_an7[a], 25, 4, 1);

    
  }

  // ============= Let's roll squared: get the data !!!
  int arm;
  int pol, polT;
  Float_t xf;
  Float_t phi, phi2, phi3;
  Float_t pt;

  //initialize kdimuon tree
  Int_t dimuonID;
  Int_t runID;
  Int_t spillID, eventID;
  Int_t negTrackID, posTrackID;
  Int_t negHits, posHits;
  Float_t xF, xT, xB, mass;
  Float_t dx, dy, dz;
  Float_t dpx, dpy, dpz;
  Float_t px1, py1, pz1;
  Float_t px2, py2, pz2;
  Float_t trackSeparation, chisq_dimuon;
  Int_t target, dump;
  Int_t targetPos;
  Float_t m3hm, m3hs, m3vm, m3vs;
  Float_t m2hm, m2hs, m2vm, m2vs;
  Float_t dhm, dvm;
  Float_t costh, phi;
  Float_t eta;
  TLorentzVector lordm;// = new TLorentzVector;

  if(Trig == 0)  sprintf (inName, "./nDST/Analysis_roadset%d_R005_V001.root", Roadset);
  //if(Trig == 2)  sprintf (inName, "./nDST/Analysis_mc_drellyan_LD2_M013_S001.root");

  TFile *inFile1 = new TFile (inName);
  gROOT -> cd();
  
  // ====================================================== Read the reconstructed cluster pairs !!!
  TTree *YieldTree = (TTree*) inFile1 -> Get ("kdimuon"); 
  //YieldTree -> SetBranchAddress ("dimuonID",        &dimuonID);
  YieldTree -> SetBranchAddress ("runID",           &runID);
  //YieldTree -> SetBranchAddress ("eventID",         &eventID);
  YieldTree -> SetBranchAddress ("spillID",         &spillID);
  //YieldTree -> SetBranchAddress ("posTrackID",    &posTrackID);
  //YieldTree -> SetBranchAddress ("negTrackID",    &negTrackID);
  //YieldTree -> SetBranchAddress ("posHits",    &posHits);
  //YieldTree -> SetBranchAddress ("negHits",    &negHits);
  //YieldTree -> SetBranchAddress ("dx",              &dx);
  //YieldTree -> SetBranchAddress ("dy",              &dy);
  //YieldTree -> SetBranchAddress ("dz",              &dz);
  YieldTree -> SetBranchAddress ("dpx",             &dpx);
  YieldTree -> SetBranchAddress ("dpy",             &dpy);
  YieldTree -> SetBranchAddress ("dpz",             &dpz);
  YieldTree -> SetBranchAddress ("mass",            &mass);
  YieldTree -> SetBranchAddress ("xF",              &xF);
  //YieldTree -> SetBranchAddress ("xB",              &xB);
  YieldTree -> SetBranchAddress ("xT",              &xT);
  //YieldTree -> SetBranchAddress ("costh",              &costh);
  //YieldTree -> SetBranchAddress ("phi",              &phi);
  //YieldTree -> SetBranchAddress ("trackSeparation", &trackSeparation);
  //YieldTree -> SetBranchAddress ("chisq_dimuon",    &chisq_dimuon);
  //YieldTree -> SetBranchAddress ("px1",             &px1);
  //YieldTree -> SetBranchAddress ("py1",             &py1);
  //YieldTree -> SetBranchAddress ("pz1",             &pz1);
  //YieldTree -> SetBranchAddress ("px2",             &px2);
  //YieldTree -> SetBranchAddress ("py2",             &py2);
  //YieldTree -> SetBranchAddress ("pz2",             &pz2);
  YieldTree -> SetBranchAddress ("target",          &target);
  YieldTree -> SetBranchAddress ("dump",            &dump);
  //YieldTree -> SetBranchAddress ("targetPos",       &targetPos);

  //here's the for loop
  int nentries = YieldTree -> GetEntries();
  int spillID0;
  int daycount = 0;
  int DspillID;
  cout << "Number of entries: " << nentries << endl;
  for (int i = 0; i < nentries; i++) {
    //for (int i = 0; i < 10000; i++) {
    YieldTree -> GetEntry (i);
    if(i%100000 == 0) cout << "entry " << i << endl;
    if(i == 0 ) spillID0 = spillID;
    if(runID > 13800 && runID < 14799)continue;
    if(xT < 0.1 || xT > 0.4)continue;
    //Now do the kinematic cuts!
    xf = xF;
    lordm.SetXYZM(dpx, dpy, dpz, mass);
    pt = lordm.Pt();
    if(pt < 0.5) continue;
    //if(fabs(lordm.Py()/lordm.Px()) < 0.176 || fabs(lordm.Py()/lordm.Px()) > 5.67) continue;
    //if(fabs(lordm.Px()/lordm.Py()) < 0.176) continue;
    phi = lordm.Phi();

    //make a left right phi!
    phi2 = phi - PI/2;
    if(phi2 < -PI){phi2 = phi2 + 2*PI;}
    phi3 = phi - PI/2;
    if(phi3 < -PI){phi3 = phi3 + 2*PI;}

    if(nbins == 1){k = 0;}
    else{
      if(Trig == 0 || Trig == 2){int k = int (10 * xf);}
    }

    if(nbins == 1){
      if(xf < 0.2 || xf > 0.6)continue;}
    else if(nbins > 1){
      if(xf < 0.2 || xf > 0.7)continue;
    }
    if(nbins == 1){k = 0;}
    else{
      int k = int (10 * (xf - 0.2));
    }

    
    if (k < 0) continue;
    if (k > nbins-1) k = nbins - 1;
    //if (k > nbins-1) continue;

    //if(i == 0)cout << "entry, day, DspillID, polT " << i <<  " " << daycount << " " << DspillID << " " << polT <<endl;
    DspillID = float(spillID - spillID0) / 650.;
    //if((spillID - spillID0) / 650 > daycount){
    if(DspillID > daycount){
      if(Seed == 0){
      if(DspillID%2 == 0)polT = 0;      
      if(DspillID%2 == 1)polT = 1;      
      }
      else{
	polT = TRand -> Uniform(2);
      }
      //cout << "entry, day, Dspill, DspillID, polT " << i <<  " " << daycount << " " << spillID - spillID0 << " " << DspillID << " " << polT <<endl;
      daycount++;
    }

    //cout << "arm, k, phiy, phib, phi " << i << " " << arm << " " << k << " " << phiyellow << " " << phiblue << " " << phi << endl;
    Yield[target][k][polT] -> Fill (mass, phi);
    Yield2[target][k][polT] -> Fill (mass, phi2);
   
    Yield3[target][k] -> Fill (mass, phi);
    yxfmass  -> Fill (mass,xf);
    yeta  -> Fill (eta);
    yxfmasspt  -> Fill (mass,xf,pt);
    yxfmasseta  -> Fill (mass,xf,eta);
    
  }

  inFile1 -> Close();
  gROOT -> cd();
  //exit(1);
  // ================================================================== mass peak determination
  //                                                                    asymmetry calculation
  
  //Canvas to draw phi dists
  TCanvas *cpa[2];
  TCanvas *cpa2[2];
  TCanvas *c1;
  TCanvas *c2;

  c1 = new TCanvas();
    for (int j = 0; j < 2; j++){
      sprintf(Hname, "cpa_%d", j);
      cpa[j] = new TCanvas(Hname, Hname, 1800, 1200);
      cpa[j] -> Divide(3, 3);
      sprintf(Hname, "cpa2_%d", j);
      cpa2[j] = new TCanvas(Hname, Hname, 1200, 400);
      cpa2[j] -> Divide(2, 1);
    }

  for (int a = 0; a < 2; a++){ // These are the slices in dump/target !!
    if(a == 0) sprintf (inArm, "Dump");
    else if(a == 1) sprintf (inArm, "Target");
    if(a == 0){sprintf(Beam,"dump");}
    if(a == 1){sprintf(Beam,"target");}

    for (int k = 0; k < nbins; k++) { // These are the slices in xf !!!
       // Mass distribution for the mixed events !!!
      //labels!
      float xfTitleMin, xfTitleMax;
      float phiTitleMin, phiTitleMax;
      if(Trig == 0 || Trig == 2){
	xfTitleMin = 0.1 * float (k) + 0.2;
	xfTitleMax = 0.1 * float (k) + 0.3;
	if(NBins == 1){xfTitleMin = 0.2, xfTitleMax = 0.4;}
      }
      
      //fit range!
      printf("//////////////////////////////////");
      printf("GET PARAMETERS FOR TARGET %d, XF BIN %d \n", a, k);
      ///////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////

      c1->cd();
      printf("Doing mass distributions for target %d, xf bin%d \n", a, k);

      tmass3 = Yield3[a][k] -> ProjectionX();
      Hmass[a][k] -> Add (tmass3);
      Hmass[a][k] -> Draw();
      sprintf (Hname, "./images_xf/mass3_roadset%d_nbins%d_target%d_xf%d.gif", Roadset, nbins, a, k);
      if(SaveOn == 1) c1-> SaveAs(Hname);
      tmass3 -> Reset();

      //Set the phi distributions for cosavg!
      tphi3 = Yield3[a][k] -> ProjectionY ("tphi3", 1,140);
      hphi_raw3[a][k] -> Reset();
      hphi_raw3[a][k] -> Add (tphi3);
      hphi_sub3[a][k] -> Reset();
      hphi_sub3[a][k] -> Add (tphi3);
      
      //Do it for the bigger phi bins !!!
      printf("//////////////////////////////////");
      printf("BIG PHI BIN PART FOR XF BIN %d \n", k);
      ///////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////
      //one phi bin at a time, then subtract background!!

	for (int j = 0; j < 2; j++)
	  for(int p = 0; p < 2; p++){
	    if (j == 0) sprintf (inPol, "Down");
	    else if (j == 1) sprintf (inPol, "Up");
	    if (p == 0)sprintf (LRdir, "Left");
	    else if (p == 1)sprintf (LRdir, "Right");
	    c1->cd();
	    //Get invariant mass
	    printf("Doing mass distributions for %s xf bin%d, phi bin %s, %s direction \n", inArm, k, LRdir, inPol);

	    tmass2 = Yield2[a][k][j] -> ProjectionX("tmass2", p+1, p+1);
	    hmass2[p][j] -> Reset();
	    hmass2[p][j] -> Add (tmass2);

	    cpa2[j] -> cd(p+1);
	    int integral = hmass2[p][j] -> Integral(1, 140);
	    sprintf (Hname, "%d COUNTS! %s %s %s %s for %1.1f < x_{F} < %1.1f, %s", integral, inArm, inTrig, inBeam, inPol, xfTitleMin, xfTitleMax, LRdir);
	    hmass2[p][j] -> SetTitle(Hname);
	    hmass2[p][j] -> Draw();
	    tmass2 -> Reset();

	    // Set the phi distributions !!!
	    hphi_sub2[a][k][j] -> SetBinContent(p+1, hmass2[p][j] -> Integral(1, 140));
	  }//end of slices in big phi, pol direction!  
      //Save Canvas
	for (int j = 0; j < 2; j++){
	  cpa2[j] -> cd();
          sprintf (Hname, "./images_mass_xf/mass2_nbins%d_roadset%d_target%d_xf%d_D%d.gif", nbins, Roadset, a, k, j);
	  if(SaveOn == 1)cpa2[j] -> SaveAs(Hname);
	  }
	
      printf("//////////////////////////////////");
      printf("LITTLE PHI BIN PART FOR XF BIN %d \n", k);
      //one phi bin at a time, then subtract background!!
	for (int j = 0; j < 2; j++)
	  for(int p = 0; p < phibins; p++){
	    if (j == 0) sprintf (inPol, "Down");
	    else if (j == 1) sprintf (inPol, "Up");
	    phiTitleMin = PI/(phibins/2) * float(p) - PI;
	    phiTitleMax = PI/(phibins/2) * float(p) - PI + PI/(phibins/2);
	    c1->cd();

	    //Get the invariant mass
	    //tmass -> Reset();
	    tmass = Yield[a][k][j] -> ProjectionX("tmass", p+1, p+1);
	    hmass[p][j] -> Reset();
	    hmass[p][j] -> Add (tmass);

	    cpa[j] -> cd(p+1);
	    int integral = hmass[p][j] -> Integral(1, 140);
	    sprintf (Hname, "%d COUNTS! %s %s %s %s for %1.1f < x_{F} < %1.1f, %s", integral, inArm, inTrig, inBeam, inPol, xfTitleMin, xfTitleMax, LRdir);
	    hmass[p][j] -> SetTitle(Hname);
	    hmass[p][j] -> Draw();
	    tmass -> Reset();

	    hphi_sub[a][k][j] -> SetBinContent(p+1, hmass[p][j] -> Integral(1, 140));
	  }//end of slices in phi, pol direction!
    
	//Save Canvas
	for (int j = 0; j < 2; j++){
	  cpa[j] -> cd();
	  sprintf (Hname, "./images_mass_xf/masssub_nbins%d_Roadset%d_target%d_xf%d_B%d_D%d.gif", nbins, Roadset, a, k, j);
	  if(SaveOn == 1)cpa[j] -> SaveAs(Hname);
	}
	
      //Get the #eta meson Yields in phi!!
      printf("NOW GETTING THE SPIN, PHI DEPENDENT YIELDS FOR %s xf bin %d \n", inArm, k);
      yphi[a][k][0] -> Add (hphi_sub[a][k][0]); // target down
      yphi[a][k][1] -> Add (hphi_sub[a][k][1]); // target up
      yphi2[a][k][0] -> Add (hphi_sub2[a][k][0]); // target down
      yphi2[a][k][1] -> Add (hphi_sub2[a][k][1]); // target up
      yphi3[a][k] -> Add (hphi_sub3[a][k]); 
    
      c1 -> cd();
      // Calculate polarization asymmetries (asymP),left-right and square root asymmetries (asymS) !!!
      double n1, n2, n3, n4;
      double e1, e2, e3, e4;
      double asym_val, asym_err;
      double asym_val_up,asym_err_up,asym_val_down,asym_err_down;
      double asym_val_left,asym_err_left,asym_val_right,asym_err_right;
      //sqrt asymmetry
      for (int p = 0; p < phibins / 2; p++) {
	  n1 = yphi[a][k][1] -> GetBinContent (p + 1);
	  n2 = yphi[a][k][0] -> GetBinContent (p + 1);
	  n3 = yphi[a][k][1] -> GetBinContent (p + 1 + phibins / 2);
	  n4 = yphi[a][k][0] -> GetBinContent (p + 1 + phibins / 2);
	  e1 = sqrt(n1);
	  e2 = sqrt(n2);
	  e3 = sqrt(n3);
	  e4 = sqrt(n4);
	  if ((n1 > 9) && (n2 > 9) && (n3 > 9) && (n4 > 9)) {
	    asym_val = square_asym  (n1, n2, n3, n4);
	    asym_err = square_error (n1, n2, n3, n4, e1, e2, e3, e4);
	    asymS[a][k] -> SetBinContent (p + 1, asym_val);
	    asymS[a][k] -> SetBinError   (p + 1, asym_err);
	  }
	}
	//polarization asymmetry
	for (int p = 0; p < phibins; p++) {
	  n1 = yphi[a][k][1] -> GetBinContent (p + 1);
	  n2 = yphi[a][k][0] -> GetBinContent (p + 1);
	  e1 = sqrt(n1);
	  e2 = sqrt(n2);
	  if ((n1 > 9) && (n2 > 9)) {
	    asymP[a][k] -> SetBinContent (p + 1, simple_asym  (n1, n2));
	    asymP[a][k] -> SetBinError   (p + 1, simple_error (n1, n2, e1, e2));
	  }
	}
	//simple left-right asymmetry
	for (int p = 0; p < phibins / 2; p++) {
	  n1 = yphi[a][k][0] -> GetBinContent (p + 1 + phibins / 2);
	  n2 = yphi[a][k][0] -> GetBinContent (p + 1);
	  n3 = yphi[a][k][1] -> GetBinContent (p + 1);
	  n4 = yphi[a][k][1] -> GetBinContent (p + 1 + phibins / 2);
	  e1 = sqrt(n1);
	  e2 = sqrt(n2);
	  e3 = sqrt(n3);
	  e4 = sqrt(n4);
	  if ((n1 > 9) && (n2 > 9) && (n3 > 9) && (n4 > 9)) {
	    asym_val_up = simple_asym(n1, n2);
	    asym_err_up = simple_error(n1, n2, e1, e2);
	    asym_val_down = simple_asym(n3, n4);
	    asym_err_down = simple_error(n3, n4, e3, e4);
	    asym_val = weighted_mean(asym_val_up, asym_val_down, asym_err_up, asym_err_down);
	    asym_err = weighted_error(asym_err_up, asym_err_down);
	    asymL[a][k] -> SetBinContent (p + 1, asym_val_up);
	    asymL[a][k] -> SetBinError   (p + 1, asym_err_down);
	  }
	}
      
      ////////////////////////////////////////////////
      //this is new do the cos average first
      double cosval[cosbins]; //[cosbins]
      int cosavg_den = 0;
      double cosavg_num = 0;
      double cosavg = 0;
      printf ("The f correction factor variables for %s xf bin %d. \n", inArm, k);
      printf ("%5s : %9s : %5s : %11s : %11s \n", "phibin", "cosval[p]", "n1", "cosavg_num", "cosavg_den");
      for (int p = 0; p < cosbins; p++) {
	n1 = 0;
	n1 = yphi3[a][k] -> GetBinContent (p + 1);
	cosval[p] = PI/(cosbins/2) * double(p) - PI + (PI/(cosbins/2)/2);
	if (n1 > 0) {
	  cosavg_num += (n1 * fabs( cos( cosval[p] ) ) );
	  cosavg_den += n1;
	}
	printf ("%5d : %1.2f : %5d : %1.2f : %1.1f \n", p, cosval[p], n1, cosavg_num, cosavg_den);
      }
      cosavg = cosavg_num / double(cosavg_den);
      printf("The correction factor f for %s xf bin %d is %1.2f. \n", inArm, k, 1/cosavg);
      //end of cos avg function f
      
      /////////////////////////////////////////////////
      //this is new let's just do sqrt, left-right
      printf ("The sqrt-formula spin dependent yields for %s xf bin %d. \n", inArm, k);
      n1 = n2 = n3 = n4 = 0;
      n1 = yphi2[a][k][1] -> GetBinContent (1);
      n2 = yphi2[a][k][1] -> GetBinContent (2);
      n3 = yphi2[a][k][0] -> GetBinContent (1);
      n4 = yphi2[a][k][0] -> GetBinContent (2);
      e1 = sqrt(n1);
      e2 = sqrt(n2);
      e3 = sqrt(n3);
      e4 = sqrt(n4);
      if ((n1 > 9) && (n2 > 9) && (n3 > 9) && (n4 > 9)) {
	printf ("%5s : %5s : %5s : %5s : %5s : %5s : %5s : %5s \n", "n1", "n2", "n3", "n4", "e1", "e2", "e3", "e4");
	printf ("%5d : %5d : %5d : %5d : %5d : %5d : %5d : %5d \n", n1, n2, n3, n4, e1, e2, e3, e4);
	asym_val = (1/cosavg)*(square_asym  (n1, n2, n3, n4));
	asym_err = (1/cosavg)*(square_error (n1, n2, n3, n4, e1, e2, e3, e4));
	cout << "The sqrt-formula value of asym_val,asym_err after f correction is:  " << asym_val << ", " << asym_err << endl;
	asymS2[a][k] -> SetBinContent (1, asym_val);
	asymS2[a][k] -> SetBinError   (1, asym_err);
	}
      //this is the end of the new sqrt asym part
      
      /////////////////////////////////////////////////
      //this is new let's just do pol up-down
      printf ("The relative luminosity spin dependent yields for %s xf bin %d. \n", inArm, k);
      n1 = n2 = n3 = n4 = 0;
      n1 = yphi2[a][k][1] -> GetBinContent (1);
      n2 = yphi2[a][k][1] -> GetBinContent (2);
      n3 = yphi2[a][k][0] -> GetBinContent (1);
      n4 = yphi2[a][k][0] -> GetBinContent (2);
      e1 = sqrt(n1);
      e2 = sqrt(n2);
      e3 = sqrt(n3);
      e4 = sqrt(n4);
 
      if ((n1 > 9) && (n2 > 9) && (n3 > 9) && (n4 > 9)) {
	printf ("%5s : %5s : %5s : %5s : %5s : %5s : %5s : %5s : %5s : %11s : %11s \n", "phibin", "n1", "n2", "n3", "n4", "e1", "e2", "e3", "e4", "cosavg_num", "cosavg_den");
	printf ("%5d : %5d : %5d : %5d : %5d : %5d : %5d : %5d : %5d : %1.2f : %1.1f \n", p, n1, n2, n3, n4, e1, e2, e3, e4, cosavg_num, cosavg_den);
	asym_val_left = (1/cosavg)*(simple_asym  (n1, n3));
	asym_err_left = (1/cosavg)*(simple_error (n1, n3, e1, e3));
	asym_val_right = (1/cosavg)*(simple_asym  (n4, n2));
	asym_err_right = (1/cosavg)*(simple_error (n4, n2, e4, e2));
	asym_val = weighted_mean(asym_val_left,asym_val_right,asym_err_left,asym_err_right);
	asym_err = weighted_error(asym_err_left,asym_err_right);
	cout << "The rel-lum value of asym_val,asym_err after f correction for beam is:  " << asym_val << ", " << asym_err << endl;
	asymP2[a][k] -> SetBinContent (1, asym_val);
	asymP2[a][k] -> SetBinError   (1, asym_err);
      }

      //this is the end of the new pol asym part
      ////////////////////////////////////////////////
    
      // Determine the amplitude of the single spin asymmetries as function of xf !!!
      printf ("==============================================\n");
      printf (" fit results for %s xf-bin %d \n", inArm, k);
      printf ("----------------------------------------------\n");
      printf ("::: sqrt,pol-asymmetries, left-right ::: \n");
      amp_val = asymS2[a][k] -> GetBinContent(1);
      amp_err = asymS2[a][k] -> GetBinError(1);

      xf_an6[a] -> SetBinContent (binjump + k, amp_val / targetPol);
      xf_an6[a] -> SetBinError   (binjump + k, amp_err / targetPol);
      
      amp_val = asymP2[a][k] -> GetBinContent(1);
      amp_err = asymP2[a][k] -> GetBinError(1);

      xf_an7[a] -> SetBinContent (binjump + k, amp_val / targetPol);
      xf_an7[a] -> SetBinError   (binjump + k, amp_err / targetPol);
	
      printf ("----------------------------------------------\n");
      printf ("::: sqrt-asymmetries ::: \n");
      printf ("plain cosine fit: \n");
      fitcos -> SetParameters (0., 0.);
      asymS[a][k] -> Fit ("an_cos", "R");
      amp_val = fitcos -> GetParameter (0);
      amp_err = fitcos -> GetParError  (0);
      xf_asymfit1[a] -> SetBinContent (binjump + k, amp_val);
      xf_asymfit1[a] -> SetBinError   (binjump + k, amp_err);
      printf (" %5.3f +/- %5.3f \n", amp_val, amp_err);
      ndf     = fitcos -> GetNDF();
      csq     = fitcos -> GetChisquare();
      if (ndf > 1){
	fit_rndf1[a] -> Fill (csq / (ndf - 1));
      }

      xf_an1[a] -> SetBinContent (binjump + k, amp_val / targetPol);
      xf_an1[a] -> SetBinError   (binjump + k, amp_err / targetPol);
      anval1[a][k] -> Fill(amp_val);
      
      printf ("sine fit with free phase: \n");
      fitsin -> SetParameters (0., 1.5 * PI);
      asymS[a][k] -> Fit ("an_sin", "R");
      amp_val = fitsin -> GetParameter (0);
      amp_err = fitsin -> GetParError  (0);
      phi_val = fitsin -> GetParameter (1);
      phi_err = fitsin -> GetParError  (1);
      // ========>  correlation of sign of amplitude and phi0 !!! <========
      if (sin (phi_val) < 0.) {phi_val += PI; amp_val *= -1.;}
      phi_val = phase_modulo (phi_val);
      xf_asymfit2[a] -> SetBinContent (binjump + k, amp_val);
      xf_asymfit2[a] -> SetBinError   (binjump + k, amp_err);
      xf_phi0fit2[a] -> SetBinContent (binjump + k, phi_val - 0.5 * PI);
      xf_phi0fit2[a] -> SetBinError   (binjump + k, phi_err);
      printf (" %5.3f +/- %5.3f \n", amp_val, amp_err);
      printf (" %5.3f +/- %5.3f \n", phi_val, phi_err);
      ndf     = fitsin -> GetNDF();
      csq     = fitsin -> GetChisquare();
      if (ndf > 1){
	fit_rndf2[a] -> Fill (csq / (ndf - 1));
      }
      printf ("----------------------------------------------\n");
      printf ("::: pol-asymmetries :::");
      printf ("constant plus cosine fit: \n");
      fitcosP -> SetParameters (0., 0.);
      asymP[a][k] -> Fit ("an_cosP", "R");
      rel_val = fitcosP -> GetParameter (0);
      rel_err = fitcosP -> GetParError  (0);
      amp_val = fitcosP -> GetParameter (1);
      amp_err = fitcosP -> GetParError  (1);
      xf_rellfit3[a] -> SetBinContent (binjump + k, rel_val);
      xf_rellfit3[a] -> SetBinError   (binjump + k, rel_err);
      xf_asymfit3[a] -> SetBinContent (binjump + k, amp_val);
      xf_asymfit3[a] -> SetBinError   (binjump + k, amp_err);
      printf (" %5.3f +/- %5.3f \n", rel_val, rel_err);
      printf (" %5.3f +/- %5.3f \n", amp_val, amp_err);
      ndf     = fitcosP -> GetNDF();
      csq     = fitcosP -> GetChisquare();
      if (ndf > 1){
	fit_rndf3[a] -> Fill (csq / (ndf - 1));
      }
      printf ("constant plus sine fit with free phase: \n");
      fitsinP -> SetParameters (0., 1.5 * PI);
      asymP[a][k] -> Fit ("an_sinP", "R");
      rel_val = fitsinP -> GetParameter (0);
      rel_err = fitsinP -> GetParError  (0);
      amp_val = fitsinP -> GetParameter (1);
      amp_err = fitsinP -> GetParError  (1);
      phi_val = fitsinP -> GetParameter (2);
      phi_err = fitsinP -> GetParError  (2);
      // ========>  correlation of sign of amplitude and phi0 !!! <========
      if (sin (phi_val) < 0.) {phi_val += PI; amp_val *= -1.;}
      phi_val = phase_modulo (phi_val);
      xf_rellfit4[a] -> SetBinContent (binjump + k, rel_val);
      xf_rellfit4[a] -> SetBinError   (binjump + k, rel_err);
      xf_asymfit4[a] -> SetBinContent (binjump + k, amp_val);
      xf_asymfit4[a] -> SetBinError   (binjump + k, amp_err);
      xf_phi0fit4[a] -> SetBinContent (binjump + k, phi_val - 0.5 * PI);
      xf_phi0fit4[a] -> SetBinError   (binjump + k, phi_err);
      printf (" %5.3f +/- %5.3f \n", rel_val, rel_err);
      printf (" %5.3f +/- %5.3f \n", amp_val, amp_err);
      printf (" %5.3f +/- %5.3f \n", phi_val, phi_err);
      ndf     = fitsinP -> GetNDF();
      csq     = fitsinP -> GetChisquare();
      if (ndf > 1){
	fit_rndf4[a] -> Fill (csq / (ndf - 1));
      }
    }// End of the slices in k !!!
    cout << "END OF SLICES IN XF BINS!" << endl;
 
    // Determine the global relative luminosity !!!
    TLine *RLine;
    Double_t avRL;
    Double_t erRL;
    TF1 *relTarget   = new TF1 ("relTarget",   "pol0", -.7, -.1);
    xf_rellfit3[a] -> Fit ("relTarget",   "R");
    avRL = relTarget   -> GetParameter (0);
    erRL = relTarget   -> GetParError  (0);
    for (int k = 0; k < nbins; k++)
      for (int p = 0; p < phibins; p++)
	if (asymP[a][k] -> GetBinError   (p + 1)){ 
	  asymF[a][k] -> SetBinContent (p + 1, asymP[a][k] -> GetBinContent (p + 1) - avRL);
	  asymF[a][k] -> SetBinError   (p + 1, asymP[a][k] -> GetBinError   (p + 1));
	}

    RLine = new TLine (.1, avRL, .8, avRL); RLine -> SetLineWidth (3);
  
    for (int k = 0; k < nbins; k++) {
      printf ("==============================================\n");
      printf ("::: final pol-asymmetries :::");
      printf ("constant plus cosine fit (global relative luminosity): \n");
      fitcosF -> SetParameters (0., 0.);
      asymF[a][k] -> Fit ("an_cosF", "R");
      amp_val = fitcosF -> GetParameter (0);
      amp_err = fitcosF -> GetParError  (0);
      xf_asymfit5[a] -> SetBinContent (binjump + k, amp_val);
      xf_asymfit5[a] -> SetBinError   (binjump + k, amp_err);
      printf (" %5.3f +/- %5.3f \n", rel_val, rel_err);
      printf (" %5.3f +/- %5.3f \n", amp_val, amp_err);
      ndf     = fitcosF -> GetNDF();
      csq     = fitcosF -> GetChisquare();
      if (ndf > 1){
	fit_rndf5[a] -> Fill (csq / (ndf - 1));
      }
      
      xf_an5[a] -> SetBinContent (binjump + k, amp_val / targetPol);
      xf_an5[a] -> SetBinError   (binjump + k, amp_err / targetPol);
      anval5[a][k] -> Fill(amp_val);
    }
    // Images !!!
    /*   if(Peak == 0){
      xf_asymfit1[a] -> SetMinimum (-.08);
      xf_asymfit1[a] -> SetMaximum ( .13);
      xf_an1[a] -> SetMinimum (-.20);
      xf_an1[a] -> SetMaximum ( .25);
    }
    else if(Peak == 1 || Peak == 2){
      xf_asymfit1[a] -> SetMinimum (-.17);
      xf_asymfit1[a] -> SetMaximum ( .17);
      xf_an1[a] -> SetMinimum (-.35); 
      xf_an1[a] -> SetMaximum ( .25);
    }*/
    xf_an1[a] -> SetMinimum (-.1);
    xf_an1[a] -> SetMaximum ( .1);

    TLegend *Legend1 = new TLegend (.15, .7, .5, .88);
    Legend1 -> SetFillStyle (0);
    Legend1 -> SetLineColor (0);
    Legend1 -> AddEntry (xf_asymfit1[a], "#epsilon_{sqrt}:a*cos(#varphi)");
    Legend1 -> AddEntry (xf_asymfit3[a], "#epsilon_{pol}:b+a*cos(#varphi)");
    Legend1 -> AddEntry (xf_asymfit5[a], "#epsilon_{pol}:#bar{b}+a*cos(#varphi)");
    
    TLine *zxf = new TLine (0., 0., 1., 0.);
    char *asymxNameText = "./images_xf/asym2p_roadset%d_nbins%d_target%d.gif";
    sprintf (Hname, asymxNameText, Roadset, nbins, a);

    TCanvas *Casymx = new TCanvas ("asym", "asym", 500, 500);
    //Casymx -> Divide (1, 2);
    //Casymx -> cd(1);
    //xf_asymfit1[a] -> Draw();
    //xf_asymfit3[a] -> Draw("SAME");
    //xf_asymfit5[a] -> Draw("SAME");
    //Legend1 -> Draw ("SAME");
    //zxf -> Draw();
    //Casymx -> cd(2);
    xf_an1[a] -> Draw();
    xf_an5[a] -> Draw("same");
    zxf -> Draw();

    Casymx -> Update();
    if(SaveOn == 1) Casymx -> SaveAs (Hname);

    TLatex *Lxf[5];
    if(a == 1){neg = 1; pos = 0;}
    if(Trig == 0 || Trig == 2){
      if(nbins == 1){
	Lxf[0] = new TLatex (-2.8, .08, " 0.2 < x_{F} < 0.7");
      }
      else{
	Lxf[0] = new TLatex (-2.8, .08, "0.2 < x_{F} < 0.3");
	Lxf[1] = new TLatex (-2.8, .08, "0.3 < x_{F} < 0.4");
	Lxf[2] = new TLatex (-2.8, .08, "0.4 < x_{F} < 0.5");
	Lxf[3] = new TLatex (-2.8, .08, "0.5 < x_{F} < 0.6");
	Lxf[4] = new TLatex (-2.8, .16, "0.6 < x_{F} < 0.7");
      }
    }

    //    for (int k = 0; k < 3, k++){Lxf[k] -> SetTextSize (0.07);}
    TLine *phi_zero1 = new TLine (-PI, 0., 0., 0.);
    TLine *phi_zero2 = new TLine (-PI, 0., PI, 0.);

    TH1D *tasym1[2][nbins];
    TH1D *tasym2[2][nbins];
    TH1D *tasym3[2][nbins];
    TH1D *tasym4[2][nbins];
    TH1D *tasym5[2][nbins];

    char *asymsNameText = "./images_xf/asym2s_roadset%d_nbins%d_target%d.gif";
    sprintf (Hname, asymsNameText, Roadset, nbins, a);

    TCanvas *Casym4 = new TCanvas ("asyms", "asyms", 600, 400*(nbins));
    Casym4 -> Divide (1, nbins);
    for (int k = 0; k < nbins; k++){
      asymF[a][k] -> SetMinimum (-0.10);
      asymF[a][k] -> SetMaximum (0.10);
      Casym4 -> cd (k + 1);

      tasym5[a][k] = (TH1D*)asymF[a][k]->Clone();
      tasym5[a][k] -> Fit ("an_cosF", "R");
      tasym5[a][k] -> Draw();
      Lxf[k] -> Draw("same");
      phi_zero2 -> Draw("same");
    }
    if(SaveOn == 1)Casym4 -> SaveAs (Hname);

    char *asymqNameText = "./images_xf/asym2q_roadset%d_nbins%d_target%d.gif";
    sprintf (Hname, asymqNameText, Roadset, nbins, a);

    TCanvas *Casym5 = new TCanvas ("asymq", "asymq", 600, 400*(nbins));
    Casym5 -> Divide (1, nbins);
    for (int k = 0; k < nbins; k++){
      asymS[a][k] -> SetMinimum (-.10);
      asymS[a][k] -> SetMaximum ( .10);     
      
      Casym5 -> cd (k+1);
      
      tasym1[a][k] = (TH1D*)asymS[a][k]->Clone();
      tasym1[a][k] -> Fit ("an_cos", "R");
      tasym1[a][k] -> Draw();
      Lxf[k] -> Draw("same");
      phi_zero1 -> Draw("same");
    }
    if(SaveOn == 1)Casym5 -> SaveAs (Hname);
    TLine *defaultshiftblue   = new TLine (-1., PI, 1., PI);
    defaultshiftblue-> SetLineStyle (2);
    TLine *defaultshiftyellow = new TLine (-1., 0., 1., 0.);
    TLegend *Legend2 = new TLegend (.16, .65, .5, .88);
    //TLegend *Legend1 = new TLegend (.15, .7, .5, .88);
    Legend2 -> SetFillStyle (0);
    Legend2 -> SetLineColor (0);
    Legend2 -> AddEntry (xf_asymfit1[a], "#epsilon_{sqrt}:a*cos(#varphi)");
    Legend2 -> AddEntry (xf_asymfit2[a], "#epsilon_{sqrt}:a*cos(#varphi+#varphi_{0})");
    Legend2 -> AddEntry (xf_asymfit3[a], "#epsilon_{pol}:b+a*cos(#varphi)");
    Legend2 -> AddEntry (xf_asymfit4[a], "#epsilon_{pol}:b+a*cos(#varphi+#varphi_{0})");

    char *fitsNameText = "./images_xf/fitsummary_roadset%d_nbins%d_target%d.gif";
    sprintf (Hname, fitsNameText, Roadset, nbins, a);

    //printf("%s \n", Hname);
    TCanvas *Cfits = new TCanvas ("fitsummary", "fitsummary", 1000, 1000);
    Cfits -> Divide (2, 2);
    
   
    Cfits -> cd (1);
    xf_asymfit1[a] -> Draw();
    xf_asymfit2[a] -> Draw("same");
    xf_asymfit3[a] -> Draw("same");
    xf_asymfit4[a] -> Draw("same");
    Legend2 -> Draw ("same");
    zxf -> Draw();
   
    Cfits -> cd (3);
    xf_rellfit3[a] -> Draw();
    xf_rellfit4[a] -> Draw ("same");
    RLine -> Draw();

    Cfits -> cd (4);
    xf_phi0fit4[a] -> Draw();
    defaultshiftblue -> Draw("same");
    defaultshiftyellow -> Draw("same");

    Cfits -> cd (2);
    xf_phi0fit2[a] -> Draw();
    defaultshiftblue   -> Draw("same");
    defaultshiftyellow -> Draw("same");  

    //Cfits -> cd();
    if(SaveOn == 1)Cfits -> SaveAs (Hname);

    //End of Images!!!
    printf ("==================================================\n");
    printf ("Arm %s mean target relative luminosity:   %5.3f +/- %5.3f \n", inArm, avRL, erRL);
    printf ("==================================================\n\n");
    
  }  //End of Arms!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11

  //Let's get the average pt, xf
  /*
  for (int k = 0; k < nbins; k++) {
    //labels!
    float xfTitleMin, xfTitleMax;
    xfTitleMin = 0.1 * float (k) + 0.2;
    xfTitleMax = 0.1 * float (k) + 0.3;
    if(NBins == 1){xfTitleMin = 0.2, xfTitleMax = 0.7;}
      
    int kmin = xfTitleMin * 100 + 1;
    int kmax = xfTitleMax * 100 + 1;
    float meanxf;
    float rmsxf;
    float meanpt;
    float meaneta;
    for(int x = kmin; x < kmax; x++)
      for(int m = 1; m <= 140; m++){
	yxfmass3 -> SetBinContent(m, x, yxfmass -> GetBinContent(m, x));
	for(int p = 0; p < 500; p++){
	  yxfmasspt3 -> SetBinContent(m, x, p, yxfmasspt -> GetBinContent(m, x, p));
	}
	for(int p = 0; p < 300; p++){
	  yxfmasseta3 -> SetBinContent(m, x, p, yxfmasseta -> GetBinContent(m, x, p));
	}
      }     
    txf3 = yxfmass3 -> ProjectionY();
    meanxf = txf3 -> GetMean();
    txf3 -> Reset();
    yxfmass3 -> Reset();
    tpt3 = yxfmasspt3 -> ProjectionZ("tpt3");
    meanpt = tpt3 -> GetMean();
    tpt3 -> Reset();
    yxfmasspt3 -> Reset();
    c1 -> cd();
    yxfmasseta3 -> Draw();
    teta3 = yxfmasseta3 -> ProjectionZ("teta3");
    meaneta = teta3 -> GetMean();
    teta3 -> Reset();
    yxfmasseta3 -> Reset();
    cout << "k, meanxf, meanpt, meaneta " << k << " " << meanxf << " " << meanpt << " " << meaneta << endl;
    xf_mean -> SetBinContent(0.5 + (binjump + k) , meanxf);
    pt_mean -> SetBinContent(0.5 + (binjump + k) , meanpt);
    eta_mean -> SetBinContent(0.5 + (binjump + k) , meaneta);
    //exit(1);
  }
  
  //Let's get the average eta
  meaneta = yeta -> GetMean();
  cout << "The mean of pseudo-rapidity is " << meaneta << endl;
  */
  //Write out to OutFile!!
  char *outNameText = "./results_tighter/asym2_roadset%d_nbins%d_halfday%d.root";
  //char *outNameText = "./results/phicut_asym2_roadset%d_nbins%d_halfday%d.root";
  sprintf (outName, outNameText, Roadset, nbins, Seed);

  TFile *outFile = new TFile (outName, "RECREATE");
    
    //yxfmass -> Write();
    //yxfmasspt -> Write();
    //yxfmass3  -> Write();
    //yxfmasspt3  -> Write();
    xf_mean -> Write();
    pt_mean -> Write();
    eta_mean -> Write();
    yeta -> Write();

    for (int a = 0; a < 2; a++) {
      
      xf_asymfit1[a] -> Write();
      
      xf_asymfit2[a] -> Write();
      xf_phi0fit2[a] -> Write();

      xf_rellfit3[a] -> Write();
      xf_asymfit3[a] -> Write();

      xf_rellfit4[a] -> Write();
      xf_asymfit4[a] -> Write();
      xf_phi0fit4[a] -> Write();

      xf_asymfit5[a] -> Write();
 
      fit_rndf1[a] -> Write();
      fit_rndf2[a] -> Write();
      fit_rndf3[a] -> Write();
      fit_rndf4[a] -> Write();
      fit_rndf5[a] -> Write();

      xf_an5[a] -> Write();
      xf_an1[a] -> Write();
      xf_an3[a] -> Write();
      xf_an6[a] -> Write();
      xf_an7[a] -> Write();
      for (int k = 0; k < nbins; k++) {
	Yield3[a][k] -> Write();
	Hmass[a][k] -> Write();
	yphi3[a][k] -> Write();
	hphi_sub3[a][k] -> Write();
	hphi_raw3[a][k] -> Write();
	for (int j = 0; j < 2; j++){
	  Yield[a][k][j] -> Write();
	  Yield2[a][k][j] -> Write();

	  
	  //hphi_raw[a][k][j] -> Write();
	  //hphi_raw2[a][k][j] -> Write();
	  hphi_sub[a][k][j] -> Write();
	  hphi_sub2[a][k][j] -> Write();

	}

	asymP[a][k] -> Write();
	asymP2[a][k] -> Write();
	asymS[a][k] -> Write();
	asymS2[a][k] -> Write();
	asymL[a][k] -> Write();
	asymF[a][k] -> Write();
	anval1[a][k] -> Write();
	anval5[a][k] -> Write();
	for (int d = 0; d < 2; d++) { // down-up
	  yphi[a][k][d] -> Write();
	  yphi2[a][k][d] -> Write();
	}
      }
    }
    
  /*
    for (int p = 0; p < phibins; p++)
    for (int j = 0; j < 2; j++){
    hmass[p][j] -> Write();
    }
    for (int p = 0; p < 2; p++)
    for (int j = 0; j < 2; j++){
    hmass2[p][j] -> Write();
    }
    hmass3 -> Write();
    }
  */
  outFile -> Write();
  outFile -> Close();
}