void toyMCele_cat1(std::string inputFile, std::string outputFile){

  // read the ntuples (in pcncu)

  TreeReader data(inputFile.data());

  // Declare the histogram

  TFile* f = new TFile(inputFile.data());
  TH1D* h_totalEvents = (TH1D*)f->Get("h_totalEv");

  TH1D* h_PRmassNoSIG = new TH1D("h_PRmassNoSIG",  "PRmassNoSIG",    40,   40,  240);
  TH1D* h_PRmassAll   = new TH1D("h_PRmassAll",    "PRmassAll",      40,   40,  240);

  h_PRmassNoSIG->Sumw2();
  h_PRmassAll  ->Sumw2();

  h_PRmassNoSIG->GetXaxis()->SetTitle("corrPRmass");
  h_PRmassAll  ->GetXaxis()->SetTitle("corrPRmass");

  // begin of event loop

  Long64_t nentries = data.GetEntriesFast();

  for(Long64_t ev = 0; ev < nentries; ev++){

    if( ev % 1000000 == 0 )
      fprintf(stderr, "Processing event %lli of %lli\n", ev + 1, nentries);

    data.GetEntry(ev);

    Float_t        eventWeight       = data.GetFloat("ev_weight"); 
    TClonesArray*  eleP4             = (TClonesArray*) data.GetPtrTObject("eleP4");
    Int_t          FATnJet           = data.GetInt("FATnJet");    
    Int_t*         FATnSubSDJet      = data.GetPtrInt("FATnSubSDJet");
    Float_t*       corrPRmass        = data.GetPtrFloat("FATjetPRmassL2L3Corr");
    TClonesArray*  FATjetP4          = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    vector<bool>&  FATjetPassIDLoose = *((vector<bool>*) data.GetPtr("FATjetPassIDLoose"));
    vector<float>* FATsubjetSDPx     = data.GetPtrVectorFloat("FATsubjetSDPx", FATnJet);
    vector<float>* FATsubjetSDPy     = data.GetPtrVectorFloat("FATsubjetSDPy", FATnJet);
    vector<float>* FATsubjetSDPz     = data.GetPtrVectorFloat("FATsubjetSDPz", FATnJet);
    vector<float>* FATsubjetSDE      = data.GetPtrVectorFloat("FATsubjetSDE", FATnJet);
    vector<float>* FATsubjetSDCSV    = data.GetPtrVectorFloat("FATsubjetSDCSV", FATnJet);

    // select good leptons
      
    vector<Int_t> goodLepID;

    TLorentzVector* thisLep = NULL;
    TLorentzVector* thatLep = NULL;

    if( !isPassZee(data,goodLepID) ) continue;
	
    thisLep = (TLorentzVector*)eleP4->At(goodLepID[0]);   
    thatLep = (TLorentzVector*)eleP4->At(goodLepID[1]);   

    // select good FATjet

    Int_t goodFATJetID = -1;
    TLorentzVector* thisJet = NULL;

    for(Int_t ij = 0; ij < FATnJet; ij++){

      thisJet = (TLorentzVector*)FATjetP4->At(ij);

      if( thisJet->Pt() < 200 ) continue;
      if( fabs(thisJet->Eta()) > 2.4 ) continue;
      if( !FATjetPassIDLoose[ij] ) continue;
      if( thisJet->DeltaR(*thisLep) < 0.8 || thisJet->DeltaR(*thatLep) < 0.8 ) continue;
      
      Int_t nsubBjet = 0;

      for(Int_t is = 0; is < FATnSubSDJet[ij]; is++){

	if( FATsubjetSDCSV[ij][is] > 0.605 ) nsubBjet++;

      }

      Double_t subjetDeltaR = -1;

      if( nsubBjet == 2 ){

	TLorentzVector l4_subjet0(0,0,0,0);
	TLorentzVector l4_subjet1(0,0,0,0);

	l4_subjet0.SetPxPyPzE(FATsubjetSDPx[ij][0],
			      FATsubjetSDPy[ij][0],
			      FATsubjetSDPz[ij][0],
			      FATsubjetSDE [ij][0]);

	l4_subjet1.SetPxPyPzE(FATsubjetSDPx[ij][1],
			      FATsubjetSDPy[ij][1],
			      FATsubjetSDPz[ij][1],
			      FATsubjetSDE [ij][1]);

	subjetDeltaR = l4_subjet0.DeltaR(l4_subjet1);

      }

      // deltaR depends loose cut

      if( subjetDeltaR > 0.3 ) continue;
      if( nsubBjet < 1 ) continue;
      
      goodFATJetID = ij;
      break;

    }

    if( goodFATJetID < 0 ) continue;

    Float_t mllbb = (*thisLep+*thatLep+*thisJet).M();  

    if( mllbb < 750 ) continue;

    h_PRmassAll->Fill(corrPRmass[goodFATJetID],eventWeight);

    if( corrPRmass[goodFATJetID] > 30 && !(corrPRmass[goodFATJetID] > 65 && corrPRmass[goodFATJetID] < 135) && corrPRmass[goodFATJetID] < 300 )
      h_PRmassNoSIG->Fill(corrPRmass[goodFATJetID],eventWeight);

  } // end of event loop

  fprintf(stderr, "Processed all events\n");

  TFile* outFile = new TFile(Form("%s_pseudoTest.root",outputFile.c_str()), "recreate");
  
  h_PRmassNoSIG->Write("corrPRmass");
  h_PRmassAll  ->Write("corrPRmassAll");
  h_totalEvents->Write("totalEvents");

  outFile->Write();

  delete f;
  delete outFile;

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

		}//end event loop----------------------------------------------------------------------------------------
	}	//end ntuple loop----------------------------------------------------------------------------------------
	cout<<"entries="<<total<<endl;	
	for(int i=0;i<6;i++)cout<<"nPassB["<<i<<"]="<<nPassB[i]<<endl;
	for(int i=0;i<16;i++)cout<<"nPass["<<i<<"]="<<nPass[i]<<endl;
	
	for(int i=0;i<3;i++)th7[3]->SetBinContent(i+1,passPileup[i]/totalPileup[i]);
	for(int i=0;i<101;i++)th7[4]->SetBinContent(i+1,passPDF[i]/totalPDF[i]);
	
	TH1D * th2o=new TH1D("Nbtagjet","Nbtagjet",5,-0.5,4.5);
	for (int i=0;i<5;i++){
		if(nameRoot==2 && i>2)continue;
		th2o->SetBinContent(i+1,nPass[i+10]);
	}
	TH1D * th2ob=new TH1D("NbtagjetB","NbtagjetB",5,-0.5,4.5);
	for (int i=0;i<5;i++){
		if(nameRoot==2 && i>2)continue;
		th2ob->SetBinContent(i+1,nPassB[i]);
	}
	
	TH1D * fixScale=new TH1D("fixScale","fixScale",2,-0.5,1.5);
	fixScale->SetBinContent(1,fixScaleNum[0]);
	fixScale->SetBinContent(2,fixScaleNum[1]);
	TH1D * cutflow=new TH1D("cutflow","cutflow",16,0.5,16.5);
	cutflow->SetBinContent(1,total);
	if(nameRoot==2)for(int ii=1;ii<14;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	else for(int ii=1;ii<16;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	
	TFile* outFile = new TFile(Form("root_file_mike/%s.root",st2.data()),"recreate");
	th2o->Write();
	th2ob->Write();
	fixScale->Write();
	cutflow->Write();
	for(int i=0;i<6;i++)th3[i]->Write();
	for(int i=0;i<14;i++)th4[i]->Write();
	for(int i=0;i<276;i++){
		th5[i]->Write();
		th6[i]->Write();
	}
	for(int i=0;i<14;i++)th7[i]->Write();
	outFile->Close();
}
int main(int argc, char * argv[]) {

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

  using namespace std;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  int nonOverlap = 0;

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


  for (int iF=0; iF<nTotalFiles; ++iF) {

    std::string filen;
    fileList >> filen;

    std::cout << "file " << iF+1 << " out of " << nTotalFiles << " filename : " << filen << std::endl;
    TFile * file_ = TFile::Open(TString(filen));
    
    TTree * _tree = NULL;
    _tree = (TTree*)file_->Get(TString(ntupleName));
  
    if (_tree==NULL) continue;
    
    TH1D * histoInputEvents = NULL;
   
    histoInputEvents = (TH1D*)file_->Get("makeroottree/nEvents");
    
    if (histoInputEvents==NULL) continue;
    
    int NE = int(histoInputEvents->GetEntries());
    
    std::cout << "      number of input events    = " << NE << std::endl;
    
    for (int iE=0;iE<NE;++iE)
      inputEventsH->Fill(0.);

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

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

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

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

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

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

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

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

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

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

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

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

	unsigned int eIndex  = electrons.at(ie);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      TLorentzVector dileptonLV = electronLV + tauLV;

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

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

      // dimuon veto
      otree->dilepton_veto = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	otree->mjj = (jet1+jet2).M();
	otree->jdeta = abs(analysisTree.pfjet_eta[indexLeadingJet]-
		    analysisTree.pfjet_eta[indexSubLeadingJet]);
 
	float etamax = analysisTree.pfjet_eta[indexLeadingJet];
	float etamin = analysisTree.pfjet_eta[indexSubLeadingJet];
	if (etamax<etamin) {
	  float tmp = etamax;
	  etamax = etamin;
	  etamin = tmp;
	}
	for (unsigned int jet=0; jet<jetspt20.size(); ++jet) {
	  int index = jetspt20.at(jet);
	  float etaX = analysisTree.pfjet_eta[index];
	  if (index!=indexLeadingJet&&index!=indexSubLeadingJet&&etaX>etamin&&etaX<etamax) 
	    otree->njetingap++;
	}
      }
      
      otree->Fill();
      selEvents++;
    } // end of file processing (loop over events in one file)
    nFiles++;
    delete _tree;
    file_->Close();
    delete file_;
  }
  std::cout << std::endl;
  int allEvents = int(inputEventsH->GetEntries());
  std::cout << "Total number of input events    = " << allEvents << std::endl;
  std::cout << "Total number of events in Tree  = " << nEvents << std::endl;
  std::cout << "Total number of selected events = " << selEvents << std::endl;
  std::cout << std::endl;
  
  file->cd("");
  file->Write();
  file->Close();
  delete file;
  
}
Beispiel #4
0
// // //
bool analysisClass::PreSelection(TString Process){
  //
  int TotalN=0;
  int TotalTau=0;
  int TotalMu=0;
  int TotalEl=0;
  int TotalJet=0;
  int TotalBJet=0;
  TotalTau  = TauCounter();
  TotalMu   = MuCounter();
  TotalEl   = ElCounter();
  TotalJet  = JetCounter();
  TotalBJet = BJetCounter();
  TotalN = TotalTau + TotalMu + TotalEl + TotalJet;
  //
  double LeadMuTauDeltaR=0;
  TLorentzVector Mu;
  TLorentzVector Tau;
  Mu.SetPtEtaPhiM(0,0,0,0);
  Tau.SetPtEtaPhiM(0,0,0,0);
  for(unsigned int iTauR=0; iTauR<HPSTauPt->size(); iTauR++){
    if( !tauRisoCheck(iTauR) )continue;
    if( tauPtcorr(iTauR)>Tau.Pt() ){
      Tau.SetPtEtaPhiM(tauPtcorr(iTauR), HPSTauEta->at(iTauR), HPSTauPhi->at(iTauR), 0);
    }
  }
  for(unsigned int iMuR=0; iMuR<MuonPt->size(); iMuR++){
    if( !muRisoCheck(iMuR) )continue;
    if( muPtcorr(iMuR)>Mu.Pt() ){
      Mu.SetPtEtaPhiM(muPtcorr(iMuR), MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
    }
  }
  if( TotalMu>0 && TotalTau>0 ) LeadMuTauDeltaR=Mu.DeltaR(Tau);
  //
  //
  if( Process != "Neutr" && Process != "Neutr2Jet" && Process != "NeutrNoQCD" && Process != "Neutr2JetNoQCD" && Process != "Neutr2Jet250ST" && Process != "Neutr2Jet250STtuneZ"
      && Process != "Neutr0Btag" && Process != "Neutr0BtagNoQCD" && Process != "Neutr2Jet350STtuneZ" && Process != "Neutr1Jet350STtuneZ"
      && Process != "Neutr1Jet350ST" && Process != "Neutr1Jet300ST" && Process != "Neutr1Jet500ST"
      && Process != "ZToMuMuAnalysis" && Process != "ZToMuTauAnalysis" && Process != "TTBar" && Process != "WJets" && Process != "FakeTaus" && Process != "ControlRegion1"
      && Process != "FakeMuons" && Process != "FakeMuonsV2" && Process != "FakeMuonsV3" && Process != "ZJets" && Process != "QCD" && Process != "LQ3M400" ){ return false; }
  //
  if( Process == "Neutr" ){
    //if( MaxDiLepInvMass()<55    ) return false;
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    //if( isZToMuMu()             ) return false;//required to exclude events in MuTrig Calculation
    if( TotalJet<1              ) return false;
  }
  if( Process == "Neutr2Jet" ){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( TotalJet<2              ) return false;
  }
  if( Process == "Neutr2Jet250ST" ){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( TotalJet<2              ) return false;
    if( ST()<250                ) return false;
  }
  if( Process == "Neutr2Jet250STtuneZ" ){
    if( MaxMuMuInvMass()>0   && MaxMuMuInvMass()<55   ) return false;
    if( MaxMuTauInvMass()>0  && MaxMuTauInvMass()<55  ) return false;
    if( MaxTauTauInvMass()>0 && MaxTauTauInvMass()<55 ) return false;
    if( TotalJet<2              ) return false;
    if( ST()<250                ) return false;
  }
  if( Process == "Neutr2Jet350STtuneZ" ){
    if( MaxMuMuInvMass()>0   && MaxMuMuInvMass()<55   ) return false;
    if( MaxMuTauInvMass()>0  && MaxMuTauInvMass()<55  ) return false;
    if( MaxTauTauInvMass()>0 && MaxTauTauInvMass()<55 ) return false;
    if( TotalJet<2              ) return false;
    if( ST()<350                ) return false;
  }
  if( Process == "Neutr1Jet350STtuneZ" ){
    if( MaxMuMuInvMass()>0   && MaxMuMuInvMass()<55   ) return false;
    if( MaxMuTauInvMass()>0  && MaxMuTauInvMass()<55  ) return false;
    if( MaxTauTauInvMass()>0 && MaxTauTauInvMass()<55 ) return false;
    if( TotalJet<1              ) return false;
    if( ST()<350                ) return false;
  }
  if( Process == "Neutr1Jet350ST" ){
    if( TotalJet<1              ) return false;
    if( ST()<350                ) return false;
  }
  if( Process == "Neutr1Jet500ST" ){
    if( TotalJet<1              ) return false;
    if( ST()<500                ) return false;
  }
  if( Process == "Neutr1Jet300ST" ){
    if( TotalJet<1              ) return false;
    if( ST()<300                ) return false;
  }
  if( Process == "Neutr0Btag"){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( TotalBJet>0             ) return false;
  }
  if( Process == "Neutr0BtagNoQCD"){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( TotalBJet>0             ) return false;
    if( METlepMT("Mu")<75       ) return false;
  }
  if( Process == "NeutrNoQCD" ){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( isZToMuMu()             ) return false;//required to exclude events in MuTrig Calculation
    if( TotalJet<1              ) return false;
    if( METlepMT("Mu")<60       ) return false;
  }
  if( Process == "Neutr2JetNoQCD" ){
    if( MaxMuMuInvMass()>0 && MaxMuMuInvMass()<50 ) return false;
    if( isZToMuMu()             ) return false;//required to exclude events in MuTrig Calculation
    if( TotalJet<2              ) return false;
    if( METlepMT("Mu")<60       ) return false;
  }
  //
  if( Process == "FakeTaus" ){
    if( TotalBJet>0              ) return false;
    if( METlepMT("Mu")<40        ) return false;
    if( TotalJet<1               ) return false;
    //if( RecoSignalType()!=-2110  ) return false;//this is mu,tau opp sign
    if( RecoSignalType()!=+2110  ) return false;//this is mu,tau same sign
    if( MaxMuTauInvMass()<80     ) return false;
    //
    if( !isOneMuonSuperIso()     ) return false;
  }
  if( Process == "ZToMuTauAnalysis" ){
    if( MaxMuTauInvMass()<20     ) return false;
    if( TotalBJet>0              ) return false;
    if( METlepMT("Mu")>40        ) return false;
    if( METlepMT("Tau")>90       ) return false;
    if( TotalJet<1               ) return false;
    if( RecoSignalType()!=-2110  ) return false;//this is mu,tau opp sign
    if( MuTaudeltaPzeta()<-15    ) return false;
    //
    if( !isOneMuonSuperIso()     ) return false;
    //
    if( MaxMuTauInvMass()<45 || MaxMuTauInvMass()>75 ) return false;
  }
  if( Process == "ZToMuMuAnalysis" ){
    double MaxMuMuInvMass_ = MaxMuMuInvMass();
    double LeadingMuPt_ =LeadingMuPt();
    if( LeadingMuPt_<35          ) return false;//LJ filter
    if( MaxMuMuInvMass_<80 || MaxMuMuInvMass_>100 ) return false;
    if( TotalJet<1               ) return false;
    if( ST()<300                 ) return false;
    if( TotalBJet>0              ) return false;
    if( RecoSignalType()!=-2020  ) return false;//this is mu,mu opp sign
  }
  if( Process == "FakeMuons" ){
    double LeadingMuPt_  = LeadingMuPt();
    if( LeadingMuPt_<35          ) return false;//LJ filter
    if( TotalJet<1               ) return false;
    double LeadingJetPt_ = LeadingJetPt();
    if( LeadingJetPt_<50         ) return false;
    if( ST()<400                 ) return false;
    if( METlepMT("Mu")>20        ) return false;
    if( METcorr("Pt")>20  ) return false;
    //if( TotalBJet>0              ) return false;
    if( abs(RecoSignalType())!=1010  ) return false;//this is one mu
  }
  if( Process == "FakeMuonsV2" ){
    ////double LeadingMuPt_  = LeadingMuPt();
    ////if( LeadingMuPt_<35          ) return false;//LJ filter removed
    if( TotalJet<1                   ) return false;
    //double LeadingJetPt_ = LeadingJetPt();
    //if( LeadingJetPt_<50         ) return false;
    //if( !isZToMuMu()             ) return false;
    //if( ST()>350                 ) return false;
    if( METlepMT("Mu")>20            ) return false;
    if( METcorr("Pt")>20      ) return false;
    if( abs(RecoSignalType())!=1010  ) return false;//this is one mu
  }
  if( Process == "FakeMuonsV3" ){
    if( METlepMT("Mu")>10            ) return false;
    if( METcorr("Pt")>10      ) return false;
    if( TotalJet<1                   ) return false;//
    if( abs(RecoSignalType())!=1010  ) return false;//this is one mu
    if( !isAllMuonsHLT()             ) return false;//mu has to match the trigger
    //
    //--------- Veto on 2nd Global Muon ---------------------
    int nGlobalMuons=0;
    for(unsigned int iMuR=0;  iMuR<MuonPt->size();     iMuR++){
      if( muPtcorr(iMuR)>MuonPtCut && fabs(MuonEta->at(iMuR))<2.1 && MuonIsGlobal->at(iMuR)==1 ) nGlobalMuons++;
    }
    if( nGlobalMuons>1               ) return false;
    //
    //--------- Check for back-to-back Jet-Muon -------------
    bool isBackToBackJet=false;
    TLorentzVector Mu;
    TLorentzVector Jet;
    for(unsigned int iMuR=0;  iMuR<MuonPt->size();     iMuR++){
      if( !muRisoCheck(iMuR)     ) continue;
      Mu.SetPtEtaPhiM(muPtcorr(iMuR), MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      for(unsigned int iJetR=0;  iJetR<PFJetPt->size();     iJetR++){
	if( !jetRTightCheck(iJetR) ) continue;
	Jet.SetPtEtaPhiM( jetPtcorr(iJetR), PFJetEta->at(iJetR), PFJetPhi->at(iJetR), 0 );
	if( (fabs(fabs(Mu.DeltaPhi(Jet))-TMath::Pi())/TMath::Pi())<0.1 )  isBackToBackJet=true;
      }
    }
    //--------- Check for back-to-back Jet-Muon ------------- 
    if( !isBackToBackJet             ) return false;
  }
  if( Process == "ControlRegion1" ){
    //low in signal contamination, to check tau fakes loose->tight ratio
    if( TotalBJet<1                    ) return false;
    if( TotalJet<2                     ) return false;
    ///ST cut reverted
    ///remove MaxMuTauInvMass CUT:  /*if( MaxMuTauInvMass()<100          ) return false;*/
    if( LeadingTauPt()<50              ) return false;
    if( RecoSignalType()!=2110         ) return false;// SS selection
    if( isZToMuMu()                    ) return false;// required to exclude events in MuTrig Calculation  
    //
    if( ST()>400                       ) return false;// Revert the ST cut
  }
  if( Process == "TTBar" ){
    double ZToMuMuCentral = 90;
    double ZToMuTauCentral = 75;
    if( MaxDiLepInvMass()<65       ) return false;
    if( TotalN<5                 ) return false;
    if( ST()<250           ) return false;
    if( RecoSignalType()>0 ) return false;
    if( TotalJet<3               ) return false;
    if( fabs(MuTauInZpeak("ZToMuMu")-ZToMuMuCentral)<10  ) return false; //exclue 80-100
    if( fabs(MuTauInZpeak("ZToMuTau")-ZToMuTauCentral)<15 ) return false; //exclude 60-90
  }
  if( Process == "WJets" ){
    double ZToMuMuCentral = 90;
    double ZToMuTauCentral = 75;
    if( MaxDiLepInvMass()<65       ) return false;
    if( TotalMu!=1          ) return false;
    if( TotalJet!=0         ) return false;
    if( ST()>250      ) return false;
    if( fabs(MuTauInZpeak("ZToMuMu")-ZToMuMuCentral)<10  ) return false; //exclue 80-100
    if( fabs(MuTauInZpeak("ZToMuTau")-ZToMuTauCentral)<15 ) return false; //exclude 60-90
  }
  if( Process == "ZJets" ){
    if( MaxDiLepInvMass()<65 ) return false;
    if( METlepMT("Mu")>50  ) return false;
    if( TotalMu < 2                ) return false;
    double ZToMuMuCentral  = 90;
    double ZToMuTauCentral = 75;
    bool   dilepZpeak_     = false;
    if( fabs(MuTauInZpeak("ZToMuMu")-ZToMuMuCentral)<10  ) dilepZpeak_=true; //accept 80-100
    if( fabs(MuTauInZpeak("ZToMuTau")-ZToMuTauCentral)<15 ) dilepZpeak_=true; //accept 60-90
    if( !dilepZpeak_               ) return false;
  }
  if( Process == "LQ3M400" ){
    if( MaxDiLepInvMass()<65       ) return false;
    if( LeadMuTauDeltaR>4          ) return false;
    if( TotalN<4                   ) return false;
    if( METcorr("Pt")<30    ) return false;
    if( ST()<400             ) return false;
    if( RecoSignalType()<0   ) return false;
  }
  //
  return true;
  //
}
Beispiel #5
0
int main(int argc, char** argv) {
    std::vector<std::string> inputFileNames;
    std::string plotFileName;
    TH1D * METResolutions = 0;
    double doJES = 1;
    bool isData = false;
    bool applyJetPt = false;
    bool e_mtw = false;
    int smearingSkim = 1;
    string sample = "";
    string ttDecayMode = "";
    string prefix = "";
    string myFlavor = "";
    int ptrw = 0;
    int metphi = 0;
    int nWM = 0;
    int nWP = 0;
    int nSRP = 0;
    int nSRM = 0;
    int nSBP = 0;
    int nSBM = 0;
    TString dirName = "";
    bool isStack = false;
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));
        if (arg_fth == "prefix") {
            f++;
            std::string in(*(argv + f));
            prefix = in + string("_");
        } else if (arg_fth == "input") {
            f++;
            std::string in(*(argv + f));
            if (dirName == "TreesEle" && in == "Data")
                inputFileNames.push_back(string("~/work/samples/postMoriond/Aug2013/" + prefix + in + "_Ele.root"));
            else
                inputFileNames.push_back(string("~/work/samples/postMoriond/Aug2013/" + prefix + in + ".root"));
            sample = in;
            plotFileName = prefix + in + "_plots.root";
        } else if (arg_fth == "JES") {
            f++;
            std::string in(*(argv + f));
            doJES = atof(in.c_str());
        } else if (arg_fth == "isData") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                isData = true;
            else
                isData = false;
        } else if (arg_fth == "METResolFileName") {
            f++;
            std::string in(*(argv + f));
            TFile * METResolFileName = TFile::Open(in.c_str());
            METResolutions = (TH1D*) METResolFileName->Get("METresolutions");
        } else if (arg_fth == "smearingSkim") {
            f++;
            std::string in(*(argv + f));
            smearingSkim = atof(in.c_str());
        } else if (arg_fth == "ttDecayMode") {
            f++;
            std::string in(*(argv + f));
            ttDecayMode = in;
        } else if (arg_fth == "dirName") {
            f++;
            std::string in(*(argv + f));
            dirName = in.c_str();
        } else if (arg_fth == "stack") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                isStack = true;
            else
                isStack = false;
        } else if (arg_fth == "dojetpt") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                applyJetPt = true;
            else
                applyJetPt = false;
        } else if (arg_fth == "flavor") {
            f++;
            std::string in(*(argv + f));
            myFlavor = in;
        } else if (arg_fth == "ptrw") {
            f++;
            std::string in(*(argv + f));
            ptrw = atof(in.c_str());
        } else if (arg_fth == "metphi") {
            f++;
            std::string in(*(argv + f));
            metphi = atof(in.c_str());
            cout << "================ " << metphi << endl;
        } else if (arg_fth == "emtw") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                e_mtw = true;
            else
                e_mtw = false;
        }
    }
    int channel = 0;
    if (dirName == "TreesEle")
        channel = 1;
    PVHists atLeastOnGPV("DefW_PV");
    JetHists Jets("DefW_Jet", 2);
    if (!isStack)
        Jets.SetErrors(true);
    JetHists BJets("DefW_BJet", 2);
    if (!isStack)
        BJets.SetErrors(true);
    JetHists nonBJets("DefW_nonBJet", 2);
    if (!isStack)
        nonBJets.SetErrors(true);
    JetHists FwDJet("DefW_FwD", 2);
    if (!isStack)
        FwDJet.SetErrors(true);
    MuonHists GoldenFinalPUMuons("DefW_Muon", 3);
    if (!isStack)
        GoldenFinalPUMuons.SetErrors(true);
    MetHists MetHist("DefW_Met");
    if (!isStack)
        MetHist.SetErrors(true);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

    cout << "START" << endl;

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    cout << nInit << "\n" << nHLTrunB << "\n" << nMt << "\n" << nFinal << "\n" << nGoodSolution << endl;
    cout << "nW+: " << nWP << "\tnW-: " << nWM << endl;
    cout << "SR+" << nSRP << endl;
    cout << "SR-" << nSRM << endl;
    cout << "SB+" << nSBP << endl;
    cout << "SB-" << nSBM << endl;
    return 0;
}
void fitSingleMass( const std::string& basedir, float mass, const std::string&  width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) {


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


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

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

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

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



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

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



  int nentries = tree->GetEntries();


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

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

    tree->GetEntry(iEntry);

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

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

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

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

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

    } // for genparts

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


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

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

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

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

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

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

  }


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

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

  model->fitTo( *data );

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

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

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

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

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

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

  c1->SetLogy();

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


  //delete bw_mean;
  //delete bw_gamma;

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

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


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

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



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

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


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



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

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

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

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

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

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

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

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

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

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

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

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

    }

    rochcor2015 *rmcor = new rochcor2015();


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

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

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

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

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

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

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

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

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

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

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

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



    int nentries = tree->GetEntries();

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

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

        myTree.GetEntry(iEntry);

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


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

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

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

        }

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

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

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

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

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


        TLorentzVector genPhoton;
        bool foundGenPhoton = false;

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

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

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

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

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

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

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

            }

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


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

        }


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


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

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


        // and now reco!

        if( myTree.nVert==0 ) continue;


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

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


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

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

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


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


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

        bool foundPhoton = false;
        TLorentzVector photon;

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

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

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

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

        }

        if( !foundPhoton ) continue;

        smearEmEnergy( photon );

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

        h1_eff_noHLT_num->Fill( genMass, weight );

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

        h1_eff_noIso_num->Fill( genMass, weight );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        outtree->Fill();

    } // for entries


    outFile->cd();

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

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

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

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

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

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


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

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

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

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

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

    }

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

    outtree->Write();

    outFile->Close();

    return 0;

}
void 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; }
Beispiel #9
0
///
///________________________________________________________________________________
///
Bool_t
UEJetAreaFinder::find( TClonesArray& Input, vector<UEJetWithArea>& _jets )
{
  /// return if no four-vectors are provided
  if ( Input.GetSize() == 0 ) return kFALSE;

  /// prepare input
  std::vector<fastjet::PseudoJet> fjInputs;
  fjInputs.reserve ( Input.GetSize() );

  int iJet( 0 );
  for( int i(0); i < Input.GetSize(); ++i )
    {
      TLorentzVector *v = (TLorentzVector*)Input.At(i);

      if ( TMath::Abs(v->Eta()) > etaRegionInput ) continue;
      if ( v->Pt()              < ptThreshold    ) continue;

      fjInputs.push_back (fastjet::PseudoJet (v->Px(), v->Py(), v->Pz(), v->E()) );
      fjInputs.back().set_user_index(iJet);
      ++iJet;
    }

  /// return if no four-vectors in visible phase space
  if ( fjInputs.size() == 0 ) return kFALSE;
  
  /// print out info on current jet algorithm
  //   cout << endl;
  //   cout << mJetDefinition->description() << endl;
  //   cout << theAreaDefinition->description() << endl;

  /// return if active area is not chosen to be calculated
  if ( ! theAreaDefinition ) return kFALSE;

  //  cout << "fastjet::ClusterSequenceActiveArea* clusterSequence" << endl;
  
  fastjet::ClusterSequenceArea* clusterSequence
    = new fastjet::ClusterSequenceArea (fjInputs, *mJetDefinition, *theAreaDefinition );

  //  cout << "retrieve jets for selected mode" << endl;

  /// retrieve jets for selected mode
  double mJetPtMin( 1. );
  std::vector<fastjet::PseudoJet> jets( clusterSequence->inclusive_jets (mJetPtMin) );
  unsigned int nJets( jets.size() );

  if ( nJets == 0 ) 
    {
      delete clusterSequence;
      return kFALSE;
    }
  //Double_t ptByArea[ nJets ];

  //   int columnwidth( 10 );
  //cout << "found " << jets.size() << " jets" << endl;
  //   cout.width( 5 );
  //   cout << "jet";
  //   cout.width( columnwidth );
  //   cout << "eta";
  //   cout.width( columnwidth );
  //   cout << "phi";
  //   cout.width( columnwidth );
  //   cout << "pT";
  //   cout.width( columnwidth );
  //   cout << "jetArea";
  //   cout.width( 15 );
  //   cout << "pT / jetArea";
  //   cout << endl;
  
  _jets.reserve( nJets );

  vector< fastjet::PseudoJet > sorted_jets ( sorted_by_pt( jets ));
  for ( int i(0); i<nJets; ++i )
    {
      //ptByArea[i] = jets[i].perp()/clusterSequence->area(jets[i]);

      //       cout.width( 5 );
      //       cout << i;
      //       cout.width( columnwidth );
      //       cout << jets[i].eta();
      //       cout.width( columnwidth );
      //       cout << jets[i].phi();
      //       cout.width( columnwidth );
      //       cout << jets[i].perp();
      //       cout.width( columnwidth );
      //       cout << clusterSequence->area(jets[i]);
      //       cout.width( 15 );
      //       cout << ptByArea[i];
      //       cout << endl;

      /// save
      ///
      /// TLorentzVector
      /// area
      /// nconstituents
      
      fastjet::PseudoJet jet( sorted_jets[i] );
      vector< fastjet::PseudoJet > constituents( clusterSequence->constituents(jet) );
      
      TLorentzVector* mom    = new TLorentzVector( jet.px(), jet.py(), jet.pz(), jet.e() );
      double          area   = clusterSequence->area(jet);
      //  double          median = TMath::Median( nJets, ptByArea );
      unsigned int    nconst = constituents.size();
      
      UEJetWithArea* theJet = new UEJetWithArea( *mom, area, nconst);
      //_jets[i] = *theJet;
      _jets.push_back( *theJet );

      delete mom;
      delete theJet;
    }
  delete clusterSequence;

  return kTRUE;
}
Beispiel #10
0
void rochcor_42X::momcor_mc( TLorentzVector& mu, float charge, float sysdev, int runopt){
  
  //sysdev == num : deviation = num

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

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

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

  //float mptsys = sran.Gaus(0.0,sysdev);
  
  float dm = 0.0;
  float da = 0.0;
  
  if(runopt == 0){
    dm = (mcor_bfA[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfAer[mu_phibin][mu_etabin])/mmavgA[mu_phibin][mu_etabin];
    da = mcor_maA[mu_phibin][mu_etabin] + mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maAer[mu_phibin][mu_etabin];
  }else if(runopt == 1){
    dm = (mcor_bfB[mu_phibin][mu_etabin] + mptsys_mc_dm[mu_phibin][mu_etabin]*mcor_bfBer[mu_phibin][mu_etabin])/mmavgB[mu_phibin][mu_etabin];
    da = mcor_maB[mu_phibin][mu_etabin] + mptsys_mc_da[mu_phibin][mu_etabin]*mcor_maBer[mu_phibin][mu_etabin];
  }
  
  float cor = 1.0/(1.0 + dm + charge*da*ptmu);
  
  //for the momentum tuning - eta,phi,Q correction
  px *= cor;
  py *= cor;
  pz *= cor;
  e  *= cor;
  
  float recm = 0.0;
  float drecm = 0.0; 
  float delta = 0.0;
  float sf = 0.0;

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

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

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

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

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

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

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

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

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

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

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

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

  double csvWgtTotal = csvWgthf * csvWgtC * csvWgtlf;

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

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

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

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

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

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

  fillCSVhistos(f_CSVwgt_HF, f_CSVwgt_LF);

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

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

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

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


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


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


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

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

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


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

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

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


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


  bool verbose = false;

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

  TH1::SetDefaultSumw2();

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

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



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

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

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

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

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

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

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


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

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

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

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

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

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


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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

  int numEvents_exselection=0;

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

    double MHT = eve->MHT_[iSys];

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

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

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

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

      int charge1 = lepton_trkCharge[iLep];

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

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

	int charge2 = lepton_trkCharge[jLep];

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

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

	dR_leplep = myLep1.DeltaR(myLep2);

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

    h_numLooseLeptons->Fill(numLooseLeptons,wgt);

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

    

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


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

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


    bool isCleanEvent = 1;

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


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

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


    if ( !lepselection2 ) continue;
    numEvents_lepselection2++;



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

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

    if ( !exselection ) continue;
    numEvents_exselection++;


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

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

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

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

    double minDR_lepton_first_jet = 99, minDR_lepton_second_jet = 99;


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

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

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

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

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

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

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

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

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

	}
      }


    } // end loop over jets
    

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

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

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


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

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

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

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

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



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


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


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


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

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

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

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

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

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


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

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

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

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

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

    

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

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


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

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

}
Beispiel #14
0
//void xAna_ele(std::string inputFile, TCanvas *c1 , TCanvas *c2 , TCanvas *c3 ,TCanvas *c4 ,TCanvas *c5 , 
void xAna_ele(TString inputFile, TCanvas *c1 , TCanvas *c2 , TCanvas *c3 ,TCanvas *c4 ,TCanvas *c5 ,
int mass_point ,double eff,double eff_err, TString dir_name, int dir_flag ){


  // define histograms

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

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

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

  Long64_t nTotal=0;
  Long64_t nPass[20]={0};
  ofstream fout;
  fout.open("ele_Eiko.txt");
//  TH1F* h_SD=new TH1F("h_SD","",100,0,200);

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

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

    data.GetEntry(jEntry);
    nTotal ++;

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


    bool hasLepton=false;

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

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

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

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

      if(hasLepton)break;

    }

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

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

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

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

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

      if(hasHadron)break;

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

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

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


      }


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


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

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

    //5. select good electrons
    std::vector<int> goodElectrons;

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

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

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

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

	double ele_pt_threshold = -999;
	if (dir_flag ==1){ele_pt_threshold = 0;}
        if (dir_flag ==2 || dir_flag ==3 || dir_flag ==6 ){ele_pt_threshold = 85;}
        if (dir_flag ==4){ele_pt_threshold = 100;}
        if (dir_flag ==5){ele_pt_threshold = 115;}
        if (dir_flag ==7 || dir_flag ==8 || dir_flag ==9 ){ele_pt_threshold = 115;}


    	if(thisEle->Pt() < ele_pt_threshold )continue;
