void AnalyseParticles(LHEF::Reader *reader, ExRootTreeBranch *branch)
{
  const LHEF::HEPEUP &hepeup = reader->hepeup;

  Int_t particle;
  Double_t signPz, cosTheta;

  TLorentzVector momentum;

  TRootLHEFParticle *element;

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

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

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

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

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

    element->LifeTime = hepeup.VTIMUP[particle];
    element->Spin = hepeup.SPINUP[particle];
  }
}
Ejemplo n.º 2
0
int loop(TString infile="/store/group/phys_heavyions/velicanu/forest/Run2015E/ExpressPhysics/Merged/HiForestExpress_baobab.root",
	 TString outfile="/data/wangj/Data2015/Bntuple/ntB_20151130_HiForestExpress_baobab.root", Bool_t REAL=true, Bool_t isPbPb=false, Int_t startEntries=0, Bool_t skim=false, Bool_t gskim=true, Bool_t checkMatching=false)
{
  void fillTree(TVector3* bP, TVector3* bVtx, TLorentzVector* b4P, Int_t j, Int_t typesize, Double_t track_mass1, Double_t track_mass2, Bool_t REAL);
  bool signalGen(Int_t Btype, Int_t j);

  cout<<endl;
  if(REAL) cout<<"--- Processing - REAL DATA"<<endl;
  else cout<<"--- Processing - MC"<<endl;

  TString ifname;
  if(iseos) ifname = Form("root://eoscms.cern.ch//eos/cms%s",infile.Data());
  else ifname = infile;
  TFile* f = TFile::Open(ifname);
  TTree* root = (TTree*)f->Get("Bfinder/root");
  TTree* hltroot = (TTree*)f->Get("hltanalysis/HltTree");
  TTree* hiroot  = (TTree*)f->Get("hiEvtAnalyzer/HiTree");
  TFile* outf = new TFile(outfile,"recreate");
  setBBranch(root);
  setHltBranch(hltroot);
  if(isPbPb) setHiTreeBranch(hiroot);

  int ifchannel[7];
  ifchannel[0] = 1; //jpsi+Kp
  ifchannel[1] = 1; //jpsi+pi
  ifchannel[2] = 1; //jpsi+Ks(pi+,pi-)
  ifchannel[3] = 1; //jpsi+K*(K+,pi-)
  ifchannel[4] = 1; //jpsi+K*(K-,pi+)
  ifchannel[5] = 1; //jpsi+phi(K+,K-)
  ifchannel[6] = 1; //jpsi+pi pi <= psi', X(3872), Bs->J/psi f0
  
  cout<<"--- Building trees"<<endl;
  TTree* nt0 = new TTree("ntKp","");     buildBranch(nt0);
  TTree* nt1 = new TTree("ntpi","");     buildBranch(nt1);
  TTree* nt2 = new TTree("ntKs","");     buildBranch(nt2);
  TTree* nt3 = new TTree("ntKstar","");  buildBranch(nt3);
  TTree* nt5 = new TTree("ntphi","");    buildBranch(nt5);
  TTree* nt6 = new TTree("ntmix","");    buildBranch(nt6);
  TTree* ntGen = new TTree("ntGen","");  buildGenBranch(ntGen);
  TTree* ntHlt = hltroot->CloneTree(0);
  TTree* ntHi = hiroot->CloneTree(0);
  cout<<"--- Building trees finished"<<endl;

  Long64_t nentries = root->GetEntries();
  TVector3* bP = new TVector3;
  TVector3* bVtx = new TVector3;
  TLorentzVector* b4P = new TLorentzVector;
  TLorentzVector* b4Pout = new TLorentzVector;
  TLorentzVector* bGen = new TLorentzVector;
  cout<<"--- Check the number of events for two trees"<<endl;
  cout<<root->GetEntries()<<" "<<hltroot->GetEntries();
  if(isPbPb) cout<<" "<<hiroot->GetEntries();
  cout<<endl;
  cout<<"--- Processing events"<<endl;
  //nentries=1000;
  for(Int_t i=startEntries;i<nentries;i++)
    {
      root->GetEntry(i);
      hltroot->GetEntry(i);
      if(isPbPb) hiroot->GetEntry(i);
      if(i%100000==0) cout<<setw(8)<<i<<" / "<<nentries<<endl;
      if(checkMatching)
	{
	  if((Int_t)Bf_HLT_Event!=EvtInfo_EvtNo||Bf_HLT_Run!=EvtInfo_RunNo||Bf_HLT_LumiBlock!=EvtInfo_LumiNo || (isPbPb&&(Bf_HiTree_Evt!=EvtInfo_EvtNo||Bf_HiTree_Run!=EvtInfo_RunNo||Bf_HiTree_Lumi!=EvtInfo_LumiNo)))
	    {
	      cout<<"Error: not matched "<<i<<" | ";
	      cout<<"EvtNo("<<Bf_HLT_Event<<","<<EvtInfo_EvtNo<<") RunNo("<<Bf_HLT_Run<<","<<EvtInfo_RunNo<<") LumiNo("<<Bf_HLT_LumiBlock<<","<<EvtInfo_LumiNo<<") | EvtNo("<<Bf_HiTree_Evt<<","<<EvtInfo_EvtNo<<") RunNo("<<Bf_HiTree_Run<<","<<EvtInfo_RunNo<<") LumiNo("<<Bf_HiTree_Lumi<<","<<EvtInfo_LumiNo<<")"<<endl;
	      continue;
	    }
	}
      Int_t Btypesize[7]={0,0,0,0,0,0,0};
      Int_t ptflag=-1,ptMatchedflag=-1,probflag=-1,probMatchedflag=-1,tktkflag=-1,tktkMatchedflag=-1;
      Double_t pttem=0,ptMatchedtem=0,probtem=0,probMatchedtem=0,tktktem=0,tktkMatchedtem=0;
      for(Int_t t=0;t<7;t++)
	{
	  Int_t tidx = t-1;
	  if(t!=4)
	    {
	      tidx = t;
	      Bsize = 0;
	      ptflag = -1;
	      pttem = 0;
	      ptMatchedflag = -1;
	      ptMatchedtem = 0;
	      probflag = -1;
	      probtem = 0;
	      probMatchedflag = -1;
	      probMatchedtem = 0;
	      tktkflag = -1;
	      tktktem = 1000000.;
	      tktkMatchedflag = -1;
	      tktkMatchedtem = 1000000.;
	    }
	  if(ifchannel[t]==1)
	    {
	      for(int j=0;j<BInfo_size;j++)
		{
		  if(BInfo_type[j]==(t+1))
		    {
		      fillTree(bP,bVtx,b4P,j,Btypesize[tidx],tk1mass[t],tk2mass[t],REAL);
		      if(BInfo_pt[j]>pttem)
			{
			  ptflag = Btypesize[tidx];
			  pttem = BInfo_pt[j];
			}
		      if(TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j])>probtem)
			{
			  probflag = Btypesize[tidx];
			  probtem = TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j]);
			}
		      if(BInfo_type[j]>2&&BInfo_type[j]<7)
			{
			  if(TMath::Abs(BInfo_tktk_mass[j]-midmass[t])<tktktem)
			    {
			      tktkflag = Btypesize[tidx];
			      tktktem = TMath::Abs(BInfo_tktk_mass[j]-midmass[t]);
			    }
			}
		      if((!REAL&&(Bgen[Btypesize[tidx]]==23333||Bgen[Btypesize[tidx]]==41000))||REAL)//////////////////////////////
			{
			  if(BInfo_pt[j]>ptMatchedtem)
			    {
			      ptMatchedflag = Btypesize[tidx];
			      ptMatchedtem = BInfo_pt[j];
			    }
			  if(TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j])>probMatchedtem)
			    {
			      probMatchedflag = Btypesize[tidx];
			      probMatchedtem = TMath::Prob(BInfo_vtxchi2[j],BInfo_vtxdof[j]);
			    }
			  if(BInfo_type[j]>2&&BInfo_type[j]<7)
			    {
			      if(TMath::Abs(BInfo_tktk_mass[j]-midmass[t])<tktkMatchedtem)
				{
				  tktkMatchedflag = Btypesize[tidx];
				  tktkMatchedtem = TMath::Abs(BInfo_tktk_mass[j]-midmass[t]);
				}
			    }
			}
		      Btypesize[tidx]++;
		    }
		}
	      if(t!=3)
		{
		  if(ptflag>=0) Bmaxpt[ptflag] = true;
		  if(probflag>=0) Bmaxprob[probflag] = true;
		  if(tktkflag>=0) Bbesttktkmass[tktkflag] = true;
		  if(ptMatchedflag>=0) BmaxptMatched[ptMatchedflag] = true;
		  if(probMatchedflag>=0) BmaxprobMatched[probMatchedflag] = true;
		  if(tktkMatchedflag>=0) BbesttktkmassMatched[tktkMatchedflag] = true;
		}
	      if(t==0)      nt0->Fill();
	      else if(t==1) nt1->Fill();
	      else if(t==2) nt2->Fill();
	      else if(t==4) nt3->Fill();
	      else if(t==5) nt5->Fill();
	      else if(t==6) nt6->Fill();
	    }
	}

      ntHlt->Fill();
      if(isPbPb) ntHi->Fill();

      if(!REAL)
	{
	  Int_t gt=0,sigtype=0;
	  Int_t gsize=0;
	  Gsize = 0;
	  for(int j=0;j<GenInfo_size;j++)
	    {
	      if((TMath::Abs(GenInfo_pdgId[j])!=BPLUS_PDGID&&TMath::Abs(GenInfo_pdgId[j])!=BZERO_PDGID&&TMath::Abs(GenInfo_pdgId[j])!=BSUBS_PDGID) && gskim) continue;
	      Gsize = gsize+1;
	      Gpt[gsize] = GenInfo_pt[j];
	      Geta[gsize] = GenInfo_eta[j];
	      Gphi[gsize] = GenInfo_phi[j];
	      GpdgId[gsize] = GenInfo_pdgId[j];
	      bGen->SetPtEtaPhiM(GenInfo_pt[j],GenInfo_eta[j],GenInfo_phi[j],GenInfo_mass[j]);
	      Gy[gsize] = bGen->Rapidity();
	      sigtype=0;
	      for(gt=1;gt<8;gt++)
		{
		  if(signalGen(gt,j))
		    {
		      sigtype=gt;
		      break;
		    }
		}
	      GisSignal[gsize] = sigtype;
	      Gmu1pt[gsize] = -1;
	      Gmu1eta[gsize] = -20;
	      Gmu1phi[gsize] = -20;
	      Gmu1p[gsize] = -1;
	      Gmu2pt[gsize] = -1;
	      Gmu2eta[gsize] = -20;
	      Gmu2phi[gsize] = -20;
	      Gmu2p[gsize] = -1;
	      Gtk1pt[gsize] = -1;
	      Gtk1eta[gsize] = -20;
	      Gtk1phi[gsize] = -20;
	      Gtk2pt[gsize] = -1;
	      Gtk2eta[gsize] = -20;
	      Gtk2phi[gsize] = -20;
	      if(sigtype!=0)
		{
		  Gmu1pt[gsize] = GenInfo_pt[GenInfo_da1[GenInfo_da1[j]]];
		  Gmu1eta[gsize] = GenInfo_eta[GenInfo_da1[GenInfo_da1[j]]];
		  Gmu1phi[gsize] = GenInfo_phi[GenInfo_da1[GenInfo_da1[j]]];
		  Gmu1p[gsize] = Gmu1pt[gsize]*cosh(Gmu1eta[gsize]);
		  Gmu2pt[gsize] = GenInfo_pt[GenInfo_da2[GenInfo_da1[j]]];
		  Gmu2eta[gsize] = GenInfo_eta[GenInfo_da2[GenInfo_da1[j]]];
		  Gmu2phi[gsize] = GenInfo_phi[GenInfo_da2[GenInfo_da1[j]]];
		  Gmu2p[gsize] = Gmu2pt[gsize]*cosh(Gmu2eta[gsize]);
		  if(sigtype==1||sigtype==2)
		    {
		      Gtk1pt[gsize] = GenInfo_pt[GenInfo_da2[j]];
		      Gtk1eta[gsize] = GenInfo_eta[GenInfo_da2[j]];
		      Gtk1phi[gsize] = GenInfo_phi[GenInfo_da2[j]];
		    }
		  else
		    {
		      Gtk1pt[gsize] = GenInfo_pt[GenInfo_da1[GenInfo_da2[j]]];
		      Gtk1eta[gsize] = GenInfo_eta[GenInfo_da1[GenInfo_da2[j]]];
		      Gtk1phi[gsize] = GenInfo_phi[GenInfo_da1[GenInfo_da2[j]]];
		      Gtk2pt[gsize] = GenInfo_pt[GenInfo_da2[GenInfo_da2[j]]];
		      Gtk2eta[gsize] = GenInfo_eta[GenInfo_da2[GenInfo_da2[j]]];
		      Gtk2phi[gsize] = GenInfo_phi[GenInfo_da2[GenInfo_da2[j]]];
		    }
		}
	      gsize++;
	    }
	  ntGen->Fill();
	}
    }

  outf->Write();
  outf->Close();
  return 1;
}
Ejemplo n.º 3
0
void oniaEff::Loop(const char* fname, bool ispbpb, bool isPsip)
{
//   In a ROOT session, you can do:
//      root> .L oniaEff.C
//      root> oniaEff t
//      root> t.GetEntry(12); // Fill t data members with entry number 12
//      root> t.Show();       // Show values of entry 12
//      root> t.Show(16);     // Read and show values of entry 16
//      root> t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
   fChain->SetBranchStatus("*",0);  // disable all branches
   fChain->SetBranchStatus("Centrality",1);  
   fChain->SetBranchStatus("HLTriggers",1);  
   fChain->SetBranchStatus("Reco_QQ_*",1);  
   fChain->SetBranchStatus("Gen_QQ_*",1);  
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();
   TFile *f = new TFile(fname, "RECREATE");
   f->cd();

   // define the histos
   // we need 2 numerators (with and without ctau3d cut), 1 denominator. Let's make them in arrays
   TH1F *hnum_centmid = new TH1F("hnum_centmid","hnum_centmid",nbins_centmid,bins_centmid);
   TH1F *hnum_centfwd = new TH1F("hnum_centfwd","hnum_centfwd",nbins_centfwd,bins_centfwd);
   TH1F *hnum_ptmid = new TH1F("hnum_ptmid","hnum_ptmid",nbins_ptmid,bins_ptmid);
   TH1F *hnum_ptfwd = new TH1F("hnum_ptfwd","hnum_ptfwd",nbins_ptfwd,bins_ptfwd);
   TH1F *hnumcut_centmid = new TH1F("hnumcut_centmid","hnumcut_centmid",nbins_centmid,bins_centmid);
   TH1F *hnumcut_centfwd = new TH1F("hnumcut_centfwd","hnumcut_centfwd",nbins_centfwd,bins_centfwd);
   TH1F *hnumcut_ptmid = new TH1F("hnumcut_ptmid","hnumcut_ptmid",nbins_ptmid,bins_ptmid);
   TH1F *hnumcut_ptfwd = new TH1F("hnumcut_ptfwd","hnumcut_ptfwd",nbins_ptfwd,bins_ptfwd);
   TH1F *hnumptdepcut_centmid = new TH1F("hnumptdepcut_centmid","hnumptdepcut_centmid",nbins_centmid,bins_centmid);
   TH1F *hnumptdepcut_centfwd = new TH1F("hnumptdepcut_centfwd","hnumptdepcut_centfwd",nbins_centfwd,bins_centfwd);
   TH1F *hnumptdepcut_ptmid = new TH1F("hnumptdepcut_ptmid","hnumptdepcut_ptmid",nbins_ptmid,bins_ptmid);
   TH1F *hnumptdepcut_ptfwd = new TH1F("hnumptdepcut_ptfwd","hnumptdepcut_ptfwd",nbins_ptfwd,bins_ptfwd);
   TH1F *hden_centmid = new TH1F("hden_centmid","hden_centmid",nbins_centmid,bins_centmid);
   TH1F *hden_centfwd = new TH1F("hden_centfwd","hden_centfwd",nbins_centfwd,bins_centfwd);
   TH1F *hden_ptmid = new TH1F("hden_ptmid","hden_ptmid",nbins_ptmid,bins_ptmid);
   TH1F *hden_ptfwd = new TH1F("hden_ptfwd","hden_ptfwd",nbins_ptfwd,bins_ptfwd);

   // also store more finely binned histos
   TH1F *hcentfine = new TH1F("hcentfine","hcentfine",200,0,200);
   TH2F *hnum2d = new TH2F("hnum2d","hnum2d",48,0,2.4,150,0,30);
   TH2F *hden2d = new TH2F("hden2d","hden2d",48,0,2.4,150,0,30);

   //nentries = 200;
   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      // if (ientry>1000) break;

      // skip the event if Gen_QQ_size != 1 for now
      b_Gen_QQ_size->GetEntry(ientry); //read only this branch
      if (Gen_QQ_size !=1) continue;

      // apply gen acceptance cuts
      b_Gen_QQ_mupl_4mom->GetEntry(ientry); //read only this branch
      b_Gen_QQ_mumi_4mom->GetEntry(ientry); //read only this branch
      TLorentzVector *tlvgenpl = (TLorentzVector*) Gen_QQ_mupl_4mom->At(0);
      TLorentzVector *tlvgenmi = (TLorentzVector*) Gen_QQ_mumi_4mom->At(0);
      //if (!isGlobalMuonInAccept2015(tlvgenpl) || !isGlobalMuonInAccept2015(tlvgenmi)) continue;
      bool isgenok = true;
      if (!isGlobalMuonInAccept2015(tlvgenpl) || !isGlobalMuonInAccept2015(tlvgenmi)) isgenok=false;
      
      // fill denominators
      b_Gen_QQ_4mom->GetEntry(ientry); //read only this branch
      TLorentzVector *tlvgenqq = (TLorentzVector*) Gen_QQ_4mom->At(0);
      double genpt = tlvgenqq->Pt();
      b_Centrality->GetEntry(ientry); //read only this branch

      // check that the dimuon is inside the analysis bins
      bool gen_inbin = false;
      if (fabs(tlvgenqq->Rapidity())<1.6 && tlvgenqq->Pt()>6.5 && tlvgenqq->Pt()<30.) gen_inbin = true;
      if (fabs(tlvgenqq->Rapidity())>1.6 && fabs(tlvgenqq->Rapidity())<2.4 && tlvgenqq->Pt()>3. && tlvgenqq->Pt()<30.) gen_inbin = true;
      //if (!gen_inbin) continue;
      if (!gen_inbin) isgenok=false;
      
      double weight = ispbpb ? fChain->GetWeight()*findNcoll(Centrality) : 1.;
      double weight_DataMC = 0.0;
      if(fabs(tlvgenqq->Rapidity())<1.6){
	weight_DataMC = 1.659 - 0.0844*genpt + 0.0019*genpt*genpt;
	if(ispbpb && !isPsip) weight_DataMC = 1.88 - 0.120*genpt + 0.0033*genpt*genpt; 
	if(!ispbpb && isPsip) weight_DataMC = 1.059 + 0.0001*genpt - 0.0005*genpt*genpt;
	if(ispbpb && isPsip) weight_DataMC = 0.254 + 0.109*genpt - 0.0033*genpt*genpt;
	
      }
      if(fabs(tlvgenqq->Rapidity())>1.6){
	weight_DataMC = 1.155 - 0.0197*genpt;
	if(ispbpb && !isPsip) weight_DataMC = 1.168 - 0.0223*genpt;
	if(!ispbpb && isPsip) weight_DataMC = 0.814 + 0.0453*genpt - 0.0021*genpt*genpt;
	if(ispbpb && isPsip) weight_DataMC = 0.721 + 0.0507*genpt; 
	
      }
      
      //weight = weight*weight_DataMC;
      TF1 *wfunt = new TF1("wfunt","[0] + [1]*x",0.0,30.0);
      wfunt->SetParameters(1.3, -0.02); 
      //weight = weight*wfunt->Eval(genpt);
      
      hcentfine->Fill(Centrality,weight);
      hden2d->Fill(fabs(tlvgenqq->Rapidity()),genpt,weight);
      
      if(isgenok==true){
	if (fabs(tlvgenqq->Rapidity()) < 1.6) {
	  hden_centmid->Fill(Centrality/2,weight);
	  hden_ptmid->Fill(genpt,weight);
	} else if (fabs(tlvgenqq->Rapidity()) < 2.4) {
	  hden_centfwd->Fill(Centrality/2,weight);
	  hden_ptfwd->Fill(genpt,weight);
	} //else continue;
      }
      
      // is there at least one reco dimuon?
      b_Reco_QQ_size->GetEntry(ientry);
      if (Reco_QQ_size==0) continue;

      // ok, now read all other branches
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      // loop on the reconstructed dimuons to find the one matched to the gen one
      double mindr=999.;
      int ibestqq=-1;
      double tnp_weight = 1.0;
      for (int i=0; i<Reco_QQ_size; i++) {
	// acceptance
	if (!areMuonsInAcceptance2015(i)) continue;
         // sign
         if (Reco_QQ_sign[i]!=0) continue;
         // quality cuts
         if (!passQualityCuts2015(i)) continue;
         // trigger matching
         if (!isTriggerMatch(i,0)) continue; // HLT_HIL1DoubleMu0_v1
         // mass cut
         double mass = ((TLorentzVector*) Reco_QQ_4mom->At(i))->M();
         double mass0 = isPsip ? masspsip : massjpsi;
	 double massdown = isPsip ? 0.5 : 0.6;
	 double massup = isPsip ? 0.5 : 0.4;
         if (mass<(mass0-massdown) || mass>(mass0+massup)) continue;
         
	 // check that the dimuon is inside the analysis bins
         bool rec_inbin = false;
         TLorentzVector *tlvrecqq = (TLorentzVector*) Reco_QQ_4mom->At(i);
	 if (fabs(tlvrecqq->Rapidity())<1.6 && tlvrecqq->Pt()>6.5 && tlvrecqq->Pt()<30.) rec_inbin = true;
         if (fabs(tlvrecqq->Rapidity())>1.6 && fabs(tlvrecqq->Rapidity())<2.4 && tlvrecqq->Pt()>3. && tlvrecqq->Pt()<30.) rec_inbin = true;
         if (!rec_inbin) continue;
	 
	 // gen-reco matching
         TLorentzVector *tlvrecpl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(i);
         TLorentzVector *tlvrecmi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(i);
	 double dr = max(tlvrecpl->DeltaR(*tlvgenpl),tlvrecmi->DeltaR(*tlvgenmi));
         if (dr<mindr) {
	   mindr = dr;
	   ibestqq = i;
	 }

      } // Reco_QQ loop
      
      if (ibestqq<0) continue;
      
      TLorentzVector *tlvrecqq = (TLorentzVector*) Reco_QQ_4mom->At(ibestqq);
      double recopt = tlvrecqq->Pt();
      
      TLorentzVector *tlvrecpl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(ibestqq);
      TLorentzVector *tlvrecmi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(ibestqq);
      double recMuPlpt = tlvrecpl->Pt();
      double recMuPlEta = tlvrecpl->Eta();
      double recMuMipt = tlvrecmi->Pt();
      double recMuMiEta = tlvrecmi->Eta();
      
      tnp_weight = tnp_weight_sta_pbpb(recMuPlpt, recMuPlEta, 0)*tnp_weight_sta_pbpb(recMuMipt, recMuMiEta, 0)*tnp_weight_muidtrg_pbpb(recMuPlpt, recMuPlEta, 0) * tnp_weight_muidtrg_pbpb(recMuMipt, recMuMiEta, 0);
      //weight = weight*tnp_weight;
      
      // fill the numerators
      if (fabs(tlvrecqq->Rapidity()) < 1.6) {
	hnum_centmid->Fill(Centrality/2,weight);
	hnum_ptmid->Fill(genpt,weight);
      } else {
	hnum_centfwd->Fill(Centrality/2,weight);
	hnum_ptfwd->Fill(genpt,weight);
      }
      
      // apply ctau3D cut
      bool ctaucutok = false;
      if (ispbpb) {
	if (fabs(tlvrecqq->Rapidity()) < 1.6) {
	  ctaucutok = (Reco_QQ_ctau3D[ibestqq] < ctaucutmid_pbpb);
	} else {
	  ctaucutok = (Reco_QQ_ctau3D[ibestqq] < ctaucutfwd_pbpb);
	}
      } else {
	if (fabs(tlvrecqq->Rapidity()) < 1.6) {
	  ctaucutok = (Reco_QQ_ctau3D[ibestqq] < ctaucutmid_pp);
	} else {
	  ctaucutok = (Reco_QQ_ctau3D[ibestqq] < ctaucutfwd_pp);
	}
      }
      
      if (ctaucutok) {
	if (fabs(tlvrecqq->Rapidity()) < 1.6) {
	  hnumcut_centmid->Fill(Centrality/2,weight);
	  hnumcut_ptmid->Fill(genpt,weight);
	} else {
	  hnumcut_centfwd->Fill(Centrality/2,weight);
	  hnumcut_ptfwd->Fill(genpt,weight);
	}
      }
      
      bool ctauptdepcutok = ctaucut(Reco_QQ_ctau3D[ibestqq], tlvrecqq->Rapidity(), tlvrecqq->Pt(), ispbpb);
      
      if (ctauptdepcutok) {
	if (fabs(tlvrecqq->Rapidity()) < 1.6) {
	  hnumptdepcut_centmid->Fill(Centrality/2,weight);
	  hnumptdepcut_ptmid->Fill(genpt,weight);
	} else {
	  hnumptdepcut_centfwd->Fill(Centrality/2,weight);
	  hnumptdepcut_ptfwd->Fill(genpt,weight);
	}
      }
      
      hnum2d->Fill(fabs(tlvrecqq->Rapidity()),tlvrecqq->Pt(),weight);
      
   } // event loop
   
   f->Write();
   f->Close();
}
Ejemplo n.º 4
0
void test_allEvt::Loop()
{
  std::map<std::string, TH1D*> h_1d;
  std::map<std::string, TH2D*> h_2d;

  GoToHXframe = new HTransformToHelicityFrame();
  GoToCSframe = new HTransformToCS();
  
  TFile *fin_ewk_syst = new TFile("fout_invariant_mass_qed.root");
  TH1D *hvpt_ewk_syst = (TH1D*) fin_ewk_syst->Get("vpt_ewk_p8std_div_ewk_p8bad");
  TH1D *hmass_ewk_syst = (TH1D*) fin_ewk_syst->Get("ewk_p8std_div_ewk_p8bad");
  TH1D *hmass_ewk_syst_photos = (TH1D*) fin_ewk_syst->Get("ewk_p8photos_div_ewk_p8bad");
  
  // TH1D *hmass=new TH1D("hmass","hmass",150,50,200);
  // hmass->Sumw2();
  
  // TH1D *hvpt=new TH1D("hvpt","hvpt",300,0,300);
  // hvpt->Sumw2();
  
  if (fChain == 0) return;

  Long64_t nentries = fChain->GetEntriesFast();

  Long64_t nbytes = 0, nb = 0;
  // for (Long64_t jentry=0; jentry<nentries;jentry++) {
  for (Long64_t jentry=0; jentry<10e6;jentry++) {
    // for (Long64_t jentry=0; jentry<10e3;jentry++) {
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    // if (Cut(ientry) < 0) continue;
    
    if(jentry%100000==0) std::cout << "jentry= "<< jentry << "/" << nentries << std::endl;
    
    if(ZGen_PostFSR_mass>50
        && MuPosGenStatus1_pt>25
        && MuNegGenStatus1_pt>25
        && TMath::Abs(MuPosGenStatus1_eta)<2.5
        && TMath::Abs(MuNegGenStatus1_eta)<2.5
        ){
          
      muPosGen_status1.SetPtEtaPhiM(MuPosGenStatus1_pt,MuPosGenStatus1_eta,MuPosGenStatus1_phi,MuPosGenStatus1_mass);
      muNegGen_status1.SetPtEtaPhiM(MuNegGenStatus1_pt,MuNegGenStatus1_eta,MuNegGenStatus1_phi,MuNegGenStatus1_mass);
      ZGen_status1 = muPosGen_status1 + muNegGen_status1;
      // mtv = sqrt(2*ptl1*ptl2*(1d0-cos(delphi)))
      double dphi = MuPosGenStatus1_phi - MuNegGenStatus1_phi; 
      if ( dphi > TMath::Pi() ) {
        dphi -= 2.0*TMath::Pi();
      } else if ( dphi <= -TMath::Pi() ) {
        dphi += 2.0*TMath::Pi();
      }
      double ZGen_status1_mT = TMath::Sqrt(2*MuPosGenStatus1_pt*MuNegGenStatus1_pt*(1-TMath::Cos(dphi)));
      // cout << "ZGen_status1_mT= " << ZGen_status1_mT << " ZGen_status1.Mt()= " << ZGen_status1.Mt() << endl;
      
      double vpt_rew_factor = hvpt_ewk_syst->Interpolate(ZGen_status1.Pt());
      double vmass_std_rew_factor = hmass_ewk_syst->Interpolate(ZGen_status1.M());
      double vmass_photos_rew_factor = hmass_ewk_syst_photos->Interpolate(ZGen_status1.M());
          
      // hmass->Fill(ZGen_PostFSR_mass);
      common_stuff::plot1D("hmass", ZGen_PostFSR_mass, 1, h_1d, 150,50,200 );
      common_stuff::plot1D("hNegleptonpt", muNegGen_status1.Pt(), 1, h_1d, 160,25,65 );
      common_stuff::plot1D("hPosleptonpt", muPosGen_status1.Pt(), 1, h_1d, 160,25,65 );
      common_stuff::plot1D("hvpt", ZGen_status1.Pt(), 1, h_1d, 300,0,300 );
      common_stuff::plot1D("hrapidity", ZGen_status1.Rapidity(), 1, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hNegleptoneta", muNegGen_status1.Eta(), 1, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hPosleptoneta", muPosGen_status1.Eta(), 1, h_1d, 25,-2.5,2.5 );
      // common_stuff::plot1D("hmT", ZGen_status1.Mt(), 1, h_1d, 100,50,100 );
      common_stuff::plot1D("hmT", ZGen_status1_mT, 1, h_1d, 100,50,100 );
      
      common_stuff::plot1D("hmass_VpTRewTo_ewk_p8std", ZGen_PostFSR_mass, vpt_rew_factor, h_1d, 150,50,200 );
      common_stuff::plot1D("hNegleptonpt_VpTRewTo_ewk_p8std", muNegGen_status1.Pt(), vpt_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hPosleptonpt_VpTRewTo_ewk_p8std", muPosGen_status1.Pt(), vpt_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hvpt_VpTRewTo_ewk_p8std", ZGen_status1.Pt(), vpt_rew_factor, h_1d, 300,0,300 );
      common_stuff::plot1D("hrapidity_VpTRewTo_ewk_p8std", ZGen_status1.Rapidity(), vpt_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hNegleptoneta_VpTRewTo_ewk_p8std", muNegGen_status1.Eta(), vpt_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hPosleptoneta_VpTRewTo_ewk_p8std", muPosGen_status1.Eta(), vpt_rew_factor, h_1d, 25,-2.5,2.5 );
      // common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std", ZGen_status1.Mt(), vpt_rew_factor, h_1d, 100,50,100 );
      common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std", ZGen_status1_mT, vpt_rew_factor, h_1d, 100,50,100 );
      
      common_stuff::plot1D("hmass_VpTRewTo_ewk_p8std_massStd", ZGen_PostFSR_mass, vpt_rew_factor*vmass_std_rew_factor, h_1d, 150,50,200 );
      common_stuff::plot1D("hNegleptonpt_VpTRewTo_ewk_p8std_massStd", muNegGen_status1.Pt(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hPosleptonpt_VpTRewTo_ewk_p8std_massStd", muPosGen_status1.Pt(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hvpt_VpTRewTo_ewk_p8std_massStd", ZGen_status1.Pt(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 300,0,300 );
      common_stuff::plot1D("hrapidity_VpTRewTo_ewk_p8std_massStd", ZGen_status1.Rapidity(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hNegleptoneta_VpTRewTo_ewk_p8std_massStd", muNegGen_status1.Eta(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hPosleptoneta_VpTRewTo_ewk_p8std_massStd", muPosGen_status1.Eta(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 25,-2.5,2.5 );
      // common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std_massStd", ZGen_status1.Mt(), vpt_rew_factor*vmass_std_rew_factor, h_1d, 100,50,100 );
      common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std_massStd", ZGen_status1_mT, vpt_rew_factor*vmass_std_rew_factor, h_1d, 100,50,100 );
      
      common_stuff::plot1D("hmass_VpTRewTo_ewk_p8std_massPhotos", ZGen_PostFSR_mass, vpt_rew_factor*vmass_photos_rew_factor, h_1d, 150,50,200 );
      common_stuff::plot1D("hNegleptonpt_VpTRewTo_ewk_p8std_massPhotos", muNegGen_status1.Pt(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hPosleptonpt_VpTRewTo_ewk_p8std_massPhotos", muPosGen_status1.Pt(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 160,25,65 );
      common_stuff::plot1D("hvpt_VpTRewTo_ewk_p8std_massPhotos", ZGen_status1.Pt(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 300,0,300 );
      common_stuff::plot1D("hrapidity_VpTRewTo_ewk_p8std_massPhotos", ZGen_status1.Rapidity(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hNegleptoneta_VpTRewTo_ewk_p8std_massPhotos", muNegGen_status1.Eta(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 25,-2.5,2.5 );
      common_stuff::plot1D("hPosleptoneta_VpTRewTo_ewk_p8std_massPhotos", muPosGen_status1.Eta(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 25,-2.5,2.5 );
      // common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std_massPhotos", ZGen_status1.Mt(), vpt_rew_factor*vmass_photos_rew_factor, h_1d, 100,50,100 );
      common_stuff::plot1D("hmT_VpTRewTo_ewk_p8std_massPhotos", ZGen_status1_mT, vpt_rew_factor*vmass_photos_rew_factor, h_1d, 100,50,100 );
    
    }
    
    costh_HX = -1e10;     phi_HX = -1e10;
    costh_HX_gen = -1e10; phi_HX_gen = -1e10;
    costh_CS = -1e10;     phi_CS = -1e10;
    costh_CS_gen = -1e10; phi_CS_gen = -1e10;
    
    muPosGen.SetPtEtaPhiM(MuPosGen_pt,MuPosGen_eta,MuPosGen_phi,MuPosGen_mass);
    muNegGen.SetPtEtaPhiM(MuNegGen_pt,MuNegGen_eta,MuNegGen_phi,MuNegGen_mass);
    ZGen_status3 = muPosGen + muNegGen;

    ComputeHXVar(muPosGen,muNegGen,true);
    common_stuff::plot2D(Form("phi_vs_costh_HX_ptbin%d_rapbin%d",hptbins->FindBin(ZGen_status3.Pt()),hrapbins->FindBin(TMath::Abs(ZGen_status3.Rapidity()))),
                        costh_HX_gen,TMath::Abs(phi_HX_gen), 1, 
                        h_2d, 12,-1,1,12,0,TMath::Pi() );

    ComputeCSVar(muPosGen,muNegGen,true);
    common_stuff::plot2D(Form("phi_vs_costh_CS_ptbin%d_rapbin%d",hptbins->FindBin(ZGen_status3.Pt()),hrapbins->FindBin(TMath::Abs(ZGen_status3.Rapidity()))),
                        costh_CS_gen,TMath::Abs(phi_CS_gen), 1, 
                        h_2d, 12,-1,1,12,0,TMath::Pi() );
    
    ComputeAllVarPietro(muPosGen,muNegGen);
    common_stuff::plot2D(Form("phi_vs_costh_HX_pietro_ptbin%d_rapbin%d",hptbins->FindBin(ZGen_status3.Pt()),hrapbins->FindBin(TMath::Abs(ZGen_status3.Rapidity()))),
                        costh_HX,TMath::Abs(phi_HX), 1, 
                        h_2d, 12,-1,1,12,0,TMath::Pi() );
    common_stuff::plot2D(Form("phi_vs_costh_CS_pietro_ptbin%d_rapbin%d",hptbins->FindBin(ZGen_status3.Pt()),hrapbins->FindBin(TMath::Abs(ZGen_status3.Rapidity()))),
                        costh_CS,TMath::Abs(phi_CS), 1, 
                        h_2d, 12,-1,1,12,0,TMath::Pi() );
                        
    // cout 
    // << "costh_HX_gen= " << costh_HX_gen
    // << " phi_HX_gen= " << phi_HX_gen
    // << " costh_CS_gen= " << costh_CS_gen
    // << " phi_CS_gen= " << phi_CS_gen
    // << endl;
    // cout 
    // << "costh_HX= " << costh_HX
    // << " phi_HX= " << phi_HX
    // << " costh_CS= " << costh_CS
    // << " phi_CS= " << phi_CS
    // << endl;
    
  }
  
  TFile*fout = new TFile("fout_mass_allGenEvts.root","RECREATE");

  common_stuff::writeOutHistos( fout, h_1d, h_2d );

  // hmass->Write();
  fout->Write();
  fout->Close();
  
}
Ejemplo n.º 5
0
void fill(int const kf, TLorentzVector* b, double weight, TLorentzVector const& p1Mom, TLorentzVector const& p2Mom, TVector3 v00)
{
   int const centrality = floor(nCent * gRandom->Rndm());

   TVector3 const vertex = getVertex(centrality);
   // smear primary vertex
   // float const sigmaVertex = sigmaVertexCent[cent];
   // TVector3 const vertex(gRandom->Gaus(0, sigmaVertex), gRandom->Gaus(0, sigmaVertex), gRandom->Gaus(0, sigmaVertex));

   v00 += vertex;

   // smear momentum
   TLorentzVector const p1RMom = smearMom(0, p1Mom);
   TLorentzVector const p2RMom = smearMom(0, p2Mom);

   // smear position
   TVector3 const p1RPos = smearPosData(0, vertex.z(), centrality, p1RMom, v00);
   TVector3 const p2RPos = smearPosData(0, vertex.z(), centrality, p2RMom, v00);
   // TVector3 const kRPos = smearPos(kMom, kRMom, v00);
   // TVector3 const pRPos = smearPos(pMom, pRMom, v00);

   // reconstruct
   TLorentzVector const rMom = p1RMom + p2RMom;
   float const p1Dca = dca(p1Mom.Vect(), v00, vertex);
   float const p2Dca = dca(p2Mom.Vect(), v00, vertex);
   float const p1RDca = dca(p1RMom.Vect(), p1RPos, vertex);
   float const p2RDca = dca(p2RMom.Vect(), p2RPos, vertex);

   TVector3 v0;
   float const dca12 = dca1To2(p1RMom.Vect(), p1RPos, p2RMom.Vect(), p2RPos, v0);
   float const decayLength = (v0 - vertex).Mag();
   float const dcaD0ToPv = dca(rMom.Vect(), v0, vertex);
   float const cosTheta = (v0 - vertex).Unit().Dot(rMom.Vect().Unit());
   float const angle12 = p1RMom.Vect().Angle(p2RMom.Vect());

   TLorentzVector p1RMomRest = p1RMom;
   TVector3 beta;
   beta.SetMagThetaPhi(rMom.Beta(), rMom.Theta(), rMom.Phi());
   p1RMomRest.Boost(-beta);
   float const cosThetaStar = rMom.Vect().Unit().Dot(p1RMomRest.Vect().Unit());

   // save
   float arr[100];
   int iArr = 0;
   arr[iArr++] = centrality;
   arr[iArr++] = vertex.X();
   arr[iArr++] = vertex.Y();
   arr[iArr++] = vertex.Z();

   arr[iArr++] = kf;
   arr[iArr++] = b->M();
   arr[iArr++] = b->Perp();
   arr[iArr++] = b->PseudoRapidity();
   arr[iArr++] = b->Rapidity();
   arr[iArr++] = b->Phi();
   arr[iArr++] = v00.X();
   arr[iArr++] = v00.Y();
   arr[iArr++] = v00.Z();

   arr[iArr++] = rMom.M();
   arr[iArr++] = rMom.Perp();
   arr[iArr++] = rMom.PseudoRapidity();
   arr[iArr++] = rMom.Rapidity();
   arr[iArr++] = rMom.Phi();
   arr[iArr++] = v0.X();
   arr[iArr++] = v0.Y();
   arr[iArr++] = v0.Z();

   arr[iArr++] = dca12;
   arr[iArr++] = decayLength;
   arr[iArr++] = dcaD0ToPv;
   arr[iArr++] = cosTheta;
   arr[iArr++] = angle12;
   arr[iArr++] = cosThetaStar;

   arr[iArr++] = p1Mom.M();
   arr[iArr++] = p1Mom.Perp();
   arr[iArr++] = p1Mom.PseudoRapidity();
   arr[iArr++] = p1Mom.Rapidity();
   arr[iArr++] = p1Mom.Phi();
   arr[iArr++] = p1Dca;

   arr[iArr++] = p1RMom.M();
   arr[iArr++] = p1RMom.Perp();
   arr[iArr++] = p1RMom.PseudoRapidity();
   arr[iArr++] = p1RMom.Rapidity();
   arr[iArr++] = p1RMom.Phi();
   arr[iArr++] = p1RPos.X();
   arr[iArr++] = p1RPos.Y();
   arr[iArr++] = p1RPos.Z();
   arr[iArr++] = p1RDca;
   arr[iArr++] = tpcReconstructed(0,1,centrality,p1RMom);

   arr[iArr++] = p2Mom.M();
   arr[iArr++] = p2Mom.Perp();
   arr[iArr++] = p2Mom.PseudoRapidity();
   arr[iArr++] = p2Mom.Rapidity();
   arr[iArr++] = p2Mom.Phi();
   arr[iArr++] = p2Dca;

   arr[iArr++] = p2RMom.M();
   arr[iArr++] = p2RMom.Perp();
   arr[iArr++] = p2RMom.PseudoRapidity();
   arr[iArr++] = p2RMom.Rapidity();
   arr[iArr++] = p2RMom.Phi();
   arr[iArr++] = p2RPos.X();
   arr[iArr++] = p2RPos.Y();
   arr[iArr++] = p2RPos.Z();
   arr[iArr++] = p2RDca;
   arr[iArr++] = tpcReconstructed(0,-1,centrality,p2RMom);

   arr[iArr++] = matchHft(1, vertex.z(), centrality, p1RMom);
   arr[iArr++] = matchHft(0, vertex.z(), centrality, p2RMom);

   nt->Fill(arr);
}
Ejemplo n.º 6
0
void fill(int const kf, TLorentzVector* b, double const weight, TClonesArray& daughters)
{
   TLorentzVector kMom;
   TLorentzVector p1Mom;
   TLorentzVector p2Mom;

   int nTrk = daughters.GetEntriesFast();
   for (int iTrk = 0; iTrk < nTrk; ++iTrk)
   {
      TParticle* ptl0 = (TParticle*)daughters.At(iTrk);

      switch(abs(ptl0->GetPdgCode()))
      {
        case 321:
          ptl0->Momentum(kMom);
          break;
        case 211:
          if(!p1Mom.P()) ptl0->Momentum(p1Mom);
          else ptl0->Momentum(p2Mom);
          break;
        default:
          break;
      }
   }
   daughters.Clear();

   // smear and get total momentum
   TLorentzVector kRMom = smearMom(kMom,fKaonMomResolution);
   TLorentzVector p1RMom = smearMom(p1Mom,fPionMomResolution);
   TLorentzVector p2RMom = smearMom(p2Mom,fPionMomResolution);
   TLorentzVector rMom = kRMom + p1RMom + p2RMom;

   // save
   float arr[100];
   int iArr = 0;
   arr[iArr++] = kf;
   arr[iArr++] = weight;
   arr[iArr++] = b->M();
   arr[iArr++] = b->Perp();
   arr[iArr++] = b->PseudoRapidity();
   arr[iArr++] = b->Rapidity();
   arr[iArr++] = b->Phi();

   arr[iArr++] = rMom.M();
   arr[iArr++] = rMom.Perp();
   arr[iArr++] = rMom.PseudoRapidity();
   arr[iArr++] = rMom.Rapidity();
   arr[iArr++] = rMom.Phi();

   arr[iArr++] = kMom.M();
   arr[iArr++] = kMom.Perp();
   arr[iArr++] = kMom.PseudoRapidity();
   arr[iArr++] = kMom.Rapidity();
   arr[iArr++] = kMom.Phi();

   arr[iArr++] = kRMom.M();
   arr[iArr++] = kRMom.Perp();
   arr[iArr++] = kRMom.PseudoRapidity();
   arr[iArr++] = kRMom.Rapidity();
   arr[iArr++] = kRMom.Phi();

   arr[iArr++] = p1Mom.M();
   arr[iArr++] = p1Mom.Perp();
   arr[iArr++] = p1Mom.PseudoRapidity();
   arr[iArr++] = p1Mom.Rapidity();
   arr[iArr++] = p1Mom.Phi();

   arr[iArr++] = p1RMom.M();
   arr[iArr++] = p1RMom.Perp();
   arr[iArr++] = p1RMom.PseudoRapidity();
   arr[iArr++] = p1RMom.Rapidity();
   arr[iArr++] = p1RMom.Phi();

   arr[iArr++] = p2Mom.M();
   arr[iArr++] = p2Mom.Perp();
   arr[iArr++] = p2Mom.PseudoRapidity();
   arr[iArr++] = p2Mom.Rapidity();
   arr[iArr++] = p2Mom.Phi();

   arr[iArr++] = p2RMom.M();
   arr[iArr++] = p2RMom.Perp();
   arr[iArr++] = p2RMom.PseudoRapidity();
   arr[iArr++] = p2RMom.Rapidity();
   arr[iArr++] = p2RMom.Phi();
   
   nt->Fill(arr);
}
Ejemplo n.º 7
0
void RunPidGetterQAEff()
{
        
    TString PidFrameworkDir = "/lustre/nyx/cbm/users/klochkov/soft/PidFramework/";
    gSystem->Load( PidFrameworkDir + "build/libPid");  
    
    gStyle->SetOptStat(0000);

    TFile *f2 = new TFile("pid_0.root");    
    TTree *PidTree = (TTree*) f2->Get("PidTree");

    TofPidGetter *getter = new TofPidGetter();
    TBranch *PidGet = PidTree->GetBranch("TofPidGetter");
    PidGet->SetAddress(&getter);

    PidGet->GetEntry(0);
    Float_t ret[3];
        
    TProfile *hEffP  = new  TProfile ("hEffP", "", 100, 0, 10);
    TProfile *hEffPi = new  TProfile ("hEffPi", "", 100, 0, 6);
    TProfile *hEffK  = new  TProfile ("hEffK", "", 100, 0, 5);

    TProfile *hEffPSigma  = new  TProfile ("hEffPSigma", "", 100, 0, 10);
    TProfile *hEffPiSigma = new  TProfile ("hEffPiSigma", "", 100, 0, 6);
    TProfile *hEffKSigma  = new  TProfile ("hEffKSigma", "", 100, 0, 5);

    TProfile2D *hEffPtYP  = new  TProfile2D ("hEffPtYP", "", 100,   -2.5, 2.5, 100, 0, 4);
    TProfile2D *hEffPtYK  = new  TProfile2D ("hEffPtYK", "", 100,   -2.5, 2.5, 100, 0, 4);
    TProfile2D *hEffPtYPi  = new  TProfile2D ("hEffPtYPi", "", 100, -2.5, 2.5, 100, 0, 4);

    TString InTreeFileName = "/lustre/nyx/cbm/users/dblau/cbm/mc/UrQMD/AuAu/10AGeV/sis100_electron/SC_ON/2016_09_01/tree/11111.root";
    TFile *InFile = new TFile(InTreeFileName);    
    TTree *InTree = (TTree*) InFile->Get("fDataTree");
    DataTreeEvent* DTEvent;
    InTree -> SetBranchAddress("DTEvent",&DTEvent);

    int nevents = 100000;//InTree->GetEntries();
    int outputstep = 100;
    std::cout << "Entries = " << nevents << std::endl;

    for (int j=0;j<nevents;j++)
    {
        if ( (j+1) % outputstep == 0) std::cout << j+1 << "/" << nevents <<  "\r" << std::flush;
        InTree->GetEntry(j);
        
        Int_t Nmc[3] = {100,100,100};
        Int_t Ntof[3] = {0,0,0};
        Int_t PdgCode[3] = {2212, 212, 211};
        Double_t sigmas [3] = {0,0,0};
                
        for (int i=0;i<DTEvent->GetNTracks(); i++)
        {
            
            TLorentzVector v;
            
            DataTreeTrack* track = DTEvent -> GetTrack(i);
            DataTreeMCTrack* mctrack = DTEvent -> GetMCTrack(i);
            Double_t p = mctrack->GetPt() * TMath::CosH( mctrack->GetEta() );
            if (track->GetTOFHitId() < 0)
            {
                if (mctrack->GetPdgId() == 2212  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.9386);
                    hEffP->Fill ( p, 0 );
                    hEffPSigma->Fill ( p, 0 );
                    hEffPtYP -> Fill( v.Rapidity() - 1.52, v.Pt(), 0 );
                }
                
                if (mctrack->GetPdgId() == 321  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.5);
                    hEffK->Fill ( p, 0 );
                    hEffKSigma->Fill ( p,  0 ); 
                    hEffPtYK -> Fill( v.Rapidity() - 1.52, v.Pt(), 0 );
                }
                
                if (mctrack->GetPdgId() == 211  )  
                {
                    v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.14);
                    hEffPi->Fill ( p, 0 );
                    hEffPiSigma->Fill ( p,  0);  
                    hEffPtYPi -> Fill( v.Rapidity() - 1.52, v.Pt(),  0 );
                }
                continue;
            }
//             
            DataTreeTOFHit* toftrack = DTEvent -> GetTOFHit(track->GetTOFHitId());
            p = toftrack->GetP();
            Double_t m2 = toftrack->GetMass2 ();
            
            Bool_t cut = toftrack->GetBeta() > 0.1 && ( track->GetChiSq(0)/track->GetNDF(0) < 3 ) && p > 1.0 ;
            if ( !cut ) continue;
            
            getter->GetBayesProbability (m2, p, ret);
            sigmas[0] = getter->GetSigmaProton (m2, p);
            sigmas[1] = getter->GetSigmaKaon (m2, p);
            sigmas[2] = getter->GetSigmaPion (m2, p);
            
    //             std::cout << "pdg = " << mctrack->GetPdgId() << " p = " << p << " Sp = " << sigmas[0] << " Sk = " << sigmas[1]<< " Spi = " << sigmas[2] << std::endl;
            
            if (mctrack->GetPdgId() == 2212  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.9386);
                hEffP->Fill ( p, ret[0] > 0.9 );
                hEffPSigma->Fill ( p,  sigmas[0] < 3&& sigmas[1] > 2 && sigmas[2] > 2 );
                hEffPtYP -> Fill( v.Rapidity() - 1.52, v.Pt(),  ret[0] > 0.9 );
            }
            
            if (mctrack->GetPdgId() == 321  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.5);
                hEffK->Fill ( p, ret[1] > 0.9 );
                hEffKSigma->Fill ( p,  sigmas[1] < 3&& sigmas[2] > 2 && sigmas[0] > 2 ); 
                hEffPtYK -> Fill(  v.Rapidity() - 1.52, v.Pt(),  ret[1] > 0.9 );
            }
            
            if (mctrack->GetPdgId() == 211  )  
            {
                v.SetPtEtaPhiM (track->GetPt(0), track->GetEta(0), track->GetPhi(0), 0.14);
                hEffPi->Fill ( p, ret[2] > 0.9 );
                hEffPiSigma->Fill ( p, sigmas[2] < 3&& sigmas[0] > 2 && sigmas[1] > 2 );  
                hEffPtYPi -> Fill( v.Rapidity() - 1.52, v.Pt(),  ret[2] > 0.9  );
            }
        }
    }

    hEffP       -> SetMarkerStyle(21);      hEffP       -> SetMarkerColor(kRed);     hEffP       -> SetLineColor(kRed); 
    hEffPi      -> SetMarkerStyle(21);      hEffPi      -> SetMarkerColor(kRed);     hEffPi      -> SetLineColor(kRed); 
    hEffK       -> SetMarkerStyle(21);      hEffK       -> SetMarkerColor(kRed);     hEffK       -> SetLineColor(kRed); 
    hEffPSigma  -> SetMarkerStyle(22);      hEffPSigma  -> SetMarkerColor(kBlue);    hEffPSigma  -> SetLineColor(kBlue);
    hEffPiSigma -> SetMarkerStyle(22);      hEffPiSigma -> SetMarkerColor(kBlue);    hEffPiSigma -> SetLineColor(kBlue);
    hEffKSigma  -> SetMarkerStyle(22);      hEffKSigma  -> SetMarkerColor(kBlue);    hEffKSigma  -> SetLineColor(kBlue);

    hEffP->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffP->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffP->GetYaxis()->SetRangeUser(0.0, 1.);

    hEffK->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffK->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffK->GetYaxis()->SetRangeUser(0.0, 1.);

    hEffPi->GetXaxis()->SetTitle( "p, GeV/c" );
    hEffPi->GetYaxis()->SetTitle(  "Efficiency"  );    
    hEffPi->GetYaxis()->SetRangeUser(0.0, 1.);
    
    hEffPtYP->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYP->GetXaxis()->SetTitle(  "Rapidity"  );
    hEffPtYK->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYK->GetXaxis()->SetTitle(  "Rapidity"  );
    hEffPtYPi->GetYaxis()->SetTitle( "p_{T}, GeV/c" );
    hEffPtYPi->GetXaxis()->SetTitle(  "Rapidity"  );
    
    TCanvas *c1 = new TCanvas ("c1", "c1", 1400, 700);
    c1->Divide(3,1);

    c1->cd(1);
    hEffP->Draw();
    hEffPSigma->Draw("same");
    c1->cd(2);
    hEffK->Draw();
    hEffKSigma->Draw("same");
    c1->cd(3);
    hEffPi->Draw();
    hEffPiSigma->Draw("same");

//     c1->cd(4);
//     getter->GetProtonSigma()->Draw();
//     getter->GetKaonSigma()->Draw("same");
//     getter->GetPionSigma()->Draw("same");
// 
//     c1->cd(5);
//     getter->GetProtonA()->Draw();
//     getter->GetKaonA()->Draw("same");
//     getter->GetPionA()->Draw("same");
// 
//     c1->cd(6);
//     getter->GetProtonM2()->Draw();
//     getter->GetKaonM2()->Draw("same");
//     getter->GetPionM2()->Draw("same");    
    
    TCanvas *c2 = new TCanvas ("c2", "c2", 1400, 700);
    
    c2->Divide(3,1);
    c2->cd(1);
    hEffPtYP->Draw("colz");

    c2->cd(2);
    hEffPtYK->Draw("colz");
    
    c2->cd(3);
    hEffPtYPi->Draw("colz");
    
   
    c1->SaveAs("Canvas_Eff_p_all.root");
    c1->SaveAs("Canvas_Eff_p_all.C");
    c1->SaveAs("Canvas_Eff_p_all.png");
   
    c2->SaveAs("Canvas_Eff_pT_Y_all.root");
    c2->SaveAs("Canvas_Eff_pT_Y_all.C");
    c2->SaveAs("Canvas_Eff_pT_Y_all.png");
   
}
Ejemplo n.º 8
0
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D) {
    gROOT->SetStyle("Plain");
    gStyle->SetTitleBorderSize(0);

    delete gRandom;
    gRandom = new TRandom3(23101987);

    // Set some strings
    const std::string workspacename = "ws_masslifetime",
                      treename = "selectedData";

    // Get the tree from the data file
    TFile *f = TFile::Open(infilename.c_str());
    TTree *tree = (TTree*)f->Get(treename.c_str());

    // Set branch addresses in tree to be able to import tree to roofit
    TLorentzVector* chic = new TLorentzVector;
    tree->SetBranchAddress("chic",&chic);
    TLorentzVector* chic_rf = new TLorentzVector;
    tree->SetBranchAddress("chic_rf",&chic_rf);
    TLorentzVector* jpsi = new TLorentzVector;
    tree->SetBranchAddress("jpsi",&jpsi);
    double lifetime = 0;
    tree->SetBranchAddress("Jpsict",&lifetime);
    double lifetimeErr = 0;
    tree->SetBranchAddress("JpsictErr",&lifetimeErr);

    char lifetimeTitle[200];

    sprintf(lifetimeTitle,"l^{#psi} [mm]");
    if(correctCtau) sprintf(lifetimeTitle,"l^{#chi} [mm]");

    // define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
    RooRealVar* JpsiMass =
        new RooRealVar("JpsiMass", "M^{#psi} [GeV]", onia::massMin, onia::massMax);
    RooRealVar* JpsiPt =
        new RooRealVar("JpsiPt", "p^{#psi}_{T} [GeV]", 0. ,1000.);
    RooRealVar* JpsiRap =
        new RooRealVar("JpsiRap", "y^{#psi}", -2., 2.);
    RooRealVar* chicMass =
        new RooRealVar("chicMass", "M^{#chi} [GeV]", onia::chimassMin, onia::chimassMax);
    RooRealVar* chicRap =
        new RooRealVar("chicRap", "y^{#chi}", -onia::chirap, onia::chirap);
    RooRealVar* chicPt =
        new RooRealVar("chicPt", "p^{#chi}_{T} [GeV]", 0. ,100.);
    RooRealVar* Jpsict =
        new RooRealVar("Jpsict", lifetimeTitle, onia::ctVarMin, onia::ctVarMax);
    RooRealVar* JpsictErr =
        new RooRealVar("JpsictErr", Form("Error on %s",lifetimeTitle), 0.0001, 1.);

    // Set bins
    Jpsict->setBins(10000,"cache");
    JpsiMass->setBins(10000,"cache");
    JpsiPt->setBins(100);
    JpsiRap->setBins(10000,"cache");
    chicMass->setBins(10000,"cache");
    //JpsictErr->setBins(100);
    JpsictErr->setBins(10000,"cache");

    // The list of data variables
    RooArgList dataVars(*JpsiMass,*JpsiPt,*JpsiRap,*chicMass,*chicRap,*chicPt,*Jpsict,*JpsictErr);

    // construct dataset to contain events
    RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

    int entries = tree->GetEntries();
    cout << "entries " << entries << endl;

    int numEntriesTotal=0;
    int numEntriesInAnalysis=0;
    int numEntriesNotInAnalysis=0;



    /*
    	/// Read in 2011 data ctauErr-histos

    	char saveDir[200];
    	char PlotID[200];
    	char savename[200];
    	sprintf(saveDir,"/afs/hephy.at/scratch/k/knuenz/ChicPol/macros/polFit/Figures/CtauErrModel");
    	gSystem->mkdir(saveDir);
    	sprintf(PlotID,"2014May26_MoreLbins");
    	sprintf(saveDir,"%s/%s",saveDir,PlotID);
    	gSystem->mkdir(saveDir);
    	sprintf(savename,"%s/CtauErrModel_histograms.root",saveDir);

    	TFile *infile = new TFile(savename,"READ");
    	cout<<"opened file"<<endl;

    	const int nPT=5;
    	const int nRAP=2;
    	const int nL=15;

    	const double bordersPT[nPT+1] = {0., 12., 16., 20., 30., 100.};
    	const double bordersRAP[nRAP+1] = {0., 0.6, 2.};
    	const double bordersL[nL+1] = {onia::ctVarMin, -0.05, -0.03, -0.02, -0.015, -0.01, -0.005,  0., 0.005, 0.01, 0.015, 0.02, 0.03, 0.05, 0.1, onia::ctVarMax};

    	TH1D* h_ctauerr_2011[nRAP+1][nPT+1][nL+1];
    	TH1D* h_ctauerr_2012[nRAP+1][nPT+1][nL+1];

    	for(int iRAP = 0; iRAP < nRAP+1; iRAP++){
    		for(int iPT = 0; iPT < nPT+1; iPT++){
    			for(int iL = 0; iL < nL+1; iL++){

    				h_ctauerr_2011[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2011_rap%d_pt%d_l%d",iRAP, iPT, iL));
    				h_ctauerr_2012[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2012_rap%d_pt%d_l%d",iRAP, iPT, iL));

    			}
    		}
    	}
    	cout<<"opened hists"<<endl;

    	/// Finished reading in 2011 data ctauErr-histos
    */


    // loop through events in tree and save them to dataset
    for (int ientries = 0; ientries < entries; ientries++) {
        numEntriesTotal++;
        if (ientries%10000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

        tree->GetEntry(ientries);

        double M_jpsi =jpsi->M();
        double pt_jpsi =jpsi->Pt();
        double y_jpsi =jpsi->Rapidity();
        double M =chic_rf->M();
        //double M =chic->M()-jpsi->M()+onia::MpsiPDG;
        double y=chic->Rapidity();
        double pt=chic->Pt();

        //if (ientries%3==0){
        //	M_jpsi = gRandom->Uniform(JpsiMass->getMin(), JpsiMass->getMax());
        //}


        //double JpsictErrRand = h_JpsictErr->GetRandom();
        //double JpsictErrRand2 = h_JpsictErr->GetRandom();
        //double JpsictMeanRand=0.;
        ////double pTcorrection=(pt-20.)*0.002;
        //
        ////JpsictErrRand-=pTcorrection;
        //if(JpsictErrRand<0) JpsictErrRand=0.001;
        ////JpsictErrRand2-=pTcorrection;
        //if(JpsictErrRand2<0) JpsictErrRand2=0.001;
        //
        //if (ientries%1000000==0){
        //	double exponent=0.4;
        //	JpsictMeanRand=gRandom->Exp(exponent);
        //}
        //
        //
        //lifetime = gRandom->Gaus(JpsictMeanRand,0.8*JpsictErrRand);
        //lifetimeErr = JpsictErrRand2;
        //if (ientries%3==0){
        //	lifetime = gRandom->Gaus(JpsictMeanRand,1.5*JpsictErrRand);
        //}
        //

        //double resCorrFactor=1.08;
        //if(lifetime<0)
        //	lifetimeErr/=resCorrFactor;


        /*
        		int iRAPindex=0;
        		int iPTindex=0;
        		int iLindex=0;

        		for(int iRAP = 1; iRAP < nRAP+1; iRAP++){
        			for(int iPT = 1; iPT < nPT+1; iPT++){
        				for(int iL = 1; iL < nL+1; iL++){

        					Double_t ptMin = bordersPT[iPT-1];;
        					Double_t ptMax = bordersPT[iPT];;
        					Double_t rapMin = bordersRAP[iRAP-1];;
        					Double_t rapMax = bordersRAP[iRAP];  ;
        					Double_t lMin = bordersL[iL-1];;
        					Double_t lMax = bordersL[iL];  ;

        					if(pt_jpsi>ptMin && pt_jpsi<ptMax && TMath::Abs(y_jpsi)>rapMin && TMath::Abs(y_jpsi)<rapMax && lifetime>lMin && lifetime<lMax){
        						iRAPindex=iRAP;
        						iPTindex=iPT;
        						iLindex=iL;
        					}

        				}

        			}
        		}

        		double lifetimeErrRand = h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetRandom();

        		lifetimeErr = lifetimeErrRand;
        		if (ientries%10000==0){
        			std::cout << "Test output: lifetimeErr " << lifetimeErr << " randomly drawn from from " << h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetName() <<  std::endl;
        		}

        */

        if (
            M > chicMass->getMin() && M < chicMass->getMax()
            && pt > chicPt->getMin() && pt < chicPt->getMax()
            && y > chicRap->getMin() && y < chicRap->getMax()
            && M_jpsi > JpsiMass->getMin() && M_jpsi < JpsiMass->getMax()
            && pt_jpsi > JpsiPt->getMin() && pt_jpsi < JpsiPt->getMax()
            && y_jpsi > JpsiRap->getMin() && y_jpsi < JpsiRap->getMax()
            && lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
            && lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
        ) {

            chicPt      ->setVal(pt);
            chicRap     ->setVal(y);
            chicMass    ->setVal(M);
            JpsiMass    ->setVal(M_jpsi);
            JpsiPt    	->setVal(pt_jpsi);
            JpsiRap     ->setVal(y_jpsi);
            Jpsict      ->setVal(lifetime);
            JpsictErr   ->setVal(lifetimeErr);

            //cout<<"JpsiRap->getVal() "<<JpsiRap->getVal()<<endl;

            fullData->add(dataVars);
            numEntriesInAnalysis++;
        }
        else {
            numEntriesNotInAnalysis++;
            //if (M < chicMass->getMin() || M > chicMass->getMax()) cout << "M " << M << endl;
            //if (pt < chicPt->getMin() || pt > chicPt->getMax()) cout << "pt " << pt << endl;
            //if (y < chicRap->getMin() || y > chicRap->getMax()) cout << "y " << y << endl;
            //if (lifetime < Jpsict->getMin() || lifetime > Jpsict->getMax()) cout << "lifetime " << lifetime << endl;
            //if (lifetimeErr < JpsictErr->getMin() || lifetimeErr > JpsictErr->getMax()) cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << "M " << M << endl;
            //cout << "pt " << pt << endl;
            //cout << "y " << y << endl;
            //cout << "lifetime " << lifetime << endl;
            //cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << " " << endl;

        }

    }//ientries

    //infile->Close();

    cout << "entries entering all bins " << fullData->sumEntries() << endl;
    cout << "numEntriesTotal " << numEntriesTotal << endl;
    cout << "numEntriesInAnalysis " << numEntriesInAnalysis << endl;
    cout << "numEntriesNotInAnalysis " << numEntriesNotInAnalysis << endl;

    //------------------------------------------------------------------------------------------------------------------
    // Define workspace and import datasets

    ////Get datasets binned in pT an y

    for(int iRap = 0; iRap <= onia::kNbRapForPTBins; iRap++) {

        Double_t yMin;
        Double_t yMax;
        if(iRap==0) {
            yMin = onia::rapForPTRange[0];
            yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
        } else {
            yMin = onia::rapForPTRange[iRap-1];
            yMax = onia::rapForPTRange[iRap];
        }

        for(int iPT = 0; iPT <= onia::kNbPTBins[iRap]; iPT++) {
            //for(int iPT = 0; iPT <= 0; iPT++)

            Double_t ptMin;
            Double_t ptMax;
            if(iPT==0) {
                ptMin = onia::pTRange[iRap][0];
                ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
            } else {
                ptMin = onia::pTRange[iRap][iPT-1];
                ptMax = onia::pTRange[iRap][iPT];
            }

            // output file name and workspace
            std::stringstream outfilename;
            outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap" << iRap << "_pt" << iPT << ".root";
            RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

            // define pt and y cuts on dataset
            std::stringstream cutString;

            if(onia::KinParticleChi && !onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(chicRap) >= " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
            }
            if(!onia::KinParticleChi) {
                cutString << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }
            if(onia::KinParticleChi && onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }


            cout << "cutString: " << cutString.str().c_str() << endl;

            // get the dataset for the fit
            RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
            std::stringstream name;
            name << "jpsi_data_rap" << iRap << "_pt" << iPT;
            binData->SetNameTitle(name.str().c_str(), "Data For Fitting");

            cout << "numEvents = " << binData->sumEntries() << endl;

            double chicMeanPt = binData->mean(*chicPt);
            RooRealVar var_chicMeanPt("var_chicMeanPt","var_chicMeanPt",chicMeanPt);
            if(!ws->var("var_chicMeanPt")) ws->import(var_chicMeanPt);
            else ws->var("var_chicMeanPt")->setVal(chicMeanPt);
            cout << "chicMeanPt = " << chicMeanPt << endl;

            double jpsiMeanPt = binData->mean(*JpsiPt);
            RooRealVar var_jpsiMeanPt("var_jpsiMeanPt","var_jpsiMeanPt",jpsiMeanPt);
            if(!ws->var("var_jpsiMeanPt")) ws->import(var_jpsiMeanPt);
            else ws->var("var_jpsiMeanPt")->setVal(jpsiMeanPt);
            cout << "jpsiMeanPt = " << jpsiMeanPt << endl;

            std::stringstream cutStringPosRapChic;
            cutStringPosRapChic << "chicRap > 0";
            RooDataSet* binDataPosRapChic = (RooDataSet*)binData->reduce(cutStringPosRapChic.str().c_str());
            double chicMeanAbsRap = binDataPosRapChic->mean(*chicRap);
            cout << "chicMeanAbsRap = " << chicMeanAbsRap << endl;
            RooRealVar var_chicMeanAbsRap("var_chicMeanAbsRap","var_chicMeanAbsRap",chicMeanAbsRap);
            if(!ws->var("var_chicMeanAbsRap")) ws->import(var_chicMeanAbsRap);
            else ws->var("var_chicMeanAbsRap")->setVal(chicMeanAbsRap);

            std::stringstream cutStringPosRapJpsi;
            cutStringPosRapJpsi << "JpsiRap > 0";
            RooDataSet* binDataPosRapJpsi = (RooDataSet*)binData->reduce(cutStringPosRapJpsi.str().c_str());
            double jpsiMeanAbsRap = binDataPosRapJpsi->mean(*JpsiRap);
            cout << "jpsiMeanAbsRap = " << jpsiMeanAbsRap << endl;
            RooRealVar var_jpsiMeanAbsRap("var_jpsiMeanAbsRap","var_jpsiMeanAbsRap",jpsiMeanAbsRap);
            if(!ws->var("var_jpsiMeanAbsRap")) ws->import(var_jpsiMeanAbsRap);
            else ws->var("var_jpsiMeanAbsRap")->setVal(jpsiMeanAbsRap);

            // Import variables to workspace
            ws->import(*binData);
            ws->writeToFile(outfilename.str().c_str());
        }//iPT
    }//iRap

    ////---------------------------------------------------------------
    ////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
    ////---------------------------------------------------------------
    if(drawRapPt2D) {
        double yMin = onia::rapForPTRange[0];
        double yMax = 1.6;//onia::rapForPTRange[onia::kNbRapForPTBins];
        double ptMin =  onia::pTRange[0][0];
        double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];

        std::stringstream cutRapPt;
        cutRapPt << "(chicPt > " << ptMin << " && chicPt < "<< ptMax << ") && "
                 << "(TMath::Abs(chicRap) > " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
        cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

        RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
        std::stringstream nameRapPt;
        nameRapPt << "data_rap0_pt0";
        rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

        // output file name and workspace
        std::stringstream outfilename;
        outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap0_pt0.root";
        RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
        //Import variables to workspace
        ws_RapPt->import(*rapPtData);
        ws_RapPt->writeToFile(outfilename.str().c_str());

        TH2D* rapPt;
        TH1D* rap1p2;
        double MassMin;
        double MassMax;

        rap1p2 = new TH1D("rap1p2","rap1p2",30,1.2, 1.8);
        if(nState==4) {
            rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
            MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
            MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
            // sigma  27.2 MeV
            // mean 3.093 GeV
        }
        if(nState==5) {
            rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
            //rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
            MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
            MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
            // sigma 34.9 MeV // pT > 7
            // sigma 34.3 MeV // pT > 10
            // mean 3.681 GeV
        }

        cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
        cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
        cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

        TTree *rapPtTree = (TTree*)rapPtData->tree();
        std::stringstream cutMass;
        cutMass<<"(chicMass > " << MassMin << " && chicMass < "<< MassMax << ")";
        //following two methods can only be used in root_v30, 34 does not work
        rapPtTree->Draw("chicPt:chicRap>>rapPt",cutMass.str().c_str(),"colz");
        cout<<"debug"<<endl;
        rapPtTree->Draw("TMath::Abs(chicRap)>>rap1p2",cutMass.str().c_str());

        TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
        rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
        rapPt->SetXTitle("y(#mu#mu)");
        gStyle->SetPalette(1);
        gPad->SetFillColor(kWhite);
        rapPt->SetTitle(0);
        rapPt->SetStats(0);
        gPad->SetLeftMargin(0.15);
        gPad->SetRightMargin(0.17);
        rapPt->GetYaxis()->SetTitleOffset(1.5);

        rapPt->Draw("colz");

        TLine* rapPtLine;

        for(int iRap=0; iRap<onia::kNbRapForPTBins+1; iRap++) {
            rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();
            rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();

            int pTBegin = 0;
            if(nState==5) pTBegin = 1;
            for(int iPt=pTBegin; iPt<onia::kNbPTBins[iRap+1]+1; iPt++) {
                rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
                rapPtLine->SetLineWidth( 2 );
                rapPtLine->SetLineStyle( 1 );
                rapPtLine->SetLineColor( kWhite );
                rapPtLine->Draw();
            }
        }

        char savename[200];
        sprintf(savename,"Figures/rapPt_Chi.pdf");
        c2->SaveAs(savename);

        TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
        rap1p2->SetYTitle("Events");
        rap1p2->SetXTitle("y(#mu#mu)");
        rap1p2->SetTitle(0);
        rap1p2->SetStats(0);
        rap1p2->GetYaxis()->SetTitleOffset(1.2);
        rap1p2->Draw();
        sprintf(savename,"Figures/rap_Chi_1p2.pdf");
        c3->SaveAs(savename);
    }

    f->Close();
}
Ejemplo n.º 9
0
void loopNonpromptBzero(string infile="/mnt/hadoop/cms/store/user/jwang/Bfinder_BoostedMC_20140418_Hijing_PPb502_MinimumBias_HIJINGemb_inclBtoPsiMuMu_5TeV.root", string outfile="../../output/myoutputBzero.root", bool REAL=0){
//////////////////////////////////////////////////////////Phi
//   This file has been automatically generated 
//     (Thu Nov 21 13:34:42 2013 by ROOT version5.27/06b)
//   from TTree root/root
//   found on file: merged_pPbData_20131114.root
//////////////////////////////////////////////////////////

  const char* infname;
  const char* outfname;

  if(REAL) cout<<"--- REAL DATA ---"<<endl;
  else cout<<"--- MC ---"<<endl;


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

  //File type
  TFile *f = new TFile(infname);
  TTree *root = (TTree*)f->Get("demo/root");
  TTree *hlt = (TTree*)f->Get("hltanalysis/HltTree");
  if (root->GetEntries()!=hlt->GetEntries()) {
     cout <<"Inconsistent number of entries!!!"<<endl;
     cout <<"HLT tree: "<<hlt->GetEntries()<<endl;
     cout <<"Bfinder tree: "<<root->GetEntries()<<endl;
  }
  
  //Chain type
  //TChain* root = new TChain("demo/root");
  //root->Add("/mnt/hadoop/cms/store/user/wangj/HI_Btuple/20140213_PAMuon_HIRun2013_PromptReco_v1/Bfinder_all_100_1_dXJ.root");
  //root->Add("/mnt/hadoop/cms/store/user/wangj/HI_Btuple/20140213_PAMuon_HIRun2013_PromptReco_v1/Bfinder_all_101_1_kuy.root");
  //root->Add("/mnt/hadoop/cms/store/user/wangj/HI_Btuple/20140213_PAMuon_HIRun2013_PromptReco_v1/Bfinder_all_10_1_ZkX.root");
  //root->Add("/mnt/hadoop/cms/store/user/wangj/HI_Btuple/20140213_PAMuon_HIRun2013_PromptReco_v1/Bfinder_all_102_1_NyI.root");
  
  TFile *outf = new TFile(outfname,"recreate");

  setBranch(root);
  setHltBranch(hlt);
    
  int ifchannel[7];
  ifchannel[0] = 1; //jpsi+Kp
  ifchannel[1] = 1; //jpsi+pi
  ifchannel[2] = 1; //jpsi+Ks(pi+,pi-)
  ifchannel[3] = 1; //jpsi+K*(K+,pi-)
  ifchannel[4] = 1; //jpsi+K*(K-,pi+)
  ifchannel[5] = 1; //jpsi+phi
  ifchannel[6] = 1; //jpsi+pi pi <= psi', X(3872), Bs->J/psi f0
  
  TTree* nt0 = new TTree("ntKp","");
  buildBranch(nt0);
  TTree* nt1 = new TTree("ntpi","");
  buildBranch(nt1);
  TTree* nt2 = new TTree("ntKs","");
  buildBranch(nt2);
  TTree* nt3 = new TTree("ntKstar","");
  buildBranch(nt3);
  TTree* nt5 = new TTree("ntphi","");
  buildBranch(nt5);
  TTree* nt6 = new TTree("ntmix","");
  buildBranch(nt6);  
  TTree* ntGen = new TTree("ntGen","");
  buildGenBranch(ntGen);

  cout<<"--- Tree building finished ---"<<endl;
  
  Long64_t nentries = root->GetEntries();
  nentries = 100000;
  Long64_t nbytes = 0;  
  TVector3* bP = new TVector3;
  TVector3* bVtx = new TVector3;
  TLorentzVector* b4P = new TLorentzVector;
  TLorentzVector* b4Pout = new TLorentzVector;
  TLorentzVector bGen;
  int type,flag;
  int flagEvt=0;  
  int offsetHltTree=0;

  int testevent=0,testcand=0;
  
  for (Long64_t i=0; i<nentries;i++) {
    nbytes += root->GetEntry(i);
    flagEvt=0;
    while (flagEvt==0)
    {
       hlt->GetEntry(i+offsetHltTree);
       //cout <<offsetHltTree<<" "<<Bfr_HLT_Event<<" "<<EvtInfo_EvtNo<<endl;
       if (Bfr_HLT_Event==EvtInfo_EvtNo && Bfr_HLT_Run==EvtInfo_RunNo) flagEvt=1; else offsetHltTree++;
    } 

    if (i%10000==0) cout <<i<<" / "<<nentries<<"   offset HLT:"<<offsetHltTree<<endl;

    int type1size=0,type2size=0,type3size=0,type4size=0,type5size=0,type6size=0,type7size=0;
    float best,best2,temy;
    int bestindex,best2index;

    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==1)
	  {
	    //if(TrackInfo_pt[BInfo_rftk1_index[j]]<0.9) continue;
	    fillTree(bP,bVtx,b4P,j,type1size,KAON_MASS,0,REAL);
	    if(chi2cl[type1size]>best)
	      {
		best = chi2cl[type1size];
		bestindex = type1size;
	      }
	    type1size++;
	  }
      }
    if(size>0)
    {
      bestchi2 = bestindex;
      isbestchi2[bestindex] = 1;
    }
    nt0->Fill();

    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==2)
	  {
	    fillTree(bP,bVtx,b4P,j,type2size,PION_MASS,0,REAL);
	    if(chi2cl[type2size]>best)
	      {
		best = chi2cl[type2size];
		bestindex = type2size;
	      }
	    type2size++;
	  }
      }
    if(size>0)
      {
	bestchi2 = bestindex;
	isbestchi2[bestindex] = 1;
      }
    nt1->Fill();
    
    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==3)
	  {
	    fillTree(bP,bVtx,b4P,j,type3size,PION_MASS,PION_MASS,REAL);
	    if(chi2cl[type3size]>best)
	      {
		best = chi2cl[type3size];
		bestindex = type3size;
	      }
	    if(abs(tktkmass[type3size]-KSHORT_MASS)<best2)
	      {
		best2 = abs(tktkmass[type3size]-KSHORT_MASS);
		best2index = type3size;
	      }
	    type3size++;
	  }
      }
    if(size>0)
      {
	bestchi2 = bestindex;
	isbestchi2[bestindex] = 1;
	besttktkmass = best2index;
	isbesttktkmass[best2index] = 1;
      }
    nt2->Fill();
    
    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==4 || BInfo_type[j]==5)
	  {
	    fillTree(bP,bVtx,b4P,j,type4size,KAON_MASS,PION_MASS,REAL);
	    if(chi2cl[type4size]>best)
	      {
		best = chi2cl[type4size];
		bestindex = type4size;
	      }
	    if(abs(tktkmass[type4size]-KSTAR_MASS)<best2)
	      {
		best2 = abs(tktkmass[type4size]-KSTAR_MASS);
		best2index = type4size;
	      }
	    type4size++;
	  }
      }
    if(size>0)
      {
	bestchi2 = bestindex;
	isbestchi2[bestindex] = 1;
	besttktkmass = best2index;
	isbesttktkmass[best2index] = 1;
      }
    nt3->Fill();
    
    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==6)
	  {
	    //if(TrackInfo_pt[BInfo_rftk1_index[j]]<0.7) continue;
	    //if(TrackInfo_pt[BInfo_rftk2_index[j]]<0.7) continue;
	    fillTree(bP,bVtx,b4P,j,type6size,KAON_MASS,KAON_MASS,REAL);
	    if(chi2cl[type6size]>best)
	      {
		best = chi2cl[type6size];
		bestindex = type6size;
	      }
	    if(abs(tktkmass[type6size]-PHI_MASS)<best2)
	      {
		best2 = abs(tktkmass[type6size]-PHI_MASS);
		best2index = type6size;
	      }
	    type6size++;
	  }
      }
    if(size>0)
      {
	bestchi2 = bestindex;
	isbestchi2[bestindex] = 1;
	besttktkmass = best2index;
	isbesttktkmass[best2index] = 1;
      }
    nt5->Fill();
    
    size=0;
    best=-1;
    bestindex=-1;
    best2=10000.;
    best2index=-1;
    for (int j=0;j<BInfo_size;j++) 
      {
	if(BInfo_type[j]>7) continue;
	if (ifchannel[BInfo_type[j]-1]!=1) continue;
	//skim{{{
	b4Pout->SetXYZM(BInfo_px[j],BInfo_py[j],BInfo_pz[j],BInfo_mass[j]);
	temy = b4Pout->Rapidity();
	if(REAL)
	  {
	    if(!(((EvtInfo_RunNo>=210498&&EvtInfo_RunNo<=211256&&abs(temy+0.465)<1.93)||(EvtInfo_RunNo>=211313&&EvtInfo_RunNo<=211631&&abs(temy-0.465)<1.93)))) continue;
	  }
	else
	  {
	    if(abs(temy+0.465)>=1.93) continue;
	  }
	if(BInfo_mass[j]<5 || BInfo_mass[j]>6) continue;
	if(BInfo_pt[j]<10.) continue;
	//}}}
	if(BInfo_type[j]==7)
	  {
	    fillTree(bP,bVtx,b4P,j,type7size,PION_MASS,PION_MASS,REAL);
	    if(chi2cl[type7size]>best)
	      {
		best = chi2cl[type7size];
		bestindex = type7size;
	      }
	    type7size++;
	  }
      }
    if(size>0)
      {
	bestchi2 = bestindex;
	isbestchi2[bestindex] = 1;
      }
    nt6->Fill();
    
    if(!REAL)
      {
	Gensize = 0;
	for (int j=0;j<GenInfo_size;j++)
	  {
	    bGen.SetPtEtaPhiM(GenInfo_pt[j],GenInfo_eta[j],GenInfo_phi[j],GenInfo_mass[j]);
	    flag=0;
	    for(type=1;type<8;type++)
	      {
		if (signalGen(type,j)) {
                  flag=type;
		  break;
                }
	      }
	    Genmu1pt[j] = -1;
	    Genmu1eta[j] = -20;
	    Genmu1phi[j] = -20;
	    Genmu1p[j] = -1;
	    Genmu2pt[j] = -1;
	    Genmu2eta[j] = -20;
	    Genmu2phi[j] = -20;
	    Genmu2p[j] = -1;
	    Gentk1pt[j] = -1;
	    Gentk1eta[j] = -20;
	    Gentk1phi[j] = -20;
	    Gentk2pt[j] = -1;
	    Gentk2eta[j] = -20;
	    Gentk2phi[j] = -20;

            if(flag!=0)
              {
                Genmu1pt[j] = GenInfo_pt[GenInfo_da1[GenInfo_da1[j]]];
                Genmu1eta[j] = GenInfo_eta[GenInfo_da1[GenInfo_da1[j]]];
                Genmu1phi[j] = GenInfo_phi[GenInfo_da1[GenInfo_da1[j]]];
                Genmu1p[j] = Genmu1pt[j]*cosh(Genmu1eta[j]);
                Genmu2pt[j] = GenInfo_pt[GenInfo_da2[GenInfo_da1[j]]];
                Genmu2eta[j] = GenInfo_eta[GenInfo_da2[GenInfo_da1[j]]];
		Genmu2phi[j] = GenInfo_phi[GenInfo_da2[GenInfo_da1[j]]];
                Genmu2p[j] = Genmu2pt[j]*cosh(Genmu2eta[j]);
		if(flag==1||flag==2)
		  {
		    Gentk1pt[j] = GenInfo_pt[GenInfo_da2[j]];
		    Gentk1eta[j] = GenInfo_eta[GenInfo_da2[j]];
		    Gentk1phi[j] = GenInfo_phi[GenInfo_da2[j]];
		  }
		else
		  {
		    Gentk1pt[j] = GenInfo_pt[GenInfo_da1[GenInfo_da2[j]]];
		    Gentk1eta[j] = GenInfo_eta[GenInfo_da1[GenInfo_da2[j]]];
		    Gentk1phi[j] = GenInfo_phi[GenInfo_da1[GenInfo_da2[j]]];
		    Gentk2pt[j] = GenInfo_pt[GenInfo_da2[GenInfo_da2[j]]];
		    Gentk2eta[j] = GenInfo_eta[GenInfo_da2[GenInfo_da2[j]]];
		    Gentk2phi[j] = GenInfo_phi[GenInfo_da2[GenInfo_da2[j]]];
		  }
              }
	    Gensize = GenInfo_size;
	    Geny[j] = bGen.Rapidity();
	    Geneta[j] = bGen.Eta();
	    Genphi[j] = bGen.Phi();
	    Genpt[j] = bGen.Pt();
	    GenpdgId[j] = GenInfo_pdgId[j];
	    GenisSignal[j] = flag;
	  }
	ntGen->Fill();
      }
  }

  outf->Write();
  outf->Close();
}
Ejemplo n.º 10
0
void analyzer (TString inputFileName,TString outputFileName, TString runPeriod, bool isData, bool isSignal, unsigned maxEvents)
{
  using namespace std;

  ///////////////////
  // Configuration

  float minMmm = 110;
  float maxMmm = 160;

  //gErrorIgnoreLevel = kError;
  const unsigned ISMEAR = 2;

  ///////////////////////////
  // Output Histograms

  setStyle();

  TH1F* dimuonMassHist = new TH1F("dimuonMass","",50,110,160);
  setHistTitles(dimuonMassHist,"M(#mu#mu) [GeV/c^{2}]","Events");
  dimuonMassHist->Sumw2();
  TH1F* nJetsHist = new TH1F("nJets","",10,0,10);
  setHistTitles(nJetsHist,"N_{Jets}","Events");
  nJetsHist->Sumw2();

  ///////////////////////////
  Double_t MASS_MUON = 0.105658367;    //GeV/c2

  //////////////////////////
  // Tree Branches
  cout << "Analyzing filename: "<< inputFileName.Data() << endl;
  if (isData)
    cout << "isData\n";
  if (isSignal)
    cout << "isSignal\n";

  TChain * tree = new TChain("tree");
  tree->Add(inputFileName);


  // These are the names of the muons (See src/DataFormats.h for definitions!)
  _MuonInfo reco1, reco2;

  tree->SetBranchAddress("reco1", &reco1);
  tree->SetBranchAddress("reco2", &reco2);

  // These are the dimuon mass, pt, rapidity, and phi
  float recoCandMass, recoCandPt, recoCandY, recoCandPhi;
  float recoCandMassRes, recoCandMassResCov;

  tree->SetBranchAddress("recoCandMass",       &recoCandMass);
  tree->SetBranchAddress("recoCandPt",         &recoCandPt);
  tree->SetBranchAddress("recoCandY",          &recoCandY);
  tree->SetBranchAddress("recoCandPhi",        &recoCandPhi);
  tree->SetBranchAddress("recoCandMassRes",    &recoCandMassRes);
  tree->SetBranchAddress("recoCandMassResCov", &recoCandMassResCov);

  // MC truth info
  float trueMass=-99999.0;
  if(!isData && tree->GetBranchStatus("trueMass"))
    tree->SetBranchAddress("trueMass", &trueMass);

  /// Higgs Boson MC truth info (after FSR)
  _genPartInfo genHpostFSR;
  if(!isData && tree->GetBranchStatus("genHpostFSR"))
    tree->SetBranchAddress("genHpostFSR", &genHpostFSR);

  _TrackInfo reco1GenPostFSR;
  if(!isData && tree->GetBranchStatus("genM1HpostFSR"))
    tree->SetBranchAddress("genM1HpostFSR", &reco1GenPostFSR);

  _TrackInfo reco2GenPostFSR;
  if(!isData && tree->GetBranchStatus("genM2HpostFSR"))
    tree->SetBranchAddress("genM2HpostFSR", &reco2GenPostFSR);

  /// the jet collection
  // these 'rawJets' already have Loose Jet ID applied, and JES corrections
  // and are cross-cleaned of tight muons
  // later, jets will have JER corrections, PUID, and basic cuts applied
  _PFJetInfo rawJets;
  tree->SetBranchAddress("pfJets",&rawJets);

  float puJetFullDisc[10];
  float puJetSimpleDisc[10];
  float puJetCutDisc[10];

  tree->SetBranchAddress("puJetFullDisc",&puJetFullDisc);
  tree->SetBranchAddress("puJetSimpleDisc",&puJetSimpleDisc);
  tree->SetBranchAddress("puJetCutDisc",&puJetCutDisc);

  float puJetFullId[10];
  float puJetSimpleId[10];
  float puJetCutId[10];

  tree->SetBranchAddress("puJetFullId",&puJetFullId);
  tree->SetBranchAddress("puJetSimpleId",&puJetSimpleId);
  tree->SetBranchAddress("puJetCutId",&puJetCutId);

  int nPU=0;
  if (!isData)
    {
      tree->SetBranchAddress("nPU",&nPU);
    }
  _VertexInfo vertexInfo;
  tree->SetBranchAddress("vertexInfo",&vertexInfo);
  _EventInfo eventInfo;
  tree->SetBranchAddress("eventInfo",&eventInfo);

  // Be careful, the met has not been well validated
  _MetInfo met;
  tree->SetBranchAddress("met",&met);

  //////////////////////////
  //for PU reweighting

  reweight::LumiReWeighting lumiWeights("pileupDists/PileUpHistMC2012Summer50nsPoissonOOTPU.root","pileupDists/PileUpHist2012ABCD.root","pileup","pileup");
  if (runPeriod == "7TeV")
  {
    cout << "Using 2011AB PU reweighting\n";
    lumiWeights = reweight::LumiReWeighting("pileupDists/PileUpHistMCFall11.root","pileupDists/PileUpHist2011AB.root","pileup","pileup");
  }
  else
  {
    cout << "Using 2012ABCD PU reweighting\n";
  }

  ///////////////////////////////
  // Which Muon Selection to Use

  bool (*muonIdFuncPtr)(_MuonInfo&);
  if (runPeriod == "7TeV")
    {
      cout << "Using 2011 Tight Muon Selection\n";
      muonIdFuncPtr = &isKinTight_2011_noIso;
    }
  else
    {
      cout << "Using 2012 Tight Muon Selection\n";
      muonIdFuncPtr = &isKinTight_2012_noIso;
    }

  /////////////////////////
  // Smearing
  SmearingTool *smearPT = new SmearingTool();
  SmearingTool2011 *smearPT2011 = new SmearingTool2011();

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

  unsigned nEvents = tree->GetEntries();
  unsigned reportEach=1000;
  if (nEvents/1000>reportEach)
    reportEach = nEvents/1000;

  ///////////////////////////////
  ///////////////////////////////
  ///////////////////////////////
  // Event Loop

  for(unsigned i=0; i<nEvents;i++)
  {
    if(i >= maxEvents)
      break;

    tree->GetEvent(i);
    if (i % reportEach == 0) cout << "Event: " << i << endl;

    // Reject events with invalid muons
    if (reco1.pt < 0. || reco2.pt < 0.)
        continue;

    /////////////////////////////////////////////////
    // Muon Resolution Smearing to match MuScleFit

    if(isSignal) // smear only signal because it has muons from higgs 
    {
      if(reco1GenPostFSR.pt<0.)
        cout << "Muon 1 Post FSR not valid!\n";
      if(reco2GenPostFSR.pt<0.)
        cout << "Muon 2 Post FSR not valid!\n";
      float ptReco1 = -1.;
      float ptReco2 = -1.;
      if(runPeriod == "7TeV")
      {
        ptReco1 = smearPT2011 -> PTsmear(reco1GenPostFSR.pt, reco1GenPostFSR.eta, reco1GenPostFSR.charge, reco1.pt, ISMEAR);
        ptReco2 = smearPT2011 -> PTsmear(reco2GenPostFSR.pt, reco2GenPostFSR.eta, reco2GenPostFSR.charge, reco2.pt, ISMEAR);
      }
      else
      {
        ptReco1 = smearPT -> PTsmear(reco1GenPostFSR.pt, reco1GenPostFSR.eta, reco1GenPostFSR.charge, reco1.pt, ISMEAR);
        ptReco2 = smearPT -> PTsmear(reco2GenPostFSR.pt, reco2GenPostFSR.eta, reco2GenPostFSR.charge, reco2.pt, ISMEAR);
      }
      TLorentzVector reco1Vec;
      TLorentzVector reco2Vec;
      reco1Vec.SetPtEtaPhiM(ptReco1,reco1.eta,reco1.phi,MASS_MUON);
      reco2Vec.SetPtEtaPhiM(ptReco2,reco2.eta,reco2.phi,MASS_MUON);
      TLorentzVector diMuonVec = reco1Vec + reco2Vec;

      reco1.pt = ptReco1;
      reco2.pt = ptReco2;
      recoCandMass = diMuonVec.M();
      recoCandPt = diMuonVec.Pt();
      recoCandY = diMuonVec.Rapidity();
      recoCandPhi = diMuonVec.Phi();
    
      reco1Vec.SetPtEtaPhiM(ptReco1,reco1.eta,reco1.phi,MASS_MUON);
      reco2Vec.SetPtEtaPhiM(ptReco2,reco2.eta,reco2.phi,MASS_MUON);
      diMuonVec = reco1Vec + reco2Vec;
    }

    //////////////////////////////////////////
    // Muon-related cuts

    if (recoCandMass > maxMmm || recoCandMass < minMmm)
        continue;

    bool muon1PassId = (*muonIdFuncPtr)(reco1);
    bool muon2PassId = (*muonIdFuncPtr)(reco2);
    if ( !(muon1PassId && muon2PassId))
        continue;

    bool muon1PassIso = (getPFRelIso(reco1) <= 0.12);
    bool muon2PassIso = (getPFRelIso(reco2) <= 0.12);
    if ( !(muon1PassIso && muon2PassIso))
        continue;

    // Order muons by pt
    if (reco1.pt < reco2.pt)
    {
      _MuonInfo tmpMuon = reco1;
      reco1 = reco2;
      reco1 = tmpMuon;
    }

    // PU reweight
    float weight = 1.;
    if (!isData)
    {
      weight *= lumiWeights.weight(nPU);
    }

    // Jet Part
    // Do basic selection on jets and JER corrections
    std::vector<TLorentzVector> jets;
    std::vector<TLorentzVector> genJets;
    const float jetPtCut = 30.;
    const float jetAbsEtaCut = 4.7;
    const int jetPUIDCut = 4; // >=    tight = 7, medium = 6, loose = 4. Only loose is useful!!
    for(unsigned iJet=0; (iJet < unsigned(rawJets.nJets) && iJet < 10);iJet++)
    {
      // apply jet energy resolution corrections
      if (rawJets.genPt[iJet]>0.0 && rawJets.pt[iJet]>15.)
        rawJets.pt[iJet] = jerCorr(rawJets.pt[iJet],rawJets.genPt[iJet],rawJets.eta[iJet]); 
      bool goodPt = rawJets.pt[iJet]>jetPtCut;
      bool goodEta = fabs(rawJets.eta[iJet])<jetAbsEtaCut;
      bool goodPUID = puJetFullId[iJet] >= jetPUIDCut;
      if (goodPt && goodEta && goodPUID)
      {
        TLorentzVector tmpJetVec;
        tmpJetVec.SetPtEtaPhiM(rawJets.pt[iJet],rawJets.eta[iJet],rawJets.phi[iJet],rawJets.mass[iJet]);
        jets.push_back(tmpJetVec);
        TLorentzVector tmpGenJetVec;
        tmpGenJetVec.SetPtEtaPhiM(rawJets.genPt[iJet],rawJets.genEta[iJet],rawJets.genPhi[iJet],rawJets.genMass[iJet]);
        genJets.push_back(tmpGenJetVec);
      }
    }

//    /////////////////////////////////////////////
//
//    cout << "Event: "<< eventInfo.run << ":" << eventInfo.event << endl;
//
//    // print muon-related info
//    cout << "recoCandMass: " << recoCandMass << endl;
//    cout << "muon Pt1: " << reco1.pt << endl;
//    cout << "muon Pt2: " << reco2.pt << endl;
//    cout << "muon eta1: " << reco1.eta << endl;
//    cout << "muon eta2: " << reco2.eta << endl;
//    cout << "muon iso1: " << getPFRelIso(reco1) << endl;
//    cout << "muon iso2: " << getPFRelIso(reco2) << endl;
//    cout << "PU weight: " << weight << endl;
//    cout << endl;
//
//    // print jet-related info
//    cout << "nJets: " << jets.size() << endl;
//    for (unsigned iJet=0; iJet < jets.size(); iJet++)
//    {
//      cout << "Jet "<<(iJet+1)<<": pt="<< jets[iJet].Pt() << " eta="<<jets[iJet].Eta()<<endl;
//    }
//    cout << endl;
//
//    /////////////////////////////////////////////
      // Fill Histograms

      dimuonMassHist->Fill(recoCandMass,weight);
      nJetsHist->Fill(jets.size(),weight);

  }

  TFile* outFile = new TFile(outputFileName,"RECREATE");
  outFile->cd();
  dimuonMassHist->Write();
  nJetsHist->Write();

}
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D, bool drawPtCPM2D){
	gROOT->SetStyle("Plain");
	gStyle->SetTitleBorderSize(0);

	// Set some strings
	const std::string workspacename = "ws_masslifetime",
				treename = "selectedData";

	// Get the tree from the data file
	TFile *f = TFile::Open(infilename.c_str());
	TTree *tree = (TTree*)f->Get(treename.c_str());

	// Set branch addresses in tree to be able to import tree to roofit
	TLorentzVector* jpsi = new TLorentzVector;
	tree->SetBranchAddress("JpsiP",&jpsi);
	double CPMval = 0;
	tree->SetBranchAddress("CPM",&CPMval);
	double massErr = 0;
	tree->SetBranchAddress("JpsiMassErr",&massErr);
	double Vprob = 0;
	tree->SetBranchAddress("JpsiVprob",&Vprob);
	double lifetime = 0;
	tree->SetBranchAddress("Jpsict",&lifetime);
	double lifetimeErr = 0;
	tree->SetBranchAddress("JpsictErr",&lifetimeErr);

	// define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
	RooRealVar* JpsiMass =
		new RooRealVar("JpsiMass", "M [GeV]", onia::massMin, onia::massMax);
	RooRealVar* JpsiMassErr =
		new RooRealVar("JpsiMassErr", "#delta M [GeV]", 0, 5);
	RooRealVar* JpsiRap =
		new RooRealVar("JpsiRap", "y", -onia::rap, onia::rap);
	RooRealVar* JpsiPt =
		new RooRealVar("JpsiPt", "p_{T} [GeV]", 0. ,100.);
	RooRealVar* JpsiCPM =
		new RooRealVar("JpsiCPM", "N_{ch}", 0. ,100.);		
	RooRealVar* Jpsict =
		new RooRealVar("Jpsict", "lifetime [mm]", -1., 2.5);
	RooRealVar* JpsictErr =
		new RooRealVar("JpsictErr", "Error on lifetime [mm]", 0.0001, 1);
	RooRealVar* JpsiVprob =
		new RooRealVar("JpsiVprob", "", 0.01, 1.);

	// Set bins
	Jpsict->setBins(10000,"cache");
	Jpsict->setBins(100);
	JpsiMass->setBins(100);
	JpsictErr->setBins(100);

	// The list of data variables    
	RooArgList dataVars(*JpsiMass,*JpsiMassErr,*JpsiRap,*JpsiPt,*JpsiCPM,*Jpsict,*JpsictErr,*JpsiVprob);

	// construct dataset to contain events
	RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

	int entries = tree->GetEntries();
	cout << "entries " << entries << endl;

	// loop through events in tree and save them to dataset
	for (int ientries = 0; ientries < entries; ientries++) {
	
		if (ientries%100000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

		tree->GetEntry(ientries);

		double M =jpsi->M();
		double y=jpsi->Rapidity();
		double pt=jpsi->Pt();
		double cpm=CPMval;


		if (M > JpsiMass->getMin() && M < JpsiMass->getMax()
				&& massErr > JpsiMassErr->getMin() && massErr < JpsiMassErr->getMax()
				&& pt > JpsiPt->getMin() && pt < JpsiPt->getMax()
				&& cpm > JpsiCPM->getMin() && cpm < JpsiCPM->getMax()
				&& y > JpsiRap->getMin() && y < JpsiRap->getMax()
				&& lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
				&& lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
				&& Vprob > JpsiVprob->getMin() && Vprob < JpsiVprob->getMax()
			 ){

			JpsiPt      ->setVal(pt); 
			JpsiCPM		->setVal(cpm);
			JpsiRap     ->setVal(y); 
			JpsiMass    ->setVal(M);
			JpsiMassErr ->setVal(massErr);
			JpsiVprob   ->setVal(Vprob);

			//cout<<"before lifetime correction \n"
			//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;

			if(correctCtau){
				lifetime    = lifetime    * onia::MpsiPDG / M ;
				lifetimeErr = lifetimeErr * onia::MpsiPDG / M ;
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
				//cout<<"MpsiPDG: "<<onia::MpsiPDG<<endl;
				//cout<<"after lifetime correction \n"
				//	<<"Jpsict: "<<lifetime<<" JpsictErr: "<<lifetimeErr<<endl;
			}
			else{
				Jpsict    ->setVal(lifetime);
				JpsictErr ->setVal(lifetimeErr);
			}

			fullData->add(dataVars);
		}
	}//ientries


	//------------------------------------------------------------------------------------------------------------------
	// Define workspace and import datasets

	////Get datasets binned in pT, cpm, and y

		for(int iRap = 1; iRap <= onia::kNbRapForPTBins; iRap++){ 

		Double_t yMin;
		Double_t yMax;
		if(iRap==0){
			yMin = onia::rapForPTRange[0];
			yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		} else{
			yMin = onia::rapForPTRange[iRap-1];
			yMax = onia::rapForPTRange[iRap];
		}

		for(int iPT = 1; iPT <= onia::kNbPTBins[iRap]; iPT++){
			//for(int iPT = 0; iPT <= 0; iPT++)

			Double_t ptMin;
			Double_t ptMax;
			if(iPT==0){
				ptMin = onia::pTRange[iRap][0];
				ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
			} else{
				ptMin = onia::pTRange[iRap][iPT-1];
				ptMax = onia::pTRange[iRap][iPT];
			}
			
		  for(int iCPM = 1; iCPM <= onia::NchBins; iCPM++){
		  
		  
	  	    Double_t cpmMin;
			Double_t cpmMax;
			if(iCPM==0){
				cpmMin = onia::cpmRange[0];
				cpmMax = onia::cpmRange[onia::NchBins];
			} else{
				cpmMin = onia::cpmRange[iCPM-1];
				cpmMax = onia::cpmRange[iCPM];
			}

			// output file name and workspace
			std::stringstream outfilename;
			outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM << ".root";
//			outfilename << "tmpFiles/fit_Psi" << nState-3 << "S_rap" << iRap << "_pt" << iPT << ".root";			
			RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

			// define pt and y cuts on dataset
			std::stringstream cutString;
			cutString << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && " << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
				<< "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";

			cout << "cutString: " << cutString.str().c_str() << endl;

			// get the dataset for the fit
			RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
			std::stringstream name;
			name << "data_rap" << iRap << "_pt" << iPT << "_cpm" << iCPM;;
			binData->SetNameTitle(name.str().c_str(), "Data For Fitting");    

			// Import variables to workspace
			ws->import(*binData);
			ws->writeToFile(outfilename.str().c_str());
			
		  }//iCPM
		}//iPT
	}//iRap

	////---------------------------------------------------------------
	////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
	////---------------------------------------------------------------
	if(drawRapPt2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* rapPt;
		TH1D* rap1p2;
		double MassMin;
		double MassMax;

		rap1p2 = new TH1D("rap1p2","rap1p2",30,0, 1.8); 
		if(nState==4){
			rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
		cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiPt:JpsiRap>>rapPt",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;
		rapPtTree->Draw("TMath::Abs(JpsiRap)>>rap1p2",cutMass.str().c_str());

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
		rapPt->SetXTitle("y(#mu#mu)");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		rapPt->SetTitle(0);
		rapPt->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		rapPt->GetYaxis()->SetTitleOffset(1.5);
		rapPt->Draw("colz");

		TLine* rapPtLine;

		for(int iRap=0;iRap<onia::kNbRapForPTBins+1;iRap++){
			rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
			rapPtLine->SetLineWidth( 2 );
			rapPtLine->SetLineStyle( 1 );
			rapPtLine->SetLineColor( kWhite );
			rapPtLine->Draw();
			int pTBegin = 0;
			if(nState==5) pTBegin = 1;
			for(int iPt=pTBegin;iPt<onia::kNbPTBins[iRap]+1;iPt++){
				rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
				rapPtLine->SetLineWidth( 2 );
				rapPtLine->SetLineStyle( 1 );
				rapPtLine->SetLineColor( kWhite );
				rapPtLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/rapPt_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
		TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
		rap1p2->SetYTitle("Events");
		rap1p2->SetXTitle("y(#mu#mu)");
		rap1p2->SetTitle(0);
		rap1p2->SetStats(0);
		rap1p2->GetYaxis()->SetTitleOffset(1.2);
		rap1p2->Draw();
		sprintf(savename,"Fit/rapDimuon_1p2_Psi%dS.pdf",nState-3);
		c3->SaveAs(savename);
	}
	
	if(drawPtCPM2D){
		double yMin = onia::rapForPTRange[0];
		double yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
		double ptMin =  onia::pTRange[0][0];
		double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];
		double cpmMin =  onia::cpmRange[0];
		double cpmMax =  onia::cpmRange[onia::NchBins];		

		std::stringstream cutRapPt;
		cutRapPt << "(JpsiCPM > " << cpmMin << " && JpsiCPM < "<< cpmMax << ") && "
			<< "(JpsiPt > " << ptMin << " && JpsiPt < "<< ptMax << ") && "
			<< "(TMath::Abs(JpsiRap) > " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
		cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

		RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
		std::stringstream nameRapPt;
		nameRapPt << "data_rap0_pt0_cpm0";
		rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

		// output file name and workspace
		std::stringstream outfilename;
		outfilename << "tmpFiles/backupWorkSpace/fit_Psi" << nState-3 << "S_rap0_pt0_cpm0.root";
		RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
		//Import variables to workspace
		ws_RapPt->import(*rapPtData);
		ws_RapPt->writeToFile(outfilename.str().c_str());

		TH2D* PtCPM;
		double MassMin;
		double MassMax;

		if(nState==4){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100);
			MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
			MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
			// sigma  27.2 MeV
			// mean 3.093 GeV
		}
		if(nState==5){
			PtCPM = new TH2D( "PtCPM", "PtCPM", 100,0,50,200,0,100); //  rap<1.5
			//rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
			MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
			MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
			// sigma 34.9 MeV // pT > 7
			// sigma 34.3 MeV // pT > 10
			// mean 3.681 GeV
		}

		cout<<"Plotting Pt-CPM for Psi"<<nState-3<<"S"<<endl;
		cout<<"MassMin for Pt-CPM plot = "<<MassMin<<endl;
		cout<<"MassMax for Pt-CPM plot = "<<MassMax<<endl;

		TTree *rapPtTree = (TTree*)rapPtData->tree();
		std::stringstream cutMass;
		cutMass<<"(JpsiMass > " << MassMin << " && JpsiMass < "<< MassMax << ")";
		//following two methods can only be used in root_v30, 34 does not work
		rapPtTree->Draw("JpsiCPM:JpsiPt>>PtCPM",cutMass.str().c_str(),"colz");
		cout<<"debug"<<endl;

		TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
		PtCPM->SetYTitle("N_{ch}");
		PtCPM->SetXTitle("p_{T}(#mu#mu) [GeV]");
		gStyle->SetPalette(1);
		gPad->SetFillColor(kWhite);
		PtCPM->SetTitle(0);
		PtCPM->SetStats(0);
		gPad->SetLeftMargin(0.15);
		gPad->SetRightMargin(0.17);
		PtCPM->GetYaxis()->SetTitleOffset(1.5);
		PtCPM->Draw("colz");

		TLine* PtCPMLine;

		int iRap=0;
		for(int iPt=0;iPt<onia::kNbPTMaxBins+1;iPt++){
		int cpmBegin = 0;
			if(nState==5) cpmBegin = 1;
			for(int icpm=cpmBegin;icpm<onia::NchBins+1;icpm++){
			
			PtCPMLine= new TLine( onia::pTRange[iRap][0], onia::cpmRange[icpm], onia::pTRange[iRap][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();
			PtCPMLine= new TLine( onia::pTRange[iRap][iPt], onia::cpmRange[0], onia::pTRange[iRap][iPt], onia::cpmRange[onia::NchBins] );
			PtCPMLine->SetLineWidth( 2 );
			PtCPMLine->SetLineStyle( 1 );
			PtCPMLine->SetLineColor( kWhite );
			PtCPMLine->Draw();

			
//				PtCPMLine= new TLine( onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm], onia::pTRange[0][onia::kNbPTMaxBins], onia::cpmRange[icpm] );
//				PtCPMLine->SetLineWidth( 2 );
//				PtCPMLine->SetLineStyle( 1 );
//				PtCPMLine->SetLineColor( kWhite );
//				PtCPMLine->Draw();
			}
		}

		char savename[200];
		sprintf(savename,"Fit/PtCPM_Psi%dS.pdf",nState-3);
		c2->SaveAs(savename);
	}

	f->Close();
}
Ejemplo n.º 12
0
//==============================================
void PolMC::Loop(Int_t selDimuType)
{
  if (fChain == 0) return;

  Long64_t nentries = fChain->GetEntries();
  Long64_t countGenEvent = 0;
  Long64_t nb = 0;
  printf("number of entries = %d\n", (Int_t) nentries);

  //loop over the events
  for (Long64_t jentry=0; jentry<nentries;jentry++) {

    if(jentry % 100000 == 0) printf("event %d\n", (Int_t) jentry);

    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);

    //protection against dummy events:
    if(muPosPx_Gen < -9900.)
      continue;

    hGen_StatEv->Fill(0.5);//count all events
    //do NOT select on the dimuon type (only a RECO variable)
    hGen_StatEv->Fill(1.5);//count all events

    Double_t enMuPos = sqrt(muPosPx_Gen*muPosPx_Gen + muPosPy_Gen*muPosPy_Gen + muPosPz_Gen*muPosPz_Gen + jpsi::muMass*jpsi::muMass);
    Double_t enMuNeg = sqrt(muNegPx_Gen*muNegPx_Gen + muNegPy_Gen*muNegPy_Gen + muNegPz_Gen*muNegPz_Gen + jpsi::muMass*jpsi::muMass);
    TLorentzVector *muPos = new TLorentzVector();
    TLorentzVector *muNeg = new TLorentzVector();
    muPos->SetPxPyPzE(muPosPx_Gen, muPosPy_Gen, muPosPz_Gen, enMuPos);
    muNeg->SetPxPyPzE(muNegPx_Gen, muNegPy_Gen, muNegPz_Gen, enMuNeg);
    Double_t etaMuPos = muPos->PseudoRapidity();
    Double_t etaMuNeg = muNeg->PseudoRapidity();
    Double_t pTMuPos = muPos->Pt();
    Double_t pTMuNeg = muNeg->Pt();

    //take muons only within a certain eta range
    if(TMath::Abs(etaMuPos) > jpsi::etaPS || TMath::Abs(etaMuNeg) > jpsi::etaPS){
      // printf("eta(pos. muon) = %f, eta(neg. muon) = %f\n", etaMuPos, etaMuNeg);
      continue;
    }
    hGen_StatEv->Fill(2.5);//count all events

    if(pTMuPos < jpsi::pTMuMin && pTMuNeg < jpsi::pTMuMin){
      // printf("pT(pos. muon) = %f, pT(neg. muon) = %f\n", pTMuPos, pTMuNeg);
      continue;
    }
    hGen_StatEv->Fill(3.5);

    //test according to Gavin's proposal:
    //if any of the two muons is within 1.4 < eta < 1.6 AND
    //the two muons are close in eta (deltaEta < 0.2)
    //reject the dimuon (no matter whether it is "Seagull" or 
    //"Cowboy"):
//     if(TMath::Abs(etaMuPos - etaMuNeg) < 0.2 &&
//        ((etaMuPos > 1.4 && etaMuPos < 1.6) || (etaMuNeg > 1.4 && etaMuNeg < 1.6))){
//       printf("rejecting the event!\n");
//       continue;
//     }

    //build the invariant mass, pt, ... of the two muons
    TLorentzVector *onia = new TLorentzVector();
    *onia = *(muPos) + *(muNeg);

    Double_t onia_mass = onia->M();
    Double_t onia_pt = onia->Pt();
    Double_t onia_P = onia->P();
    Double_t onia_eta = onia->PseudoRapidity();
    Double_t onia_rap = onia->Rapidity();
    Double_t onia_phi = onia->Phi();
    Double_t onia_mT = sqrt(onia_mass*onia_mass + onia_pt*onia_pt);

    // Int_t rapIndex = -1;
    // for(int iRap = 0; iRap < 2*jpsi::kNbRapBins; iRap++){
    //   if(onia_rap > jpsi::rapRange[iRap] && onia_rap < jpsi::rapRange[iRap+1]){
    // 	rapIndex = iRap+1;
    // 	break;
    //   }
    // }
    Int_t rapForPTIndex = -1;
    for(int iRap = 0; iRap < jpsi::kNbRapForPTBins; iRap++){
      if(TMath::Abs(onia_rap) > jpsi::rapForPTRange[iRap] && 
	 TMath::Abs(onia_rap) < jpsi::rapForPTRange[iRap+1]){
	 rapForPTIndex = iRap+1;
	break;
      }
    }
    Int_t pTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[rapForPTIndex]; iPT++){
      if(onia_pt > jpsi::pTRange[rapForPTIndex][iPT] && onia_pt < jpsi::pTRange[rapForPTIndex][iPT+1]){
	pTIndex = iPT+1;
	break;
      }
    }
    Int_t rapIntegratedPTIndex = -1;
    for(int iPT = 0; iPT < jpsi::kNbPTBins[0]; iPT++){
      if(onia_pt > jpsi::pTRange[0][iPT] && onia_pt < jpsi::pTRange[0][iPT+1]){
	rapIntegratedPTIndex = iPT+1;
	break;
      }
    }

    // if(rapIndex < 1){
    //   printf("rapIndex %d, rap(onia) = %f\n", rapIndex, onia_rap);
    //   continue;
    // }
    if(rapForPTIndex < 1){
      // printf("rapForPTIndex %d, rap(onia) = %f\n", rapForPTIndex, onia_rap);
      continue;
    }
    if(pTIndex < 1){
      // printf("pTIndex %d, pT(onia) = %f\n", pTIndex, onia_pt);
      continue;
    }

    hGen_StatEv->Fill(4.5);

    if(TMath::Abs(onia_rap) > jpsi::rapYPS)
      continue;

    hGen_StatEv->Fill(7.5);

    //remaining of the events will be used for the analysis
    countGenEvent++;

    //fill mass, phi, pt, eta and rap distributions
    //a) all bins
    hGen_Onia_mass[0][0]->Fill(onia_mass);
    hGen_Onia_mass[rapIntegratedPTIndex][0]->Fill(onia_mass);
    hGen_Onia_mass[0][rapForPTIndex]->Fill(onia_mass);
    //
    hGen_Onia_phi[0][0]->Fill(onia_phi);
    hGen_Onia_phi[rapIntegratedPTIndex][0]->Fill(onia_phi);
    hGen_Onia_phi[0][rapForPTIndex]->Fill(onia_phi);
      
    hGen_Onia_pt[0]->Fill(onia_pt);
    // hGen_Onia_eta[0]->Fill(onia_eta);
    // hGen_Onia_rap[0]->Fill(onia_rap);
    //b) individual pT and rap bins:
    hGen_Onia_mass[pTIndex][rapForPTIndex]->Fill(onia_mass);
    hGen_Onia_phi[pTIndex][rapForPTIndex]->Fill(onia_phi);
    hGen_Onia_pt[rapForPTIndex]->Fill(onia_pt);
    // hGen_Onia_eta[pTIndex]->Fill(onia_eta);
    // hGen_Onia_rap[pTIndex]->Fill(onia_rap);

    hGen_Onia_rap_pT->Fill(onia_rap, onia_pt);

    //=====================
    calcPol(*muPos, *muNeg);
    //=====================

    //test:
//     calcPol(*muNeg, *muPos);
//     //H: test:
//     if(jentry%2 == 0)
//       calcPol(*muPos, *muNeg);
//     else
//       calcPol(*muNeg, *muPos);

    //===================================================
    //calculate delta, the angle between the CS and HX frame
    //Formula from EPJC paper
    Double_t deltaHXToCS = TMath::ACos(onia_mass * onia->Pz() / (onia_mT * onia_P));
    //     Double_t deltaCSToHX = -deltaHXToCS;
    Double_t sin2Delta = pow((onia_pt * onia->Energy() / (onia_P * onia_mT)),2);
    //sin2Delta does not change sign when going from HX-->CS or vice versa
    hDelta[pTIndex][rapForPTIndex]->Fill(deltaHXToCS * 180./TMath::Pi());
    hSin2Delta[pTIndex][rapForPTIndex]->Fill(sin2Delta);
    //===================================================

    Double_t deltaPhi = muPos->Phi() - muNeg->Phi();
    if(deltaPhi < -TMath::Pi()) deltaPhi += 2.*TMath::Pi();
    else if(deltaPhi > TMath::Pi()) deltaPhi = 2.*TMath::Pi() - deltaPhi;

    //debugging histos
    hPhiPos_PhiNeg[pTIndex][rapForPTIndex]->Fill(180./TMath::Pi() * muNeg->Phi(), 180./TMath::Pi() * muPos->Phi());
    hPtPos_PtNeg[pTIndex][rapForPTIndex]->Fill(muNeg->Pt(), muPos->Pt());
    hEtaPos_EtaNeg[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity(), muPos->PseudoRapidity());
    // hDeltaPhi[pTIndex][rapIndex]->Fill(deltaPhi);
    hDeltaPhi[pTIndex][rapForPTIndex]->Fill(deltaPhi);

    hGen_mupl_pt[pTIndex][rapForPTIndex]->Fill(muPos->Pt());
    hGen_mupl_eta[pTIndex][rapForPTIndex]->Fill(muPos->PseudoRapidity());
    hGen_mupl_phi[pTIndex][rapForPTIndex]->Fill(muPos->Phi());
      
    hGen_mumi_pt[pTIndex][rapForPTIndex]->Fill(muNeg->Pt());
    hGen_mumi_eta[pTIndex][rapForPTIndex]->Fill(muNeg->PseudoRapidity());
    hGen_mumi_phi[pTIndex][rapForPTIndex]->Fill(muNeg->Phi());

    //fill the histos for all the different frames
    for(int iFrame = 0; iFrame < jpsi::kNbFrames; iFrame++){

      thisCosPhi[iFrame] = TMath::Cos(2.*thisPhi_rad[iFrame]);

      Double_t weight = CalcPolWeight(onia_P, thisCosTh[iFrame]);

      //1a) polariztion histos - all pT
      // hGen_Onia_pol_pT[iFrame][0][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // hGen_Onia_pol_pT[iFrame][0][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // hGen_Onia_pol_pT[iFrame][0][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // hGen2D_Onia_pol_pT[iFrame][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);

      //1b) polariztion histos - pT Bin
      // if(pTIndex > 0){
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // 	hGen_Onia_pol_pT[iFrame][pTIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // 	hGen2D_Onia_pol_pT[iFrame][pTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      // }

      // //2a) polariztion histos - all Rap
      // hGen_Onia_pol_rap[iFrame][0][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // hGen_Onia_pol_rap[iFrame][0][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // hGen_Onia_pol_rap[iFrame][0][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // hGen2D_Onia_pol_rap[iFrame][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);

      // //2b) polariztion histos - rap Bin
      // if(rapIndex > 0){
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
      // 	hGen_Onia_pol_rap[iFrame][rapIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
      // 	hGen2D_Onia_pol_rap[iFrame][rapIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      // }

      //3) polariztion histos - pT and rap Bin
      //all pT and rapidities
      hGen2D_Onia_pol_pT_rap[iFrame][0][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(rapIntegratedPTIndex > 0)
	hGen2D_Onia_pol_pT_rap[iFrame][rapIntegratedPTIndex][0]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(rapForPTIndex > 0)
	hGen2D_Onia_pol_pT_rap[iFrame][0][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      if(pTIndex > 0 && rapForPTIndex > 0){
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::cosThPol]->Fill(thisCosTh[iFrame], weight);
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::phiPol]->Fill(thisPhi[iFrame], weight);
	hGen_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex][jpsi::cos2PhiPol]->Fill(thisCosPhi[iFrame], weight);
	hGen2D_Onia_pol_pT_rap[iFrame][pTIndex][rapForPTIndex]->Fill(thisCosTh[iFrame], thisPhi[iFrame], weight);
      }
    }

    delete muPos;
    delete muNeg;
    delete onia;
  }//loop over entries

  printf("nb. of rec. events is %d of a total of %d events\n", (Int_t) countGenEvent, (Int_t) nentries);
}
Int_t dieleAna(TString inputlist, TString outfile, Int_t nev=-1, Int_t whichweight = 0)
{

    TH1::SetDefaultSumw2();
    TH3F *p3DEffEle[6][NWEIGHTS+1]; // mult bins, MLP weights + HC
    TH3F *p3DEffPos[6][NWEIGHTS+1];
    TH3F *p3DAccEle[6][NWEIGHTS+1];
    TH3F *p3DAccPos[6][NWEIGHTS+1];
    readAccEffMatrices(p3DAccEle, p3DAccPos, p3DEffEle, p3DEffPos);
    TH2F *smear_ele, *smear_pos;
    TFile *file_smear = new TFile("smearing_matrix.root","read");
    smear_ele = (TH2F*)file_smear->Get("smear_ele");
    smear_pos = (TH2F*)file_smear->Get("smear_pos");

    TRandom random;

/*
    TFile *pEffFile;

    pEffFile = new TFile("Input/EffMatrixMVA2RefAccNewCP_100Mio.root");
    if (pEffFile)
    {
	pEffFile->cd();
	for(Int_t i = 0 ; i < 5 ; i++){
            p3DEffEle[i][6] = (TH3F*) pEffFile->Get(Form("hHistEff3DMult%iNeg",i));
            p3DEffPos[i][6] = (TH3F*) pEffFile->Get(Form("hHistEff3DMult%iPos",i));
     //       p3DEffEle[i] = (TH3F*) pEffFile->Get("hHistEff3DNeg");
      //      p3DEffPos[i] = (TH3F*) pEffFile->Get("hHistEff3DPos");
        }
    }
    else
    {
	Error("DrawFromNtuple constructor","pointer to eff matrix file is NULL");
	for(Int_t i = 0 ; i < 5 ; i++){
	    p3DEffEle[i][6] = NULL;
	    p3DEffPos[i][6] = NULL;
        }
    }
*/

    TH1F *pEventClass;
    TH1F *pEventClass_recur;
    TFile *pEventClassFile;
//    pEventClassFile = new TFile("eventClass_mult_nonempty_4secmult_200fpj_wait.root");
//    pEventClassFile = new TFile("eventClass_target_mult_rplane_nonempty_4secmult.root");
    pEventClassFile = new TFile("eventClass_target_mult_rplane_minmom_nmix_w6.root");
    if (pEventClassFile) {
        pEventClass = (TH1F*)pEventClassFile->Get("eventClass");
        pEventClass_recur = (TH1F*)pEventClassFile->Get("eventClass_recur");
        if (pEventClass == NULL || pEventClass_recur == NULL) {
            Error("DrawFromNtuple constructor","Histogram not found in the event class file");
            exit (-1);
        }
    }    
    else {
        Error("DrawFromNtuple constructor","Event class file not found");
        exit (-1);
    }
    HLoop* loop = new HLoop(kTRUE);  // kTRUE : create Hades  (needed to work with standard eventstructure)
    TString readCategories = "";
    if (inputlist.EndsWith(".list")) {
        loop->addFilesList(inputlist);
    }
    else {
        loop->addMultFiles(inputlist);
    }
    if(!loop->setInput(readCategories)) { exit(1); }
    loop->printCategories();
    loop->readSectorFileList("FileListLepton.list");
    int sectors[6];

    HGeantKine *kine1;
    HGeantKine *kine2;

    HCategory* kineCat = (HCategory*)HCategoryManager::getCategory(catGeantKine);

    HHistMap hM(outfile.Data());
    hM.setSilentFail(kTRUE);

    //------------------------------------------------------------------
    //--------------- begin histo booking -----------------------------------------------------
    //------------------------------------------------------------------------------------------

    const Int_t nbins = 26;
    Double_t xAxis1[nbins+1] = {0, 0.010, 0.020, 0.030, 0.040, 0.050, 0.060, 0.070, 0.080, 0.090, 0.110, 0.130, 0.150, 0.170, 0.200, 0.250, 0.300, 0.350, 0.400, 0.450, 0.500, 0.550, 0.600, 0.700, 0.800, 0.900, 1.};

    hM.addHist(new TH1F(TString("hmassNP"),TString("hmassNP"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hmassPP"),TString("hmassPP"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hmassNN"),TString("hmassNN"),nbins,xAxis1));
    hM.addHist(new TH1F(TString("hoAngleNP"),TString("hoAngleNP"),2000,0,200));
    hM.addHist(new TH1F(TString("hoAnglePP"),TString("hoAnglePP"),2000,0,200));
    hM.addHist(new TH1F(TString("hoAngleNN"),TString("hoAngleNN"),2000,0,200));
    hM.addHist(new TH1F(TString("hyNP"),TString("hyNP"),100,0,2));
    hM.addHist(new TH1F(TString("hyPP"),TString("hyPP"),100,0,2));
    hM.addHist(new TH1F(TString("hyNN"),TString("hyNN"),100,0,2));
    hM.addHist(new TH1F(TString("hptNP"),TString("hptNP"),100,0,1000));
    hM.addHist(new TH1F(TString("hptPP"),TString("hptPP"),100,0,1000));
    hM.addHist(new TH1F(TString("hptNN"),TString("hptNN"),100,0,1000));
    hM.addHist(new TH2F(TString("hoAnglemassNP"),TString("hoAnglemassNP"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAnglemassPP"),TString("hoAnglemassPP"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAnglemassNN"),TString("hoAnglemassNN"),90,0,180,nbins,xAxis1));
    hM.addHist(new TH2F(TString("hoAngleptNP"),TString("hoAngleptNP"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleptPP"),TString("hoAngleptPP"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleptNN"),TString("hoAngleptNN"),90,0,180,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptNP"),TString("hmassptNP"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptPP"),TString("hmassptPP"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hmassptNN"),TString("hmassptNN"),nbins,xAxis1,120,0,1200));
    hM.addHist(new TH2F(TString("hoAngleyNP"),TString("hoAngleyNP"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hoAngleyPP"),TString("hoAngleyPP"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hoAngleyNN"),TString("hoAngleyNN"),90,0,180,100,0,2));
    hM.addHist(new TH2F(TString("hmassyNP"),TString("hmassyNP"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hmassyPP"),TString("hmassyPP"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hmassyNN"),TString("hmassyNN"),nbins,xAxis1,100,0,2));
    hM.addHist(new TH2F(TString("hptyNP"),TString("hptyNP"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hptyPP"),TString("hptyPP"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hptyNN"),TString("hptyNN"),120,0,1200,100,0,2));
    hM.addHist(new TH2F(TString("hth1th2NP"),TString("hth1th2NP"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hth1th2PP"),TString("hth1th2PP"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hth1th2NN"),TString("hth1th2NN"),90,0,90,90,0,90));
    hM.addHist(new TH2F(TString("hp1p2NP"),TString("hp1p2NP"),100,0,1100,100,0,1100));
    hM.addHist(new TH2F(TString("hp1p2PP"),TString("hp1p2PP"),100,0,1100,100,0,1100));
    hM.addHist(new TH2F(TString("hp1p2NN"),TString("hp1p2NN"),100,0,1100,100,0,1100));

    for (int i = 0; i < 5; ++i) {
        hM.addHist(new TH1F(TString("hmassNP_eff_multbin")+TString::Itoa(i,10),TString("hmassNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hmassPP_eff_multbin")+TString::Itoa(i,10),TString("hmassPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hmassNN_eff_multbin")+TString::Itoa(i,10),TString("hmassNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1));
        hM.addHist(new TH1F(TString("hoAngleNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleNP_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hoAnglePP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglePP_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hoAngleNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleNN_eff_multbin")+TString::Itoa(i,10),2000,0,200));
        hM.addHist(new TH1F(TString("hyNP_eff_multbin")+TString::Itoa(i,10),TString("hyNP_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hyPP_eff_multbin")+TString::Itoa(i,10),TString("hyPP_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hyNN_eff_multbin")+TString::Itoa(i,10),TString("hyNN_eff_multbin")+TString::Itoa(i,10),100,0,2));
        hM.addHist(new TH1F(TString("hptNP_eff_multbin")+TString::Itoa(i,10),TString("hptNP_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH1F(TString("hptPP_eff_multbin")+TString::Itoa(i,10),TString("hptPP_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH1F(TString("hptNN_eff_multbin")+TString::Itoa(i,10),TString("hptNN_eff_multbin")+TString::Itoa(i,10),100,0,1000));
        hM.addHist(new TH2F(TString("hoAnglemassNP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassNP_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAnglemassPP_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassPP_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAnglemassNN_eff_multbin")+TString::Itoa(i,10),TString("hoAnglemassNN_eff_multbin")+TString::Itoa(i,10),90,0,180,nbins,xAxis1));
        hM.addHist(new TH2F(TString("hoAngleptNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptNP_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleptPP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptPP_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleptNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleptNN_eff_multbin")+TString::Itoa(i,10),90,0,180,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptNP_eff_multbin")+TString::Itoa(i,10),TString("hmassptNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptPP_eff_multbin")+TString::Itoa(i,10),TString("hmassptPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hmassptNN_eff_multbin")+TString::Itoa(i,10),TString("hmassptNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,120,0,1200));
        hM.addHist(new TH2F(TString("hoAngleyNP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyNP_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hoAngleyPP_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyPP_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hoAngleyNN_eff_multbin")+TString::Itoa(i,10),TString("hoAngleyNN_eff_multbin")+TString::Itoa(i,10),90,0,180,100,0,2));
        hM.addHist(new TH2F(TString("hmassyNP_eff_multbin")+TString::Itoa(i,10),TString("hmassyNP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hmassyPP_eff_multbin")+TString::Itoa(i,10),TString("hmassyPP_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hmassyNN_eff_multbin")+TString::Itoa(i,10),TString("hmassyNN_eff_multbin")+TString::Itoa(i,10),nbins,xAxis1,100,0,2));
        hM.addHist(new TH2F(TString("hptyNP_eff_multbin")+TString::Itoa(i,10),TString("hptyNP_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hptyPP_eff_multbin")+TString::Itoa(i,10),TString("hptyPP_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hptyNN_eff_multbin")+TString::Itoa(i,10),TString("hptyNN_eff_multbin")+TString::Itoa(i,10),120,0,1200,100,0,2));
        hM.addHist(new TH2F(TString("hth1th2NP_eff_multbin")+TString::Itoa(i,10),TString("hth1th2NP_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hth1th2PP_eff_multbin")+TString::Itoa(i,10),TString("hth1th2PP_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hth1th2NN_eff_multbin")+TString::Itoa(i,10),TString("hth1th2NN_eff_multbin")+TString::Itoa(i,10),90,0,90,90,0,90));
        hM.addHist(new TH2F(TString("hp1p2NP_eff_multbin")+TString::Itoa(i,10),TString("hp1p2NP_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
        hM.addHist(new TH2F(TString("hp1p2PP_eff_multbin")+TString::Itoa(i,10),TString("hp1p2PP_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
        hM.addHist(new TH2F(TString("hp1p2NN_eff_multbin")+TString::Itoa(i,10),TString("hp1p2NN_eff_multbin")+TString::Itoa(i,10),100,0,1100,100,0,1100));
    }

    //--------------- end histo booking -----------------------------------------------------

    HGenericEventMixer<HGeantKine> eventmixer;
    eventmixer.setPIDs(2,3,1);
    eventmixer.setBuffSize(80);
    //eventmixer.setBuffSize(2);
    HGenericEventMixer<HGeantKine> eventmixer_eff[5];
    for (int mb = 0; mb < 5; ++mb) {
        eventmixer_eff[mb].setPIDs(2,3,1);
        eventmixer_eff[mb].setBuffSize(80);
        //eventmixer_eff[mb].setBuffSize(2);
    }

    TStopwatch timer;
    timer.Reset();
    timer.Start();

    Float_t impB = -1.;
    Float_t impB_bins[]  = {9.3, 8.1, 6.6, 4.7, 0.};

    Int_t evtsInFile = loop->getEntries();
    if(nev < 0 || nev > evtsInFile ) nev = evtsInFile;

    for(Int_t i = 1; i < nev; i++)
    {
        //----------break if last event is reached-------------
        //if(!gHades->eventLoop(1)) break;
        if(loop->nextEvent(i) <= 0) { cout<<" end recieved "<<endl; break; } // last event reached
        HTool::printProgress(i,nev,1,"Analyze :");
        loop->getSectors(sectors);

	HPartialEvent *fSimul        = ((HRecEvent*)gHades->getCurrentEvent())->getPartialEvent(catSimul);
	HGeantHeader *fSubHeader = (HGeantHeader*)(fSimul->getSubHeader());
	impB = fSubHeader->getImpactParameter();

	Int_t multbin = 0;
        if (impB >= impB_bins[4] && impB <= impB_bins[3]) {multbin=1;} // most central
	if (impB >  impB_bins[3] && impB <= impB_bins[2]) {multbin=2;}
	if (impB >  impB_bins[2] && impB <= impB_bins[1]) {multbin=3;}
	if (impB >  impB_bins[1] && impB <= impB_bins[0]) {multbin=4;} // most peripheral
	if (impB >  impB_bins[0]) {multbin=5;}
/*
	HParticleEvtInfo* evtinfo;
	evtinfo = HCategoryManager::getObject(evtinfo,catParticleEvtInfo,0);

	Int_t multbin = 0;
	Int_t mult_meta = evtinfo->getSumTofMultCut() + evtinfo->getSumRpcMultHitCut();
        if (mult_meta >  60 && mult_meta <=  88) multbin = 4; // most peripheral
        if (mult_meta >  88 && mult_meta <= 121) multbin = 3;
        if (mult_meta > 121 && mult_meta <= 160) multbin = 2;
        if (mult_meta > 160 && mult_meta <= 250) multbin = 1; // most central
        if (mult_meta > 250) multbin = 5;
*/

        if (multbin == 0 || multbin == 5) continue;

        Int_t size = kineCat->getEntries();

        // Additional loop to fill vector
        vector<HGeantKine *> vep;
        vector<HGeantKine *> vem;
        vector<HGeantKine *> vep_eff;
        vector<HGeantKine *> vem_eff;
        vector<HGeantKine *> vep_eff_multbin;
        vector<HGeantKine *> vem_eff_multbin;
	for(Int_t j = 0; j < size; j ++){
	    kine1 = HCategoryManager::getObject(kine1,kineCat,j);
            Float_t vx,vy,vz;
            kine1->getVertex(vx,vy,vz);
	    Float_t vr = TMath::Sqrt(vx*vx+vy*vy);
            if (vz < -60 || vz > 0) continue;
            if (vr > 2) continue;
            Int_t mamaNum = kine1->getParentTrack();

            if (kine1->isInAcceptance()) {
                if (kine1->getTotalMomentum() > 100 && kine1->getTotalMomentum() < 1000) {
                    Float_t px,py,pz;
                    kine1->getMomentum(px,py,pz);
                    TH2F *smear_matr;
                    if (kine1->getID() == 2) {
                        smear_matr = smear_pos;
                    } else {
                        smear_matr = smear_ele;
                    }
                    Float_t mom_ideal = kine1->getTotalMomentum();
                    Float_t mom_reco = smear(mom_ideal,smear_matr,random);
                    Float_t reco_over_ideal = mom_reco / mom_ideal;
                    kine1->setMomentum(px*reco_over_ideal,py*reco_over_ideal,pz*reco_over_ideal);
                    TLorentzVector vec;
                    HParticleTool::getTLorentzVector(kine1,vec,kine1->getID());

                    Float_t mom = vec.Vect().Mag();
                    Float_t the = vec.Theta()*TMath::RadToDeg();
                    Float_t phi = (vec.Phi()+TMath::Pi())*TMath::RadToDeg();
                    Float_t chg = (kine1->getID() == 2) ? 1 : -1;

                    if (kine1->getID() == 3) {
                        vem.push_back(new HGeantKine(*kine1));
                    }
                    if (kine1->getID() == 2) {
                        vep.push_back(new HGeantKine(*kine1));
                    }
                    Float_t eff = 1./getEfficiencyFactor(p3DEffEle[0][6],p3DEffPos[0][6],mom_ideal,the,phi,chg,false,false); // don't debug, don't check min value
                    if (isinf(eff) || isnan(eff)) eff = 0.;
                    if (random.Uniform(1) > eff) {
                        if (kine1->getID() == 3) {
                            vem_eff.push_back(new HGeantKine(*kine1));
                        }
                        if (kine1->getID() == 2) {
                            vep_eff.push_back(new HGeantKine(*kine1));
                        }
                    }
                    Float_t eff_multbin = 1./getEfficiencyFactor(p3DEffEle[multbin][6],p3DEffPos[multbin][6],mom,the,phi,chg,false,false);
                    if (isinf(eff_multbin) || isnan(eff_multbin)) eff_multbin = 0.;
                    if (random.Uniform(1) > eff_multbin) {
                        if (kine1->getID() == 3) {
                            vem_eff_multbin.push_back(new HGeantKine(*kine1));
                        }
                        if (kine1->getID() == 2) {
                            vep_eff_multbin.push_back(new HGeantKine(*kine1));
                        }
                    }
                }
            }
        }

        eventmixer.nextEvent();
        eventmixer.addVector(vep,2);
        eventmixer.addVector(vem,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_acc = eventmixer.getMixedVector();

        eventmixer_eff[0].nextEvent();
        eventmixer_eff[0].addVector(vep_eff,2);
        eventmixer_eff[0].addVector(vem_eff,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_eff = eventmixer_eff[0].getMixedVector();

        eventmixer_eff[multbin].nextEvent();
        eventmixer_eff[multbin].addVector(vep_eff,2);
        eventmixer_eff[multbin].addVector(vem_eff,3);
        vector<pair<HGeantKine *, HGeantKine* > >& pairsVec_eff_multbin = eventmixer_eff[multbin].getMixedVector();

        for (int imix = 0; imix < 3; ++imix) {
            vector<pair<HGeantKine *, HGeantKine* > > pairsVec;
            TString suffix;
            switch (imix) {
                case 0: 
                    pairsVec = pairsVec_acc;
                    suffix = TString(""); 
                    break;
                case 1: 
                    pairsVec = pairsVec_eff;
                    suffix = TString("_eff_multbin0");
                    break;
                case 2: 
                    pairsVec = pairsVec_eff_multbin;
                    suffix = TString("_eff_multbin")+TString::Itoa(multbin,10);
                    break;
            }
            size = pairsVec.size();

            for (Int_t j = 0; j < size; j ++) {
                pair<HGeantKine*,HGeantKine*>& pair = pairsVec[j];

                kine1 = pair.first;
                kine2 = pair.second;
                TLorentzVector vec1, vec2;
                HParticleTool::getTLorentzVector(kine1,vec1,kine1->getID());
                HParticleTool::getTLorentzVector(kine2,vec2,kine2->getID());

                Float_t mom1 = vec1.Vect().Mag();
                Float_t the1 = vec1.Theta()*TMath::RadToDeg();
                Float_t mom2 = vec2.Vect().Mag();
                Float_t the2 = vec2.Theta()*TMath::RadToDeg();

                TLorentzVector dilep = vec1 + vec2;
                Float_t oAngle = vec1.Angle(vec2.Vect())*TMath::RadToDeg();
                Float_t mass   = dilep.M()/1000;
                Float_t pt     = dilep.Perp();
                Float_t y      = dilep.Rapidity();
                Float_t mbinw  = hM.get("hmassNP")->GetBinWidth(hM.get("hmassNP")->FindBin(mass));

                if (oAngle < 9) continue;

                TString chg = "NP";
                if (kine1->getID() == kine2->getID()) {
                    if (kine1->getID() == 2) chg = "PP";
                    if (kine1->getID() == 3) chg = "NN";
                }

                hM.get( TString("hmass")      +chg+suffix)->Fill(mass,       1./mbinw);
                hM.get( TString("hoAngle")    +chg+suffix)->Fill(oAngle      );
                hM.get( TString("hy")         +chg+suffix)->Fill(y           );
                hM.get( TString("hpt")        +chg+suffix)->Fill(pt          );
                hM.get2(TString("hoAnglemass")+chg+suffix)->Fill(oAngle,mass,1./mbinw);
                hM.get2(TString("hoAnglept")  +chg+suffix)->Fill(oAngle,pt   );
                hM.get2(TString("hmasspt")    +chg+suffix)->Fill(mass,pt,    1./mbinw);
                hM.get2(TString("hoAngley")   +chg+suffix)->Fill(oAngle,y    );
                hM.get2(TString("hmassy")     +chg+suffix)->Fill(mass,y,     1./mbinw);
                hM.get2(TString("hpty")       +chg+suffix)->Fill(pt,y        );
                hM.get2(TString("hth1th2")    +chg+suffix)->Fill(the1,the2   );
                hM.get2(TString("hp1p2")      +chg+suffix)->Fill(mom1,mom2   );
            }
        }
//#define DELETE_MIX
#ifdef DELETE_MIX
        vector <HGeantKine *>* toDel = eventmixer.getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel->size(); ++ii) {
            delete toDel->at(ii);
        }
        toDel->clear();
        delete toDel;
        vector <HGeantKine *>* toDel_eff = eventmixer_eff[0].getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel_eff->size(); ++ii) {
            delete toDel_eff->at(ii);
        }
        toDel_eff->clear();
        delete toDel_eff;
        vector <HGeantKine *>* toDel_eff_multbin = eventmixer_eff[multbin].getObjectsToDelete();
        for (unsigned int ii = 0; ii < toDel_eff_multbin->size(); ++ii) {
            delete toDel_eff_multbin->at(ii);
        }
        toDel_eff_multbin->clear();
        delete toDel_eff_multbin;
#endif

    } // end event loop

    timer.Stop();

    hM.getFile()->cd();
    TMacro m1(__DIELEANA_FILE__);
    m1.Write();
    hM.writeHists("nomap");

    cout<<"####################################################"<<endl;
    return 0;
}
Ejemplo n.º 14
0
void MakeTree_2015(const char* inputOniaTree = "../All_v2.24_Histos_Runs_211739-211831_GlbGlb_woPileUpRej_allPV.root",
		   //miniUpsilon_Histos_Runs_210498-211631_HFvars_paapJune28.root",
		   //  const char* runNumber = "211739-211831",
		   //  const char* runNumber = "210498-211631",// whole pA run, with wrong alignment
		   //  const char* runNumber = "gt210658-211631", 
		   const char* runNumber = "HIN-15-001", 
		   //const char* runNumber = "a",
		   float newVtxProbCut   = 0.01,// default in the input tree is already 0.01
		   float ptcut           = 0., // single muon cut pt
		   int nTriggerBit       = 2, 
		   // const char* dataSource= "upsiMiniTree_pp276tev_5p41_ptmu4_woPileup_june27",
		   //   const char* dataSource= "upsiMiniTree_pA5tev_ptmu4_octb15_chunk1_runGT210658",
		   const char* dataSource= "upsiMiniTree_pp2p76tev_noIDVars_GlbGlb",
		   // const char* dataSource= "upsiMiniTree_pp7tev_dimu0v1_ptmu4",
		   //   const char* dataSource= "upsiMiniTree_aa276tevC50100_ppofficial_trktrk_ptmu4",
		   bool isAArereco       = false,// only for newly processed AA; old tree is with triger v1,v2 included
		   bool bAllTriggers     = false,
		   bool addExtraCentrality = true,
		   bool excludeWrongAlign_pa = false
		   )
{
  gROOT->Macro("setTDRStyle_modified.C+");
 
  float mass_min = 7.0; 
  float mass_max = 14.0;
  int   nBins    = 30;
  
  TFile *f = TFile::Open(Form("%s",inputOniaTree));
 
  TTree *t = (TTree*)f->Get("myTree");
  Long64_t nentries = t->GetEntries();
  cout<<"Got the tree!"<<endl;
  cout << nentries << endl;
  const int NMAX=1000000;
  UInt_t eventNb;
  UInt_t runNb;
  Int_t Centrality;
  Int_t HLTriggers;
  Int_t Reco_QQ_size;
  Int_t Reco_QQ_type[NMAX];
  Int_t Reco_QQ_sign[NMAX];
  Int_t Reco_QQ_NtrkDeltaR03[NMAX];
  Int_t Reco_QQ_NtrkDeltaR04[NMAX];
  Int_t Reco_QQ_NtrkDeltaR05[NMAX];
  Int_t Reco_QQ_NtrkPt04[NMAX];
  Int_t Reco_QQ_NtrkPt03[NMAX];
  Int_t Reco_QQ_NtrkPt02[NMAX];

  Float_t Reco_QQ_ctau[NMAX];
  Float_t Reco_QQ_ctauErr[NMAX];
  Float_t Reco_QQ_ctauTrue[NMAX];
  Float_t Reco_QQ_VtxProb[NMAX];
  float Reco_QQ_dca[NMAX]; // new float, unused in upsilon
  Int_t Reco_QQ_trig[NMAX];
  Float_t zVtx;

  int Reco_QQ_mupl_nTrkHits[NMAX];
  float Reco_QQ_mupl_normChi2_inner[NMAX];
  float Reco_QQ_mupl_normChi2_global[NMAX];
  float Reco_QQ_mupl_dxy[NMAX];
  float Reco_QQ_mupl_dxyErr[NMAX];
  float Reco_QQ_mupl_dz[NMAX];
  float Reco_QQ_mupl_dzErr[NMAX];
  Bool_t Reco_QQ_mupl_TrkMuArb[NMAX];
  Bool_t Reco_QQ_mupl_TMOneStaTight[NMAX]; // new bool, unused in upsilon(?)
  int Reco_QQ_mupl_nMuValHits[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mupl_nPixWMea[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mupl_nTrkWMea[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mupl_StationsMatched[NMAX]; // new int, unused in Upsilon
  float Reco_QQ_mupl_pt_inner[NMAX]; // new float, unused.
  float Reco_QQ_mupl_pt_global[NMAX]; //new float, unused.
  float Reco_QQ_mupl_ptErr_inner[NMAX]; // new float, unused.
  float Reco_QQ_mupl_ptErr_global[NMAX]; //new float, unused.
 
  int Reco_QQ_mumi_nTrkHits[NMAX];
  float Reco_QQ_mumi_normChi2_inner[NMAX];
  float Reco_QQ_mumi_normChi2_global[NMAX];
  float Reco_QQ_mumi_dxy[NMAX];
  float Reco_QQ_mumi_dxyErr[NMAX];
  float Reco_QQ_mumi_dz[NMAX];
  float Reco_QQ_mumi_dzErr[NMAX];
  Bool_t Reco_QQ_mumi_TrkMuArb[NMAX];
  Bool_t Reco_QQ_mumi_TMOneStaTight[NMAX];  // new bool, unused in upsilon(?)
  int Reco_QQ_mumi_nMuValHits[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mumi_nPixWMea[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mumi_nTrkWMea[NMAX]; // new int, unused in upsilon
  int Reco_QQ_mumi_StationsMatched[NMAX]; // new int, unused in Upsilon
  float Reco_QQ_mumi_pt_inner[NMAX]; // new float, unused.
  float Reco_QQ_mumi_pt_global[NMAX]; //new float, unused.
  float Reco_QQ_mumi_ptErr_inner[NMAX]; // new float, unused.
  float Reco_QQ_mumi_ptErr_global[NMAX]; //new float, unused.

  TClonesArray *Reco_QQ_vtx = 0;;
  TClonesArray *Reco_QQ_4mom = 0;
  TClonesArray *Reco_QQ_mupl_4mom = 0;
  TClonesArray *Reco_QQ_mumi_4mom = 0;
  TClonesArray *Reco_mu_4mom = 0;

  Int_t Reco_mu_size;
  Int_t Reco_mu_type[NMAX];
  Int_t Reco_mu_charge[NMAX];

  int nPlusMu;
  int nMinusMu;
  float muPt[NMAX];
  float muEta[NMAX];
  float muPhi[NMAX];
  //Int_t nReco_QQ;
  Float_t invariantMass;
  Int_t QQtrig;
  Int_t QQsign;
  Int_t QQTrkDr03;
  Int_t QQTrkDr04;
  Int_t QQTrkDr05;

  Int_t QQTrkPt04;
  Int_t QQTrkPt03;
  Int_t QQTrkPt02;

  float weight;
  float weight2;
  Float_t upsPt;
  Float_t upsEta;
  Float_t upsPhi;
  Float_t upsRapidity;	
  Float_t vProb;
  Float_t muPlusPt;
  Float_t muMinusPt;
  Float_t muPlusEta;
  Float_t muMinusEta;
  Float_t muPlusPhi;
  Float_t muMinusPhi;
  Float_t RmuPlusPhi = 0;
  Float_t RmuMinusPhi = 0;

  // centrliaty extra stuff
  Int_t Npix, NpixelTracks,Ntracks;
  Float_t SumET_HF, SumET_HFplus, SumET_HFminus, SumET_HFplusEta4, SumET_HFminusEta4, SumET_EB, SumET_ET, SumET_EE, SumET_EEplus, SumET_EEminus, SumET_ZDC, SumET_ZDCplus, SumET_ZDCminus;

  // track extra stuff
  const int NTRKMAX=100000000;
  int Reco_trk_size=0;
  TClonesArray *Reco_trk_vtx = 0;
  TClonesArray *Reco_trk_4mom = 0;
  float trkPt[NTRKMAX];
  float trkEta[NTRKMAX];
  float trkPhi[NTRKMAX];
  //---------------------------
  TBranch *b_Centrality; //!
  TBranch *b_eventNb;    //!
  TBranch *b_runNb;      //!
  TBranch *b_HLTriggers; //!
  TBranch *b_Reco_QQ_size; //!
  TBranch *b_Reco_QQ_trig; //!
  TBranch *b_Reco_QQ_type; //!
  TBranch *b_Reco_QQ_sign; //!
  TBranch *b_Reco_QQ_VtxProb;  //!
  TBranch *b_Reco_QQ_dca; // new float, unused in upsilon
  TBranch *b_Reco_QQ_ctau; //!
  TBranch *b_Reco_QQ_ctauErr; //!
  TBranch *b_Reco_QQ_ctauTrue; //!
  TBranch *b_Reco_QQ_4mom;     //!
  TBranch *b_Reco_QQ_vtx;      //!
  TBranch *b_Reco_QQ_mupl_4mom;//!
  TBranch *b_Reco_QQ_mumi_4mom;//!
  TBranch *b_Reco_QQ_NtrkDeltaR03;//!
  TBranch *b_Reco_QQ_NtrkDeltaR04;//!
  TBranch *b_Reco_QQ_NtrkDeltaR05;//!
  TBranch *b_Reco_QQ_NtrkPt04;//!
  TBranch *b_Reco_QQ_NtrkPt03;//!
  TBranch *b_Reco_QQ_NtrkPt02;//!
  //------------------------------
  TBranch *b_Reco_QQ_mupl_nTrkHits;           
  TBranch *b_Reco_QQ_mupl_normChi2_inner;
  TBranch *b_Reco_QQ_mupl_normChi2_global;
  TBranch *b_Reco_QQ_mupl_dxy;
  TBranch *b_Reco_QQ_mupl_dxyErr;
  TBranch *b_Reco_QQ_mupl_dz;
  TBranch *b_Reco_QQ_mupl_dzErr;
  TBranch *b_Reco_QQ_mupl_TrkMuArb;
  TBranch *b_Reco_QQ_mupl_TMOneStaTight; // new bool, unused in upsilon(?)
  TBranch *b_Reco_QQ_mupl_nMuValHits; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mupl_nPixWMea; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mupl_nTrkWMea; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mupl_StationsMatched; // new int, unused in Upsilon
  TBranch *b_Reco_QQ_mupl_pt_inner; // new float, unused.
  TBranch *b_Reco_QQ_mupl_pt_global; //new float, unused.
  TBranch *b_Reco_QQ_mupl_ptErr_inner; // new float, unused.
  TBranch *b_Reco_QQ_mupl_ptErr_global; //new float, unused.
    
  TBranch *b_Reco_QQ_mumi_TMOneStaTight;  // new bool, unused in upsilon(?)
  TBranch *b_Reco_QQ_mumi_nMuValHits; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mumi_nPixWMea; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mumi_nTrkWMea; // new int, unused in upsilon
  TBranch *b_Reco_QQ_mumi_StationsMatched; // new int, unused in Upsilon
  TBranch *b_Reco_QQ_mumi_pt_inner; // new float, unused.
  TBranch *b_Reco_QQ_mumi_pt_global; //new float, unused.
  TBranch *b_Reco_QQ_mumi_ptErr_inner; // new float, unused.
  TBranch *b_Reco_QQ_mumi_ptErr_global; //new float, unused.
  TBranch *b_Reco_QQ_mumi_normChi2_inner;
  TBranch *b_Reco_QQ_mumi_normChi2_global;
  TBranch *b_Reco_QQ_mumi_dxy;
  TBranch *b_Reco_QQ_mumi_dxyErr;
  TBranch *b_Reco_QQ_mumi_dz;
  TBranch *b_Reco_QQ_mumi_dzErr;
  TBranch *b_Reco_QQ_mumi_TrkMuArb;
  TBranch *b_Reco_QQ_mumi_nTrkHits;
  //-------------  //-------------  //------------- 
  TBranch *b_Reco_mu_size;  //!
  TBranch *b_Reco_mu_type;  //!
  TBranch *b_Reco_mu_charge;//!
  TBranch *b_Reco_mu_4mom;  //!
  //-------------  //-------------  //------------- 
  TBranch *b_zVtx; //!
  TBranch *b_Npix; //!
  TBranch *b_NpixelTracks; //!
  TBranch *b_Ntracks; //!
  TBranch *b_SumET_HF; //!
  TBranch *b_SumET_HFplus; //!
  TBranch *b_SumET_HFminus; //!
  TBranch *b_SumET_HFplusEta4; //!
  TBranch *b_SumET_HFminusEta4; //!
  TBranch *b_SumET_ET; //!
  TBranch *b_SumET_EE; //!
  TBranch *b_SumET_EB; //!
  TBranch *b_SumET_EEplus; //!
  TBranch *b_SumET_EEminus; //!
  TBranch *b_SumET_ZDC; //!
  TBranch *b_SumET_ZDCplus; //!
  TBranch *b_SumET_ZDCminus; //!

  //------------------------------
  TBranch *b_Reco_trk_size; //! 
  TBranch *b_Reco_trk_4mom; //!
  TBranch *b_Reco_trk_vtx;  //!

  /// new tree variables
  Int_t _mupl_nTrkHits;           
  Float_t _mupl_normChi2_inner;
  Float_t _mupl_normChi2_global;
  Float_t _mupl_dxy;
  Float_t _mupl_dxyErr;
  Float_t _mupl_dz;
  Float_t _mupl_dzErr;
  Bool_t _mupl_TrkMuArb;
  Bool_t _mupl_TMOneStaTight; // new bool, unused in upsilon(?)
  Int_t _mupl_nMuValHits; // new int, unused in upsilon
  Int_t _mupl_nPixWMea; // new int, unused in upsilon
  Int_t _mupl_nTrkWMea; // new int, unused in upsilon
  Int_t _mupl_StationsMatched; // new int, unused in Upsilon
  Float_t _mupl_pt_inner; // new float, unused.
  Float_t _mupl_pt_global; //new float, unused.
  Float_t _mupl_ptErr_inner; // new float, unused.
  Float_t _mupl_ptErr_global; //new float, unused.
    
  Bool_t _mumi_TMOneStaTight;  // new bool, unused in upsilon(?)
  Int_t _mumi_nMuValHits; // new int, unused in upsilon
  Int_t _mumi_nPixWMea; // new int, unused in upsilon
  Int_t _mumi_nTrkWMea; // new int, unused in upsilon
  Int_t _mumi_StationsMatched; // new int, unused in Upsilon
  Float_t _mumi_pt_inner; // new float, unused.
  Float_t _mumi_pt_global; //new float, unused.
  Float_t _mumi_ptErr_inner; // new float, unused.
  Float_t _mumi_ptErr_global; //new float, unused.
  Float_t _mumi_normChi2_inner;
  Float_t _mumi_normChi2_global;
  Float_t _mumi_dxy;
  Float_t _mumi_dxyErr;
  Float_t _mumi_dz;
  Float_t _mumi_dzErr;
  Bool_t _mumi_TrkMuArb;
  Int_t _mumi_nTrkHits;
  Float_t _dca;
   float _ctau; // new float, unused in upsilon
  float _ctauTrue; // new float, unused in upsilon
  float _ctauErr; // new float, unused in upsilon
  float _zVtx;
  // ###### read input TTree
  t->SetBranchAddress("Centrality",    &Centrality,   &b_Centrality);
  t->SetBranchAddress("eventNb",       &eventNb,      &b_eventNb);
  t->SetBranchAddress("runNb",         &runNb,        &b_runNb);
  t->SetBranchAddress("HLTriggers",    &HLTriggers,   &b_HLTriggers);
  t->SetBranchAddress("Reco_QQ_size",  &Reco_QQ_size, &b_Reco_QQ_size);
  t->SetBranchAddress("Reco_QQ_type",  &Reco_QQ_type, &b_Reco_QQ_type);
  t->SetBranchAddress("Reco_QQ_sign",  &Reco_QQ_sign, &b_Reco_QQ_sign);
  t->SetBranchAddress("Reco_QQ_4mom",  &Reco_QQ_4mom, &b_Reco_QQ_4mom);
  t->SetBranchAddress("Reco_QQ_vtx",       &Reco_QQ_vtx,        &b_Reco_QQ_vtx);
  t->SetBranchAddress("Reco_QQ_mupl_4mom", &Reco_QQ_mupl_4mom, &b_Reco_QQ_mupl_4mom);
  t->SetBranchAddress("Reco_QQ_mumi_4mom", &Reco_QQ_mumi_4mom, &b_Reco_QQ_mumi_4mom);
  
  t->SetBranchAddress("Reco_mu_size",  &Reco_mu_size,   &b_Reco_mu_size);
  t->SetBranchAddress("Reco_mu_type",  &Reco_mu_type,   &b_Reco_mu_type);
  t->SetBranchAddress("Reco_mu_charge",&Reco_mu_charge, &b_Reco_mu_charge);
  t->SetBranchAddress("Reco_mu_4mom",  &Reco_mu_4mom,   &b_Reco_mu_4mom);

  t->SetBranchAddress("Reco_QQ_NtrkDeltaR03",  &Reco_QQ_NtrkDeltaR03, &b_Reco_QQ_NtrkDeltaR03);
  t->SetBranchAddress("Reco_QQ_NtrkDeltaR04",  &Reco_QQ_NtrkDeltaR04, &b_Reco_QQ_NtrkDeltaR04);
  t->SetBranchAddress("Reco_QQ_NtrkDeltaR05",  &Reco_QQ_NtrkDeltaR05, &b_Reco_QQ_NtrkDeltaR05);

  t->SetBranchAddress("Reco_QQ_NtrkPt04",  &Reco_QQ_NtrkPt04, &b_Reco_QQ_NtrkPt04);
  t->SetBranchAddress("Reco_QQ_NtrkPt03",  &Reco_QQ_NtrkPt03, &b_Reco_QQ_NtrkPt03);
  t->SetBranchAddress("Reco_QQ_NtrkPt02",  &Reco_QQ_NtrkPt02, &b_Reco_QQ_NtrkPt02);
  // additional selection
  //id variables
  t->SetBranchAddress("Reco_QQ_mupl_nTrkHits", &Reco_QQ_mupl_nTrkHits, &b_Reco_QQ_mupl_nTrkHits);
  t->SetBranchAddress("Reco_QQ_mupl_normChi2_inner", &Reco_QQ_mupl_normChi2_inner, &b_Reco_QQ_mupl_normChi2_inner);
  t->SetBranchAddress("Reco_QQ_mupl_normChi2_global", &Reco_QQ_mupl_normChi2_global, &b_Reco_QQ_mupl_normChi2_global);
  t->SetBranchAddress("Reco_QQ_mupl_dxy", &Reco_QQ_mupl_dxy, &b_Reco_QQ_mupl_dxy);
  t->SetBranchAddress("Reco_QQ_mupl_dz", &Reco_QQ_mupl_dz, &b_Reco_QQ_mupl_dz);
  t->SetBranchAddress("Reco_QQ_mupl_dxyErr", &Reco_QQ_mupl_dxyErr, &b_Reco_QQ_mupl_dxyErr);
  t->SetBranchAddress("Reco_QQ_mupl_dzErr", &Reco_QQ_mupl_dzErr, &b_Reco_QQ_mupl_dzErr);
  t->SetBranchAddress("Reco_QQ_mupl_TrkMuArb", &Reco_QQ_mupl_TrkMuArb, &b_Reco_QQ_mupl_TrkMuArb);
  t->SetBranchAddress("Reco_QQ_mupl_StationsMatched",&Reco_QQ_mupl_StationsMatched, &b_Reco_QQ_mupl_StationsMatched); // new int, unused in Upsilon
  t->SetBranchAddress("Reco_QQ_mupl_TMOneStaTight", &Reco_QQ_mupl_TMOneStaTight, &b_Reco_QQ_mupl_TMOneStaTight);  // new bool, unused in upsilon(?)
  t->SetBranchAddress("Reco_QQ_mupl_nMuValHits", &Reco_QQ_mupl_nMuValHits, &b_Reco_QQ_mupl_nMuValHits);  // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mupl_nPixWMea",&Reco_QQ_mupl_nPixWMea,&b_Reco_QQ_mupl_nPixWMea); // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mupl_nTrkWMea",&Reco_QQ_mupl_nTrkWMea,&b_Reco_QQ_mupl_nTrkWMea); // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mupl_pt_inner",&Reco_QQ_mupl_pt_inner,&b_Reco_QQ_mupl_pt_inner); // new float, unused.
  t->SetBranchAddress("Reco_QQ_mupl_pt_global",&Reco_QQ_mupl_pt_global,&b_Reco_QQ_mupl_pt_global);//new float, unused.
  t->SetBranchAddress("Reco_QQ_mupl_ptErr_inner",&Reco_QQ_mupl_ptErr_inner,&b_Reco_QQ_mupl_ptErr_inner); // new float, unused.
  t->SetBranchAddress("Reco_QQ_mupl_ptErr_global",&Reco_QQ_mupl_ptErr_global,&b_Reco_QQ_mupl_ptErr_global);//new float, unused.
  //muminus
  t->SetBranchAddress("Reco_QQ_mumi_nTrkHits", &Reco_QQ_mumi_nTrkHits, &b_Reco_QQ_mumi_nTrkHits);
  t->SetBranchAddress("Reco_QQ_mumi_normChi2_inner", &Reco_QQ_mumi_normChi2_inner, &b_Reco_QQ_mumi_normChi2_inner);
  t->SetBranchAddress("Reco_QQ_mumi_normChi2_global", &Reco_QQ_mumi_normChi2_global, &b_Reco_QQ_mumi_normChi2_global);
  t->SetBranchAddress("Reco_QQ_mumi_dxy", &Reco_QQ_mumi_dxy, &b_Reco_QQ_mumi_dxy);
  t->SetBranchAddress("Reco_QQ_mumi_dz", &Reco_QQ_mumi_dz, &b_Reco_QQ_mumi_dz);
  t->SetBranchAddress("Reco_QQ_mumi_dxyErr", &Reco_QQ_mumi_dxyErr, &b_Reco_QQ_mumi_dxyErr);
  t->SetBranchAddress("Reco_QQ_mumi_dzErr", &Reco_QQ_mumi_dzErr, &b_Reco_QQ_mumi_dzErr);
  t->SetBranchAddress("Reco_QQ_mumi_TrkMuArb", &Reco_QQ_mumi_TrkMuArb, &b_Reco_QQ_mumi_TrkMuArb);  
  t->SetBranchAddress("Reco_QQ_mumi_TMOneStaTight", &Reco_QQ_mumi_TMOneStaTight, &b_Reco_QQ_mumi_TMOneStaTight);  // new bool, unused in upsilon(?)
  t->SetBranchAddress("Reco_QQ_mumi_nMuValHits", &Reco_QQ_mumi_nMuValHits, &b_Reco_QQ_mumi_nMuValHits);  // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mumi_nPixWMea",&Reco_QQ_mumi_nPixWMea,&b_Reco_QQ_mumi_nPixWMea); // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mumi_nTrkWMea",&Reco_QQ_mumi_nTrkWMea,&b_Reco_QQ_mumi_nTrkWMea); // new int, unused in upsilon
  t->SetBranchAddress("Reco_QQ_mumi_StationsMatched",&Reco_QQ_mumi_StationsMatched, &b_Reco_QQ_mumi_StationsMatched); // new int, unused in Upsilon
  t->SetBranchAddress("Reco_QQ_mumi_pt_inner",&Reco_QQ_mumi_pt_inner,&b_Reco_QQ_mumi_pt_inner); // new float, unused.
  t->SetBranchAddress("Reco_QQ_mumi_pt_global",&Reco_QQ_mumi_pt_global,&b_Reco_QQ_mumi_pt_global);//new float, unused.
  t->SetBranchAddress("Reco_QQ_mumi_ptErr_inner",&Reco_QQ_mumi_ptErr_inner,&b_Reco_QQ_mumi_ptErr_inner); // new float, unused.
  t->SetBranchAddress("Reco_QQ_mumi_ptErr_global",&Reco_QQ_mumi_ptErr_global,&b_Reco_QQ_mumi_ptErr_global);//new float, unused.
  //dimuons
  t->SetBranchAddress("Reco_QQ_dca",    &Reco_QQ_dca,   &b_Reco_QQ_dca); 
  t->SetBranchAddress("Reco_QQ_trig",  &Reco_QQ_trig, &b_Reco_QQ_trig);
  t->SetBranchAddress("Reco_QQ_VtxProb",   &Reco_QQ_VtxProb,    &b_Reco_QQ_VtxProb);
  t->SetBranchAddress("Reco_QQ_ctau",  &Reco_QQ_ctau, &b_Reco_QQ_ctau);
  t->SetBranchAddress("Reco_QQ_ctauErr",  &Reco_QQ_ctauErr, &b_Reco_QQ_ctauErr);
  t->SetBranchAddress("Reco_QQ_ctauTrue",  &Reco_QQ_ctauTrue, &b_Reco_QQ_ctauTrue);
  t->SetBranchAddress("zVtx",             &zVtx,              &b_zVtx);
  // extra centrality variables
  t->SetBranchAddress("Npix",             &Npix,              &b_Npix);
  t->SetBranchAddress("NpixelTracks",     &NpixelTracks,      &b_NpixelTracks);
  t->SetBranchAddress("Ntracks",          &Ntracks,           &b_Ntracks);
  t->SetBranchAddress("SumET_HF",         &SumET_HF,          &b_SumET_HF);
  t->SetBranchAddress("SumET_HFplus",     &SumET_HFplus,      &b_SumET_HFplus);
  t->SetBranchAddress("SumET_HFminus",    &SumET_HFminus,     &b_SumET_HFminus);
  t->SetBranchAddress("SumET_HFplusEta4", &SumET_HFplusEta4,  &b_SumET_HFplusEta4);
  t->SetBranchAddress("SumET_HFminusEta4",&SumET_HFminusEta4, &b_SumET_HFminusEta4);
  t->SetBranchAddress("SumET_ET",         &SumET_ET,          &b_SumET_ET);
  t->SetBranchAddress("SumET_EE",         &SumET_EE,          &b_SumET_EE);
  t->SetBranchAddress("SumET_EB",         &SumET_EB,          &b_SumET_EB);
  t->SetBranchAddress("SumET_EEplus",     &SumET_EEplus,      &b_SumET_EEplus);
  t->SetBranchAddress("SumET_EEminus",    &SumET_EEminus,     &b_SumET_EEminus);
  t->SetBranchAddress("SumET_ZDC"    ,    &SumET_ZDC,         &b_SumET_ZDC);
  t->SetBranchAddress("SumET_ZDCplus",    &SumET_ZDCplus,     &b_SumET_ZDCplus);
  t->SetBranchAddress("SumET_ZDCminus",   &SumET_ZDCminus,    &b_SumET_ZDCminus);
  
  // extra track variable  
  t->SetBranchAddress("Reco_trk_size",  &Reco_trk_size,   &b_Reco_trk_size);
  t->SetBranchAddress("Reco_trk_4mom",  &Reco_trk_4mom,   &b_Reco_trk_4mom);
  t->SetBranchAddress("Reco_trk_vtx",   &Reco_trk_vtx,    &b_Reco_trk_vtx);

  // #### define control histograms
  TH1F *h_QQ_mass   = new TH1F("h_QQ_mass","",nBins, mass_min,mass_max);  // all OS
  TH1F *h_QQ_mass_1 = new TH1F("h_QQ_mass_1","",nBins, mass_min,mass_max);// OS in acceptance
  TH1F *h_QQ_mass_2 = new TH1F("h_QQ_mass_2","",nBins, mass_min, mass_max);// SS 
  
  // ##### output file
  TFile *f1 = new TFile(Form("../dimuonTree_%s_Run%s_trigBit%d_allTriggers%d.root",dataSource,runNumber,nTriggerBit,bAllTriggers),"RECREATE");

  TTree *MuTree              = new TTree("MuTree","MuTree");
  TTree *UpsilonTree         = new TTree("UpsilonTree","UpsilonTree");
  TTree *UpsilonTree_allsign = new TTree("UpsilonTree_allsign","UpsilonTree_allsign");
  TTree *UpsilonTree_trkRot  = new TTree("UpsilonTree_trkRot","UpsilonTree_trkRot");

  MuTree->Branch("Reco_mu_size",   &Reco_mu_size,   "Reco_mu_size/I");
  MuTree->Branch("nPlusMu",        &nPlusMu,        "nPlusMu/I");
  MuTree->Branch("nMinusMu",       &nMinusMu,       "nMinusMu/I");
  MuTree->Branch("muPt",           &muPt,           "muPt[Reco_mu_size]/F");
  MuTree->Branch("muEta",          &muEta,          "muEta[Reco_mu_size]/F");
  MuTree->Branch("muPhi",          &muPhi,          "muPhi[Reco_mu_size]/F");
  MuTree->Branch("Reco_mu_type",   &Reco_mu_type,    "Reco_mu_type[Reco_mu_size]/I");
  MuTree->Branch("Reco_mu_charge", &Reco_mu_charge,  "Reco_mu_charge[Reco_mu_size]/I" );
  MuTree->Branch("eventNb",        &eventNb,        "eventNb/I");
  MuTree->Branch("runNb",          &runNb,          "runNb/I");

  //UpsilonTree->Branch("nReco_QQ", &nReco_QQ, "nReco_QQ/I");
  UpsilonTree->Branch("Centrality",    &Centrality,    "Centrality/I");
  UpsilonTree->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
  UpsilonTree->Branch("QQsign",        &QQsign,        "QQsign/I");
  UpsilonTree->Branch("QQTrkDr03",     &QQTrkDr03,     "QQTrkDr03/I");
  UpsilonTree->Branch("QQTrkDr04",     &QQTrkDr04,     "QQTrkDr04/I");
  UpsilonTree->Branch("QQTrkDr05",     &QQTrkDr05,     "QQTrkDr05/I");

  UpsilonTree->Branch("QQTrkPt02",     &QQTrkPt02,     "QQTrkPt02/I");
  UpsilonTree->Branch("QQTrkPt03",     &QQTrkPt03,     "QQTrkPt03/I");
  UpsilonTree->Branch("QQTrkPt04",     &QQTrkPt04,     "QQTrkPt04/I");
  
  UpsilonTree->Branch("eventNb",       &eventNb,     "eventNb/I");
  UpsilonTree->Branch("runNb",         &runNb,     "runNb/I");
  UpsilonTree->Branch("invariantMass", &invariantMass, "invariantMass/F");
  UpsilonTree->Branch("upsPt",         &upsPt, "upsPt/F");
  UpsilonTree->Branch("upsEta",        &upsEta, "upsEta/F");
  UpsilonTree->Branch("upsPhi",        &upsPhi, "upsPhi/F");
  UpsilonTree->Branch("upsRapidity",   &upsRapidity, "upsRapidity/F");
  UpsilonTree->Branch("muPlusPt",      &muPlusPt, "muPlusPt/F");
  UpsilonTree->Branch("muMinusPt",     &muMinusPt, "muMinusPt/F");
  UpsilonTree->Branch("muPlusEta",     &muPlusEta, "muPlusEta/F");
  UpsilonTree->Branch("muMinusEta",    &muMinusEta, "muMinusEta/F");
  UpsilonTree->Branch("muPlusPhi",     &muPlusPhi, "muPlusPhi/F");
  UpsilonTree->Branch("muMinusPhi",    &muMinusPhi, "muMinusPhi/F");
  // additional selection
  // id muplus
  UpsilonTree->Branch("_mupl_TrkMuArb",&_mupl_TrkMuArb,"_mupl_TrkMuArb/O");
  UpsilonTree->Branch("_mupl_TMOneStaTight",&_mupl_TMOneStaTight,"_mupl_TMOneStaTight/O");  // new bool, unused in upsilon(?)
  UpsilonTree->Branch("_mupl_nMuValHits",&_mupl_nMuValHits,"_mupl_nMuValHits/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mupl_nPixWMea",&_mupl_nPixWMea,"_mupl_nPixWMea/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mupl_nTrkWMea",&_mupl_nTrkWMea,"_mupl_nTrkWMea/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mupl_StationsMatched",&_mupl_StationsMatched,"_mupl_StationsMatched/I"); // new int, unused in Upsilon
  UpsilonTree->Branch("_mupl_pt_inner",&_mupl_pt_inner,"_mupl_pt_inner/F"); // new float, unused.
  UpsilonTree->Branch("_mupl_pt_global",&_mupl_pt_global,"_mupl_pt_global/F"); //new float, unused.
  UpsilonTree->Branch("_mupl_ptErr_inner",&_mupl_ptErr_inner,"_mupl_ptErr_inner/F"); // new float, unused.
  UpsilonTree->Branch("_mupl_ptErr_global",&_mupl_ptErr_global,"_mupl_ptErr_global/F"); //new float, unused.
  UpsilonTree->Branch("_mupl_nTrkHits",&_mupl_nTrkHits," _mupl_nTrkHits/I");
  UpsilonTree->Branch("_mupl_normChi2_inner", &_mupl_normChi2_inner," _mupl_normChi2_inner/F");
  UpsilonTree->Branch("_mupl_normChi2_global",&_mupl_normChi2_global,"_mupl_normChi2_global/F");
  UpsilonTree->Branch("_mupl_dxy",&_mupl_dxy,"_mupl_dxy/F");
  UpsilonTree->Branch("_mupl_dxyErr",&_mupl_dxyErr,"_mupl_dxyErr/F");
  UpsilonTree->Branch("_mupl_dz",&_mupl_dz,"_mupl_dz/F");
  UpsilonTree->Branch("_mupl_dzErr",&_mupl_dzErr,"_mupl_dzErr/F");
  //id muminus
  UpsilonTree->Branch("_mumi_TrkMuArb",&_mumi_TrkMuArb,"_mumi_TrkMuArb/O");
  UpsilonTree->Branch("_mumi_TMOneStaTight",&_mumi_TMOneStaTight,"_mumi_TMOneStaTight/O");  // new bool, unused in upsilon(?)
  UpsilonTree->Branch("_mumi_nMuValHits",&_mumi_nMuValHits,"_mumi_nMuValHits/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mumi_nPixWMea",&_mumi_nPixWMea,"_mumi_nPixWMea/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mumi_nTrkWMea",&_mumi_nTrkWMea,"_mumi_nTrkWMea/I"); // new int, unused in upsilon
  UpsilonTree->Branch("_mumi_StationsMatched",&_mumi_StationsMatched,"_mumi_StationsMatched/I"); // new int, unused in Upsilon
  UpsilonTree->Branch("_mumi_pt_inner",&_mumi_pt_inner,"_mumi_pt_inner/F"); // new float, unused.
  UpsilonTree->Branch("_mumi_pt_global",&_mumi_pt_global,"_mumi_pt_global/F"); //new float, unused.
  UpsilonTree->Branch("_mumi_ptErr_inner",&_mumi_ptErr_inner,"_mumi_ptErr_inner/F"); // new float, unused.
  UpsilonTree->Branch("_mumi_ptErr_global",&_mumi_ptErr_global,"_mumi_ptErr_global/F"); //new float, unused.
  UpsilonTree->Branch("_mumi_nTrkHits",&_mumi_nTrkHits," _mumi_nTrkHits/I");
  UpsilonTree->Branch("_mumi_normChi2_inner", &_mumi_normChi2_inner," _mumi_normChi2_inner/F");
  UpsilonTree->Branch("_mumi_normChi2_global",&_mumi_normChi2_global,"_mumi_normChi2_global/F");
  UpsilonTree->Branch("_mumi_dxy",&_mumi_dxy,"_mumi_dxy/F");
  UpsilonTree->Branch("_mumi_dxyErr",&_mumi_dxyErr,"_mumi_dxyErr/F");
  UpsilonTree->Branch("_mumi_dz",&_mumi_dz,"_mumi_dz/F");
  UpsilonTree->Branch("_mumi_dzErr",&_mumi_dzErr,"_mumi_dzErr/F");
 //dimuon variables
  UpsilonTree->Branch("QQtrig",        &QQtrig,        "QQtrig/I");
  UpsilonTree->Branch("_dca",&_dca,"_dca/F");// new float, unused in upsilon
  UpsilonTree->Branch("_ctau",&_ctau,"_ctau/F");// new float, unused in upsilon
  UpsilonTree->Branch("_ctauErr",&_ctauErr,"_ctauErr/F");// new float, unused in upsilon
  UpsilonTree->Branch("_ctauTrue",&_ctauTrue,"_ctauTrue/F");// new float, unused in upsilon
  UpsilonTree->Branch("_zVtx",  &_zVtx,"_zVtx/F");
  UpsilonTree->Branch("vProb",         &vProb,     "vProb/F");
  if(addExtraCentrality)
    {
      UpsilonTree->Branch("Npix",&Npix,"Npix/I");
      UpsilonTree->Branch("NpixelTracks",&NpixelTracks,"NpixelTracks/I");
      UpsilonTree->Branch("Ntracks", &Ntracks, "Ntracks/I");
      UpsilonTree->Branch("SumET_HF",&SumET_HF,"SumET_HF/F");
      UpsilonTree->Branch("SumET_HFplus",&SumET_HFplus,"SumET_HFplus/F");
      UpsilonTree->Branch("SumET_HFminus",&SumET_HFminus,"SumET_HFminus/F");
      UpsilonTree->Branch("SumET_HFplusEta4",&SumET_HFplusEta4,"SumET_HFplusEta4/F");
      UpsilonTree->Branch("SumET_HFminusEta4",&SumET_HFminusEta4,"SumET_HFminusEta4/F");
      UpsilonTree->Branch("SumET_ET",&SumET_ET,"SumET_ET/F");
      UpsilonTree->Branch("SumET_EE",&SumET_EE,"SumET_EE/F");
      UpsilonTree->Branch("SumET_EB",&SumET_EB,"SumET_EB/F");
      UpsilonTree->Branch("SumET_EEplus",&SumET_EEplus,"SumET_EEplus/F");
      UpsilonTree->Branch("SumET_EEminus",&SumET_EEminus,"SumET_EEminus/F");
      UpsilonTree->Branch("SumET_ZDC",&SumET_ZDC,"SumET_ZDC/F");
      UpsilonTree->Branch("SumET_ZDCplus",&SumET_ZDCplus,"SumET_ZDCplus/F");
      UpsilonTree->Branch("SumET_ZDCminus",&SumET_ZDCminus,"SumET_ZDCminus/F");
    }

  UpsilonTree_allsign->Branch("Centrality", &Centrality,    "Centrality/I");
  UpsilonTree_allsign->Branch("HLTriggers", &HLTriggers,    "HLTriggers/I");
  UpsilonTree_allsign->Branch("QQtrig",     &QQtrig,    "QQtrig/I");
  UpsilonTree_allsign->Branch("QQsign",     &QQsign,    "QQsign/I");
  UpsilonTree_allsign->Branch("QQTrkDr03",     &QQTrkDr03,     "QQTrkDr03/I");
  UpsilonTree_allsign->Branch("QQTrkDr04",     &QQTrkDr04,     "QQTrkDr04/I");
  UpsilonTree_allsign->Branch("QQTrkDr05",     &QQTrkDr05,     "QQTrkDr05/I");
  UpsilonTree_allsign->Branch("QQTrkPt04",     &QQTrkPt04,     "QQTrkPt04/I");
  UpsilonTree_allsign->Branch("QQTrkPt03",     &QQTrkPt03,     "QQTrkPt03/I");
  UpsilonTree_allsign->Branch("QQTrkPt02",     &QQTrkPt02,     "QQTrkPt02/I");
  UpsilonTree_allsign->Branch("weight",     &weight,    "weight/F");
  UpsilonTree_allsign->Branch("weight2",    &weight2,    "weight2/F");
  UpsilonTree_allsign->Branch("vProb",      &vProb,     "vProb/F");
  UpsilonTree_allsign->Branch("eventNb",    &eventNb,     "eventNb/I");
  UpsilonTree_allsign->Branch("runNb",      &runNb,     "runNb/I");
  UpsilonTree_allsign->Branch("invariantMass", &invariantMass, "invariantMass/F");
  UpsilonTree_allsign->Branch("upsPt",      &upsPt, "upsPt/F");
  UpsilonTree_allsign->Branch("upsEta",     &upsEta, "upsEta/F");
  UpsilonTree_allsign->Branch("upsPhi",     &upsPhi, "upsPhi/F");
  UpsilonTree_allsign->Branch("upsRapidity",&upsRapidity, "upsRapidity/F");
  UpsilonTree_allsign->Branch("muPlusPt",   &muPlusPt, "muPlusPt/F");
  UpsilonTree_allsign->Branch("muMinusPt",  &muMinusPt, "muMinusPt/F");
  UpsilonTree_allsign->Branch("muPlusEta",  &muPlusEta, "muPlusEta/F");
  UpsilonTree_allsign->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
  UpsilonTree_allsign->Branch("muPlusPhi",  &muPlusPhi, "muPlusPhi/F");
  UpsilonTree_allsign->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
  
   if(addExtraCentrality)
    {
      UpsilonTree_allsign->Branch("Npix",&Npix,"Npix/I");
      UpsilonTree_allsign->Branch("NpixelTracks",&NpixelTracks,"NpixelTracks/I");
      UpsilonTree_allsign->Branch("Ntracks", &Ntracks, "Ntracks/I");
      UpsilonTree_allsign->Branch("SumET_HF",&SumET_HF,"SumET_HF/F");
      UpsilonTree_allsign->Branch("SumET_HFplus",&SumET_HFplus,"SumET_HFplus/F");
      UpsilonTree_allsign->Branch("SumET_HFminus",&SumET_HFminus,"SumET_HFminus/F");
      UpsilonTree_allsign->Branch("SumET_HFplusEta4",&SumET_HFplusEta4,"SumET_HFplusEta4/F");
      UpsilonTree_allsign->Branch("SumET_HFminusEta4",&SumET_HFminusEta4,"SumET_HFminusEta4/F");
      UpsilonTree_allsign->Branch("SumET_ET",&SumET_ET,"SumET_ET/F");
      UpsilonTree_allsign->Branch("SumET_EE",&SumET_EE,"SumET_EE/F");
      UpsilonTree_allsign->Branch("SumET_EB",&SumET_EB,"SumET_EB/F");
      UpsilonTree_allsign->Branch("SumET_EEplus",&SumET_EEplus,"SumET_EEplus/F");
      UpsilonTree_allsign->Branch("SumET_EEminus",&SumET_EEminus,"SumET_EEminus/F");
      UpsilonTree_allsign->Branch("SumET_ZDC",&SumET_ZDC,"SumET_ZDC/F");
      UpsilonTree_allsign->Branch("SumET_ZDCplus",&SumET_ZDCplus,"SumET_ZDCplus/F");
      UpsilonTree_allsign->Branch("SumET_ZDCminus",&SumET_ZDCminus,"SumET_ZDCminus/F");
    }

  UpsilonTree_trkRot->Branch("Centrality", &Centrality,    "Centrality/I");
  UpsilonTree_trkRot->Branch("HLTriggers", &HLTriggers,    "HLTriggers/I");
  UpsilonTree_trkRot->Branch("QQtrig",     &QQtrig,    "QQtrig/I");
  UpsilonTree_trkRot->Branch("QQsign",     &QQsign,    "QQsign/I");
  UpsilonTree_trkRot->Branch("QQTrkDr03",     &QQTrkDr03,     "QQTrkDr03/I");
  UpsilonTree_trkRot->Branch("QQTrkDr04",     &QQTrkDr04,     "QQTrkDr04/I");
  UpsilonTree_trkRot->Branch("QQTrkDr05",     &QQTrkDr05,     "QQTrkDr05/I");
  UpsilonTree_trkRot->Branch("QQTrkPt04",     &QQTrkPt04,     "QQTrkPt04/I");
  UpsilonTree_trkRot->Branch("QQTrkPt03",     &QQTrkPt03,     "QQTrkPt03/I");
  UpsilonTree_trkRot->Branch("QQTrkPt02",     &QQTrkPt02,     "QQTrkPt02/I");

  UpsilonTree_trkRot->Branch("weight",     &weight,    "weight/F");
  UpsilonTree_trkRot->Branch("weight2",    &weight2,    "weight2/F");
  UpsilonTree_trkRot->Branch("vProb",      &vProb,     "vProb/F");
  UpsilonTree_trkRot->Branch("eventNb",    &eventNb,     "eventNb/I");
  UpsilonTree_trkRot->Branch("runNb",      &runNb,     "runNb/I");
  UpsilonTree_trkRot->Branch("invariantMass", &invariantMass, "invariantMass/F");
  UpsilonTree_trkRot->Branch("upsPt",      &upsPt, "upsPt/F");
  UpsilonTree_trkRot->Branch("upsEta",     &upsEta, "upsEta/F");
  UpsilonTree_trkRot->Branch("upsPhi",     &upsPhi, "upsPhi/F");
  UpsilonTree_trkRot->Branch("upsRapidity",&upsRapidity, "upsRapidity/F");
  UpsilonTree_trkRot->Branch("muPlusPt",   &muPlusPt, "muPlusPt/F");
  UpsilonTree_trkRot->Branch("muMinusPt",  &muMinusPt, "muMinusPt/F");
  UpsilonTree_trkRot->Branch("muPlusEta",  &muPlusEta, "muPlusEta/F");
  UpsilonTree_trkRot->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
  UpsilonTree_trkRot->Branch("muPlusPhi",  &muPlusPhi, "muPlusPhi/F");
  UpsilonTree_trkRot->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
  if(addExtraCentrality)
    {
      UpsilonTree_trkRot->Branch("Npix",&Npix,"Npix/I");
      UpsilonTree_trkRot->Branch("NpixelTracks",&NpixelTracks,"NpixelTracks/I");
      UpsilonTree_trkRot->Branch("Ntracks", &Ntracks, "Ntracks/I");
      UpsilonTree_trkRot->Branch("SumET_HF",&SumET_HF,"SumET_HF/F");
      UpsilonTree_trkRot->Branch("SumET_HFplus",&SumET_HFplus,"SumET_HFplus/F");
      UpsilonTree_trkRot->Branch("SumET_HFminus",&SumET_HFminus,"SumET_HFminus/F");
      UpsilonTree_trkRot->Branch("SumET_HFplusEta4",&SumET_HFplusEta4,"SumET_HFplusEta4/F");
      UpsilonTree_trkRot->Branch("SumET_HFminusEta4",&SumET_HFminusEta4,"SumET_HFminusEta4/F");
      UpsilonTree_trkRot->Branch("SumET_ET",&SumET_ET,"SumET_ET/F");
      UpsilonTree_trkRot->Branch("SumET_EE",&SumET_EE,"SumET_EE/F");
      UpsilonTree_trkRot->Branch("SumET_EB",&SumET_EB,"SumET_EB/F");
      UpsilonTree_trkRot->Branch("SumET_EEplus",&SumET_EEplus,"SumET_EEplus/F");
      UpsilonTree_trkRot->Branch("SumET_EEminus",&SumET_EEminus,"SumET_EEminus/F");
      UpsilonTree_trkRot->Branch("SumET_ZDC",&SumET_ZDC,"SumET_ZDC/F");
      UpsilonTree_trkRot->Branch("SumET_ZDCplus",&SumET_ZDCplus,"SumET_ZDCplus/F");
      UpsilonTree_trkRot->Branch("SumET_ZDCminus",&SumET_ZDCminus,"SumET_ZDCminus/F");
    }


  //____________________________________ loop over all events
  for (int i=0; i<nentries; i++) 
    {
      t->GetEntry(i);
      //      if(excludeWrongAlign_pa && runNb<=210658) continue;
     

      // ##### single muon tree
      // countng + and - single muons
      nPlusMu=0;
      nMinusMu=0;
      for(int iMu = 0; iMu < Reco_mu_size; iMu++)
	{
	  if (Reco_mu_charge[iMu] == 1) nPlusMu++;
	  else nMinusMu++;
	  TLorentzVector *Reco_mu = (TLorentzVector *) Reco_mu_4mom->At(iMu);
	  muPt[iMu]=Reco_mu->Pt();
	  muEta[iMu]=Reco_mu->Eta();
	  muPhi[iMu]=Reco_mu->Phi();
	}
      MuTree->Fill();

      // // ntrk loop
      //  for(int iTrk = 0; iTrk < Reco_trk_size; iTrk++)
      // 	{
      // 	  TLorentzVector *Reco_trk = (TLorentzVector *) Reco_trk_4mom->At(iTrk);
      // 	  trkPt[iTrk]=Reco_trk->Pt();
      // 	  trkEta[iTrk]=Reco_trk->Eta();
      // 	  trkPhi[iTrk]=Reco_trk->Phi();
      // 	}

      //----------------------------------------------------
       for(int iQQ = 0; iQQ < Reco_QQ_size; iQQ++)
	{
	  vProb  = Reco_QQ_VtxProb[iQQ];
	  QQsign = Reco_QQ_sign[iQQ];
	  
	  QQTrkDr03 = Reco_QQ_NtrkDeltaR03[iQQ];
	  QQTrkDr04 = Reco_QQ_NtrkDeltaR04[iQQ];
	  QQTrkDr05 = Reco_QQ_NtrkDeltaR05[iQQ];

	  QQTrkPt04 = Reco_QQ_NtrkPt04[iQQ];
	  QQTrkPt03 = Reco_QQ_NtrkPt03[iQQ];
	  QQTrkPt02 = Reco_QQ_NtrkPt02[iQQ];

	  //	  have to red a bit about the weighting Zhen calculates ...
	  if (Reco_QQ_sign[iQQ] == 0) // opposite sign
	    { 
	      weight  = 1;
	      weight2 = 1;
	    }
	  else // same sign
	    {
	      weight  = -1;
	      float likesign_comb        = (float)nPlusMu*(nPlusMu-1.0)/2.0+(float)nMinusMu*(nMinusMu-1.0)/2.0; // number of combinatorial pairs C(nplus)^2, C(nminus)^2
	    float unlikesign_bkgd_comb = (float)nPlusMu*nMinusMu - (nPlusMu>nMinusMu?nMinusMu:nPlusMu);
	    weight2 = -1.0 * unlikesign_bkgd_comb/likesign_comb;
	    }
	  
	  // dimuon variables
	  TLorentzVector *Reco_QQ      = (TLorentzVector *) Reco_QQ_4mom->At(iQQ);
	  TLorentzVector *Reco_QQ_mupl = (TLorentzVector *) Reco_QQ_mupl_4mom->At(iQQ);
	  TLorentzVector *Reco_QQ_mumi = (TLorentzVector *) Reco_QQ_mumi_4mom->At(iQQ);
	  invariantMass = Reco_QQ->M();
	  upsPt         = Reco_QQ->Pt();
	  upsEta        = Reco_QQ->Eta();
	  upsPhi        = Reco_QQ->Phi();
	  upsRapidity   = Reco_QQ->Rapidity();
	  
	  // single muon variables
	  muMinusPt     = Reco_QQ_mumi->Pt();
	  muMinusEta    = Reco_QQ_mumi->Eta();
	  muMinusPhi    = Reco_QQ_mumi->Phi();
	  muPlusPt      = Reco_QQ_mupl->Pt();
	  muPlusEta     = Reco_QQ_mupl->Eta();
	  muPlusPhi     = Reco_QQ_mupl->Phi();
	  	  
	  // apply extra selection
	  // id muplus

	  _mupl_nTrkHits       = Reco_QQ_mupl_nTrkHits[iQQ];
	  _mupl_normChi2_inner = Reco_QQ_mupl_normChi2_inner[iQQ];
	  _mupl_normChi2_global= Reco_QQ_mupl_normChi2_global[iQQ];
	  _mupl_dxy            = Reco_QQ_mupl_dxy[iQQ];
	  _mupl_dxyErr         = Reco_QQ_mupl_dxyErr[iQQ];
	  _mupl_dz             = Reco_QQ_mupl_dz[iQQ];
	  _mupl_dzErr          = Reco_QQ_mupl_dzErr[iQQ];
	  _mupl_TrkMuArb       = Reco_QQ_mupl_TrkMuArb[iQQ];
	  _mupl_TMOneStaTight  = Reco_QQ_mupl_TMOneStaTight[iQQ];
	  _mupl_nMuValHits     = Reco_QQ_mupl_nMuValHits[iQQ];
	  _mupl_nPixWMea       = Reco_QQ_mupl_nPixWMea[iQQ];
	  _mupl_nTrkWMea       = Reco_QQ_mupl_nTrkWMea[iQQ];
	  _mupl_StationsMatched = Reco_QQ_mupl_StationsMatched[iQQ]; 
	  _mupl_pt_inner      = Reco_QQ_mupl_pt_inner[iQQ];
	  _mupl_pt_global     = Reco_QQ_mupl_pt_global[iQQ];
	  _mupl_ptErr_inner   = Reco_QQ_mupl_ptErr_inner[iQQ];
	  _mupl_ptErr_global  = Reco_QQ_mupl_ptErr_global[iQQ];

	  // id muminus
	  
	  _mumi_nTrkHits       = Reco_QQ_mumi_nTrkHits[iQQ];
	  _mumi_normChi2_inner = Reco_QQ_mumi_normChi2_inner[iQQ];
	  _mumi_normChi2_global= Reco_QQ_mumi_normChi2_global[iQQ];
	  _mumi_dxy            = Reco_QQ_mumi_dxy[iQQ];
	  _mumi_dxyErr         = Reco_QQ_mumi_dxyErr[iQQ];
	  _mumi_dz             = Reco_QQ_mumi_dz[iQQ];
	  _mumi_dzErr          = Reco_QQ_mumi_dzErr[iQQ];
	  _mumi_TrkMuArb       = Reco_QQ_mumi_TrkMuArb[iQQ];	
	  _mumi_TMOneStaTight  =Reco_QQ_mumi_TMOneStaTight[iQQ];
	  _mumi_nMuValHits     = Reco_QQ_mumi_nMuValHits[iQQ];
	  _mumi_nPixWMea       = Reco_QQ_mumi_nPixWMea[iQQ];
	  _mumi_nTrkWMea       = Reco_QQ_mumi_nTrkWMea[iQQ];
	  _mumi_StationsMatched = Reco_QQ_mumi_StationsMatched[iQQ];
	  _mumi_pt_inner       = Reco_QQ_mumi_pt_inner[iQQ]; 
	  _mumi_pt_global      = Reco_QQ_mumi_pt_global[iQQ];
	  _mumi_ptErr_inner    = Reco_QQ_mumi_ptErr_inner[iQQ];
	  _mumi_ptErr_global   = Reco_QQ_mumi_ptErr_global[iQQ];

	  //dimuon variables
	  
	  QQtrig = Reco_QQ_trig[iQQ];
	  _ctau = (invariantMass/3.0968)*Reco_QQ_ctau[iQQ];
  	  _ctauTrue = (invariantMass/3.0968)*Reco_QQ_ctauTrue[iQQ];
  	  _ctauErr = (invariantMass/3.0968)*Reco_QQ_ctauErr[iQQ];
	  _zVtx=zVtx[iQQ];	     
	  _dca=Reco_QQ_dca[iQQ];
	 
	  bool bProcess = false;
	  if(!bAllTriggers) bProcess = ((HLTriggers&nTriggerBit)==nTriggerBit && (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit && 
					vProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut);
	  // for PbPB sample, the v1 and v2 same trigger is in nNtriggerBit=1 and nTriggerBit=2 respectivelly
	  /* if(isAArereco) bProcess = (( ( (HLTriggers&nTriggerBit)==nTriggerBit && (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit ) || 
	  			       ( (HLTriggers&(nTriggerBit+1))==(nTriggerBit+1) && (Reco_QQ_trig[iQQ]&(nTriggerBit+1))==(nTriggerBit+1) ) )
				       &&  vProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut);*/
	  //special case of a new tree in which I match only by filter (I assume this is equivalent as having HLTriggers fired)
	  if(isAArereco) bProcess =  (( (Reco_QQ_trig[iQQ]&(nTriggerBit+1))==(nTriggerBit+1) || (Reco_QQ_trig[iQQ]&nTriggerBit)==nTriggerBit )&& vProb>newVtxProbCut && muMinusPt>ptcut && muPlusPt>ptcut ); 
	  if (bProcess)
	    {
	      if (i%1000==0) 	      cout << i << endl;
	      UpsilonTree_allsign->Fill();// all sign and all mass
	      if (QQsign==0) // opposite sign
		{
		  UpsilonTree->Fill();// OS and all mass
		  if (Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) 
		    {
		      h_QQ_mass->Fill(Reco_QQ->M());// all upsilons in 7->14
		    }
		  if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) 
		    {
		      h_QQ_mass_1->Fill(Reco_QQ->M()); // all OS upsilons in 7->14 and pt_mu>4GeV/c
		    }
		}//opposite sign
	      else // same sign in the acceptance
		if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>mass_min && Reco_QQ->M()<mass_max) 
		  {
		    h_QQ_mass_2->Fill(Reco_QQ->M());// all SS upsilons in 7->14 and pt_mu>4GeV/c
		  }
	      

	  //--------------------------------------------------------
	  // %%%%%%%%%% track rotation: redefine some of the variables, the others remain the same
	  Double_t ran = gRandom->Rndm();
	  
	  if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();
	  else  RmuMinusPhi = muMinusPhi + TMath::Pi();
	    
	  TLorentzVector mu1;
	  mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, RmuPlusPhi, 0.105);
	  TLorentzVector mu2;
	  mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, RmuMinusPhi, 0.105);
	  
	  TLorentzVector dimuon;
	  dimuon = mu1 + mu2;
	  
	  invariantMass = dimuon.M();
	  upsPt         = dimuon.Pt();
	  upsEta        = dimuon.Eta();
	  upsRapidity   = dimuon.Rapidity();

	  UpsilonTree_trkRot->Fill();
	  
	}// if bProcess
      }// for each QQ pair		
    }// for each event in the tree
  
  //  __________________________________________________________________
  // ###### plotting 
  TH1 * phMAxis = new TH1D("phMAxis",";m_{#mu#mu} [GeV/c^{2}];Events/(0.1 GeV/c^{2})",1,mass_min,mass_max);
  phMAxis->SetDirectory(0);
  phMAxis->SetMinimum(1);
  phMAxis->SetMaximum(4e4);

  TCanvas *c1 = new TCanvas("c1","c1");
  phMAxis->Draw();
  
  //h_QQ_mass->GetYaxis()->SetRangeUser(0,180);
  h_QQ_mass->SetMarkerColor(kRed);
  h_QQ_mass->SetMarkerStyle(22);
  h_QQ_mass->Draw("PEsame");
  
  h_QQ_mass_1->SetMarkerColor(kBlue);
  h_QQ_mass_1->SetMarkerStyle(20);
  h_QQ_mass_1->GetXaxis()->CenterTitle(kTRUE);
  h_QQ_mass_1->Draw("PEsame");
  
  //h_QQ_mass_2->GetYaxis()->SetRangeUser(0,400);
  h_QQ_mass_2->SetMarkerColor(kRed);
  h_QQ_mass_2->SetMarkerStyle(24);
  h_QQ_mass_2->GetXaxis()->CenterTitle(kTRUE);
  h_QQ_mass_2->Draw("PEsame");
  
  TLegend *legend = new TLegend(.4,.7,.8,.9);
  legend->SetTextSize(0.025);
  legend->AddEntry(h_QQ_mass,  Form("OS && M [%.1f,%.1f]GeV: %.0f",mass_min, mass_max,h_QQ_mass->Integral(1,nBins)),"P");
  legend->AddEntry(h_QQ_mass_1,Form("OS && M [%.1f,%.1f]GeV && p_{T}>%.1fGeV/c: %.0f",mass_min, mass_max,ptcut,h_QQ_mass_1->Integral(1,nBins)),"P");
  legend->AddEntry(h_QQ_mass_2,Form("SS && M [%.1f,%.1f]GeV && p_{T}>%.1fGeV/c:%.0f",mass_min, mass_max,ptcut,h_QQ_mass_2->Integral(1,nBins)),"P");

  legend->Draw();
  
  h_QQ_mass->Write();
  h_QQ_mass_1->Write();
  h_QQ_mass_2->Write();
  c1->SaveAs(Form("dimuonDistribution_%s_Run%s_trigBit%d_allTriggers%d.pdf",dataSource,runNumber,nTriggerBit,bAllTriggers));
  c1->SaveAs(Form("dimuonDistribution_%s_Run%s_trigBit%d_allTriggers%d.gif",dataSource,runNumber,nTriggerBit,bAllTriggers));
  c1->Write();
  f1->Write();
}
Ejemplo n.º 15
0
void ljpsiresol::Loop(const char* fname, bool isdata, bool ispbpb)
{
//   In a ROOT session, you can do:
//      root> .L ljpsiresol.C
//      root> ljpsiresol t
//      root> t.GetEntry(12); // Fill t data members with entry number 12
//      root> t.Show();       // Show values of entry 12
//      root> t.Show(16);     // Read and show values of entry 16
//      root> t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
   fChain->SetBranchStatus("*",0);  // disable all branches
   fChain->SetBranchStatus("HLTriggers",1);  
   fChain->SetBranchStatus("Centrality",1);  
   fChain->SetBranchStatus("Reco_QQ_*",1);  
   fChain->SetBranchStatus("Gen_QQ_*",!isdata);  
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   TFile *f = new TFile(fname, "RECREATE");
   f->cd();

   // define the histos
   // we need 2 numerators (with and without ctau3d cut), 1 denominator. Let's make them in arrays
   // TH1F *hnum_centmid = new TH1F("hnum_centmid","hnum_centmid",nbins_centmid,bins_centmid);
   vector<TH1F*> hists_mid, hists_fwd, hists_midcent, hists_fwdcent;
   for (int i=0; i<nbins_ptmid; i++) {
      double ptmin = bins_ptmid[i];
      double ptmax = bins_ptmid[i+1];
      TH1F *hist = new TH1F(Form("hmid_pt%.1f-%.1f",ptmin,ptmax),"",70,-0.15,0.2);
      hists_mid.push_back(hist);
   }
   for (int i=0; i<nbins_ptfwd; i++) {
      double ptmin = bins_ptfwd[i];
      double ptmax = bins_ptfwd[i+1];
      TH1F *hist = new TH1F(Form("hfwd_pt%.1f-%.1f",ptmin,ptmax),"",70,-0.15,0.2);
      hists_fwd.push_back(hist);
   }
   for (int i=0; i<nbins_centmid; i++) {
      double centmin = bins_centmid[i];
      double centmax = bins_centmid[i+1];
      TH1F *hist = new TH1F(Form("hmid_cent%.1f-%.1f",centmin,centmax),"",70,-0.15,0.2);
      hists_midcent.push_back(hist);
   }
   for (int i=0; i<nbins_centfwd; i++) {
      double centmin = bins_centfwd[i];
      double centmax = bins_centfwd[i+1];
      TH1F *hist = new TH1F(Form("hfwd_cent%.1f-%.1f",centmin,centmax),"",70,-0.15,0.2);
      hists_fwdcent.push_back(hist);
   }

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      // if (ientry>1000) break;

      // skip the event if Gen_QQ_size != 1 for now
      TLorentzVector *tlvgenpl=NULL, *tlvgenmi=NULL, *tlvgenqq=NULL;
      if (!isdata) {
         b_Gen_QQ_size->GetEntry(ientry); //read only this branch
         if (Gen_QQ_size !=1) continue;

         // apply gen acceptance cuts
         b_Gen_QQ_mupl_4mom->GetEntry(ientry); //read only this branch
         b_Gen_QQ_mumi_4mom->GetEntry(ientry); //read only this branch
         tlvgenpl = (TLorentzVector*) Gen_QQ_mupl_4mom->At(0);
         tlvgenmi = (TLorentzVector*) Gen_QQ_mumi_4mom->At(0);
         if (!isGlobalMuonInAccept2015(tlvgenpl) || !isGlobalMuonInAccept2015(tlvgenmi)) continue;

         // fill denominators
         b_Gen_QQ_4mom->GetEntry(ientry); //read only this branch
         TLorentzVector *tlvgenqq = (TLorentzVector*) Gen_QQ_4mom->At(0);
         double genpt = tlvgenqq->Pt();
         b_Centrality->GetEntry(ientry); //read only this branch

         // check that the dimuon is inside the analysis bins
         bool gen_inbin = false;
         if (fabs(tlvgenqq->Rapidity())<1.6 && tlvgenqq->Pt()>6.5 && tlvgenqq->Pt()<30.) gen_inbin = true;
         if (fabs(tlvgenqq->Rapidity())>1.6 && fabs(tlvgenqq->Rapidity())<2.4 && tlvgenqq->Pt()>3. && tlvgenqq->Pt()<30.) gen_inbin = true;
         if (!gen_inbin) continue;
      }

      double weight = ispbpb ? fChain->GetWeight()*findNcoll(Centrality) : 1.;

      // is there at least one reco dimuon?
      b_Reco_QQ_size->GetEntry(ientry);
      if (Reco_QQ_size==0) continue;

      // ok, now read all other branches
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      // loop on the reconstructed dimuons to find the one matched to the gen one
      double mindr=999.;
      int ibestqq=-1;
      for (int i=0; i<Reco_QQ_size; i++) {
         // acceptance
         if (!areMuonsInAcceptance2015(i)) continue;
         // sign
         if (Reco_QQ_sign[i]!=0) continue;
         // quality cuts
         if (!passQualityCuts2015(i)) continue;
         // trigger matching
         if (!isTriggerMatch(i,0)) continue; // HLT_HIL1DoubleMu0_v1
         // mass cut
         double mass = ((TLorentzVector*) Reco_QQ_4mom->At(i))->M();
         double mass0 = massjpsi;
         if (mass<(mass0-massdown) || mass>(mass0+massup)) continue;
         // check that the dimuon is inside the analysis bins
         bool rec_inbin = false;
         TLorentzVector *tlvrecqq = (TLorentzVector*) Reco_QQ_4mom->At(i);
         if (fabs(tlvrecqq->Rapidity())<1.6 && tlvrecqq->Pt()>6.5 && tlvrecqq->Pt()<30.) rec_inbin = true;
         if (fabs(tlvrecqq->Rapidity())>1.6 && fabs(tlvrecqq->Rapidity())<2.4 && tlvrecqq->Pt()>3. && tlvrecqq->Pt()<30.) rec_inbin = true;
         if (!rec_inbin) continue;
         // gen-reco matching
         TLorentzVector *tlvrecpl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(i);
         TLorentzVector *tlvrecmi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(i);
         if (!isdata) {
            double dr = max(tlvrecpl->DeltaR(*tlvgenpl),tlvrecmi->DeltaR(*tlvgenmi));
            if (dr<mindr) {
               mindr = dr;
               ibestqq = i;
            }
         } else {
            ibestqq=0;
         }
      } // Reco_QQ loop

      if (ibestqq<0) continue;

      // fill the numerators
      TLorentzVector *tlvrecqq = (TLorentzVector*) Reco_QQ_4mom->At(ibestqq);
      double rap = fabs(tlvrecqq->Rapidity());
      double pt = tlvrecqq->Pt();

      if (rap<1.6) {
         for (int i=0; i<nbins_ptmid; i++)
            if (pt>=bins_ptmid[i]&&pt<bins_ptmid[i+1])
               hists_mid[i]->Fill(Reco_QQ_ctau3D[ibestqq],weight);
         for (int i=0; i<nbins_centmid; i++)
            if (Centrality>=bins_centmid[i]&&Centrality<bins_centmid[i+1])
               hists_midcent[i]->Fill(Reco_QQ_ctau3D[ibestqq],weight);
      } else if (rap<2.4) {
         for (int i=0; i<nbins_ptfwd; i++)
            if (pt>=bins_ptfwd[i]&&pt<bins_ptfwd[i+1])
               hists_fwd[i]->Fill(Reco_QQ_ctau3D[ibestqq],weight);
         for (int i=0; i<nbins_centfwd; i++)
            if (Centrality>=bins_centfwd[i]&&Centrality<bins_centfwd[i+1])
               hists_fwdcent[i]->Fill(Reco_QQ_ctau3D[ibestqq],weight);
      }
   } // event loop

   f->Write();
   f->Close();
}
Ejemplo n.º 16
0
void xAna_ele_selection(TString inputFile, TCanvas *c1 , TCanvas *c2 , TCanvas *c3 ,TCanvas *c4 ,TCanvas *c5 , TCanvas *c6 ,
int mass_point ,double eff,double eff_err, TString dir_name, int dir_flag ,int signal_background_flag, int background_file_index ){


  // define histograms

  TString title2 = Form("ele pT for Zprime mass = %d",mass_point);
  TString title3 = Form("lepton pairs' pT for Zprime mass = %d",mass_point);
  TString title4 = Form("SD mass for Zprime mass = %d",mass_point);
  TString title5 = Form("Z mass for Zprime mass = %d",mass_point);
  TString title6 = Form("Zprime mass for Zprime mass = %d",mass_point);
  TString title7 = Form("|dEta| of ZH for Zprime mass = %d",mass_point);
  TString title8 = Form("|dPhi| of ZH for Zprime mass = %d",mass_point);
  TString title9 = Form("dR of ZH for Zprime mass = %d",mass_point);

  TH1D* h_ele_pT = new TH1D("h_ele_pT", title2 ,3000 , 0,3000 );
  TH1D* h_lepton_pair_pT = new TH1D("h_lepton_pair_pT", title3 ,400 , 0,4000 );
  TH1D* h_SD =new TH1D("h_SD",title4 ,100,0,200);
  TH1D* h_Z_mass = new TH1D("h_Z_mass",title5 ,250,0,500);
  TH1D* h_Zprime_mass = new TH1D("h_Zprime_mass",title6 ,1000,0,5000);
  TH1D* h_abs_dEta_ZH = new TH1D("h_abs_dEta_ZH",title7 ,120,-1,5);
  TH1D* h_abs_dPhi_ZH = new TH1D("h_abs_dPhi_ZH",title8 ,120,0,6);
  TH1D* h_abs_dR_ZH   = new TH1D("h_abs_dR_ZH"  ,title9 ,120,0,6);

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

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

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

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

    data.GetEntry(jEntry);
    nTotal ++;

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

    // 1. make sure there is a h-> bb, Yu-Hsiang change it
  
    nPass[0]++;
    nPass[1]++;
     
    //2. pass electron or muon trigger
    std::string* trigName = data.GetPtrString("hlt_trigName");
    vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
    const Int_t nsize = data.GetPtrStringSize();

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

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


      }


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


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

    //4. look for good electrons first
    Int_t run          = data.GetInt("runId");
    Int_t lumi         = data.GetInt("lumiSection");
    Int_t event        = data.GetInt("eventId");
    TClonesArray* eleP4 = (TClonesArray*) data.GetPtrTObject("eleP4");


    //5. select good electrons
	
    //6. select a good Z boson

    // Z->e e finder 
    vector<Int_t> Z_electron_index;
    int FindZ_flag =-1;
    FindZ_flag = ZtoEEfinder( data , &Z_electron_index );
    //
    if( FindZ_flag!=1 )   {  continue;}

    TLorentzVector l4_Z(0,0,0,0);

    if(Z_electron_index.size()>0)
    {
        TLorentzVector* Ele1 = (TLorentzVector*)eleP4->At(Z_electron_index[0]);
        TLorentzVector* Ele2 = (TLorentzVector*)eleP4->At(Z_electron_index[1]);

    l4_Z=( *Ele1 + *Ele2);
    }

    nPass[4]++;



    //7.select a good CA8 and cleaned jet
	
    Int_t nJet         = data.GetInt("FATnJet");
    TClonesArray* jetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    Float_t*  jetSDmass = data.GetPtrFloat("FATjetSDmass");
    Float_t*  jetPRmass = data.GetPtrFloat("FATjetPRmass");

    Int_t*   nSubSoftDropJet = data.GetPtrInt("FATnSubSDJet");
    vector<float>   *subjetSDCSV =  data.GetPtrVectorFloat("FATsubjetSDCSV", nJet);

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

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


	// overlap with electron pair of Z 
        bool hasOverLap=false;
	{
        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(Z_electron_index[0]);
        if(thisEle->DeltaR(*thisJet)<0.8)hasOverLap=true;

        TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(Z_electron_index[1]);
        if(thatEle->DeltaR(*thisJet)<0.8)hasOverLap=true;
	}
        if(hasOverLap)continue;
	//

	
	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;


	// at least one sub jet CSV> 0.605
	int nSubBTag=0;
//	if( nSubSoftDropJet[ij]!=2){	  continue;}

	for(int is=0; is < nSubSoftDropJet[ij]; is++)
	  {
	    if(subjetSDCSV[ij][is] < 0.605 || subjetSDCSV[ij][is] >1)continue;
	    nSubBTag++;
	  }
	if(nSubBTag<1) continue;
	//


     	if(!findAJet)
	  {
	    l4_leadingJet = *thisJet;
            SD_Mass.push_back( jetSDmass[ij] );
	    goodJets.push_back(ij);// save leading jet
	  }
	    
     	findAJet=true;

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

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

     double Mass_Point = mass_point;
     double mass_upper = Mass_Point + Mass_Point*0.15;
     double mass_lower = Mass_Point - Mass_Point*0.15;

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

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


{

      int ie = Z_electron_index[0];// leading electron
    TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
    h_ele_pT->Fill( thisEle->Pt() );



}
 

                h_lepton_pair_pT->Fill( l4_Z.Pt() );
                h_Z_mass->Fill( l4_Z.M() );

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

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

    // save delta Eta, delta Phi and delta R BTW reco-Z and reco-H
      {

        int ie_1st = Z_electron_index[0];
        int ie_2nd = Z_electron_index[1];
    	TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie_1st);
    	TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(ie_2nd);

	int ij_1st = goodJets[0];
        TLorentzVector* thisJet = (TLorentzVector*)jetP4->At(ij_1st);

	// get Eta, Phi of Z and H
//        float eta_H = thisJet->Eta();
        float eta_H = thisJet->Rapidity();
        float phi_H = thisJet->Phi();
//        float eta_Z = (*thisEle+*thatEle).Eta();
        float eta_Z = (*thisEle+*thatEle).Rapidity();
        float phi_Z = (*thisEle+*thatEle).Phi();

	// calculate the |dEta|, |dPhi| and dR
	float abs_dEta = fabs(eta_H - eta_Z);
        float abs_dPhi = -99;
	if(fabs(phi_H - phi_Z) < 3.14){ abs_dPhi = fabs(phi_H - phi_Z); }
        if(fabs(phi_H - phi_Z) > 3.14){ abs_dPhi = 6.28 - fabs(phi_H - phi_Z); }
	float dR_ZH = (*thisEle+*thatEle).DeltaR( *thisJet ); 

	// fill histogram
	h_abs_dEta_ZH ->Fill( abs_dEta );
	h_abs_dPhi_ZH ->Fill( abs_dPhi);
	h_abs_dR_ZH   ->Fill( dR_ZH );

      }


  ////////

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

  } // end of loop over entries





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




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


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

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

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





  // Yu-Hsiang add cut flow figure


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

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

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

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

//

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



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

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

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

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

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


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

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

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

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

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

  c6->cd();
  h_Zprime_mass->Draw();
  
  TCanvas *c7 = new TCanvas("c7","",200,10,700,500);
  TCanvas *c8 = new TCanvas("c8","",200,10,700,500);
  TCanvas *c9 = new TCanvas("c9","",200,10,700,500);

  c7->cd();
  h_abs_dEta_ZH->Draw();

  c8->cd();
  h_abs_dPhi_ZH->Draw();

  c9->cd();
  h_abs_dR_ZH->Draw();


////

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


   TString ROOT_name;

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

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

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

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


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

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


   myFile->Close();
   delete myFile;
}


   // delete the finished used TH1D so it will not replacing the existing TH1 (no potential memory leak warning) when loop again 
/*
   delete h_CutFlow;
   delete h_ele_pT;
   delete h_lepton_pair_pT;
   delete h_SD;
   delete h_Z_mass;
*/
}
Ejemplo n.º 17
0
inline float kinematics::ySystem( TLorentzVector* pa, TLorentzVector* pb )
{
	TLorentzVector pTmp = (*pa)+(*pb);
	return pTmp.Rapidity();
}
Ejemplo n.º 18
0
void testsl() {
  gSystem->Load("libStarLight");
  gSystem->Load("libAliStarLight");

  TStarLight* sl = new TStarLight("starlight generator", "title", "");

  sl->SetParameter("baseFileName = slight	#suite of output files will be saved with this base name");
  sl->SetParameter("BEAM_1_Z = 82    #Z of projectile");
  sl->SetParameter("BEAM_1_A = 208   #A of projectile");
  sl->SetParameter("BEAM_2_Z = 82   #Z of target");
  sl->SetParameter("BEAM_2_A = 208   #A of target");
  sl->SetParameter("BEAM_1_GAMMA = 1470.0 #Gamma of the colliding ion 1");
  sl->SetParameter("BEAM_2_GAMMA = 1470.0 #Gamma of the colliding ion 2");
  sl->SetParameter("W_MAX = -1   #Max value of w");
  sl->SetParameter("W_MIN = -1    #Min value of w");
  sl->SetParameter("W_N_BINS = 50    #Bins i w");
  sl->SetParameter("RAP_MAX = 9.    #max y");
  sl->SetParameter("RAP_N_BINS = 200    #Bins i y");
  sl->SetParameter("CUT_PT = 0 #Cut in pT? 0 = (no, 1 = yes)");
  sl->SetParameter("PT_MIN = 1.0 #Minimum pT in GeV");
  sl->SetParameter("PT_MAX = 3.0 #Maximum pT in GeV");
  sl->SetParameter("CUT_ETA = 0 #Cut in pseudorapidity? (0 = no, 1 = yes)");
  sl->SetParameter("ETA_MIN = -10 #Minimum pseudorapidity");
  sl->SetParameter("ETA_MAX = 10 #Maximum pseudorapidity");
  sl->SetParameter("PROD_MODE = 2     #gg or gP switch (1 = 2-photon, 2 = coherent vector meson (narrow), 3 = coherent vector meson (wide), 4 = incoherent vector meson)");
  sl->SetParameter("N_EVENTS = 1000   #Number of events");
  sl->SetParameter("PROD_PID = 443013   #Channel of interest; this is j/psi --> mu+ mu-");
  sl->SetParameter("RND_SEED = 5574533 #Random number seed");
  sl->SetParameter("BREAKUP_MODE = 5     #Controls the nuclear breakup; a 5 here makes no requirement on the breakup of the ions");
  sl->SetParameter("INTERFERENCE = 0     #Interference (0 = off, 1 = on)");
  sl->SetParameter("IF_STRENGTH = 1.    #percent of intefernce (0.0 - 0.1)");
  sl->SetParameter("INT_PT_MAX = 0.24  #Maximum pt considered, when interference is turned on");
  sl->SetParameter("INT_PT_N_BINS =120   #Number of pt bins when interference is turned on");
  sl->SetParameter("XSEC_METHOD = 1 # Set to 0 to use old method for calculating gamma-gamma luminosity");
  sl->SetParameter("PYTHIA_FULL_EVENTRECORD = 0 # Write full pythia information to output (vertex, parents, daughter etc).");

  sl->InitStarLight();
  sl->PrintInputs(std::cout);
  TClonesArray tca("TParticle", 100);

  TLorentzVector v[2], vSum;
  TH1* hM  = new TH1D("hM",  "STARLIGHT;M#(){#pi^{+}#pi^{-}}",    200, 3.0, 3.2);
  TH1* hPt = new TH1D("hPt", "STARLIGHT;P_{T}#(){#pi^{+}#pi^{-}}", 80, 0., 2.);
  TH1* hY  = new TH1D("hY",  "STARLIGHT;Y#(){#pi^{+}#pi^{-}}",    100,-10., 10.);

  std::ofstream ofs("sl.txt");
  TParticle *p;
  for (Int_t counter(0); counter<20000; ) {
    sl->GenerateEvent();
    sl->BoostEvent();
    sl->ImportParticles(&tca, "ALL");
    Bool_t genOK = kTRUE;
    TLorentzVector vSum;
    for (Int_t i=0; i<tca.GetEntries() && genOK; ++i) {
      p = (TParticle*)tca.At(i);
      p->Momentum(v[i]);
      vSum += v[i];
//       genOK = TMath::Abs(v[i].Rapidity()) <= 1.5;
    }
    tca.Clear();
    if (!genOK) continue;
    Printf("%5d %d", counter, genOK);
    ++counter;
    vSum = v[0] + v[1];
    ofs << std::fixed << std::setprecision(4)
	<< vSum.M() << " " << vSum.Perp() << " " << vSum.Rapidity() << " "
	<< v[0].Eta() << " " << v[0].Px() << " " << v[0].Py() << " " << v[0].Pz() << " "
	<< v[1].Eta() << " " << v[1].Px() << " " << v[1].Py() << " " << v[1].Pz()
	<< std::endl;
    hM->Fill(vSum.M());
    hPt->Fill(vSum.Perp());
    hY->Fill(vSum.Rapidity());
  }
  TFile::Open("sl.root", "RECREATE");
  sl->Write();
  gFile->Write();

  hM->Draw();
  c1->SaveAs("SL.pdf(");
  hPt->Draw();
  c1->SaveAs("SL.pdf");
  hY->Draw();
  c1->SaveAs("SL.pdf)");
}
Ejemplo n.º 19
0
Bool_t EventSelector_Unf::Process(Long64_t entry)
{

   //Int_t trig = 0;
   bool isMC = true;  //SHould alkways be true - we will always run it on data

   //FIXME do this before we find a better option
   double Mass_xbin2[7] = {20, 30, 45, 60, 120, 200, 1500};
   double Mass_xbin2_156[8] = {0,20, 30, 45, 60, 120, 200, 1500};

   //FIXME deprecated
   // _runopt = 0;
   // if( momCorrType == "RunC")  _runopt = 1;
   
   // The Process() function is called for each entry in the tree (or possibly
   // keyed object in the case of PROOF) to be processed. The entry argument
   // specifies which entry in the currently loaded tree is to be processed.
   // It can be passed to either EventSelector_Unf::GetEntry() or TBranch::GetEntry()
   // to read either all or the required parts of the data. When processing
   // keyed objects with PROOF, the object is already loaded and is available
   // via the fObject pointer.
   //
   // This function should contain the "body" of the analysis. It can contain
   // simple or elaborate selection criteria, run algorithms on the data
   // of the event and typically fill histograms.
   //
   // The processing can be stopped by calling Abort().
   //
   // Use fStatus to set the return value of TTree::Process().
   //
   // The return value is currently not used.

   // Link to current element, if any
   TString filename = dataset;

   TPair* elemPair = 0;
   if (fInput && (elemPair = dynamic_cast<TPair*>(fInput->FindObject("PROOF_CurrentElement")))) {
     TDSetElement* current = dynamic_cast<TDSetElement*>(elemPair->Value());
     if (current) {
       filename = current->GetFileName();
       if (current->TestBit(TDSetElement::kNewRun)) {
         Info("Process", "entry %lld: starting new run for dataset '%s'",
                          entry, current->GetDataSet());
       }
       if (current->TestBit(TDSetElement::kNewPacket)) {
         dataset = current->GetDataSet();
         ds->SetTitle(dataset);
         Info("Process", "entry %lld: new packet from: %s, first: %lld, last: %lld",
                          entry, current->GetName(), current->GetFirst(),
                          current->GetFirst()+current->GetNum()-1);
       }
     }
   }

   Int_t eventSize = fChain->GetTree()->GetEntry(entry);
   ++fNumberOfEvents;

   //normalization purposes
   if (dataset != "DATA") Nntuple->Fill(0.5);

   // compute the total size of all events
   fTotalDataSize += eventSize;

   if ( fNumberOfEvents % 100000 == 0 ) std::cout << dataset << " : " << fNumberOfEvents << std::endl;

   //split below by trigger path
   for (Int_t trig = 0; trig < 1; trig++) {
    //reset weights
     Double_t WEIGHT = 1.;
     Double_t FEWZ_WEIGHT = 1.;
     Double_t PU_WEIGHT = 1.;

     //split data mc 
     if ( dataset == "DATA") {
        isMC = false; 
        //FIXME important requirement
        if (trig != 0) continue;
     }

      //pick up the weight
      if (isMC) {
           if (filename.Contains("DYM1020") || filename.Contains("DYE1020")) {
              WEIGHT = Sigma_DY1020*FilterEff_DY1020;
           } else if (filename.Contains("DYM200") || filename.Contains("DYE200")) {
              WEIGHT = Sigma_DY200*FilterEff_DY200;
           } else if ((filename.Contains("DYM20") && !filename.Contains("DYM200")) || (filename.Contains("DYE20") && !filename.Contains("DYE200"))) {
              WEIGHT = Sigma_DY20*FilterEff_DY20;
           } else if (filename.Contains("DYM400") || filename.Contains("DYE400")) {
              WEIGHT = Sigma_DY400*FilterEff_DY400;
           } else if (filename.Contains("DYM500") || filename.Contains("DYE500")) {
              WEIGHT = Sigma_DY500*FilterEff_DY500;
           } else if (filename.Contains("DYM700") || filename.Contains("DYE700")) {
              WEIGHT = Sigma_DY700*FilterEff_DY700;
           } else if (filename.Contains("DYM800") || filename.Contains("DYE800")) {
              WEIGHT = Sigma_DY800*FilterEff_DY800;
           } else if (filename.Contains("DYM1000") || filename.Contains("DYE1000")) {
              WEIGHT = Sigma_DY1000*FilterEff_DY1000;
           };
      } //isMC

     if (filename.Contains("DYM") || filename.Contains("DYE")) {

         b_GENnPair->GetEntry(entry);
         b_GENInvMass->GetEntry(entry);
         b_GENRapidity->GetEntry(entry);
         b_GENLepton1_eta->GetEntry(entry);
         b_GENLepton1_pT->GetEntry(entry);
         b_GENLepton1_pdgID->GetEntry(entry);
         b_GENLepton1_status->GetEntry(entry);
         b_GENLepton1_charge->GetEntry(entry);
         b_GENLepton2_eta->GetEntry(entry);
         b_GENLepton2_pT->GetEntry(entry);
         b_GENLepton2_pdgID->GetEntry(entry);
         b_GENLepton2_status->GetEntry(entry);


         // gen. mass
         double genMass = -1;
         double genRapidity = -1;
         double genDiMuPt = -1;
         int GENIndex = -1;
         for( int j = 0; j < GENnPair; j++ ) {
          if( (fabs(GENLepton1_pdgID[j]) != 13 && mode == "MuMu") || (fabs(GENLepton1_pdgID[j]) != 11 && mode == "EE")) continue;
          if( (fabs(GENLepton2_pdgID[j]) != 13 && mode == "MuMu") || (fabs(GENLepton2_pdgID[j]) != 11 && mode == "EE")) continue;
          //pre FSR
          if( GENLepton1_status[j] != 3 ) continue;
          if( GENLepton2_status[j] != 3 ) continue;

          genMass = GENInvMass[j];
          GENIndex = j;
          break;
         }

         //binned in GEN mass samples

         //if ((filename.Contains("DYM400") || filename.Contains("DYE400")) && genMass > 400) { continue; }

         if ((filename.Contains("DYM200") || filename.Contains("DYE200")) && genMass > 400) { continue; }
         else if (((filename.Contains("DYM20") && !filename.Contains("DYM200")) || (filename.Contains("DYE20") && !filename.Contains("DYE200"))) && genMass > 200) {continue;}
         else if ((filename.Contains("DYM400") || filename.Contains("DYE400")) && genMass > 500) { continue; }
         else if ((filename.Contains("DYM500") || filename.Contains("DYE500")) && genMass > 700) { continue; }
         else if ((filename.Contains("DYM700") || filename.Contains("DYE700")) && genMass > 800) { continue; }
         else if ((filename.Contains("DYM800") || filename.Contains("DYE800")) && genMass > 1000) { continue; }

         //pre FSR values
         genRapidity = GENRapidity[GENIndex];
         genDiMuPt = sqrt((GENLepton1_Px[GENIndex]+GENLepton2_Px[GENIndex])*(GENLepton1_Px[GENIndex]+GENLepton2_Px[GENIndex])+(GENLepton1_Py[GENIndex]+GENLepton2_Py[GENIndex])*(GENLepton1_Py[GENIndex]+GENLepton2_Py[GENIndex]));
         //FIXME look up FEWZ weight
         FEWZ_WEIGHT = weight(genDiMuPt, fabs(genRapidity), genMass, true);
        }

        b_HLT_trigFired->GetEntry(entry);
        bool isTriggered = false;
 
        //lepton loop
        double best_val_mu = -99999;
        std::vector<purdue::Dimuon>::const_iterator index_mu;
        double best_val_e = -99999;
        std::vector<purdue::Dielectron>::const_iterator index_e;

        if (mode == "MuMu") {

          if (hlt_trigFired[1] == 1) isTriggered = true;
          if( !isTriggered ) return kTRUE;

          muons->clear();
          b_muons->GetEntry(entry);
          dimuons->clear();
          b_dimuons->GetEntry(entry);

          if (muons->size()==0 || dimuons->size()==0) continue;

          for (std::vector<purdue::Dimuon>::const_iterator dimu_it = dimuons->begin(); dimu_it != dimuons->end(); ++dimu_it) {
            //get the links
            purdue::Muon* mu1 = &(muons->at(dimu_it->muon_links_.first));
            purdue::Muon* mu2 = &(muons->at(dimu_it->muon_links_.second));

            if( mu1->pt_ < 20 || mu2->pt_ < 10 ) {
                if( mu2->pt_ < 20 || mu1->pt_ < 10 ) continue;
                 }

            if (!(goodMuon(*mu1) && goodMuon(*mu2))) continue;
            //Dimuon cuts section

          // 3D angle
            if( dimu_it->angle_ < 0.005 ) continue;
         
          // vtx prob
            if( dimu_it->vtxTrkProb_ < 0.02 ) continue;
            if( mu1->q_*mu2->q_ >= 0) continue;

            if( dimu_it->vtxTrkProb_ > best_val_mu ) {
              best_val_mu = dimu_it->vtxTrkProb_;
              index_mu = dimu_it;
            }
         }
        } else if (mode == "EE") {
          //Up to date selection requirements
          //http://cmssw.cvs.cern.ch/cgi-bin/cmssw.cgi/UserCode/ikravchenko/DrellYanDMDY/Include/EleIDCuts.hh?revision=1.6&view=markup
          if (hlt_trigFired[6] == 1) isTriggered = true;
          if( !isTriggered ) return kTRUE;

          electrons->clear();
          b_electrons->GetEntry(entry);
          dielectrons->clear();
          b_dielectrons->GetEntry(entry);

          if (electrons->size()==0 || dielectrons->size()==0) continue;
          //lepton loop
          for (std::vector<purdue::Dielectron>::const_iterator diel_it = dielectrons->begin(); diel_it != dielectrons->end(); ++diel_it) {
            //get the links
            purdue::Electron* ele1 = &(electrons->at(diel_it->ele_links_.first));
            purdue::Electron* ele2 = &(electrons->at(diel_it->ele_links_.second));

            if( ele1->scEt_ < 20 || ele2->scEt_ < 10 ) {
               if( ele2->scEt_ < 20 || ele1->scEt_ < 10 ) continue;
              }
            if (!(goodElectron(*ele1) && goodElectron(*ele2))) continue;
             
            index_e = diel_it;
            best_val_e = 0;
         }
       }

        if(mode == "MuMu" && best_val_mu == -99999) continue;
        if(mode == "EE" && best_val_e == -99999) continue;

        // setup for momentum correction
        // Only for RECO, do nothing for GEN
        TLorentzVector muMinus;
        TLorentzVector muPlus;
        TLorentzVector recoDYcand;

        //in case you apply correction
        double recoMass_corr = -1.;
        double recoRap_corr = -1.;
        double recoMass = -1.;
        double recoRap = -1.;

        if(mode == "MuMu") {
          //take back the links of best muons
          purdue::Muon* bestMu1 = &(muons->at(index_mu->muon_links_.first));
          purdue::Muon* bestMu2 = &(muons->at(index_mu->muon_links_.second));

          //Use one for systematics
          float dummy = 0;
          MomScaleCorrection(rmcor, muMinus, muPlus,
                bestMu1->px_,bestMu1->py_,bestMu1->pz_,bestMu1->q_,
                bestMu2->px_,bestMu2->py_,bestMu2->pz_,bestMu2->q_,
                dummy, _runopt, !isMC);

          recoDYcand = muPlus + muMinus;
    
          //in case you apply correction
          recoMass_corr = recoDYcand.M();
          recoRap_corr = fabs(recoDYcand.Rapidity());
          //Common for mumu and ee but diferenbt pointer of course
          recoMass = index_mu->mass_;
          recoRap = index_mu->y_;
        } //mom scale correction - for muons only 
        else if (mode == "EE") {
          recoMass = index_e->mass_;
          recoRap = index_e->y_;
        } 

        // gen. mass
        double simMass = -1;
        int simIndex = -1;
        double simRapidity = -1;
        for( int j = 0; j < GENnPair; j++ ) {
            if( (fabs(GENLepton1_pdgID[j]) != 13 && mode == "MuMu") || (fabs(GENLepton1_pdgID[j]) != 11 && mode == "EE")) continue;
            if( (fabs(GENLepton2_pdgID[j]) != 13 && mode == "MuMu") || (fabs(GENLepton2_pdgID[j]) != 11 && mode == "EE")) continue;
            //pre FSR
            if( GENLepton1_status[j] != 1 ) continue;
            if( GENLepton2_status[j] != 1 ) continue;
             
            // cout << "genMass " << genMass << endl;
            simMass = GENInvMass[j];
            simRapidity = GENRapidity[j];
            break;
          }

          //put the fills 
  	  htrue->Fill(simMass, WEIGHT);
 	  hmeas->Fill(recoMass, WEIGHT);
	  hden->Fill(simMass, recoMass, WEIGHT);

          htrue_PU->Fill(simMass, PU_WEIGHT*WEIGHT);
          hmeas_PU->Fill(recoMass, PU_WEIGHT*WEIGHT);
          hden_PU->Fill(simMass, recoMass, PU_WEIGHT*WEIGHT);

          if (mode == "MuMu") {
            htrue_Roch->Fill(simMass, WEIGHT);
            hmeas_Roch->Fill(recoMass_corr, WEIGHT);
            hden_Roch->Fill(simMass, recoMass_corr, WEIGHT);

            htrue_corr->Fill(simMass, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
            hmeas_corr->Fill(recoMass_corr, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
            hden_corr->Fill(simMass, recoMass_corr, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
          }

          //2D case
          double val_reco = -1;
          double val_sim = -1;

          for( int j = 0; j < 6; j++ ) {
            if( recoMass > Mass_xbin2[j] && recoMass < Mass_xbin2[j+1] ) {
              int nbins; 
              double bin_size;
              if( j == 5 ) {
                nbins = 12;
                bin_size = 0.2;
              }
              else {
                nbins = 24;
                bin_size = 0.1;
              }
              for( int k = 0; k < nbins; k++ ) {
                if( fabs(recoRap) > k*bin_size && fabs(recoRap) < (k+1)*bin_size ) val_reco = k + j*24;
              }   
            }     
            if( simMass > Mass_xbin2[j] && simMass < Mass_xbin2[j+1] ) {
              int nbins;
              double bin_size;
              if( j == 5 ) {
                nbins = 12;
                bin_size = 0.2;
              }
              else {
                nbins = 24;
                bin_size = 0.1;
              }
              for( int k = 0; k < nbins; k++ ) {
                if (fabs(simRapidity) > k*bin_size && fabs(simRapidity) < (k+1)*bin_size ) val_sim = k + j*24;
              }
            }
          }

          hmeas2->Fill(val_reco, WEIGHT);
          htrue2->Fill(val_sim, WEIGHT);
          hden2->Fill(val_reco, val_sim, WEIGHT);

          hmeas2_PU->Fill(val_reco, PU_WEIGHT*WEIGHT);
          htrue2_PU->Fill(val_sim, PU_WEIGHT*WEIGHT);
          hden2_PU->Fill(val_reco, val_sim, PU_WEIGHT*WEIGHT);

          if (mode == "MuMu") {
            //with the rochester correction
            val_reco = -1;
            val_sim = -1;
            for( int j = 0; j < 6; j++ ) {
              if( recoMass_corr > Mass_xbin2[j] && recoMass_corr < Mass_xbin2[j+1] ) {
                int nbins;
                double bin_size;
               if( j == 5 ) {
                  nbins = 12;
                  bin_size = 0.2;
                }
                else {
                  nbins = 24;
                  bin_size = 0.1;
                }
                for( int k = 0; k < nbins; k++ ) {
                  if( fabs(recoRap_corr) > k*bin_size && fabs(recoRap_corr) < (k+1)*bin_size ) val_reco = k + j*24;
                }
              }
             if( simMass > Mass_xbin2[j] && simMass < Mass_xbin2[j+1] ) {
               int nbins;
               double bin_size;
               if( j == 5 ) {
                 nbins = 12;
                 bin_size = 0.2;
               }
               else {
                 nbins = 24;
                 bin_size = 0.1;
               }
               for( int k = 0; k < nbins; k++ ) {
                 if (fabs(simRapidity) > k*bin_size && fabs(simRapidity) < (k+1)*bin_size ) val_sim = k + j*24;
               }
             }
           }

           hmeas2_Roch->Fill(val_reco, WEIGHT);
           htrue2_Roch->Fill(val_sim, WEIGHT);
           hden2_Roch->Fill(val_reco, val_sim, WEIGHT);
  
           hmeas2_corr->Fill(val_reco, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
           htrue2_corr->Fill(val_sim, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
           hden2_corr->Fill(val_reco, val_sim, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);

          //over under flows
           if( recoMass_corr > 0 && recoMass_corr < 20 ) {
             double bin_size = 0.1;
            //FIXME reset
            val_reco = -1;
            for( int k = 0; k < 24; k++ ) {
              if( fabs(recoRap_corr) > k*bin_size && fabs(recoRap_corr) < (k+1)*bin_size ) val_reco = k;
            }

            hmeas2_24_Roch->Fill(val_reco, WEIGHT);
            hmeas2_24_corr->Fill(val_reco, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
         }
         if( simMass > 0 && simMass < 20 ) {
            double bin_size = 0.1;
            //FIXME reset
            val_sim = -1;
            for( int k = 0; k < 24; k++ ) {
              if (fabs(simRapidity) > k*bin_size && fabs(simRapidity) < (k+1)*bin_size ) val_sim = k;
            }

            htrue2_24->Fill(val_sim, WEIGHT);
            htrue2_24_Roch->Fill(val_sim, WEIGHT);
            htrue2_24_corr->Fill(val_sim, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
         }
       } //mumu only


         //over under flows
         val_reco = -1;
         val_sim = -1;
         if( recoMass > 0 && recoMass < 20 ) {
             double bin_size = 0.1;
            //FIXME reset
            val_reco = -1;
            for( int k = 0; k < 24; k++ ) {
              if( fabs(recoRap) > k*bin_size && fabs(recoRap) < (k+1)*bin_size ) val_reco = k;
            }

            hmeas2_24->Fill(val_reco, WEIGHT);
         }
         val_reco = -1;
         val_sim = -1;
         for( int jj = 0; jj < 7; jj++ ) {
           if( recoMass > Mass_xbin2_156[jj] && recoMass < Mass_xbin2_156[jj+1] ) {
            int nbins;
            double bin_size;
            if( jj == 6) {
              nbins = 12;
              bin_size = 0.2;
            }
            else {
              nbins = 24;
              bin_size = 0.1;
            }
            for( int kk = 0; kk < nbins; kk++ ) {
              if( fabs(recoRap) > kk*bin_size && fabs(recoRap) < (kk+1)*bin_size ) val_reco = kk + jj*24;
            }
          }   
          if( simMass > Mass_xbin2_156[jj] && simMass < Mass_xbin2_156[jj+1] ) {
            int nbins;
            double bin_size;
            if(jj == 6) {
              nbins = 12;
              bin_size = 0.2;
            }
            else {
              nbins = 24;
              bin_size = 0.1;
            }
            for( int kk = 0; kk < nbins; kk++ ) {
              if (fabs(simRapidity) > kk*bin_size && fabs(simRapidity) < (kk+1)*bin_size ) val_sim = kk + jj*24;
            }
          }
         }
         hden2_156->Fill(val_reco, val_sim, WEIGHT);
         hden2_156_PU->Fill(val_reco, val_sim, PU_WEIGHT*WEIGHT);


       if (mode == "MuMu") {
         val_reco = -1;
         val_sim = -1;
         for( int jj = 0; jj < 7; jj++ ) {
          if( recoMass_corr > Mass_xbin2_156[jj] && recoMass_corr < Mass_xbin2_156[jj+1] ) {
            int nbins;
            double bin_size;
            if( jj == 6) {
              nbins = 12;
              bin_size = 0.2;
            }
            else { 
              nbins = 24;
              bin_size = 0.1;
            }
            for( int kk = 0; kk < nbins; kk++ ) {
              if( fabs(recoRap_corr) > kk*bin_size && fabs(recoRap_corr) < (kk+1)*bin_size ) val_reco = kk + jj*24;
            }
          }
          if( simMass > Mass_xbin2_156[jj] && simMass < Mass_xbin2_156[jj+1] ) {
            int nbins;
            double bin_size;
            if(jj == 6) {
              nbins = 12;
              bin_size = 0.2;
            }
            else {
              nbins = 24;
              bin_size = 0.1;
            }
            for( int kk = 0; kk < nbins; kk++ ) {
              if (fabs(simRapidity) > kk*bin_size && fabs(simRapidity) < (kk+1)*bin_size ) val_sim = kk + jj*24;
            }
          }
        }
        hden2_156_Roch->Fill(val_reco, val_sim, WEIGHT);
        hden2_156_corr->Fill(val_reco, val_sim, FEWZ_WEIGHT*PU_WEIGHT*WEIGHT);
      } //mumu only

   }//end split by trig path

   return kTRUE;
}
Ejemplo n.º 20
0
void MakeTree_2012(){
	//gROOT->LoadMacro("setTDRStyle_modified.C");
	//setTDRStyle();
	TFile *f = TFile::Open("Upsilon_Histos_191212_FULL.root");
	//TFile *f = TFile::Open("/castor/cern.ch/user/t/tdahms/Jpsi_Histos_ppReReco.root");
	TTree *t =(TTree*)f->Get("myTree");
	Long64_t nentries = t->GetEntries();

	const int NMAX=100;
	UInt_t eventNb;
	UInt_t runNb;
	Int_t Centrality;
	Int_t HLTriggers;
	Int_t Reco_QQ_size;
	Int_t Reco_QQ_trig[NMAX];
	Int_t Reco_QQ_type[NMAX];
	Int_t Reco_QQ_sign[NMAX];
	Float_t Reco_QQ_VtxProb[NMAX];
	TClonesArray *Reco_QQ_4mom;
	TClonesArray *Reco_QQ_mupl_4mom;
	TClonesArray *Reco_QQ_mumi_4mom;
	Int_t Reco_mu_size;
	Int_t Reco_mu_type[NMAX];
	Int_t Reco_mu_charge[NMAX];
	TClonesArray *Reco_mu_4mom;
	int nPlusMu;
	int nMinusMu;
	float muPt[NMAX];
	float muEta[NMAX];
	float muPhi[NMAX];
	//Int_t nReco_QQ;
	Float_t invariantMass;
	Int_t QQtrig;
	Int_t QQsign;
	float weight;
	float weight2;
	Float_t upsPt;
	Float_t upsEta;
	Float_t upsRapidity;	
	Float_t vProb;
	Float_t muPlusPt;
	Float_t muMinusPt;
	Float_t muPlusEta;
	Float_t muMinusEta;
	Float_t muPlusPhi;
	Float_t muMinusPhi;
	Float_t RmuPlusPhi = 0;
	Float_t RmuMinusPhi = 0;
	//float theta_HX;
	//float phi_HX;
	//float theta_CS;
	//float phi_CS;

	float QQmuPlusDxy[100];
	float QQmuPlusDz[100];
	int QQmuPlusNhits[100];
	int QQmuPlusNPixelhits[100];
	int QQmuPlusNPxlLayers[100];
	float QQmuPlusInnerChi[100];
	float QQmuPlusGlobalChi[100];
	int QQmuPlusNMuonhits[100];
	float QQmuPlusDB[100];

	float QQmuMinusDxy[100];
	float QQmuMinusDz[100];
	int QQmuMinusNhits[100];
	int QQmuMinusNPixelhits[100];
	int QQmuMinusNPxlLayers[100];
	float QQmuMinusInnerChi[100];
	float QQmuMinusGlobalChi[100];
	int QQmuMinusNMuonhits[100];
	float QQmuMinusDB[100];

	float muPlusDxy;
	float muPlusDz;
	int muPlusNhits;
	int muPlusNPixelhits;
	int muPlusNPxlLayers;
	float muPlusInnerChi;
	float muPlusGlobalChi;
	int muPlusNMuonhits;
	float muPlusDB;

	float muMinusDxy;
	float muMinusDz;
	int muMinusNhits;
	int muMinusNPixelhits;
	int muMinusNPxlLayers;
	float muMinusInnerChi;
	float muMinusGlobalChi;
	int muMinusNMuonhits;
	float muMinusDB;

	t->SetBranchAddress("Centrality",    &Centrality    );
	t->SetBranchAddress("eventNb",    &eventNb    );
	t->SetBranchAddress("runNb",    &runNb    );
	t->SetBranchAddress("HLTriggers",    &HLTriggers    );
	t->SetBranchAddress("Reco_QQ_size",  &Reco_QQ_size  );
	t->SetBranchAddress("Reco_QQ_trig",  &Reco_QQ_trig  );
	t->SetBranchAddress("Reco_QQ_type",  Reco_QQ_type   );
	t->SetBranchAddress("Reco_QQ_sign",  Reco_QQ_sign   );
	t->SetBranchAddress("Reco_QQ_VtxProb",  Reco_QQ_VtxProb);
	t->SetBranchAddress("Reco_QQ_4mom",  &Reco_QQ_4mom  );
	t->SetBranchAddress("Reco_QQ_mupl_4mom", &Reco_QQ_mupl_4mom);
	t->SetBranchAddress("Reco_QQ_mumi_4mom", &Reco_QQ_mumi_4mom);

	/*
	   t->SetBranchAddress("muPlusDxy",QQmuPlusDxy);
	   t->SetBranchAddress("muPlusDz",QQmuPlusDz);
	   t->SetBranchAddress("muPlusNhits",QQmuPlusNhits);
	   t->SetBranchAddress("muPlusNPixelhits",QQmuPlusNPixelhits);
	   t->SetBranchAddress("muPlusNPxlLayers",QQmuPlusNPxlLayers);
	   t->SetBranchAddress("muPlusInnerChi",QQmuPlusInnerChi);
	   t->SetBranchAddress("muPlusGlobalChi",QQmuPlusGlobalChi);
	   t->SetBranchAddress("muPlusNMuonhits",QQmuPlusNMuonhits);
	   t->SetBranchAddress("muPlusDB",QQmuPlusDB);

	   t->SetBranchAddress("muMinusDxy",QQmuMinusDxy);
	   t->SetBranchAddress("muMinusDz",QQmuMinusDz);
	   t->SetBranchAddress("muMinusNhits",QQmuMinusNhits);
	   t->SetBranchAddress("muMinusNPixelhits",QQmuMinusNPixelhits);
	   t->SetBranchAddress("muMinusNPxlLayers",QQmuMinusNPxlLayers);
	   t->SetBranchAddress("muMinusInnerChi",QQmuMinusInnerChi);
	   t->SetBranchAddress("muMinusGlobalChi",QQmuMinusGlobalChi);
	   t->SetBranchAddress("muMinusNMuonhits",QQmuMinusNMuonhits);
	   t->SetBranchAddress("muMinusDB",QQmuMinusDB);
	 */
	t->SetBranchAddress("Reco_mu_size",  &Reco_mu_size  );
	t->SetBranchAddress("Reco_mu_type",  Reco_mu_type   );
	t->SetBranchAddress("Reco_mu_charge",Reco_mu_charge );
	t->SetBranchAddress("Reco_mu_4mom",  &Reco_mu_4mom);

	TH1F *h_QQ_mass = new TH1F("h_QQ_mass","",70,7,14);
	TH1F *h_QQ_mass_1 = new TH1F("h_QQ_mass_1","",70,7,14);
	TH1F *h_QQ_mass_2 = new TH1F("h_QQ_mass_2","",70,7,14);	

	TFile *f1 = new TFile("dimuonTree_fullFiltered.root","RECREATE");

	TTree *MuTree = new TTree("MuTree","MuTree");
	TTree *UpsilonTree = new TTree("UpsilonTree","UpsilonTree");
	TTree *UpsilonTree_allsign = new TTree("UpsilonTree_allsign","UpsilonTree_allsign");
	TTree *UpsilonTree_trkRot = new TTree("UpsilonTree_trkRot","UpsilonTree_trkRot");

	MuTree->Branch("Reco_mu_size",   &Reco_mu_size,   "Reco_mu_size/I");
	MuTree->Branch("nPlusMu",        &nPlusMu,        "nPlusMu/I");
	MuTree->Branch("nMinusMu",       &nMinusMu,       "nMinusMu/I");
	MuTree->Branch("muPt",           &muPt,           "muPt[Reco_mu_size]/F");
	MuTree->Branch("muEta",          &muEta,          "muEta[Reco_mu_size]/F");
	MuTree->Branch("muPhi",          &muPhi,          "muPhi[Reco_mu_size]/F");
	MuTree->Branch("Reco_mu_type",   Reco_mu_type,    "Reco_mu_type[Reco_mu_size]/I");
	MuTree->Branch("Reco_mu_charge", Reco_mu_charge,  "Reco_mu_charge[Reco_mu_size]/I" );
	MuTree->Branch("eventNb",    &eventNb,     "eventNb/I");
	MuTree->Branch("runNb",    &runNb,     "runNb/I");


	//UpsilonTree->Branch("nReco_QQ", &nReco_QQ, "nReco_QQ/I");
	UpsilonTree->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
	//	UpsilonTree->Branch("theta_HX", &theta_HX, "theta_HX/F");
	//	UpsilonTree->Branch("phi_HX", &phi_HX, "phi_HX/F");
	//	UpsilonTree->Branch("theta_CS", &theta_CS, "theta_CS/F");
	//	UpsilonTree->Branch("phi_CS", &phi_CS, "phi_CS/F");

	/*
	   UpsilonTree->Branch("muPlusDxy", &muPlusDxy,"muPlusDxy/F");
	   UpsilonTree->Branch("muPlusDz", &muPlusDz,"muPlusDz/F");
	   UpsilonTree->Branch("muPlusNhits", &muPlusNhits,"muPlusNhits/I");
	   UpsilonTree->Branch("muPlusNPixelhits", &muPlusNPixelhits,"muPlusNPixelhits/I");
	   UpsilonTree->Branch("muPlusNPxlLayers", &muPlusNPxlLayers,"muPlusNPxlLayers/I");
	   UpsilonTree->Branch("muPlusInnerChi", &muPlusInnerChi,"muPlusInnerChi/F");
	   UpsilonTree->Branch("muPlusGlobalChi", &muPlusGlobalChi,"muPlusGlobalChi/F");
	   UpsilonTree->Branch("muPlusNMuonhits", &muPlusNMuonhits,"muPlusNMuonhits/I");
	   UpsilonTree->Branch("muPlusDB", &muPlusDB,"muPlusDB/F");

	   UpsilonTree->Branch("muMinusDxy", &muMinusDxy,"muMinusDxy/F");
	   UpsilonTree->Branch("muMinusDz", &muMinusDz,"muMinusDz/F");
	   UpsilonTree->Branch("muMinusNhits", &muMinusNhits,"muMinusNhits/I");
	   UpsilonTree->Branch("muMinusNPixelhits", &muMinusNPixelhits,"muMinusNPixelhits/I");
	   UpsilonTree->Branch("muMinusNPxlLayers", &muMinusNPxlLayers,"muMinusNPxlLayers/I");
	   UpsilonTree->Branch("muMinusInnerChi", &muMinusInnerChi,"muMinusInnerChi/F");
	   UpsilonTree->Branch("muMinusGlobalChi", &muMinusGlobalChi,"muMinusGlobalChi/F");
	   UpsilonTree->Branch("muMinusNMuonhits", &muMinusNMuonhits,"muMinusNMuonhits/I");
	   UpsilonTree->Branch("muMinusDB", &muMinusDB,"muMinusDB/F");
	 */
	UpsilonTree_allsign->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree_allsign->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree_allsign->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree_allsign->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree_allsign->Branch("weight",   &weight,    "weight/F");
	UpsilonTree_allsign->Branch("weight2",   &weight2,    "weight2/F");
	UpsilonTree_allsign->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree_allsign->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree_allsign->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree_allsign->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree_allsign->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree_allsign->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree_allsign->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree_allsign->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree_allsign->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree_allsign->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree_allsign->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree_allsign->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree_allsign->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");
	//	UpsilonTree_allsign->Branch("theta_HX", &theta_HX, "theta_HX/F");
	//	UpsilonTree_allsign->Branch("phi_HX", &phi_HX, "phi_HX/F");
	//	UpsilonTree_allsign->Branch("theta_CS", &theta_CS, "theta_CS/F");
	//	UpsilonTree_allsign->Branch("phi_CS", &phi_CS, "phi_CS/F");

	UpsilonTree_trkRot->Branch("Centrality",    &Centrality,    "Centrality/I");
	UpsilonTree_trkRot->Branch("HLTriggers",    &HLTriggers,    "HLTriggers/I");
	UpsilonTree_trkRot->Branch("QQtrig",   &QQtrig,    "QQtrig/I");
	UpsilonTree_trkRot->Branch("QQsign",   &QQsign,    "QQsign/I");
	UpsilonTree_trkRot->Branch("weight",   &weight,    "weight/F");
	UpsilonTree_trkRot->Branch("weight2",   &weight2,    "weight2/F");
	UpsilonTree_trkRot->Branch("vProb",    &vProb,     "vProb/F");
	UpsilonTree_trkRot->Branch("eventNb",    &eventNb,     "eventNb/I");
	UpsilonTree_trkRot->Branch("runNb",    &runNb,     "runNb/I");
	UpsilonTree_trkRot->Branch("invariantMass", &invariantMass, "invariantMass/F");
	UpsilonTree_trkRot->Branch("upsPt", &upsPt, "upsPt/F");
	UpsilonTree_trkRot->Branch("upsEta", &upsEta, "upsEta/F");
	UpsilonTree_trkRot->Branch("upsRapidity", &upsRapidity, "upsRapidity/F");
	UpsilonTree_trkRot->Branch("muPlusPt", &muPlusPt, "muPlusPt/F");
	UpsilonTree_trkRot->Branch("muMinusPt", &muMinusPt, "muMinusPt/F");
	UpsilonTree_trkRot->Branch("muPlusEta", &muPlusEta, "muPlusEta/F");
	UpsilonTree_trkRot->Branch("muMinusEta", &muMinusEta, "muMinusEta/F");
	UpsilonTree_trkRot->Branch("muPlusPhi", &muPlusPhi, "muPlusPhi/F");
	UpsilonTree_trkRot->Branch("muMinusPhi", &muMinusPhi, "muMinusPhi/F");


	for (int i=0; i<nentries; i++) {
		t->GetEntry(i);
		//nReco_QQ=0;
		if (i%1000==0) cout<<i<<endl;
		nPlusMu=0;
		nMinusMu=0;
		for(int iMu = 0; iMu < Reco_mu_size; iMu++){
			if (Reco_mu_charge[iMu] == 1) nPlusMu++;
			else nMinusMu++;
			TLorentzVector *Reco_mu = (TLorentzVector *) Reco_mu_4mom->At(iMu);
			muPt[iMu]=Reco_mu->Pt();
			muEta[iMu]=Reco_mu->Eta();
			muPhi[iMu]=Reco_mu->Phi();
		}
		MuTree->Fill();

		for(int iQQ = 0; iQQ < Reco_QQ_size; iQQ++){
			//eventNb=eventNb[iQQ];
			//runNb=runNb[iQQ];
			vProb = Reco_QQ_VtxProb[iQQ];
			QQtrig = Reco_QQ_trig[iQQ];
			QQsign = Reco_QQ_sign[iQQ];
			if (Reco_QQ_sign[iQQ] == 0) { 
				weight = 1;
				weight2 = 1;
			}
			else {
				weight = -1;
				float likesign_comb = (float)nPlusMu*(nPlusMu-1.0)/2.0+(float)nMinusMu*(nMinusMu-1.0)/2.0;
				float unlikesign_bkgd_comb = (float)nPlusMu*nMinusMu - (nPlusMu>nMinusMu?nMinusMu:nPlusMu);
				weight2 = -1.0 * unlikesign_bkgd_comb/likesign_comb;
			}

			TLorentzVector *Reco_QQ = (TLorentzVector *) Reco_QQ_4mom->At(iQQ);
			TLorentzVector *Reco_QQ_mupl = (TLorentzVector *) Reco_QQ_mupl_4mom->At(iQQ);
			TLorentzVector *Reco_QQ_mumi = (TLorentzVector *) Reco_QQ_mumi_4mom->At(iQQ);
			invariantMass=Reco_QQ->M();
			upsPt=Reco_QQ->Pt();
			upsEta=Reco_QQ->Eta();
			upsRapidity=Reco_QQ->Rapidity();
			muMinusPt=Reco_QQ_mumi->Pt();
			muMinusEta=Reco_QQ_mumi->Eta();
			muMinusPhi=Reco_QQ_mumi->Phi();
			muPlusPt=Reco_QQ_mupl->Pt();
			muPlusEta=Reco_QQ_mupl->Eta();
			muPlusPhi=Reco_QQ_mupl->Phi();
			//	theta_HX = GetAngles_HX(*Reco_QQ_mupl,*Reco_QQ_mumi).first;
			//	phi_HX = GetAngles_HX(*Reco_QQ_mupl,*Reco_QQ_mumi).second;
			//	theta_CS = GetAngles_CS(*Reco_QQ_mupl,*Reco_QQ_mumi).first;
			//	phi_CS = GetAngles_CS(*Reco_QQ_mupl,*Reco_QQ_mumi).second;

			muPlusDxy=QQmuPlusDxy[iQQ];
			muPlusDz=QQmuPlusDz[iQQ];
			muPlusNhits=QQmuPlusNhits[iQQ];
			muPlusNPixelhits=QQmuPlusNPixelhits[iQQ];
			muPlusNPxlLayers=QQmuPlusNPxlLayers[iQQ];
			muPlusInnerChi=QQmuPlusInnerChi[iQQ];
			muPlusGlobalChi=QQmuPlusGlobalChi[iQQ];
			muPlusNMuonhits=QQmuPlusNMuonhits[iQQ];
			muPlusDB=QQmuPlusDB[iQQ];

			muMinusDxy=QQmuMinusDxy[iQQ];
			muMinusDz=QQmuMinusDz[iQQ];
			muMinusNhits=QQmuMinusNhits[iQQ];
			muMinusNPixelhits=QQmuMinusNPixelhits[iQQ];
			muMinusNPxlLayers=QQmuMinusNPxlLayers[iQQ];
			muMinusInnerChi=QQmuMinusInnerChi[iQQ];
			muMinusGlobalChi=QQmuMinusGlobalChi[iQQ];
			muMinusNMuonhits=QQmuMinusNMuonhits[iQQ];
			muMinusDB=QQmuMinusDB[iQQ];
			/*
			   if (fabs(muPlusDxy)<3 && fabs(muPlusDz)<15 
			   && muPlusNhits>10 && muPlusNPxlLayers>0 && muPlusNMuonhits>6 
			   && muPlusInnerChi<4 && muPlusGlobalChi<6
			   && fabs(muMinusDxy)<3 && fabs(muMinusDz)<15 
			   && muMinusNhits>10 && muMinusNPxlLayers>0 && muMinusNMuonhits>6 
			   && muMinusInnerChi<4 && muMinusGlobalChi<6 
			   && vProb>0.01) 

			   if (fabs(muPlusDxy)<3 && fabs(muPlusDz)<15 
			   && muPlusNhits>10 && muPlusNPxlLayers>0 && muPlusNMuonhits>12 
			   && muPlusInnerChi<2.1 && muPlusGlobalChi<2.7
			   && fabs(muMinusDxy)<3 && fabs(muMinusDz)<15 
			   && muMinusNhits>10 && muMinusNPxlLayers>0 && muMinusNMuonhits>12 
			   && muMinusInnerChi<2.1 && muMinusGlobalChi<2.7 
			   && vProb>0.19) 
			 */

			if ((HLTriggers&1)==1 && (Reco_QQ_trig[iQQ]&1)==1 && (Reco_QQ_type[iQQ]<3) 
			   )
			{
				UpsilonTree_allsign->Fill();
				if (Reco_QQ_sign[iQQ]==0) {
					UpsilonTree->Fill();
					if (Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
						h_QQ_mass->Fill(Reco_QQ->M());
					}
					if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
						h_QQ_mass_1->Fill(Reco_QQ->M());
					}
				}
				else if (Reco_QQ_mupl->Pt()>=ptcut && Reco_QQ_mumi->Pt()>=ptcut && Reco_QQ->M()>8.5 && Reco_QQ->M()<11.5) {
					h_QQ_mass_2->Fill(Reco_QQ->M());
				}

				//track rotation
				Double_t ran = gRandom->Rndm();

				if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();
				else  RmuMinusPhi = muMinusPhi + TMath::Pi();

				TLorentzVector mu1;
				mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, RmuPlusPhi, 0.105);
				TLorentzVector mu2;
				mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, RmuMinusPhi, 0.105);

				TLorentzVector dimuon;
				dimuon = mu1 + mu2;

				invariantMass=dimuon.M();
				upsPt=dimuon.Pt();
				upsEta=dimuon.Eta();
				upsRapidity=dimuon.Rapidity();

				if ((HLTriggers&1)==2 && (Reco_QQ_trig[iQQ]&1)==1 && (Reco_QQ_type[iQQ]==0)
				   )
				{
					UpsilonTree_trkRot->Fill();
				}

				/*
				   for (int k=0;k<10;k++){
				//track rotation
				//if(ran < 0.5 ) RmuPlusPhi = muPlusPhi + TMath::Pi();
				//else  RmuMinusPhi = muMinusPhi + TMath::Pi();
				Double_t ran = gRandom->Rndm();

				if (k<5) {
				muMinusPhi = muMinusPhi + TMath::Pi()*ran;
				}   
				else {
				muPlusPhi = muPlusPhi + TMath::Pi()*ran;
				}   

				TLorentzVector mu1;
				mu1.SetPtEtaPhiM( muPlusPt, muPlusEta, muPlusPhi, 0.105);
				TLorentzVector mu2;
				mu2.SetPtEtaPhiM( muMinusPt, muMinusEta, muMinusPhi, 0.105);

				TLorentzVector dimuon;
				dimuon = mu1 + mu2;

				invariantMass=dimuon.M();
				upsPt=dimuon.Pt();
				upsEta=dimuon.Eta();
				upsRapidity=dimuon.Rapidity();

				UpsilonTree_trkRot->Fill();
				} 
				 */  
			}
		}		//	UpsilonTree->Fill();
	}

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

	TCanvas *c1 = new TCanvas("c1","c1");
	//h_QQ_mass->GetYaxis()->SetRangeUser(0,180);
	h_QQ_mass->SetMarkerColor(kRed);
	h_QQ_mass->SetMarkerStyle(22);
	h_QQ_mass->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass->SetYTitle("Events/(0.1 GeV/c^{2})");
	h_QQ_mass->Draw("PE");

	h_QQ_mass_1->SetMarkerColor(kBlue);
	h_QQ_mass_1->SetMarkerStyle(20);
	h_QQ_mass_1->GetXaxis()->CenterTitle(kTRUE);
	h_QQ_mass_1->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass_1->SetYTitle("Events/(0.1 GeV/c^{2})");
	h_QQ_mass_1->Draw("PEsame");

	//h_QQ_mass_2->GetYaxis()->SetRangeUser(0,400);
	h_QQ_mass_2->SetMarkerColor(kRed);
	h_QQ_mass_2->SetMarkerStyle(24);
	h_QQ_mass_2->GetXaxis()->CenterTitle(kTRUE);
	h_QQ_mass_2->SetXTitle("m_{#mu#mu} (GeV/c^{2})");
	h_QQ_mass_2->SetYTitle("Events/(0.1 MeV/c^{2})");
	h_QQ_mass_2->Draw("PEsame");

	TLegend *legend = new TLegend(.5,.7,.9,.9);
	legend->AddEntry(h_QQ_mass,"N_{#mu^{+}#mu^{-}} acceptance cut","P");
	legend->AddEntry(h_QQ_mass_1,"Unlike-Sign, N_{#mu^{+}#mu^{-}}","P");
	legend->AddEntry(h_QQ_mass_2,"Like-sign, N_{#mu^{+}#mu^{+}}+N_{#mu^{-}#mu^{-}}","P");
	legend->AddEntry((TObject*)0,"#mu p_{T} > 3 GeV/c","");
	legend->Draw();

	h_QQ_mass->Write();
	h_QQ_mass_1->Write();
	h_QQ_mass_2->Write();
	c1->SaveAs("dimuon_likesign_pt4.pdf");
	c1->SaveAs("dimuon_likesign_pt4.gif");
	c1->Write();
	f1->Write();

}
void UpsCheck() {
  TFile *file = TFile::Open("/scratch_rigel/CMSTrees/PbPb_Data/MegaTree/OniaTree_MEGA_Peripheral30100_PromptReco_262548_263757.root");
//Track Tree Set Up
  TTree *trackTree = (TTree*)file->Get("anaTrack/trackTree");
  trackTree->SetBranchStatus("*",0);
  trackTree->SetBranchStatus("nLumi", 1);
  trackTree->SetBranchStatus("nTrk", 1);
  trackTree->SetBranchStatus("trkPt", 1);
  trackTree->SetBranchStatus("trkEta", 1);
  trackTree->SetBranchStatus("trkPhi", 1);
  trackTree->SetBranchStatus("trkCharge", 1);
  trackTree->SetBranchStatus("nEv", 1);
  Int_t Lumi, nTrk, event;
  Float_t eta[9804];
  Float_t phi[9804];
  Int_t charge[9804];
  Float_t pT[9804];
  trackTree->SetBranchAddress("nLumi", &Lumi);
  trackTree->SetBranchAddress("nTrk", &nTrk);
  trackTree->SetBranchAddress("trkPt", pT);
  trackTree->SetBranchAddress("trkEta", eta);
  trackTree->SetBranchAddress("trkPhi", phi);
  trackTree->SetBranchAddress("trkCharge", charge);
  trackTree->SetBranchAddress("nEv", &event);
//Dimuon Tree Set Up
  TTree *myTree = (TTree*)file->Get("hionia/myTree");
  myTree->SetBranchStatus("*",0);
  myTree->SetBranchStatus("Reco_QQ_4mom",1);
  myTree->SetBranchStatus("Reco_QQ_mupl_4mom",1);
  myTree->SetBranchStatus("Reco_QQ_mumi_4mom",1);
  myTree->SetBranchStatus("Reco_QQ_size",1);
  myTree->SetBranchStatus("Centrality",1);
  myTree->SetBranchStatus("HLTriggers",1);
  myTree->SetBranchStatus("Reco_QQ_trig",1);
  myTree->SetBranchStatus("Reco_QQ_sign",1);
  TClonesArray *Reco_QQ_4mom=0;
  TClonesArray *Reco_QQ_mupl_4mom=0;
  TClonesArray *Reco_QQ_mumi_4mom=0;
  TLorentzVector *dimuon;
  TLorentzVector *mumi;
  TLorentzVector *mupl;
  double events=0;
  events = myTree->GetEntries();
  cout << events << endl;
  Int_t QQsize=0;
  Int_t Centrality=0;
  ULong64_t HLTrigger=0;
  ULong64_t Reco_QQ_trig[21];
  Int_t Reco_QQ_sign[21];
  myTree->SetBranchAddress("Centrality",&Centrality);
  myTree->SetBranchAddress("HLTriggers",&HLTrigger);
  myTree->SetBranchAddress("Reco_QQ_4mom",&Reco_QQ_4mom);
  myTree->SetBranchAddress("Reco_QQ_mupl_4mom", &Reco_QQ_mupl_4mom);
  myTree->SetBranchAddress("Reco_QQ_mumi_4mom", &Reco_QQ_mumi_4mom);
  myTree->SetBranchAddress("Reco_QQ_size", &QQsize);
  myTree->SetBranchAddress("Reco_QQ_trig", Reco_QQ_trig);
  myTree->SetBranchAddress("Reco_QQ_sign", Reco_QQ_sign);
//Histogram Initialization
  TH1D* phidiffmid = new TH1D( "phidiffmid", "#Delta#phi for mid mass band (9.0-9.8 GeV)",128,0,3.2);
  TH1D* rapdiffmid = new TH1D( "rapdiffmid", "#Delta#eta for mid mass band (9.0-9.8 GeV)",200,-5, 5);
  TH2D* midmass = new TH2D("midmass","#Delta#phi vs #Delta#eta for mid mass band",128,0,3.2,200,-5,5);
//Event Loop
  int test = 0;
  int mid = 0;
  int index = 0;
  for(int i = 0; i < trackTree->GetEntries(); i++) { 
	trackTree->GetEntry(i);
	myTree->GetEntry(i);
	if(Centrality > 140) {
	if((HLTrigger&128) == 128 || (HLTrigger&256) == 256) {
		for(Int_t j=0; j < QQsize; j++) {
                        dimuon = (TLorentzVector*)Reco_QQ_4mom->At(j);
                        mumi = (TLorentzVector*)Reco_QQ_mumi_4mom->At(j);
                        mupl = (TLorentzVector*)Reco_QQ_mupl_4mom->At(j);
			if(((Reco_QQ_trig[j]&128) == 128 || (Reco_QQ_trig[j]&256) == 256) && Reco_QQ_sign[j] == 0) {
			if(mumi->Pt() > 4 && mupl->Pt() > 4 && TMath::Abs(mumi->Eta()) < 2.4 && TMath::Abs(mupl->Eta()) < 2.4 )  {
				index++;
				if(dimuon->M() > 9.3 && dimuon->M() < 9.6) {
					test++;
					for(Int_t k=0; k < nTrk; k++) {
						if(TMath::Abs(eta[k]) < 2.4 && pT[k] > .1 && TMath::Abs(charge[k]) == 1) {
							if(TMath::Abs(dimuon->Phi() - phi[k]) > 3.1416) { 
								phidiffmid->Fill(6.2832-TMath::Abs(phi[k]-dimuon->Phi()));
								rapdiffmid->Fill(eta[k] - dimuon->Rapidity());
								midmass->Fill(6.2832-TMath::Abs(phi[k]-dimuon->Phi()),eta[k]-dimuon->Rapidity());
							}
							if(TMath::Abs(dimuon->Phi() - phi[k]) <= 3.1416) {
								phidiffmid->Fill(TMath::Abs(phi[k] - dimuon->Phi()));
                                        	        	rapdiffmid->Fill(eta[k]-dimuon->Rapidity());
								midmass->Fill(TMath::Abs(phi[k]-dimuon->Phi()),eta[k]-dimuon->Rapidity());
							} 
						}
					 }
				 } 
                                }
			} } 
		}
	}  }

  TFile out("EtaPhiMidCent.root", "RECREATE");
  phidiffmid->Write();
  rapdiffmid->Write();
  midmass->Write();
  out.Close();
  cout << "Done!   " << test << "	Total Dimuons: " << index <<endl;
  cout << "Mid:	" << mid << endl;
  return; }
Ejemplo n.º 22
0
double TrimEventContent(Int_t iRapBin = 1,
		      Int_t iPTBin = 1,
		      Double_t fracL = 0.5, Double_t nSigma = 2., 
		      Int_t nUpsState=0,//[0]... 1S, [1]... 2S, [2]... 3S
		      bool UpsMC=false,
		      bool f_BG_zero=false,
		      bool ProjectLSBdata=false,
		      bool ProjectRSBdata=false,
		      bool CombineSignalPeaks=false,
		      bool Y1Sto2S_SB=false,
		      bool LeftSided=false,
		      bool RightSided=false,
		      bool MassScan=false,
		      bool adjustOverlapBorders=true
		      ){

  printf("\n\n\nfracL = %1.3f, nSigma = %1.1f, iState = %d, rap %d, pT %d\n", fracL, nSigma, nUpsState, iRapBin, iPTBin);

  Char_t name[100], title[100];
  Char_t fileNameIn[100];
  sprintf(fileNameIn, "tmpFiles/data_Ups_rap%d_pT%d.root", iRapBin, iPTBin);
  //==============================
  //read inputs from input file:
  TFile *fIn = new TFile(fileNameIn);
  TLorentzVector *lepP;
  TLorentzVector *lepN;
  TTree *treeIn = (TTree *) gDirectory->Get("selectedData");
  if(gDirectory->Get("selectedData")==NULL){
    printf("\n\n\nskip processing this bin.\n\n\n");
    return -999.;
  }

  TH2D *hBG_cosThetaPhiLR[onia::kNbFrames][2];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    sprintf(name, "hBG_cosThetaPhi_%s_L", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][L] = (TH2D *) gDirectory->Get(name);
    sprintf(name, "hBG_cosThetaPhi_%s_R", onia::frameLabel[iFrame]);
    hBG_cosThetaPhiLR[iFrame][R] = (TH2D *) gDirectory->Get(name);
  }
  //==============================

  //definition of output variables 
  Char_t fileNameOut[100];
  sprintf(fileNameOut, "AllStates_%1.2fSigma_FracLSB%dPercent/data_%dSUps_rap%d_pT%d.root", nSigma, int(fracL*100), nUpsState+1, iRapBin, iPTBin);
  TFile *fOut = new TFile(fileNameOut, "RECREATE");
  gStyle->SetPadRightMargin(0.2);
  TTree *treeOut = treeIn->CloneTree(0);
  // treeOut->SetName("data");
  TH2D *hBG_cosThetaPhi[onia::kNbFrames];
  // TH2D *hBG_cosThetaPhiSignal[onia::kNbFrames];
  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    // //book the histo for the signal
    // sprintf(name, "total_%s", onia::frameLabel[iFrame]);
    // sprintf(title, ";cos#theta_{%s};#phi_{%s} [deg]", onia::frameLabel[iFrame], onia::frameLabel[iFrame]);
    // hBG_cosThetaPhiSignal[iFrame] = new TH2D(name, title, onia::kNbBinsCosT, onia::cosTMin, onia::cosTMax, 
    // 					  onia::kNbBinsPhiPol, onia::phiPolMin, onia::phiPolMax);
    // hBG_cosThetaPhiSignal[iFrame]->Sumw2();
    //copy the L and R sideband histos into one output BG histogram
    hBG_cosThetaPhiLR[iFrame][L]->Scale(fracL/hBG_cosThetaPhiLR[iFrame][L]->Integral());
    hBG_cosThetaPhiLR[iFrame][R]->Scale((1.-fracL)/hBG_cosThetaPhiLR[iFrame][R]->Integral());
    sprintf(name, "background_costhphi%s", onia::frameLabel[iFrame]);
    hBG_cosThetaPhi[iFrame] = (TH2D *) hBG_cosThetaPhiLR[iFrame][L]->Clone(name);
    hBG_cosThetaPhi[iFrame]->Add(hBG_cosThetaPhiLR[iFrame][R]);
  }

  //==========================================================
  //reading fit parameters to establish signal mass window
  //as well as the L and R sideband window for the 3D BG histo
  //==========================================================
  fIn->cd();
  TTree *treeFitPar = (TTree *) gDirectory->Get("massFitParameters");
  TF1 *fUps[kNbSpecies], *fBG = 0;
  fUps[0] = 0, fUps[1] = 0, fUps[2] = 0;
  treeFitPar->SetBranchAddress("fUps1S", &fUps[0]);
  treeFitPar->SetBranchAddress("fUps2S", &fUps[1]);
  treeFitPar->SetBranchAddress("fUps3S", &fUps[2]);
  treeFitPar->SetBranchAddress("fBG", &fBG);
  treeFitPar->LoadTree(0);
  treeFitPar->GetEntry(0);


  Double_t mass[kNbSpecies], sigma[kNbSpecies];
  for(int iState = 0; iState < kNbSpecies; iState++){
    mass[iState] = fUps[iState]->GetParameter(1);
    sigma[iState] = fUps[iState]->GetParameter(2);
  }
  printf("1S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS1S], sigma[UPS1S]);
  printf("2S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS2S], sigma[UPS2S]);
  printf("3S: mass = %1.3f GeV, sigma = %1.3f GeV\n", mass[UPS3S], sigma[UPS3S]);
  Double_t poleMass = mass[nUpsState], massMin, massMax;
  massMin = poleMass - nSigma*sigma[nUpsState];
  massMax = poleMass + nSigma*sigma[nUpsState];

  if(LeftSided){
	  massMin = poleMass - nSigma*sigma[nUpsState];
	  massMax = poleMass;
  }

  if(RightSided){
	  massMin = poleMass;
	  massMax = poleMass + nSigma*sigma[nUpsState];
  }

//	  massMin = poleMass - 3.*sigma[nUpsState];
//	  massMax = poleMass - 1.*sigma[nUpsState];

//	  massMin = poleMass + 1.*sigma[nUpsState];
//	  massMax = poleMass + 3.*sigma[nUpsState];

  cout<<"massMin = "<<massMin<<endl;
  cout<<"massMax = "<<massMax<<endl;


  if(adjustOverlapBorders){
  if( nUpsState==2 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting lower border of Y(3S) mass window due to overlap"<<endl;
	  massMin=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==1 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting lower border of Y(2S) mass window due to overlap"<<endl;
	  massMin=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  if( nUpsState==1 && mass[2]-nSigma*sigma[2]<mass[1]+nSigma*sigma[1] ){
	  cout<<"adjusting upper border of Y(2S) mass window due to overlap"<<endl;
	  massMax=(sigma[2]*mass[1]+sigma[1]*mass[2])/(sigma[1]+sigma[2]);
  }
  if( nUpsState==0 && mass[1]-nSigma*sigma[1]<mass[0]+nSigma*sigma[0] ){
	  cout<<"adjusting upper border of Y(1S) mass window due to overlap"<<endl;
	  massMax=(sigma[1]*mass[0]+sigma[0]*mass[1])/(sigma[1]+sigma[0]);
  }
  }


  if( nUpsState==0){
  contamination2Sin1S=fUps[1]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 1S sample by 2S events = "<<contamination2Sin1S*100<<" %"<<endl;
  }
  if( nUpsState==1){
  contamination1Sin2S=fUps[0]->Integral(massMin, massMax)/(fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  contamination3Sin2S=fUps[2]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 2S sample by 1S events = "<<contamination1Sin2S*100<<" %"<<endl;
  cout<<"Contamination of the 2S sample by 3S events = "<<contamination3Sin2S*100<<" %"<<endl;
  }
  if( nUpsState==2){
  contamination2Sin3S=fUps[1]->Integral(massMin, massMax)/(fUps[2]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax));
  cout<<"Contamination of the 3S sample by 2S events = "<<contamination2Sin3S*100<<" %"<<endl;
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];
  }

////////////////// Background mass scan
const int nMassScan=12;
int nMassScanCurrent;
//double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};
double MassScanBorders[nMassScan+1] = {8.6, 8.95, 9.3, 9.45, 9.6, 9.85, 10.0125, 10.175, 10.3425, 10.51, 10.8, 11.1, 11.4};

for(int i=1;i<nMassScan+1;i++){
if(nSigma<i+0.5) {nMassScanCurrent=i; break;}
}

double BuffMinL=onia::massMinL;
double BuffMaxL=mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
double BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
double BuffMaxR=onia::massMaxR;

double MassScanMin=MassScanBorders[nMassScanCurrent-1];
double MassScanMax=MassScanBorders[nMassScanCurrent];

if(nSigma==1){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==2){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==3){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==4){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}

if(nSigma==5){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==6){
	MassScanMin=BuffMinR+1./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
}
if(nSigma==7){
	MassScanMin=BuffMinR+2./3.*(BuffMaxR-BuffMinR);
	MassScanMax=BuffMaxR;
}
if(nSigma==8){
	MassScanMin=BuffMinR;
	MassScanMax=BuffMaxR;
}
if(nSigma>8){
	BuffMaxL=mass[UPS1S] - 7*sigma[UPS1S];
	BuffMinR=mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
}
if(nSigma==9){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==10){
	MassScanMin=BuffMinL+1./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
}
if(nSigma==11){
	MassScanMin=BuffMinL+2./3.*(BuffMaxL-BuffMinL);
	MassScanMax=BuffMaxL;
}
if(nSigma==12){
	MassScanMin=BuffMinL;
	MassScanMax=BuffMaxL;
}


  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;
  }
/////////////////////////////////////

  printf("--> signal mass window: %1.3f < M < %1.3f GeV\n", massMin, massMax);

  //calculate the fraction of BG under the signal mass window
  Double_t nBG = fBG->Integral(massMin, massMax);
//  Double_t nSignal = fUps[nUpsState]->Integral(massMin, massMax);
  Double_t nSignal = fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax)+fUps[2]->Integral(massMin, massMax);
  Double_t fracBG = nBG / (nBG + nSignal);
  sprintf(name, ";;fraction of BG in %1.1f sigma window", nSigma);
  TH1D *hFracBG = new TH1D("background_fraction", name, 1, 0., 1.);
  if(!UpsMC&&!f_BG_zero) hFracBG->SetBinContent(1, fracBG);
  if(UpsMC||f_BG_zero)  hFracBG->SetBinContent(1, 0.001);

 /* fBG->ReleaseParameter(1);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  double fBGPar0=fBG->GetParameter(1);
  double err_fBGPar0=fBG->GetParError(1);
  cout<<"fBGPar0 "<<fBGPar0<<endl;
  cout<<"err_fBGPar0 "<<err_fBGPar0<<endl;

  fBG->FixParameter(1,fBGPar0+100*err_fBGPar0);
  cout<<"fBGPar0 "<<fBG->GetParameter(1)<<endl;
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
  fBG->SetParameter(1,fBGPar0);
  cout<<"fBG "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[nUpsState]->Integral(massMin, massMax))<<endl;
*/

  if(Y1Sto2S_SB){
cout<<"Y1Sto2S_SB fBG = "<<fBG->Integral(massMin, massMax) / (fBG->Integral(massMin, massMax) + fUps[0]->Integral(massMin, massMax)+fUps[1]->Integral(massMin, massMax))<<endl;
  }

  backgroundFrac=fracBG;

  //calculate the L and R mass windows:
  Double_t massMinBG[2], massMaxBG[2];
  massMinBG[L] = onia::massMinL;
  massMaxBG[L] = mass[UPS1S] - onia::nSigmaL*sigma[UPS1S];
  massMinBG[R] = mass[UPS3S] + onia::nSigmaR*sigma[UPS3S];
  massMaxBG[R] = onia::massMaxR;
  printf("--> L mass window: %1.3f < M < %1.3f GeV\n", massMinBG[L], massMaxBG[L]);
  printf("--> R mass window: %1.3f < M < %1.3f GeV\n", massMinBG[R], massMaxBG[R]);
//cout<<"here?"<<endl;
  bool PseudoBin=false;

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  if(!UpsMC){
  if(massMaxBG[L] > massMin){
    printf("the right sideband window is LARGER than the left signal window!!!!\n\n\n\n");
    massMaxBG[L]=9.;
    massMinBG[L]=8.6;
    massMin=9.;
    PseudoBin=true;
//    exit(0);
  }
  if(massMinBG[R] < massMax){
    printf("the left sideband window is SMALLER than the right signal window!!!!\n\n\n\n");
    massMaxBG[R]=11.4;
    massMinBG[R]=11.;
    massMax=10.;
    PseudoBin=true;
//    exit(0);
  }
  }

  if(ProjectLSBdata){
	  massMin=massMinBG[L];
	  massMax=massMaxBG[L];
  }
  if(ProjectRSBdata){
	  massMin=massMinBG[R];
	  massMax=massMaxBG[R];
  }

  if(CombineSignalPeaks) {
	  massMin=9.15;
	  massMax=10.65;
  }

  double meanMass=0;
  double MassDistCurrent=0.001;
  TH1D *hMassScanInfo = new TH1D("hMassScanInfo", "hMassScanInfo", 2, 0., 1.);

  if(MassScan){
  massMin=MassScanMin;
  massMax=MassScanMax;

  double IntCurrent = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
  }

  hMassScanInfo->SetBinContent(1,meanMass);
  hMassScanInfo->SetBinContent(2,1-fracBG);

  }

  if(Y1Sto2S_SB){
	  massMin = mass[0] + 3.*sigma[0];
	  massMax = mass[1] - 4.*sigma[1];

	  double IntCurrent = fBG->Integral(massMin, massMax);
	  for(int i=1;i<1000000;i++){
		  if(fBG->Integral(massMin, massMin+i*MassDistCurrent)>IntCurrent/2.) {meanMass=massMin+i*MassDistCurrent; break;}
	  }
	  hMassScanInfo->SetBinContent(1,meanMass);
	  hMassScanInfo->SetBinContent(2,1-fracBG);
  }


  if(UpsMC&&iPTBin>5&&fracL<0.35){
	  cout<<"using exact mass window definition of data"<<endl;

  Double_t massMinUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.38372, 9.38435, 9.38425, 9.38487, 9.38326},
    {0,0,0,0,0, 9.35644, 9.3574, 9.35555, 9.35522, 9.34896}};
  Double_t massMaxUps1S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.518, 9.51711, 9.51826, 9.51701, 9.51941},
    {0,0,0,0,0, 9.53728, 9.53853, 9.5394, 9.54169, 9.54538}};

  Double_t massMinUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.94218, 9.94285, 9.94275, 9.9434, 9.94169},
    {0,0,0,0,0, 9.91328, 9.91429, 9.91234, 9.91198, 9.90535}};
  Double_t massMaxUps2S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.0844, 10.0835, 10.0847, 10.0834, 10.086},
    {0,0,0,0,0, 10.1049, 10.1062, 10.1071, 10.1096, 10.1135}};

  Double_t massMinUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.2715, 10.2722, 10.2721, 10.2728, 10.271},
    {0,0,0,0,0, 10.2416, 10.2427, 10.2407, 10.2403, 10.2335}};
  Double_t massMaxUps3S_1sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.4185, 10.4175, 10.4188, 10.4174, 10.42},
    {0,0,0,0,0, 10.4396, 10.441, 10.4419, 10.4444, 10.4485}};

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

  Double_t massMinUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.24945, 9.2516, 9.25025, 9.25273, 9.24711},
    {0,0,0,0,0, 9.1756, 9.17626, 9.17171, 9.16874, 9.15253}};
  Double_t massMaxUps1S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.65227, 9.64987, 9.65227, 9.64915, 9.65557},
    {0,0,0,0,0, 9.71811, 9.71966, 9.72048, 9.72149, 9.72017}};

  Double_t massMinUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 9.79992, 9.80219, 9.80076, 9.80339, 9.79744},
    {0,0,0,0,0, 9.72168, 9.72238, 9.72048, 9.72149, 9.72017}};
  Double_t massMaxUps2S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};

  Double_t massMinUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.1765, 10.1763, 10.1769, 10.1765, 10.177},
    {0,0,0,0,0, 10.1721, 10.1733, 10.1728, 10.1739, 10.1725}};
  Double_t massMaxUps3S_3sigma[3][10] = {
    {0,0,0,0,0, 0,0,0,0,0},
    {0,0,0,0,0, 10.5655, 10.5628, 10.5655, 10.562, 10.5691},
    {0,0,0,0,0, 10.6375, 10.6392, 10.6432, 10.6485, 10.6635}};


  if(nSigma==1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==3){
	  if(nUpsState==0){
		  massMin=massMinUps1S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_3sigma[iRapBin][iPTBin-1];
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_3sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_3sigma[iRapBin][iPTBin-1];
	  }
  }

  if(nSigma==0.5){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/4.;
	  }
  }

  if(nSigma==0.1){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1]+(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1]+(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1]+(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/20.;
	  }
  }

  if(nSigma==9){
	  if(nUpsState==0){
		  massMin=massMinUps1S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMin=massMinUps2S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMin=massMinUps3S_1sigma[iRapBin][iPTBin-1];
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }

  if(nSigma==10){
	  if(nUpsState==0){
		  massMax=massMaxUps1S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps1S_1sigma[iRapBin][iPTBin-1]-(massMaxUps1S_1sigma[iRapBin][iPTBin-1]-massMinUps1S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==1){
		  massMax=massMaxUps2S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps2S_1sigma[iRapBin][iPTBin-1]-(massMaxUps2S_1sigma[iRapBin][iPTBin-1]-massMinUps2S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
	  if(nUpsState==2){
		  massMax=massMaxUps3S_1sigma[iRapBin][iPTBin-1];
		  massMin=massMaxUps3S_1sigma[iRapBin][iPTBin-1]-(massMaxUps3S_1sigma[iRapBin][iPTBin-1]-massMinUps3S_1sigma[iRapBin][iPTBin-1])/2.;
	  }
  }


}





  ActualMassMin=massMin;
  ActualMassMax=massMax;


  //calculate central fracL

  double fracLCentral;

  if(!f_BG_zero){
  double mean_LSB;
  double mean_RSB;
  double mean_nS;

  double MassDist=0.001;
  double IntLSB = fBG->Integral(massMinBG[L], massMaxBG[L]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[L], massMinBG[L]+i*MassDist)>IntLSB/2.) {mean_LSB=massMinBG[L]+i*MassDist; break;}
  }
  double IntRSB = fBG->Integral(massMinBG[R], massMaxBG[R]);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMinBG[R], massMinBG[R]+i*MassDist)>IntRSB/2.) {mean_RSB=massMinBG[R]+i*MassDist; break;}
  }
  double IntSig = fBG->Integral(massMin, massMax);
  for(int i=1;i<1000000;i++){
	  if(fBG->Integral(massMin, massMin+i*MassDist)>IntSig/2.) {mean_nS=massMin+i*MassDist; break;}
  }

  fracLCentral=1-(mean_nS-mean_LSB)/(mean_RSB-mean_LSB);
  cout<<"Median LSB: "<<mean_LSB<<endl;
  cout<<"Median RSB: "<<mean_RSB<<endl;
  cout<<"Median signal region: "<<mean_nS<<endl;
  cout<<"Central FracL: "<<fracLCentral<<endl;


  }



  //build the 3D (pT, |y|, M) histos for the L and R mass sideband 
  TH3D *hBG_pTRapMass[2];
  hBG_pTRapMass[L] = new TH3D("hBG_pTRapMass_L", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[L]->Sumw2();
  //
  hBG_pTRapMass[R] = new TH3D("hBG_pTRapMass_R", ";p_{T} [GeV/c]; |y|; M [GeV]", 
			      7, onia::pTRange[iRapBin][iPTBin-1], onia::pTRange[iRapBin][iPTBin],
			      2, onia::rapForPTRange[iRapBin-1], onia::rapForPTRange[iRapBin],
			      7, massMin, massMax);//*signal* mass window!
  hBG_pTRapMass[R]->Sumw2();

  lepP = 0; lepN = 0;
  treeIn->SetBranchAddress("lepP", &lepP);
  treeIn->SetBranchAddress("lepN", &lepN);
  TLorentzVector *onia = new TLorentzVector();


  Double_t onia_mass;
  for(int iEn = 0; iEn < treeIn->GetEntries(); iEn++){ 
    Long64_t iEntry = treeIn->LoadTree(iEn);
    treeIn->GetEntry(iEntry);
    if(iEn % 10000 == 0)
      cout << "entry " << iEntry << " out of " << treeIn->GetEntries() << endl;

    *onia = *(lepP) + *(lepN);
    onia_mass = onia->M();

	  if(UpsMC||f_BG_zero) hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));
	  if(UpsMC||f_BG_zero) hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), gRandom->Uniform(massMin, massMax));

	  if(!UpsMC&&!f_BG_zero){
    if(onia_mass  > massMinBG[L] && onia_mass < massMaxBG[L])
      hBG_pTRapMass[L]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
    else if(onia_mass > massMinBG[R] && onia_mass < massMaxBG[R])
      hBG_pTRapMass[R]->Fill(onia->Pt(), TMath::Abs(onia->Rapidity()), fBG->GetRandom(massMin, massMax));
	  }

    if(onia_mass > massMin && onia_mass < massMax){
      treeOut->Fill(); //stores TLorenzVectors of the two muons

      // //store now the cosTheta and phi distributions of the signal window:
      // calcPol(*lepP, *lepN);

      // for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++)
      // 	hCosThetaPhiSignal[iFrame]->Fill(thisCosTh[iFrame], thisPhi[iFrame]);
    }


  }