//     	  if(thisEle->Pt() < 115)continue;
//        if(thisEle->Pt() < 100)continue;
//        if(thisEle->Pt() < 85)continue;

    	if(!passHEEPID[ie])continue;
    	
    	if(eleMiniIso[ie]>0.1)continue;

    	goodElectrons.push_back(ie);
      }

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

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

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

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

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

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

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

            double ll_pt_threshold = -999;
            if (dir_flag ==1){ll_pt_threshold = 0;}
            if (dir_flag ==2 ||dir_flag ==3 ||dir_flag ==4 ||dir_flag ==5 ||dir_flag ==6 ){ll_pt_threshold = 200;}

            if(ptll<ll_pt_threshold )continue;
//	    if(ptll<200)continue;


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

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

	    findEPair=true;
	  }	
      }

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


    //7.select a good CA8 and cleaned jet

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

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

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

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

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

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

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

    	goodMuons.push_back(im);
      }

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

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


        double SD_low = -999, SD_high = 999;
        if (dir_flag ==1){ SD_low= 0; SD_high = 9999;}
        if (dir_flag ==2){ SD_low= 40; SD_high = 140;}
        if (dir_flag ==3){ SD_low= 50; SD_high = 140;}
        if (dir_flag ==4 || dir_flag ==5 || dir_flag ==6){ SD_low= 60; SD_high = 140;}

        if (dir_flag ==7){ SD_low= 93; SD_high = 143;}
        if (dir_flag ==8){ SD_low= 95; SD_high = 145;}
        if (dir_flag ==9){ SD_low= 91; SD_high = 141;}

        if(jetSDmass[ij]<SD_low || jetSDmass[ij]>SD_high)continue;
//	if(jetSDmass[ij]<50 || jetSDmass[ij]>110)continue; // this is soft drop mass ?
//      if(jetSDmass[ij]<105 || jetSDmass[ij]>145)continue;  // Yu-Hsiang change to Higgs mass window
//      if(jetSDmass[ij]<60 || jetSDmass[ij]>140)continue;  // Yu-Hsiang change to Higgs mass window
//      if(jetSDmass[ij]<50 || jetSDmass[ij]>140)continue;  // Yu-Hsiang change to Higgs mass window
//      if(jetSDmass[ij]<40 || jetSDmass[ij]>140)continue;  // Yu-Hsiang change to Higgs mass window

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

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

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

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

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

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

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

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

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

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

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

  ////////

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

  } // end of loop over entries

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




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


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

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

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





  // Yu-Hsiang add cut flow figure


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

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

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

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

//

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



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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

   myFile->Close();
   delete myFile;

   // delete the finished used TH1D so it will not replacing the existing TH1 (no potential memory leak warning) when loop again 
/*
   delete h_CutFlow;
   delete h_ele_pT;
   delete h_lepton_pair_pT;
   delete h_SD;
   delete h_Z_mass;
*/
}
void testPhiSRvsDetPhi(){


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


				if (sumB.Pt() >= 3 && sumB.Pt() <= 50 && sumB.M() >= 0 && sumB.M() <= 100 && sumB.Eta() >= -1.4 && sumB.Eta() <= 1.4)
				{
					passInitialCut_B = true;
				}
			
				if (passInitialCut_B && (pair1->spinBit() == 9 || pair1->spinBit() == 10))
				{
					
					cout << pair1->phiSR('b') << "  " << sumB.Phi() << endl;
					
					hPhiSRvPhi_Up->Fill(pair1->phiSR('b'), sumB.Phi());
					
				}
				
				if (passInitialCut_B && (pair1->spinBit() == 5 || pair1->spinBit() == 6))
				{
					hPhiSRvPhi_Down->Fill(pair1->phiSR('b'), sumB.Phi());
				}
				
				
				
				
			}
				
			
			
			
			
		}
		
		
		
		
	}
	
	
	TCanvas* cUp = new TCanvas();
	hPhiSRvPhi_Up->Draw("colz");
			
	TCanvas* cDown = new TCanvas();
	hPhiSRvPhi_Down->Draw("colz");
			
			
			
}
Beispiel #16
0
void selectAntiWm(const TString conf="wm.conf", // input file
              const TString outputDir="."       // output directory
) {
  gBenchmark->Start("selectAntiWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.4;
  const Double_t MUON_MASS = 0.105658369;

  const Double_t VETO_PT   = 10;
  const Double_t VETO_ETA  = 2.4;

  const Int_t BOSON_ID  = 24;
  const Int_t LEPTON_ID = 13;

  // load trigger menu
  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/pileup_weights_2015B.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("npv_rw");

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  UInt_t  id_1, id_2;
  Double_t x_1, x_2, xPDF_1, xPDF_2;
  Double_t scalePDF, weightPDF;
  TLorentzVector *genV=0, *genLep=0;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t genLepPt, genLepPhi;
  Float_t scale1fb, puWeight;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Float_t tkMet, tkMetPhi, tkSumEt, tkMt, tkU1, tkU2;
  Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaMt, mvaU1, mvaU2;
  Int_t   q;
  TLorentzVector *lep=0;
  ///// muon specific /////
  Float_t trkIso, emIso, hadIso;
  Float_t pfChIso, pfGamIso, pfNeuIso, pfCombIso;
  Float_t d0, dz;
  Float_t muNchi2;
  UInt_t nPixHits, nTkLayers, nValidHits, nMatch, typeBits;
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo *info  = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen  = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr    = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;
  
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    Bool_t isData=kFALSE;
    if(isam==0 && !hasData) continue;
    else if (isam==0) isData=kTRUE;
    
    // Assume signal sample is given name "wm"
    Bool_t isSignal = (snamev[isam].CompareTo("wm",TString::kIgnoreCase)==0);
    // flag to reject W->mnu events when selecting wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("wx",TString::kIgnoreCase)==0);  
    
    CSample* samp = samplev[isam];
  
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");

    outTree->Branch("runNum",     &runNum,     "runNum/i");     // event run number
    outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");    // event lumi section
    outTree->Branch("evtNum",     &evtNum,     "evtNum/i");     // event number
    outTree->Branch("npv",        &npv,        "npv/i");        // number of primary vertices
    outTree->Branch("npu",        &npu,        "npu/i");        // number of in-time PU events (MC)
    outTree->Branch("id_1",       &id_1,       "id_1/i");       // PDF info -- parton ID for parton 1
    outTree->Branch("id_2",       &id_2,       "id_2/i");       // PDF info -- parton ID for parton 2
    outTree->Branch("x_1",        &x_1,        "x_1/d");        // PDF info -- x for parton 1
    outTree->Branch("x_2",        &x_2,        "x_2/d");        // PDF info -- x for parton 2
    outTree->Branch("xPDF_1",     &xPDF_1,     "xPDF_1/d");     // PDF info -- x*F for parton 1
    outTree->Branch("xPDF_2",     &xPDF_2,     "xPDF_2/d");     // PDF info -- x*F for parton 2
    outTree->Branch("scalePDF",   &scalePDF,   "scalePDF/d");   // PDF info -- energy scale of parton interaction
    outTree->Branch("weightPDF",  &weightPDF,  "weightPDF/d");  // PDF info -- PDF weight
    outTree->Branch("genV",       "TLorentzVector", &genV);     // GEN boson 4-vector (signal MC)
    outTree->Branch("genLep",     "TLorentzVector", &genLep);   // GEN lepton 4-vector (signal MC)
    outTree->Branch("genVPt",     &genVPt,     "genVPt/F");     // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",    &genVPhi,    "genVPhi/F");    // GEN boson phi (signal MC)
    outTree->Branch("genVy",      &genVy,      "genVy/F");      // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass",   &genVMass,   "genVMass/F");   // GEN boson mass (signal MC)
    outTree->Branch("genLepPt",   &genLepPt,   "genLepPt/F");   // GEN lepton pT (signal MC)
    outTree->Branch("genLepPhi",  &genLepPhi,  "genLepPhi/F");  // GEN lepton phi (signal MC)
    outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");   // event weight per 1/fb (MC)
    outTree->Branch("puWeight",   &puWeight,   "puWeight/F");    // scale factor for pileup reweighting (MC)
    outTree->Branch("met",        &met,        "met/F");        // MET
    outTree->Branch("metPhi",     &metPhi,     "metPhi/F");     // phi(MET)
    outTree->Branch("sumEt",      &sumEt,      "sumEt/F");      // Sum ET
    outTree->Branch("mt",         &mt,         "mt/F");         // transverse mass
    outTree->Branch("u1",         &u1,         "u1/F");         // parallel component of recoil
    outTree->Branch("u2",         &u2,         "u2/F");         // perpendicular component of recoil
    outTree->Branch("tkMet",      &tkMet,      "tkMet/F");      // MET (track MET)
    outTree->Branch("tkMetPhi",   &tkMetPhi,   "tkMetPhi/F");   // phi(MET) (track MET)
    outTree->Branch("tkSumEt",    &tkSumEt,    "tkSumEt/F");    // Sum ET (track MET)
    outTree->Branch("tkMt",       &tkMt,       "tkMt/F");       // transverse mass (track MET)
    outTree->Branch("tkU1",       &tkU1,       "tkU1/F");       // parallel component of recoil (track MET)
    outTree->Branch("tkU2",       &tkU2,       "tkU2/F");       // perpendicular component of recoil (track MET)
    outTree->Branch("mvaMet",     &mvaMet,     "mvaMet/F");     // MVA MET
    outTree->Branch("mvaMetPhi",  &mvaMetPhi,  "mvaMetPhi/F");  // phi(MVA MET)
    outTree->Branch("mvaSumEt",   &mvaSumEt,   "mvaSumEt/F");   // Sum ET (MVA MET)
    outTree->Branch("mvaMt",      &mvaMt,      "mvaMt/F");      // transverse mass (MVA MET)
    outTree->Branch("mvaU1",      &mvaU1,      "mvaU1/F");      // parallel component of recoil (mva MET)
    outTree->Branch("mvaU2",      &mvaU2,      "mvaU2/F");      // perpendicular component of recoil (mva MET)
    outTree->Branch("q",          &q,          "q/I");          // lepton charge
    outTree->Branch("lep",        "TLorentzVector", &lep);      // lepton 4-vector
    ///// muon specific /////
    outTree->Branch("trkIso",     &trkIso,     "trkIso/F");     // track isolation of lepton
    outTree->Branch("emIso",      &emIso,      "emIso/F");      // ECAL isolation of lepton
    outTree->Branch("hadIso",     &hadIso,     "hadIso/F");     // HCAL isolation of lepton
    outTree->Branch("pfChIso",    &pfChIso,    "pfChIso/F");    // PF charged hadron isolation of lepton
    outTree->Branch("pfGamIso",   &pfGamIso,   "pfGamIso/F");   // PF photon isolation of lepton
    outTree->Branch("pfNeuIso",   &pfNeuIso,   "pfNeuIso/F");   // PF neutral hadron isolation of lepton
    outTree->Branch("pfCombIso",  &pfCombIso,  "pfCombIso/F");  // PF combined isolation of lepton
    outTree->Branch("d0",         &d0,         "d0/F");         // transverse impact parameter of lepton
    outTree->Branch("dz",         &dz,         "dz/F");         // longitudinal impact parameter of lepton
    outTree->Branch("muNchi2",    &muNchi2,    "muNchi2/F");    // muon fit normalized chi^2 of lepton
    outTree->Branch("nPixHits",   &nPixHits,   "nPixHits/i");   // number of pixel hits of muon
    outTree->Branch("nTkLayers",  &nTkLayers,  "nTkLayers/i");  // number of tracker layers of muon
    outTree->Branch("nMatch",     &nMatch,     "nMatch/i");     // number of matched segments of muon	 
    outTree->Branch("nValidHits", &nValidHits, "nValidHits/i"); // number of valid muon hits of muon 
    outTree->Branch("typeBits",   &typeBits,   "typeBits/i");   // number of valid muon hits of muon 
    
    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... "; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);
      
      Bool_t hasJSON = kFALSE;
      baconhep::RunLumiRangeMap rlrm;
      if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
	hasJSON = kTRUE;
	rlrm.addJSONFile(samp->jsonv[ifile].Data()); 
      }

      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);
      eventTree->SetBranchAddress("Info", &info);    TBranch *infoBr = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
        eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }
    
      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeight=0;

      if (hasGen) {
	TH1D *hall = new TH1D("hall", "", 1,0,1);
	eventTree->Draw("0.5>>hall", "GenEvtInfo->weight");
	totalWeight=hall->Integral();
	delete hall;
	hall=0;
      }

      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
        infoBr->GetEntry(ientry);

	if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

        Double_t weight=1;
        if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(hasGen) {
          genPartArr->Clear();
          genBr->GetEntry(ientry);
          genPartBr->GetEntry(ientry);
	  weight*=gen->weight;
        }

        // veto w -> xv decays for signal and w -> mv for bacground samples (needed for inclusive WToLNu sample)
        if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
	else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
        
	// check for certified lumi (if applicable)
        baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        if(hasJSON && !rlrm.hasRunLumi(rl)) continue;  

        // trigger requirement               
	if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;
      
        // good vertex requirement
        if(!(info->hasGoodPV)) continue;

        //
	// SELECTION PROCEDURE:
	//  (1) Look for 1 good muon matched to trigger
	//  (2) Reject event if another muon is present passing looser cuts
	//
	muonArr->Clear();
        muonBr->GetEntry(ientry);

	Int_t nLooseLep=0;
	const baconhep::TMuon *goodMuon=0;
	Bool_t passSel=kFALSE;

        for(Int_t i=0; i<muonArr->GetEntriesFast(); i++) {
          const baconhep::TMuon *mu = (baconhep::TMuon*)((*muonArr)[i]);

          if(fabs(mu->eta) > VETO_PT)  continue; // loose lepton |eta| cut
          if(mu->pt        < VETO_ETA) continue; // loose lepton pT cut
//          if(passMuonLooseID(mu)) nLooseLep++; // loose lepton selection
          if(nLooseLep>1) {  // extra lepton veto
            passSel=kFALSE;
            break;
          }
          
          if(fabs(mu->eta) > ETA_CUT)         continue; // lepton |eta| cut
          if(mu->pt < PT_CUT)                 continue; // lepton pT cut   
          if(!passAntiMuonID(mu))             continue; // lepton anti-selection
          if(!isMuonTriggerObj(triggerMenu, mu->hltMatchBits, kFALSE)) continue;
	  
	  passSel=kTRUE;
	  goodMuon = mu;
	}

	if(passSel) {	  
	  /******** We have a W candidate! HURRAY! ********/
	  nsel+=weight;
          nselvar+=weight*weight;
	  
	  TLorentzVector vLep; 
	  vLep.SetPtEtaPhiM(goodMuon->pt, goodMuon->eta, goodMuon->phi, MUON_MASS);

	  //
	  // Fill tree
	  //
	  runNum   = info->runNum;
	  lumiSec  = info->lumiSec;
	  evtNum   = info->evtNum;
	  
	  vertexArr->Clear();
	  vertexBr->GetEntry(ientry);

	  npv      = vertexArr->GetEntries();
	  npu	   = info->nPUmean;
	  genV      = new TLorentzVector(0,0,0,0);
          genLep    = new TLorentzVector(0,0,0,0);
	  genVPt    = -999;
          genVPhi   = -999;
          genVy     = -999;
          genVMass  = -999;
          u1        = -999;
          u2        = -999;
          tkU1      = -999;
          tkU2      = -999;
	  mvaU1     = -999;
          mvaU2     = -999;
          id_1      = -999;
          id_2      = -999;
          x_1       = -999;
          x_2       = -999;
          xPDF_1    = -999;
          xPDF_2    = -999;
          scalePDF  = -999;
          weightPDF = -999;

	  if(isSignal && hasGen) {
	    TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	    toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,1);

            if (gvec && glep1) {
	      genV      = new TLorentzVector(0,0,0,0);
              genV->SetPtEtaPhiM(gvec->Pt(),gvec->Eta(),gvec->Phi(),gvec->M());
              genLep    = new TLorentzVector(0,0,0,0);
              genLep->SetPtEtaPhiM(glep1->Pt(),glep1->Eta(),glep1->Phi(),glep1->M());
              genVPt    = gvec->Pt();
              genVPhi   = gvec->Phi();
              genVy     = gvec->Rapidity();
              genVMass  = gvec->M();
              genLepPt  = glep1->Pt();
              genLepPhi = glep1->Phi();

	      TVector2 vWPt((genVPt)*cos(genVPhi),(genVPt)*sin(genVPhi));
	      TVector2 vLepPt(vLep.Px(),vLep.Py());
	      
	      TVector2 vMet((info->pfMETC)*cos(info->pfMETCphi), (info->pfMETC)*sin(info->pfMETCphi));
	      TVector2 vU = -1.0*(vMet+vLepPt);
	      u1 = ((vWPt.Px())*(vU.Px()) + (vWPt.Py())*(vU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      u2 = ((vWPt.Px())*(vU.Py()) - (vWPt.Py())*(vU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

	      TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));
	      TVector2 vTkU = -1.0*(vTkMet+vLepPt);
	      tkU1 = ((vWPt.Px())*(vTkU.Px()) + (vWPt.Py())*(vTkU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      tkU2 = ((vWPt.Px())*(vTkU.Py()) - (vWPt.Py())*(vTkU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
	      
	      TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
	      TVector2 vMvaU = -1.0*(vMvaMet+vLepPt);
	      mvaU1 = ((vWPt.Px())*(vMvaU.Px()) + (vWPt.Py())*(vMvaU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      mvaU2 = ((vWPt.Px())*(vMvaU.Py()) - (vWPt.Py())*(vMvaU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
          
            }
	    id_1      = gen->id_1;
            id_2      = gen->id_2;
            x_1       = gen->x_1;
            x_2       = gen->x_2;
            xPDF_1    = gen->xPDF_1;
            xPDF_2    = gen->xPDF_2;
            scalePDF  = gen->scalePDF;
            weightPDF = gen->weight;

	    delete gvec;
            delete glep1;
            delete glep2;
            gvec=0; glep1=0; glep2=0;
	  }
	  scale1fb = weight;
	  puWeight = h_rw->GetBinContent(info->nPUmean+1);
	  met	   = info->pfMETC;
	  metPhi   = info->pfMETCphi;
	  sumEt    = 0;
	  mt       = sqrt( 2.0 * (vLep.Pt()) * (info->pfMETC) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->pfMETCphi))) );
	  tkMet    = info->trkMET;
          tkMetPhi = info->trkMETphi;
          tkSumEt  = 0;
          tkMt     = sqrt( 2.0 * (vLep.Pt()) * (info->trkMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->trkMETphi))) );
	  mvaMet   = info->mvaMET;
          mvaMetPhi = info->mvaMETphi;
          mvaSumEt  = 0;
          mvaMt     = sqrt( 2.0 * (vLep.Pt()) * (info->mvaMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->mvaMETphi))) );
	  q        = goodMuon->q;
	  lep      = &vLep;
	  
	  ///// muon specific /////
	  trkIso     = goodMuon->trkIso;
          emIso      = goodMuon->ecalIso;
          hadIso     = goodMuon->hcalIso;
          pfChIso    = goodMuon->chHadIso;
          pfGamIso   = goodMuon->gammaIso;
          pfNeuIso   = goodMuon->neuHadIso;
          pfCombIso  = goodMuon->chHadIso + TMath::Max(goodMuon->neuHadIso + goodMuon->gammaIso -
						       0.5*(goodMuon->puIso),Double_t(0));
	  d0         = goodMuon->d0;
	  dz         = goodMuon->dz;
	  muNchi2    = goodMuon->muNchi2;
	  nPixHits   = goodMuon->nPixHits;
	  nTkLayers  = goodMuon->nTkLayers;
	  nMatch     = goodMuon->nMatchStn;
	  nValidHits = goodMuon->nValidHits;
	  typeBits   = goodMuon->typeBits;

	  outTree->Fill();
	  delete genV;
	  delete genLep;
	  genV=0, genLep=0, lep=0;
        }
      }
      delete infile;
      infile=0, eventTree=0;    

      cout << nsel  << " +/- " << sqrt(nselvar);
      if(isam!=0) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close();
  }
  delete h_rw;
  delete f_rw;
  delete info;
  delete gen;
  delete genPartArr;
  delete muonArr;
  delete vertexArr;
      
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " W -> mu nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectAntiWm"); 
}
void test_JVBF(int erg_tev=8, float mSample=0, bool isggH=false){
  float mPOLE=mSample;
  if (mPOLE<=0) mPOLE=125.6;
  float wPOLE=4.15e-3;
  char TREE_NAME[] = "SelectedTree";

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

  Mela mela(erg_tev, mPOLE);

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

  float MC_weight_noxsec;

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

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

  float ZZMass, ZZPt, ZZPhi, ZZEta;

  int GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

        newtree->Fill();
      }
    }
  }


  foutput->WriteTObject(newtree);
  delete newtree;
  foutput->Close();
  delete tree;
}
void HH4bBtagEffBase_80_v2(int wMs,int wM, string st,string st2,string option=""){	
	//1=signal ,0=QCD ,2=data-----------------------------------------------------------
	int nameRoot=1;
	if((st2.find("QCD")!= std::string::npos)||
	(st2.find("bGen")!= std::string::npos)||
	(st2.find("bEnriched")!= std::string::npos))nameRoot=0;
	if(st2.find("data")!= std::string::npos)nameRoot=2;
	//Thea correction---------------------
	TFile *f3;
	f3=TFile::Open("puppiCorr.root");
	TF1* tf1[3];
	tf1[0]=(TF1 *) f3->FindObjectAny("puppiJECcorr_gen");
	tf1[1]=(TF1 *) f3->FindObjectAny("puppiJECcorr_reco_0eta1v3");
	tf1[2]=(TF1 *) f3->FindObjectAny("puppiJECcorr_reco_1v3eta2v5");
	//option-----------------------------------------------------------
	int JESOption=0;
	if(option.find("JESUp")!= std::string::npos)JESOption=1;
	if(option.find("JESDown")!= std::string::npos)JESOption=2;
	if(option.find("BtagUp")!= std::string::npos)JESOption=3;
	if(option.find("BtagDown")!= std::string::npos)JESOption=4;
	if(option.find("tau21Up")!= std::string::npos)JESOption=5;
	if(option.find("tau21Down")!= std::string::npos)JESOption=6;
	cout<<"JESOption = "<<JESOption<<endl;
	bool printHighPtSubjet=0;
	bool isFast=1;
	//tuple tree and cutflow variables------------------------------------------------------------------------------------
	TFile *f;
	TTree *tree;
	double nPass[30]={0},total=0;
	double fixScaleNum[2]={0};
	//using for Btag Eff -----------------------------------------------------------------------------
	string btagsystematicsType="central";
	if(JESOption==3)btagsystematicsType="up";
	else if(JESOption==4)btagsystematicsType="down";
	BTagCalibration calib("CSVv2L", "subjet_CSVv2_ichep.csv");
	BTagCalibrationReader LF(BTagEntry::OP_LOOSE,"central", {"up", "down"});  
	BTagCalibrationReader HFC(BTagEntry::OP_LOOSE, "central", {"up", "down"});      // other sys types
	BTagCalibrationReader HF(BTagEntry::OP_LOOSE,"central",{"up", "down"});      // other sys types
	LF.load(calib, BTagEntry::FLAV_UDSG,    // btag flavour
            "incl");               // measurement type
	HFC.load(calib, BTagEntry::FLAV_C,    // btag flavour
            "lt");               // measurement type
	HF.load(calib, BTagEntry::FLAV_B,    // btag flavour
            "lt");               // measurement type
	TFile *f1;
	if(nameRoot==2)f1=TFile::Open("btagEffSource/data.root");
	else if (nameRoot!=2 && (JESOption==0||JESOption==3||JESOption==4||JESOption==5||JESOption==6))f1=TFile::Open(Form("btagEffSource/%s.root",st2.data()));
	else if (nameRoot!=2 && JESOption==1)f1=TFile::Open(Form("btagEffSource/%s_JESUp.root",st2.data()));
	else if (nameRoot!=2 && JESOption==2)f1=TFile::Open(Form("btagEffSource/%s_JESDown.root",st2.data()));
	TH1D* th1[6];
	string btaggingEff[6]={"effD_b","effN_b","effD_c","effN_c","effD_l","effN_l"};
	for(int i=0;i<6;i++){
		th1[i]=(TH1D*)f1->FindObjectAny(Form("%s_1d",btaggingEff[i].data()));
		if(i==1||i==3||i==5)th1[i]->Divide(th1[i-1]);
	}
	//saving variables----------------------------------------------------------------------------------------
	TH1D * th5[300],* th_flavor[4][300];
	for(int i=0;i<2;i++){
		for(int j=0;j<2;j++){
			for(int k=0;k<5;k++){
				th5[(i*2+j)*5+k]=new TH1D(Form("Pt_j%d_sj%d_%db",i,j,k),Form("Pt_j%d_sj%d_%db",i,j,k),200,0,2000);
				th5[(i*2+j)*5+k+20]=new TH1D(Form("Eta_j%d_sj%d_%db",i,j,k),Form("Eta_j%d_sj%d_%db",i,j,k),60,-3,3);
				th5[(i*2+j)*5+k+85]=new TH1D(Form("subCSV_j%d_sj%d_%db",i,j,k),Form("subCSV_j%d_sj%d_%db",i,j,k),20,0,1);
				th5[(i*2+j)*5+k+194]=new TH1D(Form("subCSVCut_j%d_sj%d_%db",i,j,k),Form("subCSVCut_j%d_sj%d_%db",i,j,k),20,0,1);
			}
		}
		for(int k=0;k<5;k++){
			th5[i*5+k+40]=new TH1D(Form("deltaR_j%d_%db",i,k),Form("deltaR_j%d_%db",i,k),20,0,1);
			th5[i*5+k+50]=new TH1D(Form("Pt_j%d_%db",i,k),Form("Pt_j%d_%db",i,k),200,0,2000);
			th5[i*5+k+60]=new TH1D(Form("Eta_j%d_%db",i,k),Form("Eta_j%d_%db",i,k),60,-3,3);
			th5[i*5+k+70]=new TH1D(Form("prMassL2L3_j%d_%db",i,k),Form("prMassL2L3_j%d_%db",i,k),15,90,150);
			th5[i*5+k+105]=new TH1D(Form("tau21_j%d_%db",i,k),Form("tau21_j%d_%db",i,k),25,0,1);
			th5[i*5+k+120]=new TH1D(Form("PuppiSDMassL2L3_j%d_%db",i,k),Form("PuppiSDMassL2L3_j%d_%db",i,k),15,90,150);
			th5[i*5+k+130]=new TH1D(Form("puppiTau21_j%d_%db",i,k),Form("puppiTau21_j%d_%db",i,k),25,0,1);
			th5[i*5+k+140]=new TH1D(Form("prMass_j%d_%db",i,k),Form("prMass_j%d_%db",i,k),15,90,150);
			th5[i*5+k+150]=new TH1D(Form("PuppiSDMass_j%d_%db",i,k),Form("PuppiSDMass_j%d_%db",i,k),15,90,150);
			th5[i*5+k+170]=new TH1D(Form("doubleSV_j%d_%db",i,k),Form("doubleSV_j%d_%db",i,k),40,-1,1);
			th5[i*5+k+184]=new TH1D(Form("FatSV_j%d_%db",i,k),Form("FatSV_j%d_%db",i,k),20,0,1);
			th5[i*5+k+250]=new TH1D(Form("PuppiSDMassThea_j%d_%db",i,k),Form("PuppiSDMassThea_j%d_%db",i,k),15,90,150);
		}
	}
	for(int k=0;k<5;k++){
		th5[k+80]=new TH1D(Form("totalMass_%db",k),Form("totalMass_%db",k),200,1000,5000);
		th5[k+115]=new TH1D(Form("deltaEta_%db",k),Form("deltaEta_%db",k),40,0,2);
		th5[k+160]=new TH1D(Form("logPt_%db",k),Form("logPt_%db",k),70,0,7);
		th5[k+165]=new TH1D(Form("totalMassRed_%db",k),Form("totalMassRed_%db",k),200,1000,5000);
	}
	th5[180]= new TH1D("h_nvtx","h_nvtx",60,0,60);
	th5[181]= new TH1D("h_ntrue","h_ntrue",60,0,60);
	th5[182]= new TH1D("h_nvtx_cut","h_nvtx_cut",60,0,60);
	th5[183]= new TH1D("h_ntrue_cut","h_ntrue_cut",60,0,60);
	
	string prMass_no[4]={"prMass","prMassL2L3","PuppiSDMass","PuppiSDMassL2L3"};
	string tau21_no[2]={"tau21","puppiTau21"};
	for (int i=0;i<4;i++){
		th5[214+i*2]=new TH1D(Form("%s_j0_noPr_noTau21",prMass_no[i].data()),Form("%s_j0_noPr_noTau21",prMass_no[i].data()),200,0,200);
		th5[215+i*2]=new TH1D(Form("%s_j1_noPr_noTau21",prMass_no[i].data()),Form("%s_j1_noPr_noTau21",prMass_no[i].data()),200,0,200);
		th5[222+i*2]=new TH1D(Form("%s_j0_noPr",prMass_no[i].data()),Form("%s_j0_noPr",prMass_no[i].data()),200,0,200);
		th5[223+i*2]=new TH1D(Form("%s_j1_noPr",prMass_no[i].data()),Form("%s_j1_noPr",prMass_no[i].data()),200,0,200);
		th5[230+i*2]=new TH1D(Form("%s_j0_noTau21",prMass_no[i].data()),Form("%s_j0_noTau21",prMass_no[i].data()),15,90,150);
		th5[231+i*2]=new TH1D(Form("%s_j1_noTau21",prMass_no[i].data()),Form("%s_j1_noTau21",prMass_no[i].data()),15,90,150);
	}
	for (int i=0;i<2;i++){
		th5[238+i*2]=new TH1D(Form("%s_j0_noPr_noTau21",tau21_no[i].data()),Form("%s_j0_noPr_noTau21",tau21_no[i].data()),25,0,1);
		th5[239+i*2]=new TH1D(Form("%s_j1_noPr_noTau21",tau21_no[i].data()),Form("%s_j1_noPr_noTau21",tau21_no[i].data()),25,0,1);
		th5[242+i*2]=new TH1D(Form("%s_j0_noPr",tau21_no[i].data()),Form("%s_j0_noPr",tau21_no[i].data()),25,0,1);
		th5[243+i*2]=new TH1D(Form("%s_j1_noPr",tau21_no[i].data()),Form("%s_j1_noPr",tau21_no[i].data()),25,0,1);
		th5[246+i*2]=new TH1D(Form("%s_j0_noTau21",tau21_no[i].data()),Form("%s_j0_noTau21",tau21_no[i].data()),25,0,1);
		th5[247+i*2]=new TH1D(Form("%s_j1_noTau21",tau21_no[i].data()),Form("%s_j1_noTau21",tau21_no[i].data()),25,0,1);
	}
	for(int i=0;i<260;i++){
		th5[i]->Sumw2();
		th_flavor[0][i]=(TH1D* )th5[i]->Clone(Form("%s_bb",th5[i]->GetTitle()));
		th_flavor[1][i]=(TH1D* )th5[i]->Clone(Form("%s_b",th5[i]->GetTitle()));
		th_flavor[2][i]=(TH1D* )th5[i]->Clone(Form("%s_cc",th5[i]->GetTitle()));
		th_flavor[3][i]=(TH1D* )th5[i]->Clone(Form("%s_udcsg",th5[i]->GetTitle()));
		//th_flavor[0][i]->Sumw2();
		//th_flavor[1][i]->Sumw2();
		//th_flavor[2][i]->Sumw2();
		//th_flavor[3][i]->Sumw2();
	}
	
	//pileup uncertainty----------------------------------------------------------------------------------------
	TH1D* th7[14];
	th7[0]=new TH1D("totalMass","totalMass",200,1000,5000);
	th7[1]=new TH1D("totalMass_pileup_up","totalMass_pileup_up",200,1000,5000);
	th7[2]=new TH1D("totalMass_pileup_down","totalMass_pileup_down",200,1000,5000);
	th7[3]=new TH1D("pileupEff","pileupEff",15,0.5,15.5);
	double totalPileup[3]={0},passPileup[3]={0};
	standalone_LumiReWeighting LumiWeights_central(0),LumiWeights_up(1),LumiWeights_down(-1);
	//PDF uncertainty
	th7[4]=new TH1D("PDFEff","PDFEff",101,0.5,101.5);
	double passPDF[101]={0},totalPDF[101]={0};
	//QCD uncertainty
	for(int i=5;i<14;i++)th7[i]=new TH1D(Form("uns_QCD_%d",i-5),Form("uns_QCD_%d",i-5),200,1000,5000);
	
	
	
	//NCUtuple loop----------------------------------------------------------------------------------------
	for (int w=wMs;w<wM;w++){
		if(w%20==0)cout<<w<<endl;
		//Get ntuple----------------------------------------------------------------------------------------
		if (nameRoot!=1)f = TFile::Open(Form("%s%d.root",st.data(),w));
		else f = TFile::Open(st.data());
		if (!f || !f->IsOpen())continue;
		TDirectory * dir;
		if (nameRoot!=1)dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
		else dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));
		dir->GetObject("treeMaker",tree);
		TreeReader data(tree);
		total+=data.GetEntriesFast();
		
		//TFile* fileFast=TFile::Open(Form("fast/%s/%d.root",st2.data(),w));
		//TTree* treeFast=(TTree* )fileFast->Get("hh4bFast");
		//TreeReader dataFast(treeFast);
		//if(isFast)dataFast=TreeReader(treeFast);
		
		for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ;jEntry++){//event loop----------------------------------------------------------------------------------------
			data.GetEntry(jEntry);
			//if(isFast)dataFast.GetEntry(jEntry);
			
			Int_t nVtx        = data.GetInt("nVtx");
			Float_t ntrue= data.GetFloat("pu_nTrueInt");
			//Float_t*  pdfscaleSysWeights= data.GetPtrFloat("pdfscaleSysWeights");
			
			double PU_weight[3]={1,1,1};
			
			if(nameRoot!=2){
				if(ntrue<51){
					PU_weight[0] = LumiWeights_central.weight(ntrue);
					PU_weight[1]= LumiWeights_up.weight(ntrue);
					PU_weight[2] = LumiWeights_down.weight(ntrue);
				}
				else {
					PU_weight[0] = LumiWeights_central.weight(50);
					PU_weight[1] = LumiWeights_up.weight(50);
					PU_weight[2]= LumiWeights_down.weight(50);
				}
			}
			fixScaleNum[0]+=PU_weight[0];
			for(int i=0;i<3;i++)totalPileup[i]+=PU_weight[i];
			for(int i=0;i<101;i++)totalPDF[i]+=PU_weight[0];
			
			//Int_t nPassFast;  
			//if(isFast)nPassFast= dataFast.GetInt("nPassB");
			//cout<<nPassFast<<endl;
			//if(isFast &&nPassFast<8)continue;
			//0. has a good vertex
			if(nVtx<1)continue;nPass[0]+=PU_weight[0];
			//1.trigger
			std::string* trigName = data.GetPtrString("hlt_trigName");
		 	vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
			bool passTrigger=false;
			for(int it=0; it< data.GetPtrStringSize(); it++){
				std::string thisTrig= trigName[it];
				bool results = trigResult[it];
				if( ((thisTrig.find("HLT_PFHT800")!= std::string::npos||
						//thisTrig.find("HLT_PFHT650")!= std::string::npos||
						thisTrig.find("HLT_PFHT650_WideJetMJJ900DEtaJJ1p5_v")!= std::string::npos||
						thisTrig.find("HLT_PFHT650_WideJetMJJ950DEtaJJ1p5_v")!= std::string::npos||
						thisTrig.find("HLT_AK8PFJet360_TrimMass30_v")!= std::string::npos||
						thisTrig.find("HLT_AK8PFHT700_TrimR0p1PT0p03Mass50_v")!= std::string::npos
						) && results==1)){
					passTrigger=true;
					break;
				}
			}
			if(!passTrigger && nameRoot==2)continue;nPass[1]+=PU_weight[0];
			
			int nFATJet         = data.GetInt("FATnJet");
			TClonesArray* fatjetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
			float*  FATjetCorrUncUp = data.GetPtrFloat("FATjetCorrUncUp"); 
			float*  FATjetCorrUncDown = data.GetPtrFloat("FATjetCorrUncDown"); 
			vector<bool>    &FATjetPassIDTight = *((vector<bool>*) data.GetPtr("FATjetPassIDTight"));
			//2.nJets
			if(nFATJet<2)continue;nPass[2]+=PU_weight[0];
			TLorentzVector* thisJet ,* thatJet;
			if (JESOption==1){
				TLorentzVector test0= (*((TLorentzVector*)fatjetP4->At(0)))*(1+FATjetCorrUncUp[0] );
				TLorentzVector test1= (*((TLorentzVector*)fatjetP4->At(1)))*(1+FATjetCorrUncUp[1] );
				thisJet= &test0;
				thatJet= &test1;
			}
			else if (JESOption==2){
				TLorentzVector test0= (*((TLorentzVector*)fatjetP4->At(0)))*(1-FATjetCorrUncDown[0] );
				TLorentzVector test1= (*((TLorentzVector*)fatjetP4->At(1)))*(1-FATjetCorrUncDown[1] );
				thisJet= &test0;
				thatJet= &test1;
			}
			else{
				thisJet= (TLorentzVector*)fatjetP4->At(0);
				thatJet = (TLorentzVector*)fatjetP4->At(1);
			}
			//3. Pt 
			if(thisJet->Pt()<200||thatJet->Pt()<200)continue;
			nPass[3]+=PU_weight[0];
			//4tightId-----------------------------------------
			if(FATjetPassIDTight[0]==0||FATjetPassIDTight[1]==0)continue;
			Float_t*  FATjetCEmEF = data.GetPtrFloat("FATjetCEmEF");
			Float_t*  FATjetMuEF = data.GetPtrFloat("FATjetMuEF");
			if(FATjetMuEF[0]>0.8||FATjetMuEF[1]>0.8)continue;
			if(FATjetCEmEF[0]>0.9||FATjetCEmEF[1]>0.9)continue;
			nPass[4]+=PU_weight[0];
			//5. Eta-----------------------------------------
			if(fabs(thisJet->Eta())>2.4||fabs(thatJet->Eta())>2.4)continue;
			nPass[5]+=PU_weight[0];
			
			int event_flavor=-1;
			Int_t* FATjetHadronFlavor        = data.GetPtrInt("FATjetHadronFlavor");
			vector<Int_t>   *FATsubjetSDHadronFlavor =  data.GetPtrVectorInt("FATsubjetSDHadronFlavor");
			if(FATjetHadronFlavor[0]==5 && FATsubjetSDHadronFlavor[0][0]==5 && FATsubjetSDHadronFlavor[0][1]==5)event_flavor=0;
				else if(FATjetHadronFlavor[1]==5 && FATsubjetSDHadronFlavor[1][0]==5 && FATsubjetSDHadronFlavor[1][1]==5)event_flavor=0;
				else if(FATjetHadronFlavor[0]==5 && (FATsubjetSDHadronFlavor[0][0]==5 || FATsubjetSDHadronFlavor[0][1]==5))event_flavor=1;
				else if(FATjetHadronFlavor[1]==5 && (FATsubjetSDHadronFlavor[1][0]==5 || FATsubjetSDHadronFlavor[1][1]==5))event_flavor=1;
				else if(FATjetHadronFlavor[0]==4 && FATsubjetSDHadronFlavor[0][0]==4 && FATsubjetSDHadronFlavor[0][1]==4)event_flavor=2;
				else if(FATjetHadronFlavor[1]==4 && FATsubjetSDHadronFlavor[1][0]==4 && FATsubjetSDHadronFlavor[1][1]==4)event_flavor=2;
				else event_flavor=3;
			
			th5[180]->Fill(nVtx,PU_weight[0]);
			th5[181]->Fill(ntrue,PU_weight[0]);
			
			th_flavor[event_flavor][180]->Fill(nVtx,PU_weight[0]);
			th_flavor[event_flavor][181]->Fill(ntrue,PU_weight[0]);
			//6. DEta-----------------------------------------
			float dEta = fabs(thisJet->Eta()-thatJet->Eta());
			if(dEta>1.3)continue;
			nPass[6]+=PU_weight[0];
			//7. Mjj-----------------------------------------
			float mjj = (*thisJet+*thatJet).M();
			float mjjRed = (*thisJet+*thatJet).M()+250-thisJet->M()-thatJet->M();
			if(mjjRed<1000)continue;
			nPass[7]+=PU_weight[0];
			//8. fatjetPRmassL2L3Corr-----------------------------------------
			Float_t*  fatjetPRmassL2L3Corr = data.GetPtrFloat("FATjetPRmassL2L3Corr");
			Float_t*  FATjetPuppiSDmassL2L3Corr = data.GetPtrFloat("FATjetPuppiSDmassL2L3Corr");
			Float_t*  FATjetPRmass = data.GetPtrFloat("FATjetPRmass");
			Float_t*  FATjetPuppiSDmass = data.GetPtrFloat("FATjetPuppiSDmass");
			
			
			
			vector<float>   *subjetSDCSV =  data.GetPtrVectorFloat("FATsubjetSDCSV");
			vector<float>   *subjetSDPx  =  data.GetPtrVectorFloat("FATsubjetSDPx", nFATJet);
			vector<float>   *subjetSDPy  =  data.GetPtrVectorFloat("FATsubjetSDPy", nFATJet);
			vector<float>   *subjetSDPz  =  data.GetPtrVectorFloat("FATsubjetSDPz", nFATJet);
			vector<float>   *subjetSDE   =  data.GetPtrVectorFloat("FATsubjetSDE", nFATJet);
			
			int nbtag=0,nbtag2=0;
			float MaxBJetPt = 670., MaxLJetPt = 1000.;
			double sf[2][2],eta[2],pt[2],dr[2],subjetPt[2][2],subjetEta[2][2],eff[2][2],btaggingscaleFactor=1;
			pt[0]=thisJet->Pt();
			pt[1]=thatJet->Pt();
			TLorentzVector* subjetP4[2][2];
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					sf[i][j]=1;
					subjetP4[i][j]=new TLorentzVector(0,0,0,0);
					subjetP4[i][j]->SetPxPyPzE(subjetSDPx[i][j],subjetSDPy[i][j],subjetSDPz[i][j],subjetSDE[i][j]);
					subjetPt[i][j]=subjetP4[i][j]->Pt();
					subjetEta[i][j]=subjetP4[i][j]->Eta();
				}
				dr[i]=subjetP4[i][0]->DeltaR(*subjetP4[i][1]);
			}
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					//get btagging eff------------------------------------------------------------
					int getPtBin=1;
					if(subjetPt[i][j]<140)getPtBin=1;
					else if (140<=subjetPt[i][j] && subjetPt[i][j]<180)getPtBin=2;
					else if (180<=subjetPt[i][j] && subjetPt[i][j]<240)getPtBin=3;
					else getPtBin=4;
					//if(FATsubjetSDHadronFlavor[i][j]==5)eff[i][j]=th1[1]->GetBinContent(getPtBin,ceil(subjetEta[i][j]/0.2)+15);
					//else if(FATsubjetSDHadronFlavor[i][j]==4)eff[i][j]=th1[3]->GetBinContent(getPtBin,ceil(subjetEta[i][j]/0.2)+15);
					//else eff[i][j]=th1[5]->GetBinContent(getPtBin,ceil(subjetEta[i][j]/0.2)+15);
					if(FATsubjetSDHadronFlavor[i][j]==5)eff[i][j]=th1[1]->GetBinContent(getPtBin);
					else if(FATsubjetSDHadronFlavor[i][j]==4)eff[i][j]=th1[3]->GetBinContent(getPtBin);
					else {
						int temp=0;
						if(subjetPt[i][j]>=900)temp=10;
						else temp=ceil(subjetPt[i][j]/100);
						
						bool checkBinContentIfZero=0;
						while(checkBinContentIfZero==0){
							if(th1[4]->GetBinContent(temp)==0){
								temp--;
							}
							else checkBinContentIfZero=1;
						}
						eff[i][j]=th1[5]->GetBinContent(temp);
					}
					
					//Get SF from csv------------------------------------------------------------
					if(FATsubjetSDHadronFlavor[i][j]==5){
						sf[i][j]=HF.eval_auto_bounds("central",BTagEntry::FLAV_B, subjetEta[i][j],subjetPt[i][j]); 
						//sf[i][j]=HF.eval(BTagEntry::FLAV_B,subjetEta[i][j],subjetPt[i][j]); 
					
					}
					else if(FATsubjetSDHadronFlavor[i][j]==4){
						sf[i][j]=HFC.eval_auto_bounds("central",BTagEntry::FLAV_C, subjetEta[i][j],subjetPt[i][j]); 
						//sf[i][j]=HF.eval(BTagEntry::FLAV_C,subjetEta[i][j],subjetPt[i][j]); 
				
					}
					else {
						sf[i][j]=LF.eval_auto_bounds("central",BTagEntry::FLAV_UDSG, subjetEta[i][j],subjetPt[i][j]); 
						//sf[i][j]=LF.eval(BTagEntry::FLAV_UDSG,subjetEta[i][j],subjetPt[i][j]); 
						
					}
					//conut nbtag---------------------------------------------------------
					if(subjetSDCSV[i][j]>0.46)nbtag++;
					//get tot. btagging SF
					if(subjetSDCSV[i][j]>=0.46)btaggingscaleFactor*=sf[i][j];
					else btaggingscaleFactor*=((1-eff[i][j]*sf[i][j])/(1-eff[i][j]));
					
				}
			}
			
			
			
			if(nameRoot==2)btaggingscaleFactor=1;
			double scaleFactor=PU_weight[0]*btaggingscaleFactor;
			
			
			
			Float_t*  fatjetTau1 = data.GetPtrFloat("FATjetTau1");
			Float_t*  fatjetTau2 = data.GetPtrFloat("FATjetTau2");
			Float_t*  FATjetPuppiTau1 = data.GetPtrFloat("FATjetPuppiTau1");
			Float_t*  FATjetPuppiTau2 = data.GetPtrFloat("FATjetPuppiTau2");
			double tau21[2];
			tau21[0]=(fatjetTau2[0]/fatjetTau1[0]),tau21[1]=(fatjetTau2[1]/fatjetTau1[1]);
			double puppiTau21[2];
			puppiTau21[0]=(FATjetPuppiTau2[0]/FATjetPuppiTau1[0]),puppiTau21[1]=(FATjetPuppiTau2[1]/FATjetPuppiTau1[1]);
			
			for (int i=0;i<2;i++){
				th5[214+i]->Fill(FATjetPRmass[i],scaleFactor);
				th5[216+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th5[218+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th5[220+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th5[238+i]->Fill(tau21[i],scaleFactor);
				th5[240+i]->Fill(puppiTau21[i],scaleFactor);
				
				th_flavor[event_flavor][214+i]->Fill(FATjetPRmass[i],scaleFactor);
				th_flavor[event_flavor][216+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][218+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th_flavor[event_flavor][220+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][238+i]->Fill(tau21[i],scaleFactor);
				th_flavor[event_flavor][240+i]->Fill(puppiTau21[i],scaleFactor);
			}
			
			if(!(tau21[0]>0.6 || tau21[1]>0.6)){
				for (int i=0;i<2;i++){
					
					th5[222+i]->Fill(FATjetPRmass[i],scaleFactor);
					th5[224+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
					th5[226+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
					th5[228+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
					th5[242+i]->Fill(tau21[i],scaleFactor);
					th5[244+i]->Fill(puppiTau21[i],scaleFactor);
					
					th_flavor[event_flavor][222+i]->Fill(FATjetPRmass[i],scaleFactor);
					th_flavor[event_flavor][224+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
					th_flavor[event_flavor][226+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
					th_flavor[event_flavor][228+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
					th_flavor[event_flavor][242+i]->Fill(tau21[i],scaleFactor);
					th_flavor[event_flavor][244+i]->Fill(puppiTau21[i],scaleFactor);
				}
			}
			
			
			if(fatjetPRmassL2L3Corr[0]<105||fatjetPRmassL2L3Corr[0]>135)continue;
			if(fatjetPRmassL2L3Corr[1]<105||fatjetPRmassL2L3Corr[1]>135)continue;
			nPass[8]+=PU_weight[0];
			for (int i=0;i<2;i++){
				
				th5[230+i]->Fill(FATjetPRmass[i],scaleFactor);
				th5[232+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th5[234+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th5[236+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th5[246+i]->Fill(tau21[i],scaleFactor);
				th5[248+i]->Fill(puppiTau21[i],scaleFactor);
				
				th_flavor[event_flavor][230+i]->Fill(FATjetPRmass[i],scaleFactor);
				th_flavor[event_flavor][232+i]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][234+i]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th_flavor[event_flavor][236+i]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][246+i]->Fill(tau21[i],scaleFactor);
				th_flavor[event_flavor][248+i]->Fill(puppiTau21[i],scaleFactor);
			}
			
			//9.-----------------------------------------
			if(tau21[0]>0.6 || tau21[1]>0.6) continue;
			nPass[9]+=PU_weight[0];
			double tau21_SF=1.031*0.881;
			if(JESOption==5)tau21_SF=(1.031+0.126)*(0.881+0.49);
			if(JESOption==6)tau21_SF=(1.031-0.126)*(0.881-0.49);
			if(tau21[0]<0.6 && tau21[1]<0.6 ){
				tau21_SF=1.031*1.031;
				if(JESOption==5)tau21_SF=(1.031+0.126)*(1.031+0.126);
				if(JESOption==6)tau21_SF=(1.031-0.126)*(1.031-0.126);
			}
			
			
			
			
			
			//10.btag
			
			
			//uncertainty -------------------------------------
			//double scaleFactor=btaggingscaleFactor*PU_weight[0]*tau21_SF;
			
			for(int i=0;i<3;i++){
				passPileup[i]+=btaggingscaleFactor*PU_weight[i]*tau21_SF;
				th7[i]->Fill(mjj,btaggingscaleFactor*PU_weight[i]*tau21_SF);
			}
			 for(int i=0;i<101;i++)passPDF[i]+=btaggingscaleFactor*PU_weight[0]*tau21_SF;
			 for(int i=5;i<14;i++)th7[i]->Fill(mjj,btaggingscaleFactor*PU_weight[0]*tau21_SF);
			 fixScaleNum[1]+=PU_weight[0];
			//--------------------------------------
			Float_t  FATjetPuppiSDmassThea[2] ={0};
			FATjetPuppiSDmassThea[0]=FATjetPuppiSDmass[0]*getPUPPIweight(thisJet->Pt(),thisJet->Eta(),tf1);
			FATjetPuppiSDmassThea[1]=FATjetPuppiSDmass[1]*getPUPPIweight(thatJet->Pt(),thatJet->Eta(),tf1);
			eta[0]=thisJet->Eta();
			eta[1]=thatJet->Eta();
			Float_t*  ADDjet_DoubleSV = data.GetPtrFloat("ADDjet_DoubleSV");
			Float_t  FATjet_DoubleSV[2]={0};
			
			Int_t ADDnJet        = data.GetInt("ADDnJet");
			bool matchThis=0,matchThat=0;
			TClonesArray* ADDjetP4 = (TClonesArray*) data.GetPtrTObject("ADDjetP4");
			for(int i=0;i<ADDnJet;i++){
				TLorentzVector* thisAddJet ;
				thisAddJet= (TLorentzVector*)ADDjetP4->At(i);
				if(!matchThis && thisAddJet->DeltaR(*thisJet)<0.8){
					matchThis=1;
					FATjet_DoubleSV[0]=ADDjet_DoubleSV[i];
					continue;
				}
				if(!matchThat && thisAddJet->DeltaR(*thatJet)<0.8){
					matchThat=1;
					FATjet_DoubleSV[1]=ADDjet_DoubleSV[i];
				}
				if(matchThis&& matchThat)break;
			}
			
			
			
			
			Float_t*  FATjetCISVV2 = data.GetPtrFloat("FATjetCISVV2");
			for(int i=0;i<2;i++){
				for(int j=0;j<2;j++){
					
					th5[(i*2+j)*5+nbtag]->Fill(subjetPt[i][j],scaleFactor);
					th5[(i*2+j)*5+nbtag+20]->Fill(subjetEta[i][j],scaleFactor);
					th5[(i*2+j)*5+nbtag+85]->Fill(subjetSDCSV[i][j],scaleFactor);
					if(subjetPt[i][j]>30 && fabs(subjetEta[i][j])<2.4)th5[(i*2+j)*5+nbtag+194]->Fill(subjetSDCSV[i][j],scaleFactor);
					
					th_flavor[event_flavor][(i*2+j)*5+nbtag]->Fill(subjetPt[i][j],scaleFactor);
					th_flavor[event_flavor][(i*2+j)*5+nbtag+20]->Fill(subjetEta[i][j],scaleFactor);
					th_flavor[event_flavor][(i*2+j)*5+nbtag+85]->Fill(subjetSDCSV[i][j],scaleFactor);
					if(subjetPt[i][j]>30 && fabs(subjetEta[i][j])<2.4)th_flavor[event_flavor][(i*2+j)*5+nbtag+194]->Fill(subjetSDCSV[i][j],scaleFactor);
					
				}
				th5[i*5+nbtag+40]->Fill(dr[i],scaleFactor);
				th5[i*5+nbtag+50]->Fill(pt[i],scaleFactor);
				th5[i*5+nbtag+60]->Fill(eta[i],scaleFactor);
				th5[i*5+nbtag+70]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th5[i*5+nbtag+105]->Fill(tau21[i],scaleFactor);
				th5[i*5+nbtag+120]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th5[i*5+nbtag+130]->Fill(puppiTau21[i],scaleFactor);
				th5[i*5+nbtag+140]->Fill(FATjetPRmass[i],scaleFactor);
				th5[i*5+nbtag+150]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th5[i*5+nbtag+170]->Fill(FATjet_DoubleSV[i],PU_weight[0]);
				th5[i*5+nbtag+184]->Fill(FATjetCISVV2[i],scaleFactor);
				th5[i*5+nbtag+250]->Fill(FATjetPuppiSDmassThea[i],scaleFactor);
				
				th_flavor[event_flavor][i*5+nbtag+40]->Fill(dr[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+50]->Fill(pt[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+60]->Fill(eta[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+70]->Fill(fatjetPRmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+105]->Fill(tau21[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+120]->Fill(FATjetPuppiSDmassL2L3Corr[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+130]->Fill(puppiTau21[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+140]->Fill(FATjetPRmass[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+150]->Fill(FATjetPuppiSDmass[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+170]->Fill(FATjet_DoubleSV[i],PU_weight[0]);
				th_flavor[event_flavor][i*5+nbtag+184]->Fill(FATjetCISVV2[i],scaleFactor);
				th_flavor[event_flavor][i*5+nbtag+250]->Fill(FATjetPuppiSDmassThea[i],scaleFactor);
				
			}
			th5[nbtag+80]->Fill(mjj,scaleFactor);
			th5[nbtag+115]->Fill(dEta,scaleFactor);
			th5[nbtag+165]->Fill(mjjRed,scaleFactor);
			
			th_flavor[event_flavor][nbtag+80]->Fill(mjj,scaleFactor);
			th_flavor[event_flavor][nbtag+115]->Fill(dEta,scaleFactor);
			th_flavor[event_flavor][nbtag+165]->Fill(mjjRed,scaleFactor);
			
			nPass[nbtag+10]+=PU_weight[0]*btaggingscaleFactor;
				
			
			
			int nDoubleSV=0;
			if(FATjet_DoubleSV[0]>0.6)nDoubleSV++;
			if(FATjet_DoubleSV[1]>0.6)nDoubleSV++;
			
			if(nDoubleSV==0)nPass[15]+=PU_weight[0];
			else if(nDoubleSV==2)nPass[17]+=PU_weight[0];
			else {
				nPass[16]+=PU_weight[0];
				if((FATjet_DoubleSV[0]>0.6 && subjetSDCSV[1][0]<0.46 && subjetSDCSV[1][1]<0.46) ||
				     (FATjet_DoubleSV[1]>0.6 && subjetSDCSV[0][0]<0.46 && subjetSDCSV[0][1]<0.46))nPass[18]+=PU_weight[0];
				else if((FATjet_DoubleSV[0]>0.6 && subjetSDCSV[1][0]>0.46 && subjetSDCSV[1][1]>0.46) ||
				               (FATjet_DoubleSV[1]>0.6 && subjetSDCSV[0][0]>0.46 && subjetSDCSV[0][1]>0.46))nPass[20]+=PU_weight[0];
				else nPass[19]+=PU_weight[0];
			}
			
			
			th5[182]->Fill(nVtx,scaleFactor);
			th5[183]->Fill(ntrue,scaleFactor);
			th_flavor[event_flavor][182]->Fill(nVtx,scaleFactor);
			th_flavor[event_flavor][183]->Fill(ntrue,scaleFactor);

		}//end event loop----------------------------------------------------------------------------------------
	}	//end ntuple loop----------------------------------------------------------------------------------------
	cout<<"entries="<<total<<endl;	
	for(int i=0;i<22;i++)cout<<"nPass["<<i<<"]="<<nPass[i]<<endl;
	
	for(int i=0;i<3;i++)th7[3]->SetBinContent(i+1,passPileup[i]/totalPileup[i]);
	for(int i=0;i<101;i++)th7[4]->SetBinContent(i+1,passPDF[i]/totalPDF[i]);
	
	TH1D * th2o=new TH1D("Nbtagjet","Nbtagjet",5,-0.5,4.5);
	for (int i=0;i<5;i++){
		if(nameRoot==2 && i>2)continue;
		th2o->SetBinContent(i+1,nPass[i+10]);
	}
	
	TH1D * fixScale=new TH1D("fixScale","fixScale",2,-0.5,1.5);
	fixScale->SetBinContent(1,fixScaleNum[0]);
	fixScale->SetBinContent(2,fixScaleNum[1]);
	TH1D * cutflow=new TH1D("cutflow","cutflow",21,0.5,21.5);
	cutflow->SetBinContent(1,fixScaleNum[0]);
	if(nameRoot!=2)for(int ii=1;ii<22;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	else for(int ii=1;ii<16;ii++)cutflow->SetBinContent(ii+1,nPass[ii-1]);
	
	TFile* outFile ;
	if(JESOption==0)outFile= new TFile(Form("sf2/%s.root",st2.data()),"recreate");
	else if(JESOption==1)outFile= new TFile(Form("sf2/%s_JESUp.root",st2.data()),"recreate");
	else if(JESOption==2)outFile= new TFile(Form("sf2/%s_JESDown.root",st2.data()),"recreate");
	else if(JESOption==3)outFile= new TFile(Form("sf2/%s_BtagUp.root",st2.data()),"recreate");
	else if(JESOption==4)outFile= new TFile(Form("sf2/%s_BtagDown.root",st2.data()),"recreate");
	else if(JESOption==5)outFile= new TFile(Form("sf2/%s_tau21Up.root",st2.data()),"recreate");
	else if(JESOption==6)outFile= new TFile(Form("sf2/%s_tau21Down.root",st2.data()),"recreate");
	th2o->Write();
	fixScale->Write();
	cutflow->Write();
	
	for(int i=0;i<260;i++){
		th5[i]->Write();
		th_flavor[0][i]->Write();
		th_flavor[1][i]->Write();
		th_flavor[2][i]->Write();
		th_flavor[3][i]->Write();
	}
	
	for(int i=0;i<14;i++)th7[i]->Write();
	outFile->Close();
}
void HH4bCategoryBase_80(int wMs,int wM, string st,string st2,string option=""){	

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

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

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

    //TH2::SetDefaultSumw2();

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

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

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

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

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

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

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



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


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


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



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

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

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

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

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

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

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

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

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


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


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

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

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

    int numberOfLeptons;



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

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

    TLorentzVector *pJet[50];

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

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

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

    TLorentzVector *pRekoTop;
    TLorentzVector *pRekoAntiTop;

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

    TLorentzVector *pNu;
    TLorentzVector *pAntiNu;

    TLorentzVector *pBBoosted;
    TLorentzVector *pBbarBoosted;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        tree->GetEntry(iEvent);

        EventCounter++;

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

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

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

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

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

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

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

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

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

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


            
            // REKO THETA 

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

    outputFile->cd("");
    outputFile->Write();
    outputFile->Close();
    delete outputFile;
}
/**
 * @brief Matching L1 jets from L1UpgradeTree, to reference GenJets from L1ExtraTree.
 *
 * @author Robin Aggleton, March 2016
 */
int main(int argc, char* argv[]) {

    cout << "Running Matcher, L1 Jets to GenJets" << std::endl;

    // deal with user args
    RunMatcherOpts opts(argc, argv);

    ///////////////////////
    // SETUP INPUT FILES //
    ///////////////////////

    // get input TTrees
    // Reference jets - GenJets
    TString refJetDirectory = opts.refJetDirectory();
    L1GenericTree<L1AnalysisGeneratorDataFormat> refJetTree(opts.inputFilename(),
                                                          refJetDirectory+"/L1GenTree",
                                                          "Generator");
    L1AnalysisGeneratorDataFormat * refData = refJetTree.getData();

    // L1 jets
    TString l1JetDirectory = opts.l1JetDirectory();
    L1GenericTree<L1AnalysisL1UpgradeDataFormat> l1JetTree(opts.inputFilename(),
                                                           l1JetDirectory+"/L1UpgradeTree",
                                                           "L1Upgrade");
    L1AnalysisL1UpgradeDataFormat * l1Data = l1JetTree.getData();

    // hold Event tree
    L1GenericTree<L1AnalysisEventDataFormat> eventTree(opts.inputFilename(),
                                                         "l1EventTree/L1EventTree",
                                                         "Event");
    L1AnalysisEventDataFormat * eventData = eventTree.getData();

    // input filename stem (no .root)
    fs::path inPath(opts.inputFilename());
    TString inStem(inPath.stem().c_str());

    ////////////////////////
    // SETUP OUTPUT FILES //
    ////////////////////////

    // setup output file to store results
    // check that we're not overwriting the input file!
    if (opts.outputFilename() == opts.inputFilename()) {
        throw std::runtime_error("Cannot use input filename as output filename!");
    }
    TFile * outFile = openFile(opts.outputFilename(), "RECREATE");
    fs::path outPath(opts.outputFilename());
    TString outDir(outPath.parent_path().c_str());
    if (outDir != "") {
        outDir += "/";
    }

    // setup output tree to store raw variable for quick plotting/debugging
    TTree outTree("valid", "valid");

    // Quantities for L1 jets:
    float out_pt(-1.), out_eta(99.), out_phi(99.);
    int out_nL1(-1); // number of jets in the event,
    int out_indL1(-1); // index of this jet in the collection (ordered by descending pT)
    outTree.Branch("pt", &out_pt, "pt/Float_t");
    outTree.Branch("eta", &out_eta, "eta/Float_t");
    outTree.Branch("phi", &out_phi, "phi/Float_t");
    outTree.Branch("nL1", &out_nL1, "nL1/Int_t");
    outTree.Branch("indL1", &out_indL1, "indL1/Int_t");
    // Quantities for reference jets (GenJet, etc):
    float out_ptRef(-1.), out_etaRef(99.), out_phiRef(99.);
    int out_nRef(-1); // number of jets in the event,
    int out_indRef(-1); // index of this jet in the collection (ordered by descending pT)
    outTree.Branch("ptRef", &out_ptRef, "ptRef/Float_t");
    outTree.Branch("etaRef", &out_etaRef, "etaRef/Float_t");
    outTree.Branch("phiRef", &out_phiRef, "phiRef/Float_t");
    outTree.Branch("nRef", &out_nRef, "nRef/Int_t");
    outTree.Branch("inRef", &out_indRef, "indRef/Int_t");
    // Quantities to describe relationship between the two:
    float out_rsp(-1.);
    float out_dr(99.), out_deta(99.), out_dphi(99.);
    float out_ptDiff(99999.), out_resL1(99.), out_resRef(99.);
    int out_nMatches(0);
    outTree.Branch("ptDiff", &out_ptDiff, "ptDiff/Float_t"); // L1 - Ref
    outTree.Branch("rsp", &out_rsp, "rsp/Float_t"); // response = l1 pT/ ref jet pT
    outTree.Branch("dr", &out_dr, "dr/Float_t");
    outTree.Branch("deta", &out_deta, "deta/Float_t");
    outTree.Branch("dphi", &out_dphi, "dphi/Float_t");
    outTree.Branch("resL1", &out_resL1, "resL1/Float_t"); // resolution = L1 - Ref / L1
    outTree.Branch("resRef", &out_resRef, "resRef/Float_t"); // resolution = L1 - Ref / Ref
    outTree.Branch("nMatches", &out_nMatches, "nMatches/Int_t");
    // PU quantities
    float out_trueNumInteractions(-1.), out_numPUVertices(-1.);
    int out_recoNVtx(0);
    outTree.Branch("trueNumInteractions", &out_trueNumInteractions, "trueNumInteractions/Float_t");
    outTree.Branch("numPUVertices", &out_numPUVertices, "numPUVertices/Float_t");
    outTree.Branch("recoNVtx", &out_recoNVtx, "recoNVtx/Int_t");

    // Event number
    ULong64_t out_event(0);
    outTree.Branch("event", &out_event, "event/Int_t");

    // L1 sums
    int out_nL1JetsSum(0);
    float out_httL1(0.);
    float out_mhtL1(0.), out_mhtPhiL1(0.);
    outTree.Branch("nL1JetsSum", &out_nL1JetsSum);
    outTree.Branch("httL1", &out_httL1);
    outTree.Branch("mhtL1", &out_mhtL1);
    outTree.Branch("mhtPhiL1", &out_mhtPhiL1);

    // Reference jet Sums
    int out_nRefJetsSum(0);
    float out_httRef(0.);
    float out_mhtRef(0.), out_mhtPhiRef(0.);
    outTree.Branch("nRefJetsSum", &out_nRefJetsSum);
    outTree.Branch("httRef", &out_httRef);
    outTree.Branch("mhtRef", &out_mhtRef);
    outTree.Branch("mhtPhiRef", &out_mhtPhiRef);

    // check # events in boths trees is same
    Long64_t nEntriesRef = refJetTree.getEntries();
    Long64_t nEntriesL1  = l1JetTree.getEntries();
    Long64_t nEntries(0);
    if (nEntriesRef != nEntriesL1) {
        throw std::range_error("Different number of events in L1 & ref trees");
    } else {
        nEntries = (opts.nEvents() > 0) ? opts.nEvents() : nEntriesL1;
        cout << "Running over " << nEntries << " events." << endl;
    }

    ///////////////////////
    // SETUP JET MATCHER //
    ///////////////////////
    double maxDeltaR(opts.deltaR()), minRefJetPt(opts.refJetMinPt()), maxRefJetPt(5000.);
    double minL1JetPt(opts.l1JetMinPt()), maxL1JetPt(5000.), maxJetEta(5.);
    // use base class smart pointer for ease of swapping in/out different
    //  matchers if so desired
    std::unique_ptr<Matcher> matcher(new DeltaR_Matcher(maxDeltaR, minRefJetPt, maxRefJetPt, minL1JetPt, maxL1JetPt, maxJetEta));
    std::cout << *matcher << std::endl;

    //////////////////////
    // LOOP OVER EVENTS //
    //////////////////////
    // produce matching pairs and store
    Long64_t drawCounter = 0;
    for (Long64_t iEntry = 0; iEntry < nEntries; ++iEntry) {
        if (iEntry % 10000 == 0) {
            cout << "Entry: " << iEntry << " at " << getCurrentTime() << endl;
        }

        if (refJetTree.getEntry(iEntry) < 1 || l1JetTree.getEntry(iEntry) < 1 ||
            eventTree.getEntry(iEntry) < 1)// || recoVtxTree.getEntry(iEntry) < 1)
            break;

        ////////////////////////
        // Generic event info //
        ////////////////////////
        out_event = eventData->event;

        /////////////////////////////
        // Store pileup quantities //
        /////////////////////////////
        // note these get stored once per pair of matched jets NOT once per event
        out_trueNumInteractions = refData->nMeanPU;
        out_numPUVertices = refData->nVtx;
        // out_recoNVtx = recoVtxData->nVtx;

        /////////////////////////////////////////////
        // Make vectors of ref & L1 jets from trees //
        /////////////////////////////////////////////
        std::vector<TLorentzVector> refJets = makeTLorentzVectors(refData->jetPt, refData->jetEta, refData->jetPhi);
        std::vector<TLorentzVector> l1Jets = makeTLorentzVectors(l1Data->jetEt, l1Data->jetEta, l1Data->jetPhi);

        out_nL1 = l1Jets.size();
        out_nRef = refJets.size();

        if (out_nL1 == 0 || out_nRef == 0) continue;

        ////////////////
        // Store sums //
        ////////////////
        // L1 sums
        std::vector<TLorentzVector> httL1Jets = getJetsForHTT(l1Jets);
        out_nL1JetsSum = httL1Jets.size();
        out_httL1 = l1Data->sumEt[2];
        out_mhtL1 = l1Data->sumEt[3];
        out_mhtPhiL1 = l1Data->sumPhi[3];
        // float httL1_check = scalarSumPt(httL1Jets);

        // Check my calc with stored value
        // Doens't make sense to do this when applying calibrations on the fly
        // if (fabs(out_httL1 - httL1_check) > 0.01 && out_httL1 < 2047.5) {
        //     cout << "HTT L1 not agreeing with calculation: " + lexical_cast<std::string>(out_httL1) + " vs " + lexical_cast<std::string>(httL1_check) << endl;
        //     for (const auto& itr: l1Jets) {
        //         cout << itr.Pt() << " " << itr.Eta() << endl;
        //     }
        // }

        // TLorentzVector mhtL1_check = vectorSum(httL1Jets);

        // Override sums with calibrated jets
        // out_httL1 = httL1_check;
        // out_mhtL1 = mhtL1_check.Pt();
        // out_mhtPhiL1 = mhtL1_check.Phi();

        // Ref jet sums
        std::vector<TLorentzVector> httRefJets = getJetsForHTT(refJets);
        out_nRefJetsSum = httRefJets.size();
        out_httRef = scalarSumPt(httRefJets);
        // Pass jets to matcher, do matching
        TLorentzVector mhtVecRef = vectorSum(httRefJets);
        out_mhtRef = mhtVecRef.Pt();
        out_mhtPhiRef = mhtVecRef.Phi();

        ///////////////////////////////////////
        // Pass jets to matcher, do matching //
        ///////////////////////////////////////
        matcher->setRefJets(refJets);
        matcher->setL1Jets(l1Jets);
        std::vector<MatchedPair> matchResults = matcher->getMatchingPairs();
        // matcher->printMatches(); // for debugging

        //////////////////////////////////////////
        // store L1 & ref jet variables in tree //
        //////////////////////////////////////////
        out_nMatches = matchResults.size();

        for (const auto &it: matchResults) {
            // std::cout << it << std::endl;
            out_pt = it.l1Jet().Et();
            out_eta = it.l1Jet().Eta();
            out_phi = it.l1Jet().Phi();
            out_dr = it.refJet().DeltaR(it.l1Jet());
            out_deta = it.refJet().Eta() - it.l1Jet().Eta();
            out_dphi = it.refJet().DeltaPhi(it.l1Jet());
            out_ptRef = it.refJet().Pt();
            out_etaRef = it.refJet().Eta();
            out_phiRef = it.refJet().Phi();
            out_ptDiff = out_pt - out_ptRef;
            out_rsp = out_pt/out_ptRef;
            out_resL1 = out_ptDiff/out_pt;
            out_resRef = out_ptDiff/out_ptRef;
            outTree.Fill();
        }

        ///////////////////////////////////////////////////
        // debugging plot - plots eta vs phi map of jets //
        ///////////////////////////////////////////////////
        if (drawCounter < opts.drawNumber()) {
            if (matchResults.size() > 0) {
                TString label = TString::Format(
                    "%.1f < E^{gen}_{T} < %.1f GeV, " \
                    "L1 jet %.1f < E^{L1}_{T} < %.1f GeV, |#eta_{jet}| < %.1f",
                    minRefJetPt, maxRefJetPt, minL1JetPt, maxL1JetPt, maxJetEta);
                // get jets post pT, eta cuts
                JetDrawer drawer(matcher->getRefJets(), matcher->getL1Jets(), matchResults, label);

                TString pdfname = TString::Format("%splots_%s_%s_%s/jets_%lld.pdf",
                    outDir.Data(), inStem.Data(), "gen", "l1", iEntry);
                drawer.drawAndSave(pdfname);

                drawCounter++;
            }
        }
    } // end of loop over entries

    // save tree to new file and cleanup
    outTree.Write("", TObject::kOverwrite);
    outFile->Close();
    return 0;
}
void sqrtBins(){


	//OPTIONS AND CUTS______________
	bool useBlueBeam = false;
	bool useYellowBeam = true;
	bool randomizeSpin = false;
	bool fullEta = false;

	double PI = 3.14159265359;
	
	
	
	
	cout << "\n";
	if (useBlueBeam && useYellowBeam){cout << "using both beams-----" << endl;}
	if (useBlueBeam && !useYellowBeam){cout << "using blue beam------" << endl;}
	if (!useBlueBeam && useYellowBeam){cout << "using yellow beam----" << endl;}
	cout << "\n";
	if (randomizeSpin){cout << "randomizing spin-----" << endl;}
	//______________________________


  
	//LOAD LIBS_____________________
	cout << "\n";
	gROOT->Macro("StRoot/LoadLibs.C");
	gSystem->Load("pionPair");
	cout << " loading of pionPair library done" << endl;
	//______________________________


	//SET UP INPUT FILE_____________
	TFile* infile = new TFile("/star/u/klandry/ucladisk/2012IFF/schedOut_Full_4_2/allPairs_4_2.root");

	string outFileName = "./resultsNew_4_22/yellowEtaGT0_pairs_4_2.root"; 

	
	
  //______________________________

	
	//SET UP TREE TO RECEIVE INPUT__
	pionPair* pair1 = new pionPair();
	TTree* pairTree = infile->Get("pionPairTree");
	pairTree->SetBranchAddress("pionPair", &pair1);
	//______________________________
	
	
	//SET UP HISTOGRAMS_____________
	//event variable histograms
	/*
	TH1D* hInvarM    = new TH1D("invarM","invarM",80,0,2);
	TH1D* hEtaTot	   = new TH1D("etaTot","etaTot",60,-1.5,1.5);
	TH1D* hPhiR      = new TH1D("hPhiR","hPhiR",60,-4,4);
	TH1D* hPhiS      = new TH1D("hPhiS","hPhiS",60,-4,4);
	TH1D* hPhiSR     = new TH1D("hPhiSR","hPhiSR",60,-4,4);
	TH1D* hTheta     = new TH1D("hTheta","hTheta",30,-0.85,4);
	TH1D* hCosTheta  = new TH1D("hCosTheta","hCosTheta",80,-1,1);
	TH1D* hZ         = new TH1D("hZ","hZ",80,0,1);
	TH1D* hPtot      = new TH1D("hPtot","hPtot",80,0,20);
	TH1D* hPtTOT     = new TH1D("hPt","hPt",80,0,15);
	*/
	
	//histos for asym analysis	
	double histMin = -PI;
	double histMax =  PI;
	
	TH1D * hNumberUp   = new TH1D("hNumberUp","hNumberUp",nPhisrBins,histMin,histMax);
	TH1D * hNumberDown = new TH1D("hNumberDown","hNumberDown",nPhisrBins,histMin,histMax);
	
	TH1D * hNumberUp_Pt[nPtBins];
	TH1D * hNumberDown_Pt[nPtBins];
	
	TH1D * hNumberUp_Mass[nMassBins]; 
	TH1D * hNumberDown_Mass[nMassBins];

	TH1D * hNumberUp_Eta[nEtaBins];   
	TH1D * hNumberDown_Eta[nEtaBins];
	
	createFiveBins(hNumberUp_Pt,nPhisrBins,histMin,histMax,"hNumUp_Ptbin_");
	createFiveBins(hNumberDown_Pt,nPhisrBins,histMin,histMax,"hNumDwn_Ptbin_");
	createFiveBins(hNumberUp_Mass,nPhisrBins,histMin,histMax,"hNumUp_Massbin_");
	createFiveBins(hNumberDown_Mass,nPhisrBins,histMin,histMax,"hNumDwn_Massbin_");
	createFourBins(hNumberUp_Eta,nPhisrBins,histMin,histMax,"hNumUp_Etabin_");
	createFourBins(hNumberDown_Eta,nPhisrBins,histMin,histMax,"hNumDwn_Etabin_");
	
	TH1D* hAut_Pt[nPtBins];
	TH1D* hAut_Mass[nMassBins];
	TH1D* hAut_Eta[nEtaBins];

	createFiveBins(hAut_Pt, nPhisrBins, histMin, histMax, "hAut_Ptbin_");
	createFiveBins(hAut_Mass, nPhisrBins, histMin, histMax, "hAut_Massbin_");
	createFourBins(hAut_Eta, nPhisrBins, histMin, histMax, "hAut_Etabin_");
	
	
	/*
	TH1D* polOfBinUp_Pt[nPtBins][binNumber];
	TH1D* polOfBinDown_Pt[nPtBins][binNumber];
	TH1D* polOfBinUp_Mass[nMassBins][binNumber];
	TH1D* polOfBinDown_Mass[nMassBins][binNumber];
	TH1D* polOfBinUp_Eta[nEtaBins][binNumber];
	TH1D* polOfBinDown_Eta[nEtaBins][binNumber];
	createPolHists(polOfBinUp_Pt, 25, 0, 1, "hPolOfBinUp_Ptbin_");
	createPolHists(polOfBinDown_Pt, 25, 0, 1, "hPolOfBinDown_Ptbin_");
	createPolHists(polOfBinUp_Mass, 25, 0, 1, "hPolOfBinUp_Massbin_");
	createPolHists(polOfBinDown_Mass, 25, 0, 1, "hPolOfBinDown_Massbin_");
	createPolHists(polOfBinUp_Eta, 25, 0, 1, "hPolOfBinUp_Etabin_");
	createPolHists(polOfBinDown_Eta, 25, 0, 1, "hPolOfBinDown_Etabin_");
  */
	
	TH1D* polOfBin_Pt[nPtBins][nPhisrBins];
	TH1D* polOfBin_Mass[nMassBins][nPhisrBins];
	TH1D* polOfBin_Eta[nEtaBins][nPhisrBins];
	createPolHists(polOfBin_Pt, 25, 0, 1, "hPolOfBin_Ptbin_");
	createPolHists(polOfBin_Mass, 25, 0, 1, "hPolOfBin_Massbin_");
	createPolHistsEta(polOfBin_Eta, 25, 0, 1, "hPolOfBin_Etabin_");
	
	
	//HISTOGRAMS TO HOLD PT MASS AND ETA VALES
	TH1D* hPt[nPtBins];
	TH1D* hMass[nMassBins];
	TH1D* hEta[nEtaBins];
	createFiveBins(hPt, 500, 3.0, 50, "hPt_Ptbin_");
	createFiveBins(hMass, 1000, 0.0, 100, "hMass_Massbin_");
	createFourBins(hEta, 20, -1.4, 1.4, "hEta_Etabin_");
	
	
	//TH1D * hDiff  = new TH1D("hNumberSum","hNumberSum",binNumber,histMin,histMax);
	//TH1D * hAut = new TH1D("Aut","Aut",binNumber,histMin,histMax);
	//______________________________
	
	
	
	//BEAM POLARIZATION_____________
	ifstream polFile;
	polFile.open("/star/u/klandry/ucladisk/2012IFF/BeamPolarization2012.txt");
	

	map<int, double> polarizationOfFill_Y;
	map<int, double> polErrOfFill_Y;
	
	map<int, double> polarizationOfFill_B;
	map<int, double> polErrOfFill_B;
	
	
	
	int    fill;
	int    beamE;
	int    startT;
	string plusminus;
	
	double pAvrgBlue;
	double pErrAvrgBlue;
	
	double pInitialBlue;
	double pErrInitialBlue;
	double dPdTBlue;
	double dPdTErrBlue;
	
	double pAvrgYellow;
	double pErrAvrgYellow;
	
	double pInitialYellow;
	double pErrInitialYellow;
	double dPdTYellow;
	double dPdTErrYellow;
	
	string header;
	
	for (int i=0; i<19; i++){polFile >> header;}
	
	while (!polFile.eof())
	{
		
		polFile >> fill;
		polFile >> beamE;
		polFile >> startT;
		
		polFile >> pAvrgBlue;
		polFile >> plusminus;
		polFile >> pErrAvrgBlue;
		
		polFile >> pInitialBlue;
		polFile >> plusminus;
		polFile >> pErrInitialBlue;
		
		polFile >> dPdTBlue;
		polFile >> plusminus;
		polFile >> dPdTErrBlue;
		
		polFile >> pAvrgYellow;
		polFile >> plusminus;
		polFile >> pErrAvrgYellow;
		
		polFile >> pInitialYellow;
		polFile >> plusminus;
		polFile >> pErrInitialYellow;
		
		polFile >> dPdTYellow;
		polFile >> plusminus;
		polFile >> dPdTErrYellow;
		
		
		polarizationOfFill_B[fill] = pAvrgBlue/100.;
		polErrOfFill_B[fill] = pErrAvrgBlue/100.;
		
		polarizationOfFill_Y[fill] = pAvrgYellow/100.;
		polErrOfFill_Y[fill] = pErrAvrgYellow/100.;
		
	}
	
	double avgPolOfBinUp[nPhisrBins];
	double polOfBinSumUp[nPhisrBins];
	
	double avgPerrorOfBinUp[nPhisrBins];
	double pErrorOfBinUp[nPhisrBins];
	
	double avgPolOfBinDown[nPhisrBins];
	double polOfBinSumDown[nPhisrBins];
	
	double avgPerrorOfBinDown[nPhisrBins];
	double pErrorOfBinDown[nPhisrBins];
	
	for (int i=0; i<nPhisrBins; i++)
	{
		avgPolOfBinUp[i] = 0;
		polOfBinSumUp[i] = 0;
		
		avgPerrorOfBinUp[i] = 0;
		pErrorOfBinUp[i] = 0;
		
		avgPolOfBinDown[i] = 0;
		polOfBinSumDown[i] = 0;
		
		avgPerrorOfBinDown[i] = 0;
		pErrorOfBinDown[i] = 0;
		
	}
	//______________________________
	
	
	
	//CUTS__________________________
	double lowLimitPt    = ptBinStart[0];
	double hiLimitPt     = ptBinEnd[4];
	double lowLimitEta   = etaBinStart[0];
	double hiLimitEta    = etaBinEnd[3];
	double lowLimitMass  = massBinStart[0];
	double hiLimitMass   = massBinEnd[4];
	
	double blueLowLimitEta  = 0;
	double yellowLowLimitEta = 0;  //this is for testing individual beams
	
	
	//hiLimitEta = 0;
	
	if (fullEta)
	{
		assert(hiLimitEta > 0);
		assert(lowLimitEta < 0);
	}
	
	cout << "Pt  between " << lowLimitPt << " and " << hiLimitPt << endl;
	cout << "M   between " << lowLimitMass << " and " << hiLimitMass << endl;
	cout << "Eta between " << lowLimitEta << " and " << hiLimitEta << endl;
	//______________________________
	
	//*
	
	//   ======================================================================
	//============================================================================
	//START ANALYSIS==============================================================
	//============================================================================
	//   ======================================================================
		//*
	cout << "\n";
	cout << "<----STARTING ANALYSIS---->" << endl;
  cout << "\n";
	cout << pairTree->GetEntries() << " pairs to analyze" << endl;
	
	
	
	int blueFillNo;
	int yellowFillNo;
	
	int phiSRbin;
	
	TLorentzVector sum;
	TLorentzVector sumY;
	TLorentzVector sumB;
	
	//random number for randomizing spin.
	//set seed to zero to gaurenty unique numbers each time.
	TRandom3 r;
	r.SetSeed(0);
	
	int rand5 = 0;
	int rand6 = 0;
	int rand9 = 0;
	int rand10 = 0;
	
	
	int totalPairsFinal = 0;
	int blueD = 0;
	int blueU = 0;
	int yellowD = 0;
	int yellowU = 0;
	
	int pionStarNumber = 0;
	int test = 0;
	
	for (int iPair = pionStarNumber; iPair < pairTree->GetEntries(); iPair++)
	{
		
		if (iPair%10000 == 0) {cout << "processing pair number " << iPair << endl;}
		//if (iPair == pionStarNumber+100000){break;}

		pairTree->GetEntry(iPair);

		
		if (pair1->withinRadius(0.05, 0.3))
		{

			bool triggerFired = false;
			bool fromKaon = false;
			bool passInitialCut_B = false;
			bool passInitialCut_Y = false;
			bool passDCAcut = false;

			StTriggerId trigId = pair1->triggerIds();
						
			//JP0,JP1,JP2,AJP
			if (trigId.isTrigger(370601) || trigId.isTrigger(370611) || trigId.isTrigger(370621) || trigId.isTrigger(370641))
			{
				triggerFired = true;
			}
			
			//BHT0VPD,BHT1VPD,BHT2BBC,BHT2
			if (trigId.isTrigger(370501) || trigId.isTrigger(370511) || trigId.isTrigger(370522) || trigId.isTrigger(370531))
			{
				triggerFired = true;
			}
			
			
			if (triggerFired)
			{
				
				blueFillNo   = pair1->runInfo().beamFillNumber(1); //1 = blue beam
				yellowFillNo = pair1->runInfo().beamFillNumber(0); //0 = yellow beam 

				sum = pair1->piPlusLV() + pair1->piMinusLV();
				sumB = sum; //blue beam.
				
				
				//yellow beam must rotate around y axis by pi so the eta cut can be the same for both beams. 				
				sumY = sum;
				sumY.RotateY(PI);

				//blue low limit eta is 0 yellow high limit eta is 0 this is a test
				if (sumB.Pt() >= lowLimitPt && sumB.Pt() <= hiLimitPt && sumB.M() >= lowLimitMass && sumB.M() <= hiLimitMass && sumB.Eta() >= lowLimitEta && sumB.Eta() <= hiLimitEta)
				{
					passInitialCut_B = true;
				}
				if (sumY.Pt() >= lowLimitPt && sumY.Pt() <= hiLimitPt && sumY.M() >= lowLimitMass && sumY.M() <= hiLimitMass && sumY.Eta() >= yellowLowLimitEta && sumY.Eta() <= hiLimitEta)
				{
					passInitialCut_Y = true;
				}
				
				if (passInitialCut_B && useBlueBeam)
				{
					//BLUE BEAM SPIN UP: spin bin 9 and 10
					if (pair1->spinBit() == 9 || pair1->spinBit() == 10)
					{						
						fillCorrectPtBin(hNumberUp_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
						
					}
					
					//BLUE BEAM SPIN DOWN: spin bin 5 and 6
					if (pair1->spinBit() == 5 || pair1->spinBit() == 6)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumB, pair1->phiSR('b'), polOfBin_Pt, polarizationOfFill_B[blueFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumB, pair1->phiSR('b'), polOfBin_Mass, polarizationOfFill_B[blueFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumB, pair1->phiSR('b'), polOfBin_Eta, polarizationOfFill_B[blueFillNo],hEta);}
			
					}
				}//done with blue beam
				
				if (passInitialCut_Y && useYellowBeam)
				{
					//YELLOW BEAM SPIN UP: spin bin 6 and 10
					if (pair1->spinBit() == 6 || pair1->spinBit() == 10)
					{
						fillCorrectPtBin(hNumberUp_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberUp_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberUp_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					
					}						
					
					//YELLOW BEAM SPIN DOWN: spin bit 5 and 9
					if (pair1->spinBit() == 5 || pair1->spinBit() == 9)
					{
						fillCorrectPtBin(hNumberDown_Pt, sumY, pair1->phiSR('y'), polOfBin_Pt, polarizationOfFill_Y[yellowFillNo],hPt);
						fillCorrectMassBin(hNumberDown_Mass, sumY, pair1->phiSR('y'), polOfBin_Mass, polarizationOfFill_Y[yellowFillNo],hMass);
						if(fullEta){fillCorrectEtaBin(hNumberDown_Eta, sumY, pair1->phiSR('y'), polOfBin_Eta, polarizationOfFill_Y[yellowFillNo],hEta);}
					}
				}//done with yellow beam
			}//end trigger check
		}//end radius check
	}//end pion tree loop
	

	
	
	//CALCULATE ASYMMETRY BIN BY BIN
	cout << "\n";
	cout << "<----CALCULATING ASYMMETRY---->" << endl;
	cout << "\n";
	
	
	
	double asymsPt[5]; 
	double asymsMass[5];
	double asymsEta[4];

	double asymsPtE[5];
	double asymsMassE[5];
	double asymsEtaE[4];
	
	cout << "\n";
	cout << "\n";

	cout << "\n \n calcing pt asym " << endl;
	calcAsym(hAut_Pt, hNumberUp_Pt, hNumberDown_Pt, polOfBin_Pt, asymsPt, asymsPtE);
	cout << "\n";
	cout << "\n";
	cout << "\n \n calcing mass asym " << endl;
	calcAsym(hAut_Mass, hNumberUp_Mass, hNumberDown_Mass, polOfBin_Mass, asymsMass, asymsMassE);
	cout << "\n";
	cout << "\n";
	if (fullEta)
	{
		cout << "\n \n calcing eta asym " << endl;	
		calcAsymEta(hAut_Eta, hNumberUp_Eta, hNumberDown_Eta, polOfBin_Eta, asymsEta, asymsEtaE);
	}

	
	
	
	//PLOT ASYMMETRIES
	cout << "\n";
	cout << "<----PLOTTING ASYMMETRIES---->" << endl;
	cout << "\n";
	
	double ptPoints[5];
	double ptPointsErr[5];
	double massPoints[5];
	double massPointsErr[5];
	double etaPoints[5];
	double etaPointsErr[5];
	
	
	getPtPoints(hPt, ptPoints, ptPointsErr);
	getMassPoints(hMass, massPoints, massPointsErr);
	if(fullEta){getEtaPoints(hEta, etaPoints, etaPointsErr);}
	
	
	TCanvas* cAsymPt = new TCanvas();
	TGraphErrors* gAsymPt = new TGraphErrors(nPtBins,ptPoints,asymsPt,ptPointsErr,asymsPtE);
	
	gAsymPt->Draw("AP");
	
	TCanvas* cAsymMass = new TCanvas();	
	TGraphErrors* gAsymMass = new TGraphErrors(nMassBins,massPoints,asymsMass,massPointsErr,asymsMassE);
	
	gAsymMass->Draw("AP");
	
	if (fullEta)
	{
		TCanvas* cAsymEta = new TCanvas();
		TGraphErrors* gAsymEta = new TGraphErrors(nEtaBins,etaPoints,asymsEta,etaPointsErr,asymsEtaE);
		gAsymEta->Draw("AP");
		
	}
	
	
	
	
	
	//DRAW HISTOGRAMS
	cout << "\n";
	cout << "<----DRAWING HISTOGRAMS---->" << endl;
	cout << "\n";
	
	
	
	
	TCanvas* cPt   = new TCanvas("cPt","cPt",1200,600);
	TCanvas* cMass = new TCanvas("cMass","cMass",1200,600);
	if(fullEta){TCanvas* cEta  = new TCanvas("cEta","cEta",800,600);}
	
	//drawAllBins(hPt, cPt);
	//drawAllBins(hMass, cMass);
	
	drawFiveBins(hAut_Pt, cPt);
	drawFiveBins(hAut_Mass, cMass);
  if(fullEta){drawFourBins(hAut_Eta, cEta);}
	
	TFile* outFile = new TFile(outFileName.c_str(),"recreate");
	
	writeFiveBins(hPt);
	writeFiveBins(hMass);
	writeFourBins(hEta);
	writeFiveBins(hAut_Pt);
	writeFiveBins(hAut_Mass);
	if(fullEta){writeFourBins(hAut_Eta);}
	gAsymPt->Write();
	gAsymMass->Write();
	if(fullEta){gAsymEta->Write();}
	/*
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.png");
	cPt->SaveAs("./resultsNew_4_22/ptCanvasFullrangeLoEta.pdf");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.png");
	cMass->SaveAs("./resultsNew_4_22/massCanvasFullrangeLoEta.pdf");
	
	if(fullEta)
	{
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.png");
		cEta->SaveAs("./resultsNew_4_22/etaCanvasFullrangeHiEta.pdf");
	}
	*/
	
	
	for (int ibin = 1; ibin <= 16; ibin++)
	{
		
		cout << "bin " << ibin << endl;
		cout << "Nup   = " << hNumberUp_Mass[0]->GetBinContent(ibin) << endl;
		cout << "Ndown = " << hNumberDown_Mass[0]->GetBinContent(ibin) << endl;

	}
	
	

	cout << "<----END---->" << endl; 


}
Beispiel #23
0
// // //
double analysisClass::MuTauInZpeak(TString Pair){
  TLorentzVector mu;
  TLorentzVector mu2;
  TLorentzVector tau;
  TLorentzVector tau2;
  double Zmass = 91.188;
  double MuPt = 0;
  double TauPt = 0;
  double Dilepmass = 9999999;
  bool pairfound_ = false;
  //
  /*
  if( Pair == "ZToMuTau" ){ // MET is redistributed to Mu and Tau.. 
    TLorentzVector MET;
    MET.SetPtEtaPhiM( METcorr("Pt"), 0 , METcorr("Phi") , 0 );
    for(unsigned int iMuR=0; iMuR<MuonPt->size(); iMuR++){
      if(!muRisoCheck(iMuR)){continue;}
      mu.SetPtEtaPhiM( muPtcorr(iMuR), MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      MuPt = MET.Pt()*TMath::Cos(mu.DeltaPhi(MET)) + muPtcorr(iMuR); //adding projected MET on transverse plane Muon.
      mu.SetPtEtaPhiM( MuPt , MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      for(unsigned int iTauR=0; iTauR<HPSTauPt->size(); iTauR++){
	if(!tauRisoCheck(iTauR)){continue;}
	tau.SetPtEtaPhiM( tauPtcorr(iTauR), HPSTauEta->at(iTauR) , HPSTauPhi->at(iTauR), 0); 
	TauPt = MET.Pt()*TMath::Cos(tau.DeltaPhi(MET)) + tauPtcorr(iTauR); //adding projected MET on transverse plane Tau.
	tau.SetPtEtaPhiM( TauPt, HPSTauEta->at(iTauR), HPSTauPhi->at(iTauR), 0);
	pairfound_=true;
	if( fabs((mu+tau).M()-Zmass) < fabs(Dilepmass-Zmass) ) Dilepmass=(mu+tau).M();
      }
    }
  }
  */
  //
  if( Pair == "ZToMuTau" ){ // MET is added to TauPt..         mu <-- Z --> Tau (Tau_vis, neutrino :: collinear)
    TLorentzVector MET;
    MET.SetPtEtaPhiM( METcorr("Pt"), 0 , METcorr("Phi") , 0 );
    for(unsigned int iMuR=0; iMuR<MuonPt->size(); iMuR++){
      if(!muRisoCheck(iMuR)){continue;}
      mu.SetPtEtaPhiM( muPtcorr(iMuR), MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      //MuPt = MET.Pt()*TMath::Cos(mu.DeltaPhi(MET)) + muPtcorr(iMuR); //adding projected MET on transverse plane Muon.
      // mu.SetPtEtaPhiM( MuPt , MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      for(unsigned int iTauR=0; iTauR<HPSTauPt->size(); iTauR++){
	if(!tauRisoCheck(iTauR)){continue;}
	tau.SetPtEtaPhiM( tauPtcorr(iTauR), HPSTauEta->at(iTauR) , HPSTauPhi->at(iTauR), 0); 
	//TauPt = MET.Pt()*TMath::Cos(tau.DeltaPhi(MET)) + tauPtcorr(iTauR); //adding projected MET on transverse plane Tau.
	TauPt = MET.Pt()*TMath::Cos(tau.DeltaPhi(MET)) + tauPtcorr(iTauR); //adding MET to TauPt.
	tau.SetPtEtaPhiM( TauPt, HPSTauEta->at(iTauR), HPSTauPhi->at(iTauR), 0);
	pairfound_=true;
	if( fabs((mu+tau).M()-Zmass) < fabs(Dilepmass-Zmass) ) Dilepmass=(mu+tau).M();
      }
    }
  }
  //
  if( Pair == "ZToMuMu" ){
    for(unsigned int iMuR=0; iMuR<MuonPt->size(); iMuR++){
      if(!muRisoCheck(iMuR)){continue;}
      mu.SetPtEtaPhiM( muPtcorr(iMuR), MuonEta->at(iMuR), MuonPhi->at(iMuR), 0);
      for(unsigned int iMuR2=iMuR+1; iMuR2<MuonPt->size(); iMuR2++){
	if(!muRisoCheck(iMuR2)){continue;}
	mu2.SetPtEtaPhiM( muPtcorr(iMuR2), MuonEta->at(iMuR2), MuonPhi->at(iMuR2), 0);
	pairfound_=true;
	if( fabs((mu+mu2).M()-Zmass) < fabs(Dilepmass-Zmass) ) Dilepmass=(mu+mu2).M();
      }
    }
  }
  //
  if( Pair == "ZToTauTau" ){
    for(unsigned int iTauR=0; iTauR<HPSTauPt->size(); iTauR++){
      if(!tauRisoCheck(iTauR)){continue;}
      tau.SetPtEtaPhiM( tauPtcorr(iTauR), HPSTauEta->at(iTauR), HPSTauPhi->at(iTauR), 0);
      for(unsigned int iTauR2=iTauR+1; iTauR2<HPSTauPt->size(); iTauR2++){
	if(!tauRisoCheck(iTauR2)){continue;}
	tau2.SetPtEtaPhiM( tauPtcorr(iTauR2), HPSTauEta->at(iTauR2), HPSTauPhi->at(iTauR2), 0);
	pairfound_=true;
	if( fabs((tau+tau2).M()-Zmass) < fabs(Dilepmass-Zmass) ) Dilepmass=(tau+tau2).M();
      }
    }
  }
  //
  if( pairfound_ ) return Dilepmass;
  else return 0;
}
Beispiel #24
0
void pgsAnalysis::Loop()
{

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

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

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


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

	vector<TVector3> leptons;

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


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

	if (fChain == 0) return;
	

	int nentries = n;

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


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

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

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

		
		}//end instance loop (particles in an event

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

		fillFlag = false;

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


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

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

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


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


			

		fillFlag = true;
		}



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

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

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

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

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

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

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

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


			}
			eeee++;
		fillFlag = true;
		} 


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

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

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

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

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


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

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

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


			}
		xxxx++;
		fillFlag = true;
		}


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

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

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

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

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

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

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

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

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

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

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


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


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


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

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

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

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

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

	   	//Filling up histogram for the phi angle distribution

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

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

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



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


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

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

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

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

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

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

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

		
		
	// filling the TTree


	}//end entries loop (events)

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

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




}//end loop void
void xAna_hh_massResolutionBase(std::string inputFile,TString outputFile,bool matchb=false, bool debug=false, bool cut=false){


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

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

  const int nHistos=3;

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

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

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

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

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

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

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

      // study the difference with respect to 125 GeV

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

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

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

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

    }


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

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

    data.GetEntry(jEntry);
    nTotal++;

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

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

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

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

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

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

    }    

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

    nPass[0]++;

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

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

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


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

    // check matching first

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

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

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

	    if(findAMatch)break;

	  }	

	if(findAMatch)break;

      }

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

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



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

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

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

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

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


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

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

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

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

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

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

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

  } // end of loop over entries

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

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

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

}
Beispiel #26
0
void CreateTree_tmva_all::Loop(TString input_filename,TString output_dir, int data, int set_type)
{
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
	TMVAstruct TMVA;

	TString dataset_type[2] = {"_double","_single"};	

	int events_saved=0;

	float weight;	
 

	TFile file("main_tmva_tree_"+output_dir+"_v21"+dataset_type[set_type]+".root","recreate");
	TTree *tree0 = new TTree("TMVA","TMVA");
	tree0->Branch("CSV1",&TMVA.CSV1,"CSV1/F");
	tree0->Branch("CSV2",&TMVA.CSV2,"CSV2/F");
	tree0->Branch("Mqq",&TMVA.Mqq,"Mqq/F");
	tree0->Branch("Mbb",&TMVA.Mbb,"Mbb/F");
	tree0->Branch("bb_pt",&TMVA.bb_pt,"bb_pt/F");
	tree0->Branch("DeltaEtaQQ",&TMVA.DeltaEtaQQ,"DeltaEtaQQ/F");
	tree0->Branch("DeltaPhiQQ",&TMVA.DeltaPhiQQ,"DeltaPhiQQ/F");
	tree0->Branch("SoftN5",&TMVA.SoftN5,"SoftN5/I");
	tree0->Branch("HTsoft",&TMVA.HTsoft,"HTsoft/F");
	tree0->Branch("axis2_jet1",&TMVA.axis2_jet1,"axis2_jet1/F");
	tree0->Branch("axis2_jet2",&TMVA.axis2_jet2,"axis2_jet2/F");
	tree0->Branch("DeltaEtaQB1",&TMVA.DeltaEtaQB1,"DeltaEtaQB1/F");
	tree0->Branch("DeltaEtaQB2",&TMVA.DeltaEtaQB2,"DeltaEtaQB2/F");
	tree0->Branch("DeltaEtaQB",&TMVA.DeltaEtaQB,"DeltaEtaQB/F");
	tree0->Branch("DeltaEtaQB_minus",&TMVA.DeltaEtaQB_minus,"DeltaEtaQB_minus/F");
	tree0->Branch("cosOqqbb",&TMVA.cosOqqbb,"cosOqqbb/F");
	tree0->Branch("qqbb_pt",&TMVA.qqbb_pt,"qqbb_pt/F");
	tree0->Branch("qqbb_eta",&TMVA.qqbb_eta,"qqbb_eta/F");
	tree0->Branch("qqbb_pz",&TMVA.qqbb_pz,"qqbb_pz/F");
//	tree0->Branch("qgl1_VBF",&TMVA.qgl1_VBF,"qgl1_VBF/F");
//	tree0->Branch("qgl2_VBF",&TMVA.qgl2_VBF,"qgl2_VBF/F");
	tree0->Branch("Etot",&TMVA.Etot,"Etot/F");
	tree0->Branch("Jet5_pt",&TMVA.Jet5_pt,"Jet5_pt/F");
	tree0->Branch("x1",&TMVA.x1,"x1/F");
	tree0->Branch("x2",&TMVA.x2,"x2/F");
//	tree0->Branch("VB1",&TMVA.VB1,"VB1/F");
//	tree0->Branch("VB2",&TMVA.VB2,"VB2/F");
	tree0->Branch("blike1_VBF",&TMVA.blike1_VBF,"blike1_VBF/F");
	tree0->Branch("blike2_VBF",&TMVA.blike2_VBF,"blike2_VBF/F");
	tree0->Branch("weight",&weight);


	TF1 *func_r = new TF1("erffunc",erf,0.,1000.,3);

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
	   Long64_t ientry = LoadTree(jentry);
	   if (ientry < 0) break;
	   nb = fChain->GetEntry(jentry);   nbytes += nb;
			  
		if (data==1) genWeight = 1.;
		if (genWeight <0) continue;
		if (json!=1) continue;

		weight = bTagWeight*puWeight;

		if (!((Vtype==-1)||(Vtype>3))) continue;

		int good_jets = 0;
		vector<TLorentzVector> jets_pv;
		for (int i=0;i<nJet;i++){
			TLorentzVector jet0;
			if (!((Jet_id[i]>2)&&(Jet_puId[i]>0))) continue;
			jet0.SetPtEtaPhiM(Jet_pt[i],Jet_eta[i],Jet_phi[i],Jet_mass[i]);
			jets_pv.push_back(jet0);
			good_jets++;
		}

		if (good_jets<4)continue;




		
		int btag_max1_number = -1;
		int btag_max2_number = -1;
		int pt_max1_number = -1;
		int pt_max2_number = -1;
		TLorentzVector Bjet1;
		TLorentzVector Bjet2;
		TLorentzVector Qjet1;
		TLorentzVector Qjet2;
		TLorentzVector qq;

		if (set_type==0) {
			if (preselection_single_blike(nJet, Jet_pt,Jet_eta, Jet_phi, Jet_mass, Jet_blike_VBF, Jet_id, Jet_puId, btag_max1_number, btag_max2_number, pt_max1_number, pt_max2_number, HLT_BIT_HLT_QuadPFJet_SingleBTagCSV_VBF_Mqq460_v, Bjet1, Bjet2, Qjet1, Qjet2, qq) ==0) continue;

			if (preselection_double(nJet, Jet_pt,Jet_eta, Jet_phi, Jet_mass, Jet_btagCSV, Jet_id, Jet_puId, btag_max1_number, btag_max2_number, pt_max1_number, pt_max2_number, HLT_BIT_HLT_QuadPFJet_DoubleBTagCSV_VBF_Mqq200_v, Bjet1, Bjet2, Qjet1, Qjet2, qq) !=0 ) continue;
		}
		else {
			if (set_type==1) {
				if (preselection_single_blike(nJet, Jet_pt,Jet_eta, Jet_phi, Jet_mass, Jet_blike_VBF, Jet_id, Jet_puId, btag_max1_number, btag_max2_number, pt_max1_number, pt_max2_number, HLT_BIT_HLT_QuadPFJet_SingleBTagCSV_VBF_Mqq460_v, Bjet1, Bjet2, Qjet1, Qjet2, qq) !=0) continue;
			}
		}

		float trigWeight = 1.;		

		float trigCor0_nom_single[10] = {1.,1.,1., 1.17774e+00  ,1.};
		float trigCor1_nom_single[10] = {8.24458e+01,7.95354e+01,5.29763e+01, -3.93424e+01 };
		float trigCor2_nom_single[10] = {2.90000e+01,1.45915e+01,1.62510e+01,9.49616e+00};

		float trigCor0_nom_double[10] = {1.,1.,1., 1. , 1.08783e+00  };
		float trigCor1_nom_double[10] = {7.60656e+01,7.14527e+01,3.78975e+01 ,-2.94747e+00,-3.07239e+01 };
		float trigCor2_nom_double[10] = {2.90000e+01,1.68348e+01,3.71160e+01 ,1.00767e+00, 6.52856e+00 };
	
		func_r->FixParameter(0,1.);
		if ((set_type==0)&&(data!=1)) {
			func_r->FixParameter(1,trigCor1_nom_double[0] );
			func_r->FixParameter(2,trigCor2_nom_double[0] );
			trigWeight*=func_r->Eval(jets_pv[0].Pt());
		}
		if ((set_type==0)&&(data!=1)) {
			func_r->FixParameter(1,trigCor1_nom_double[1] );
			 func_r->FixParameter(2,trigCor2_nom_double[1] );
			trigWeight*=func_r->Eval(jets_pv[1].Pt());
		}
		if ((set_type==0)&&(data!=1)) {
			func_r->FixParameter(1,trigCor1_nom_double[2] );
			 func_r->FixParameter(2,trigCor2_nom_double[2] );
			trigWeight*=func_r->Eval(jets_pv[2].Pt());
		}
		if ((set_type==0)&&(data!=1)){
			func_r->FixParameter(1,trigCor1_nom_double[3] );
			func_r->FixParameter(2,trigCor2_nom_double[3] );
			trigWeight*=func_r->Eval(-1.*TMath::Log(1.-Jet_btagCSV[btag_max1_number]));
		}
		if ((set_type==0)&&(data!=1)){
			func_r->FixParameter(0,trigCor0_nom_double[4] );
			func_r->FixParameter(1,trigCor1_nom_double[4] );
			func_r->FixParameter(2,trigCor2_nom_double[4] );
			trigWeight*=func_r->Eval(-1.*TMath::Log(1.-Jet_btagCSV[btag_max2_number]));
		}
//////////////////////

		func_r->FixParameter(0,1.);

		if ((set_type==1)&&(data!=1)){
			func_r->FixParameter(1,trigCor1_nom_single[0] );
			func_r->FixParameter(2,trigCor2_nom_single[0] );
			trigWeight*=func_r->Eval(jets_pv[0].Pt());
		}
		if ((set_type==1)&&(data!=1)){
			func_r->FixParameter(1,trigCor1_nom_single[1] );
			func_r->FixParameter(2,trigCor2_nom_single[1] );
			trigWeight*=func_r->Eval(jets_pv[1].Pt());
		}
		if ((set_type==1)&&(data!=1)){
			func_r->FixParameter(1,trigCor1_nom_single[2] );
			func_r->FixParameter(2,trigCor2_nom_single[2] );
			trigWeight*=func_r->Eval(jets_pv[2].Pt());
		} 
		if ((set_type==1)&&(data!=1)){
			func_r->FixParameter(0,trigCor0_nom_single[3] );
			func_r->FixParameter(1,trigCor1_nom_single[3] );
			func_r->FixParameter(2,trigCor2_nom_single[3] );
			trigWeight*=func_r->Eval(-1.*TMath::Log(1.-Jet_btagCSV[btag_max1_number]));
		} 


		weight*=trigWeight;



		int loopJet_max;
			if (nJet<7) loopJet_max = nJet; 
			else loopJet_max = 7; 


		Float_t Jet5_pt = -1;
		for (int i=0;i<loopJet_max;i++){
			if ((i==btag_max1_number)||(i==btag_max2_number)||(i==pt_max1_number)||(i==pt_max2_number)||(Jet_id[i]<=2)||(Jet_puId[i]==0)) continue;
			Jet5_pt=Jet_pt[i];
			break;
		}


		Float_t alpha_bjet1_reg = 1; 
		Float_t alpha_bjet2_reg = 1 ;
		if (Jet_pt_regVBF[btag_max1_number]>0) alpha_bjet1_reg = Jet_pt_regVBF[btag_max1_number]/Jet_pt[btag_max1_number];
  		if (Jet_pt_regVBF[btag_max2_number]>0) alpha_bjet2_reg = Jet_pt_regVBF[btag_max2_number]/Jet_pt[btag_max2_number];
		Bjet1*=alpha_bjet1_reg;
		Bjet2*=alpha_bjet2_reg;

		
		Float_t Mqq = qq.M();
		Float_t bbDeltaPhi = TMath::Abs(Bjet1.DeltaPhi(Bjet2));
		Double_t qqDeltaPhi = TMath::Abs(Qjet1.DeltaPhi(Qjet2));
		Float_t qqDeltaEta = TMath::Abs(Qjet1.Eta()-Qjet2.Eta());
		TLorentzVector bb;
		bb = Bjet1+Bjet2;
		Float_t Mbb = bb.M();
		TLorentzVector bbqq;
		bbqq = Bjet1 + Bjet2 + Qjet1 + Qjet2;
		Float_t cosOqqbb =TMath::Cos( ( ( Bjet1.Vect() ).Cross(Bjet2.Vect()) ).Angle( ( Qjet1.Vect() ).Cross(Qjet2.Vect()) ) );	

		
		Float_t EtaBQ1;
	 	Float_t EtaBQ2;
		Float_t PhiBQ1; 	
		Float_t PhiBQ2;
		 if (Qjet1.Eta() >= Qjet2.Eta()) {
			if (Bjet1.Eta() >= Bjet2.Eta())  {
				EtaBQ1 = Qjet1.Eta()-Bjet1.Eta();
				PhiBQ1 = TMath::Abs(Bjet1.DeltaPhi(Qjet1));		
			}
			else {
				EtaBQ1 = Qjet1.Eta()-Bjet2.Eta();
				PhiBQ1 = TMath::Abs(Bjet2.DeltaPhi(Qjet1));	
			}	
		} else if (Bjet1.Eta() >= Bjet2.Eta()) {
				EtaBQ1 = Qjet2.Eta()-Bjet1.Eta();
				PhiBQ1 = TMath::Abs(Bjet1.DeltaPhi(Qjet2));	
				
				}
			else {
				EtaBQ1 = Qjet2.Eta()-Bjet2.Eta();
				PhiBQ1 = TMath::Abs(Bjet2.DeltaPhi(Qjet2));	
			}


		 if (Qjet1.Eta() <= Qjet2.Eta()) {
			if (Bjet1.Eta() <= Bjet2.Eta())  {
				EtaBQ2 = Qjet1.Eta()-Bjet1.Eta();
				PhiBQ2 = TMath::Abs(Bjet1.DeltaPhi(Qjet1));		
			}
			else {
				EtaBQ2 = Qjet1.Eta()-Bjet2.Eta();
				PhiBQ2 = TMath::Abs(Bjet2.DeltaPhi(Qjet1));	
			}	
		} else if (Bjet1.Eta() <= Bjet2.Eta()) {
				EtaBQ2 = Qjet2.Eta()-Bjet1.Eta();
				PhiBQ2 = TMath::Abs(Bjet1.DeltaPhi(Qjet2));	
				
				}
			else {
				EtaBQ2 = Qjet2.Eta()-Bjet2.Eta();
				PhiBQ2 = TMath::Abs(Bjet2.DeltaPhi(Qjet2));	
			}
		


		Float_t Etot = Bjet1.E()+Bjet2.E()+Qjet1.E()+Qjet2.E();
		Float_t PzTot = Bjet1.Pz()+Bjet2.Pz()+Qjet1.Pz()+Qjet2.Pz();
		Float_t PxTot = Bjet1.Px()+Bjet2.Px()+Qjet1.Px()+Qjet2.Px();
		Float_t PyTot = Bjet1.Py()+Bjet2.Py()+Qjet1.Py()+Qjet2.Py();
	
		Float_t x1 = 0.;
		Float_t x2 = 0.;
		x1 = (Etot + PzTot)/2./13000.;
		x2 = (Etot - PzTot)/2./13000.;


		for (int i=0;i<nJet;i++){
			if (Jet_btagCSV[i]>1) Jet_btagCSV[i]=1.;
			if (Jet_btagCSV[i]<0) Jet_btagCSV[i]=0.;
		}

		TMVA.Mqq = Mqq;
		TMVA.CSV1 = Jet_btagCSV[btag_max1_number];	
		TMVA.CSV2 = Jet_btagCSV[btag_max2_number];
		TMVA.DeltaEtaQQ = qqDeltaEta;
		TMVA.DeltaPhiQQ = qqDeltaPhi;
		TMVA.SoftN5 = softActivity_njets5;
		TMVA.HTsoft = softActivity_HT;
		TMVA.DeltaEtaQB1 = EtaBQ1;
		TMVA.DeltaEtaQB2 = EtaBQ2;
		TMVA.DeltaEtaQB = (EtaBQ1 + EtaBQ2);
		TMVA.cosOqqbb = cosOqqbb;
		TMVA.Jet5_pt = Jet5_pt;
		TMVA.Etot = Etot;
		TMVA.x1 = x1;
		TMVA.x2 = x2;
		TMVA.blike1_VBF = Jet_blike_VBF[btag_max1_number];
		TMVA.blike2_VBF = Jet_blike_VBF[btag_max2_number];
		TMVA.Mbb = Mbb;
		TMVA.axis2_jet1 = Jet_axis2[pt_max1_number];
		TMVA.axis2_jet2 = Jet_axis2[pt_max2_number];
		TMVA.bb_pt = bb.Pt();
		TMVA.DeltaEtaQB_minus = (EtaBQ1 - EtaBQ2);
		TMVA.qqbb_pt = (Bjet1+Bjet2+Qjet1+Qjet2).Pt();
		TMVA.qqbb_eta = (Bjet1+Bjet2+Qjet1+Qjet2).Eta();
		TMVA.qqbb_pz = (Bjet1+Bjet2+Qjet1+Qjet2).Pz();

		tree0->Fill();	
		events_saved++;		
		if (set_type==0) if (events_saved>=71510) break;
		if (set_type==1) if (events_saved>=60151) break;

	}  

	file.Write();
	file.Close();

}
Beispiel #27
0
 bool operator()( TLorentzVector j1, TLorentzVector j2 ) const
 {
   return j1.Pt() > j2.Pt() ;
 }
void xAna_hh_massResolutionBase(std::string inputFile, TString outputFile="",int PU_up=60,int PU_down=0,bool matchb=false, bool debug=false, bool cut=false){

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


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

  const int nHistos=3;

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

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

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

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

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

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

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

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

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

      // study the difference with respect to 125 GeV

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

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

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

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

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

    }


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

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


    if(debug && jEntry>10)break;

    data.GetEntry(jEntry);
    nTotal++;
	
	Int_t nVtx        = data.GetInt("nVtx");
	if(nVtx<PU_down || nVtx>PU_up)continue;
	
    //2. pass electron or muon trigger                                                                                                                                          
    std::string* trigName = data.GetPtrString("hlt_trigName");
    vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
    const Int_t nsize = data.GetPtrStringSize();

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

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

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


      }

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



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

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

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

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

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

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

    }    

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

    nPass[0]++;

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

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

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


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

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

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

    // check matching first

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

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

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

	    if(findAMatch)break;

	  }	

	if(findAMatch)break;

      }

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

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

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

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

	    if(findAK8Match)break;

	  }	

	if(findAK8Match)break;

      }

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



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

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

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

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

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


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

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

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

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

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

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


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

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

      }
    

  } // end of loop over entries

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

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

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

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

  outFile->Close();


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


  // define histograms

  TString title2 = Form("ele pT for Zprime mass = %d",mass_point);
  TString title3 = Form("lepton pairs' pT for Zprime mass = %d",mass_point);
  TString title4 = Form("SD mass for Zprime mass = %d",mass_point);
  TString title5 = Form("Z mass for Zprime mass = %d",mass_point);
  TString title6 = Form("Zprime mass for Zprime mass = %d",mass_point);
  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 ,80,-1,3);
  TH1D* h_abs_dPhi_ZH = new TH1D("h_abs_dPhi_ZH",title8 ,80,0,4);
  TH1D* h_abs_dR_ZH   = new TH1D("h_abs_dR_ZH"  ,title9 ,80,0,4);

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

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

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

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

    data.GetEntry(jEntry);
    nTotal ++;

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

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

    bool hasLepton=false;

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

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


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


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


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

      if(hasLepton)break;

    }