/*  Char_t name2[100];
  sprintf(name2, "Reco_Onia_mass_rap%d_pT%d", iRapBin, iPTBin);
  TH1F* hMass = (TH1F*) gDirectory->Get(name2);
  hMass->Rebin(2);
  double binWidth = hMass->GetBinWidth(1); //valid only for an equal bin histogram!
  printf("binwidth = %1.2e\n", binWidth);
*/
  double nY[3];
  double nBG_;
  double binWidth = 0.02; //You have to manually change that parameter from the mass fit!!!

    nY[2] = fUps[2]->Integral(massMin, massMax)/binWidth;
    nY[1] = fUps[1]->Integral(massMin, massMax)/binWidth;
    nY[0] = fUps[0]->Integral(massMin, massMax)/binWidth;
    nBG_ = fBG->Integral(massMin, massMax)/binWidth;
    double nAll=nY[0]+nY[1]+nY[2]+nBG_;

    printf("1 sigma region num background = %1.3f\n",nBG_);
    printf("1 sigma region num 1S = %1.3f\n",nY[0]);
    printf("1 sigma region num 2S = %1.3f\n",nY[1]);
    printf("1 sigma region num 3S = %1.3f\n",nY[2]);
    printf("1 sigma region num all = %1.3f\n",nAll);
    printf("1 sigma region calcNumAll - numEventsInDataSet = %1.3f\n",nAll-treeOut->GetEntries());

    double tempBfrac=nBG_/(treeOut->GetEntries());
    printf("1 sigma region background fraction = %1.3f\n",tempBfrac);
    printf("Used           background fraction = %1.3f\n",backgroundFrac);

    SignalEvents=nY[nUpsState];

    double BackgroundEvents=SignalEvents*(1-backgroundFrac)/backgroundFrac;

    err_backgroundFrac=TMath::Power(SignalEvents*BackgroundEvents,0.5)/TMath::Power(SignalEvents+BackgroundEvents,1.5);

  //now, add the L and R 3D (pT, |y|, M) histos
  TH3D *hBG_pTRapMassSum;
  hBG_pTRapMass[L]->Scale(fracL/hBG_pTRapMass[L]->Integral());
  hBG_pTRapMass[R]->Scale((1.-fracL)/hBG_pTRapMass[R]->Integral());
  sprintf(name, "background_pTrapMass");
  hBG_pTRapMassSum = (TH3D*) hBG_pTRapMass[L]->Clone(name);
  hBG_pTRapMassSum->Add(hBG_pTRapMass[R]);

  //write the output
  fOut->cd();
  treeOut->Write();

  for(int iFrame = 0; iFrame < onia::kNbFrames; iFrame++){
    hBG_cosThetaPhi[iFrame]->Write();
    hBG_cosThetaPhiLR[iFrame][L]->Write();
    hBG_cosThetaPhiLR[iFrame][R]->Write();
    // hCosThetaPhiSignal[iFrame]->Write();
  }
  hBG_pTRapMassSum->Write();
  hFracBG->Write();
  if(MassScan){
	  hMassScanInfo->Write();
  }
  fOut->Close();
  fIn->Close();

  return fracLCentral;
}
Ejemplo n.º 23
0
//////////////////Taking in/out file name as input
void loop(string infile, string outfile, bool REAL=0){
//void loop(bool REAL=0){

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

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

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

     }

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

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

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

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

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

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

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

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

  outf->Write();
  outf->Close();
}
Ejemplo n.º 24
0
void HistInvMass(const int start = 0, const int end = 1){
  
  //Declare all histograms
  TH1F *Hinvmass0 = new TH1F("0", "Invariant Mass Distribution", 200, 0, 10);
  //Hinvmass0->Sumw2();
  TH1F *Hinvmass1 = new TH1F("1", "Invariant Mass Distribution", 200, 0, 101);
  //Hinvmass1->Sumw2();

  bool treedata = false; //true = pure tree data; false = calculated data
  
  //Muon Enhanced Proton Proton High Forest Data
  //
  //https://github.com/ilaflott/For_Ian/blob/master/4_Create_NTuples/filelists/ppMuon_data_filelist.txt
  //Copy this text file into a document called "ppMuon_data_filelist.txt" and save to src
  const string dataFileList = "ppMuon_data_filelist.txt";
  string fileList = dataFileList;
  ifstream fileStream(fileList.c_str(), ifstream::in);
  string fileName;
  fileStream >> fileName;
  
  int w = 0;
  for(; w < start; w++){fileStream>>fileName;} //skips all files before start file
  
  for(; w < end; w++){ //cycles from start file to end file
    cout<<fileName<<endl;
    if((w+1)%10==0){cout<<w+1<<endl;}
    
    TFile *file = TFile::Open(fileName.c_str());
    TTree *pf = (TTree*)file->Get("pfcandAnalyzer/pfTree");
    TTree *track = (TTree*)file->Get("ppTrack/trackTree");
    TTree *skim = (TTree*)file->Get("skimanalysis/HltTree");
    TTree *muon = (TTree*)file->Get("muonTree/HLTMuTree");
    TTree *hi =(TTree*)file->Get("hiEvtAnalyzer/HiTree");
    TTree *hlt = (TTree*)file->Get("hltanalysis/HltTree");
    
    Float_t mass = .1056583715;//mass of muon

    Float_t pfpt[100000];
    Float_t pfeta[100000];
    Float_t pfphi[100000];
    Int_t nPFpart;
    Int_t pfId[100000];
    Int_t charge[100000];
    Int_t pPA;
    Int_t noise;
    Int_t h = 0;
    Int_t i = 0;
    Int_t j = 0;
    Float_t mpt[100000];
    Float_t mrapidity[100000];
    Int_t pairs;
    Float_t mmass[100000];
    Int_t ch1[100000];
    Int_t ch2[100000];
    Float_t pz;
    Float_t vz;
    Float_t dipt1[100000];
    Float_t dipt2[100000];
    Float_t dieta1[100000];
    Float_t dieta2[100000];
    Float_t dieta[100000];
    Float_t diphi1[100000];
    Float_t diphi2[100000];
    Long64_t entries = 0;
    Float_t motherpt;
    Float_t motherrap;
    Float_t imass;
    Int_t mu12;
    Int_t mu7;
    Int_t mu3;
    Float_t Di_mass_sorted;
    
    pf->SetBranchAddress("pfPt",pfpt);
    pf->SetBranchAddress("pfEta",pfeta);
    pf->SetBranchAddress("pfPhi",pfphi);
    pf->SetBranchAddress("nPFpart",&nPFpart);
    pf->SetBranchAddress("pfId",&pfId);
    track->SetBranchAddress("trkCharge",charge);
    skim->SetBranchAddress("pPAcollisionEventSelectionPA", &pPA);
    skim->SetBranchAddress("pHBHENoiseFilter", &noise);
    muon->SetBranchAddress("Di_pt",mpt);
    muon->SetBranchAddress("Di_rapidity",mrapidity);
    muon->SetBranchAddress("Di_npair",&pairs);
    muon->SetBranchAddress("Di_mass",mmass);
    muon->SetBranchAddress("Di_charge1",ch1);
    muon->SetBranchAddress("Di_charge2",ch2);
    muon->SetBranchAddress("Di_pt1",dipt1);
    muon->SetBranchAddress("Di_pt2",dipt2);
    muon->SetBranchAddress("Di_eta",dieta);
    muon->SetBranchAddress("Di_eta1",dieta1);
    muon->SetBranchAddress("Di_eta2",dieta2);
    muon->SetBranchAddress("Di_phi1",diphi1);
    muon->SetBranchAddress("Di_phi2",diphi2);
    hi->SetBranchAddress("vz",&vz);
    hlt->SetBranchAddress("HLT_PAMu12_v1",&mu12);
    hlt->SetBranchAddress("HLT_PAMu7_v1",&mu7);
    hlt->SetBranchAddress("HLT_PAMu3_v1",&mu3);

    pf->AddFriend(muon);
    pf->AddFriend(track);
    pf->AddFriend(skim);
    pf->AddFriend(hi);
    pf->AddFriend(hlt);

    entries = pf->GetEntries();

    //Loop over each event
    for(h = 0; h < entries; h++){//Loop over every particle (first of pair)
      pf->GetEvent(h);
      
      if(pPA == 0 || noise == 0 || abs(vz) > 15)//cuts
	continue;

      if(treedata){//no (or minimal) calculation

	for(Int_t e = 0; e < pairs; e++){//loop through dimuon pairs
	  if(ch1[e] == ch2[e])
	    continue;
	  
	  motherpt = mpt[e];
	  motherrap = mrapidity[e];
	  imass = mmass[e];

	  //Fill all histograms
	  if(imass <= 10)
	    Hinvmass0->Fill(imass);
	  Hinvmass1->Fill(imass);
	}//end dimuon pair loop

      }//end if

      else{//all calculated data
	
	for(i = 0; i < nPFpart; i++){//loop through each particle
	  
	  if(pfId[i] != 3)//muon = 3
	    continue;
	  
	  for(j = i+1; j < nPFpart; j++){//loop through REST of particles; every pair is only checked once
	    
	    if(pfId[j] != 3)
	      continue;
	    if(charge[i] == charge[j])//pairs can only have opposite charge
	      continue;

	    TLorentzVector *muon1 = new TLorentzVector();
	    TLorentzVector *muon2 = new TLorentzVector();
	    muon1->SetPtEtaPhiE(pfpt[i], pfeta[i], pfphi[i], 0);//Pt Eta Phi Energy 4 vector
	    muon2->SetPtEtaPhiE(pfpt[j], pfeta[j], pfphi[j], 0);
	    muon1->SetPtEtaPhiE(pfpt[i], pfeta[i], pfphi[i], getEnergy(mass,muon1->P()));//remake vectors now that we have P
	    muon2->SetPtEtaPhiE(pfpt[j], pfeta[j], pfphi[j], getEnergy(mass,muon2->P()));
	    
	    TLorentzVector *mother = new TLorentzVector();
	    *mother = *muon1 + *muon2;
	    
	    motherpt = mother->Pt();
	    motherrap = mother->Rapidity();
	    imass = invmass(mass, muon1, muon2);
	    
	    //Fill all histograms
	    if(imass <= 10)
	      Hinvmass0->Fill(imass);
	    Hinvmass1->Fill(imass);

	  }//end second particle loop
	  
	}//end first particle loop
	
      }//end else
      
    }//end event loop
    fileStream >> fileName;
  }

  //Write all histograms to file  

  //TFile *plots = new TFile("invmass.root","RECREATE"); //Use if running as macro
  TFile f(Form("Output_%d.root",(start/(end-start))),"RECREATE"); //Use if running as batch job
  Hinvmass0->Write();
  Hinvmass1->Write();
}
Ejemplo n.º 25
0
int xAna::HggTreeWriteLoop(const char* filename, int ijob, 
					  bool correctVertex, bool correctEnergy, 
					  bool setRho0
					  ) {

  //bool invDRtoTrk = false;


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

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

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


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

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

//  mode_ = ijob; //  

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

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

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

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

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


  


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

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // 2x. radion analysis

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

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

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

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

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

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

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

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

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

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

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

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

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

      }
    }

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

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

  return nEvts[nEvts.size()-1];
}
Ejemplo n.º 26
0
void test_allEvt::ComputeAllVarPietro(TLorentzVector lepP,TLorentzVector lepN){
  // Preliminary definitions:

  const double pbeam = 7000.; // exact number irrelevant as long as pbeam >> Mprot
  const double Mprot = 0.9382720;
  const double Mlepton = 0.10566;  // (muon)
  const double gPI = TMath::Pi();
  const double Ebeam = sqrt( pbeam*pbeam + Mprot*Mprot );
  TLorentzVector beam1_LAB( 0., 0., pbeam, Ebeam );
  TLorentzVector beam2_LAB( 0., 0., -pbeam, Ebeam );


  // assuming that we have a TTree "data" (data ntuple) containing the 4-vectors lepP and lepN of lepton and antilepton

  // event by event (in some loop over dilepton events in the data ntuple):


  // data->GetEvent( i_event );

  // double lepP_pT  = lepP->Pt();
  // double lepN_pT  = lepN->Pt();

  // double lepP_eta = lepP->PseudoRapidity();
  // double lepN_eta = lepN->PseudoRapidity();

  // dilepton 4-vector:

  TLorentzVector dilepton = lepP + lepN;
  double pT   = dilepton.Pt();
  double rap  = dilepton.Rapidity();
  double mass = dilepton.M();

  // calculation of decay angles in three polarization frames

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


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


  // positive lepton in the dilepton rest frame:

  TLorentzVector lepton_DILEP = lepP;
  lepton_DILEP.Boost(lab_to_dilep);

  // CS frame angles:

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

  TRotation rotation;
  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.Vect();
  lepton_DILEP_rotated.Transform(rotation);

  /* double */ costh_CS = lepton_DILEP_rotated.CosTheta();
  /* double */ phi_CS   = lepton_DILEP_rotated.Phi() * 180. / gPI;
  double phith_CS;
  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;
  phi_CS   = phi_CS / 180. * gPI;


  // HELICITY frame angles:

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

  rotation.SetToIdentity();
  rotation.RotateAxes( newXaxis, newYaxis, newZaxis );
  rotation.Invert();
  lepton_DILEP_rotated = lepton_DILEP.Vect();
  lepton_DILEP_rotated.Transform(rotation);

  /* double */ costh_HX = lepton_DILEP_rotated.CosTheta();
  /* double */ phi_HX   = lepton_DILEP_rotated.Phi() * 180. / gPI;
  double phith_HX;
  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;
  phi_HX   = phi_HX / 180. * gPI;


  // // PERPENDICULAR HELICITY frame angles:

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

  // rotation.SetToIdentity();
  // rotation.RotateAxes( newXaxis, newYaxis, newZaxis );
  // rotation.Invert();
  // lepton_DILEP_rotated = lepton_DILEP.Vect();
  // lepton_DILEP_rotated.Transform(rotation);

  // double costh_PX = lepton_DILEP_rotated.CosTheta();
  // double phi_PX   = lepton_DILEP_rotated.Phi() * 180. / gPI;
  // double phith_PX;
  // 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;
  // phi_PX   = phi_PX / 180. * gPI;



}