*/

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

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

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

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

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

      if(hasHadron)break;

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

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

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


      }


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


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

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

    //5. select good electrons

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

    std::vector<int> goodElectrons;

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

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

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

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

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

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

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

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

        if(eleMiniIso[ie]>0.1)continue;

        goodElectrons.push_back(ie);
      }

    // 

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


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

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

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


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

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

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

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

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

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

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

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

            Float_t Phi_ll = (*thisEle+*thatEle).Phi();
            Float_t Eta_ll = (*thisEle+*thatEle).Eta();

//	    cout<<" Phi_ll: "<< Phi_ll <<endl;
//	    cout<<" Eta_ll: "<< Eta_ll <<endl;

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

            findEPair=true;
          }
      }


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


    //7.select a good CA8 and cleaned jet

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

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

    	TLorentzVector* thisMu = (TLorentzVector*)muP4->At(im);

    	if(!isHighPtMuon[im] && !isCustomTrackerMuon[im])continue;
    	
    	if(muMiniIso[im]>0.1)continue;	

        if ( goodMuons.size()==1 ) {
	  bool highPt_AND_tracker = isHighPtMuon[0] && isCustomTrackerMuon[im];
	  bool tracker_AND_highPt = isHighPtMuon[im] && isCustomTrackerMuon[0]; 
            if ( !(highPt_AND_tracker or tracker_AND_highPt) ) continue; 
        }

    	if(fabs(thisMu->Eta())>2.1)continue;

    	if(thisMu->Pt() < 50)continue;

    	goodMuons.push_back(im);
      }

	
    Int_t nJet         = data.GetInt("FATnJet");
    TClonesArray* jetP4 = (TClonesArray*) data.GetPtrTObject("FATjetP4");
    Float_t*  jetSDmass = data.GetPtrFloat("FATjetSDmass");
    Float_t*  jetPRmass = data.GetPtrFloat("FATjetPRmass");

    std::vector<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 SD_low = 60, SD_high = 140;
//        if(jetSDmass[ij]<SD_low || jetSDmass[ij]>SD_high)continue;

        double PR_low = 95, PR_high = 130;
        if(jetPRmass[ij]<PR_low || jetPRmass[ij]>PR_high)continue;


	bool hasOverLap=false;

{
        TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(leading_ele_index[0]);
        if(thisEle->DeltaR(*thisJet)<0.8)hasOverLap=true;

        TLorentzVector* thatEle = (TLorentzVector*)eleP4->At(subleading_ele_index[0]);
        if(thatEle->DeltaR(*thisJet)<0.8)hasOverLap=true;
}

/*	for(unsigned int im=0; im < goodMuons.size(); im++)
	  {
	    TLorentzVector* thisMuo = (TLorentzVector*)muP4->At(goodMuons[im]);
	    if(thisMuo->DeltaR(*thisJet)<0.8)hasOverLap=true;
	    if(hasOverLap)break;
	    
	  }
*/	

	if(hasOverLap)continue;
	
	if(thisJet->Pt()<200)continue;
	if(fabs(thisJet->Eta())>2.4)continue;

     	if(!findAJet)
	  {
	    l4_leadingJet = *thisJet;
//	    h_SD->Fill(jetSDmass[ij]);
            SD_Mass.push_back( jetSDmass[ij] );
	    goodJets.push_back(ij);// save leading jet
	  }
	    
     	findAJet=true;
//        SD_Mass.push_back( jetSDmass[ij] ); // change to this place so that loop to all jets passing cuts    	

      }
    
    if(!findAJet)
      continue;
    nPass[5]++;

     Float_t MGrav = (l4_leadingJet + l4_Z).M();

     double Mass_Point = mass_point;
     double mass_upper = Mass_Point + Mass_Point*0.15;
     double mass_lower = Mass_Point - Mass_Point*0.15;
//     cout<<"Mass_Point: "<<Mass_Point  <<" mass_upper: "<< mass_upper <<" mass_lower: "<< mass_lower <<endl;

     if( MGrav< mass_lower || MGrav>mass_upper )continue;
     h_Zprime_mass->Fill( MGrav );
     nPass[6]++;

  // if event can go here, then fill the histograms to plot the distributions. Yu-Hsiang add 


{

    int ie = leading_ele_index[0];
//    int ie = subleading_ele_index[0];
    TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
    h_ele_pT->Fill( thisEle->Pt() );
//    if(eleSCEt[ie]<10){    cout<<"eleSCEt[ie]: "<< eleSCEt[ie] << endl;}
//   cout<<"eleSCEt[ie]: "<< eleSCEt[ie] << endl;
//    h_ele_pT->Fill( eleSCEt[ie] );

//cout<<endl;
//cout<< "jEntry: "<< jEntry <<endl;

//cout<<"ie: " << ie<< endl;
//cout<<"thisEle->Pt(): " << thisEle->Pt()<< endl;


}
/*
    for(unsigned int i=0; i< LeadingElectrons.size(); i++)
      {         int ie = LeadingElectrons[i];
		TLorentzVector* thisEle = (TLorentzVector*)eleP4->At(ie);
		h_ele_pT->Fill( thisEle->Pt() );
      }
*/
    for(unsigned int i=0; i< LeptonPairPt.size(); i++)
      {         
                
                h_lepton_pair_pT->Fill( LeptonPairPt[i] );
      }

    for(unsigned int i=0; i< LeptonPairM.size(); i++)
      {

                h_Z_mass->Fill( LeptonPairM[i] );
      }

    for(unsigned int i=0; i< SD_Mass.size(); i++)
      {

                h_SD->Fill( SD_Mass[i] );
      }

    // save delta Eta, delta Phi and delta R BTW reco-Z and reco-H
      {

    	int ie_1st = leading_ele_index[0];
    	int ie_2nd = subleading_ele_index[0];
    	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 phi_H = thisJet->Phi();
        float eta_Z = (*thisEle+*thatEle).Eta();
        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 ); 

//        cout<<"eta_H :"<< eta_H<<endl;
//        cout<<"eta_Z :"<< eta_Z<<endl;
// 	  cout<<"abs_dEta :"<< abs_dEta<<endl;
//        cout<<"phi_H :"<< phi_H<<endl;
//        cout<<"phi_Z :"<< phi_Z<<endl;
//        cout<<"abs_dPhi :"<< abs_dPhi<<endl;
//        cout<<"dR_ZH :"<< dR_ZH<<endl;

	// 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;
*/
}
Beispiel #30
0
void test(char * tag= "0", char *infName = "/d102/yjlee/hiForest2MC/Pythia80_HydjetDrum_mix01_HiForest2_v22_simTrack05.root")
{
   // Define the input file and HiForest
   HiForest *c = new HiForest(infName,"",cPPb);
   c->hasPFTree=0;
   c->hasPhotonTree=0;
   c->hasTowerTree=0;
   c->hasHbheTree=0;
   c->hasEbTree=0;
   c->hasGenpTree=0;
   c->hasGenParticleTree=0;   
   c->hasAkPu2CaloJetTree=0;
   c->hasAkPu3CaloJetTree=0;
   c->hasAkPu4CaloJetTree=0;
//   c->doTrackCorrections=1;
//   c->InitTree();
   
   // Output file
   TFile *output = new TFile(Form("output-%s.root",tag),"recreate");
   
   // Output
   TTree * t = new TTree("t","gammajet");
   
   JetData data(t,1);

   HistoData histos_MergedGeneralCalo("MergedGeneral");
   HistoData histos2_MergedGeneral("MergedGeneral2");   // phi dependent corr
   
   TH1D *hWeight = new TH1D("hWeight","",1000,0,100);
   TH1D *hWeight2 = new TH1D("hWeight2","",1000,0,100);
   TH1D *hPt = new TH1D("hPt","",100,0,100);
   TH1D *hNoWPt = new TH1D("hNoWPt","",100,0,100);


   TNtuple *nt = new TNtuple("nt","","m:eta:phi:pt:pt1:pt2:ch1:ch2:phi1:phi2:dxy1:dxy2:hiBin:N");
   TNtuple *ntEvt = new TNtuple("ntEvt","","N");
   nt->SetAutoFlush(30000);
   cout <<nt->GetAutoFlush()<<endl;
   TCanvas *cc = new TCanvas("cc","",600,600);   
//	 nt->SetCircular(1000);
   // Main loop

   TLorentzVector *v2 = new TLorentzVector;
   TLorentzVector *v = new TLorentzVector;
   TLorentzVector phi;

   for (int i=0;i<c->GetEntries()/1.;i++) {
      c->GetEntry(i);
      if (!c->selectEvent()) continue;
      if (i%1000==0){
         cout <<i<<" / "<<c->GetEntries()<<endl;
       } 
      int N=0;   
      for (int j=0;j<c->track.nTrk;j++) {
         if (!c->selectTrack(j)) continue;
         if (fabs(c->track.trkEta[j])>2.4) continue;
         if (fabs(c->track.trkPt[j])<0.4) continue;
         N++;
      }   
      ntEvt->Fill(N);
      for (int j=0;j<c->track.nTrk;j++) {
         if (!c->selectTrack(j)) continue;
         if (fabs(c->track.trkPt[j])<1) continue; 
//      if (fabs(c->track.trkDxy1[j]/c->track.trkDxyError1[j])<1) continue;
         for (int k=j+1;k<c->track.nTrk;k++) {
            if (j==k) continue;
            if (!c->selectTrack(k)) continue;
//            if (c->track.trkCharge[k]==c->track.trkCharge[j]) continue; 
     	    if (fabs(c->track.trkPt[k])<1) continue;
            v->SetPtEtaPhiM(c->track.trkPt[j],c->track.trkEta[j],c->track.trkPhi[j],0.493677);
            v2->SetPtEtaPhiM(c->track.trkPt[k],c->track.trkEta[k],c->track.trkPhi[k],0.493677);
//          v2->SetPtEtaPhiM(c->track.trkPt[k],c->track.trkEta[k],c->track.trkPhi[k],0.13957);
//          v->SetPtEtaPhiM(c->track.trkPt[j],c->track.trkEta[j],c->track.trkPhi[j],0.938272);
//          v->SetPtEtaPhiM(c->track.trkPt[j],c->track.trkEta[j],c->track.trkPhi[j],0.13957);
//          v2->SetPtEtaPhiM(c->track.trkPt[k],c->track.trkEta[k],c->track.trkPhi[k],0.13957);
  	    phi = (*v) + (*v2);
//         if ((phi.M())>5) {
            if ((phi.M())>1.2||phi.M()<0.0) {
//	       phi.Delete();
	       continue;
	    }    
	    nt->Fill(phi.M(),phi.Eta(),phi.Phi(),phi.Pt(),v->Pt(),v2->Pt(),c->track.trkCharge[j],c->track.trkCharge[k],v->Phi(),v2->Phi(),c->track.trkDxy1[j],c->track.trkDxy1[k],c->evt.hiBin,N);
//	       phi.Delete();
   }
      }

      //cout <<data.mpt<<endl;
      t->Fill();
   }
  // t->Write();
   histos_MergedGeneralCalo.calcEff();
   histos2_MergedGeneral.calcEff();
   output->Write();
   output->Close();
}