Esempio n. 1
0
// File: ST_Monitoring_Efficiency.C
// Last Modified: 05/27/2015
// Creator: Mahmoud Kamel [email protected]
// Purpose: Displaying histograms for online monitoring purposes
void ST_Monitoring_Eff () {
  // Define the directory that contains the histograms
  TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("st_tracking");
  if(dir) dir->cd();
  // Grab 1D histograms 
  TH1D *MacropEff     = (TH1D*)dir->FindObjectAny("MacropEff");
  TH1D *MacropEff_adc     = (TH1D*)dir->FindObjectAny("MacropEff_adc");
  TH1D *h_phi_sec_pred_hit_cntr = (TH1D*)dir->FindObjectAny("h_phi_sec_pred_hit_cntr");
  TH1D *h_phi_sec_hit_cntr  = (TH1D*)dir->FindObjectAny("h_phi_sec_hit_cntr");
  TH1D *h_phi_sec_adc_cntr = (TH1D*)dir->FindObjectAny("h_phi_sec_adc_cntr");

  // get Binomial errors in an efficiency plot
  // hit object efficiency
  h_phi_sec_hit_cntr->Sumw2();
  h_phi_sec_pred_hit_cntr->Sumw2();
  MacropEff->Sumw2();
  MacropEff->Divide(h_phi_sec_hit_cntr,h_phi_sec_pred_hit_cntr,1,1,"B");

  // adc efficiency
  h_phi_sec_adc_cntr->Sumw2();
  MacropEff_adc->Sumw2();
  MacropEff_adc->Divide(h_phi_sec_adc_cntr,h_phi_sec_pred_hit_cntr,1,1,"B");

  //Create the canvas
  if(gPad == NULL)
    {
      TCanvas *c1 = new TCanvas("c1","Start Counter 1D Histograms", 200, 10, 600, 480);
      c1->cd(0);
      c1->Draw();
      c1->Update();
    }
  if(!gPad) return;
  TCanvas *c1 = gPad->GetCanvas();
  c1->Divide(2,1);
  // ST ADC Efficiency histogram
  c1->cd(1);
  gStyle->SetOptStat(0);
  gStyle->SetErrorX(0); 
  gPad->SetTicks();
  gPad->SetGrid();
  if (MacropEff_adc) {
   MacropEff_adc->Draw("E1");
   MacropEff_adc->SetMarkerStyle(21);
   MacropEff_adc->SetMarkerSize(1.5);
   MacropEff_adc->SetMarkerColor(4.0);
   MacropEff_adc->SetAxisRange(0., 1.,"Y");
   MacropEff_adc->GetYaxis()->SetTitleOffset(1.26);
   Double_t TWA_adc=0;
   Double_t sumE_adc=0;
   Double_t Final_adc=0;
   Double_t error_adc=0.;
   Double_t BC_adc=0.;
   Double_t WA_adc=0.;
   //Double_t Final_adc=0.;
   for (int i = 0; i < 30; i++)
     {
       error_adc =   MacropEff_adc->GetBinError(i+2);
       sumE_adc = sumE_adc + error_adc;
       BC_adc =   MacropEff_adc->GetBinContent(i+2);
       WA_adc = BC_adc*error_adc;
       TWA_adc = TWA_adc + WA_adc ;
       Final_adc = TWA_adc/sumE_adc;
       // cout << "error_adc =  "<< error_adc << endl;
       // cout << "BC_adc =  "<< BC_adc << endl;
       // cout << "Final_adc =  "<< Final_adc << endl;
     } 
   TLine *line = new TLine(1,Final_adc,30,Final_adc);
   line->SetLineWidth(3);
   line->SetLineColor(2);
   //Write the eff value on the histogram 
   char tFinal_adc[40];
   char terror_adc[40];
   sprintf(tFinal_adc,"ADC Efficiency (%%) = %g",Final_adc*100);
   sprintf(terror_adc,"ADC Efficiency error (%%) = %g",error_adc*100);
   line->Draw();
   TPaveLabel *p = new TPaveLabel(0.3,0.6,0.7,0.7,tFinal_adc,"brNDC");
   p->Draw();
   TPaveLabel *p1 = new TPaveLabel(0.3,0.5,0.7,0.6,terror_adc,"brNDC");
   p1->Draw();
  }
  // ST Hit Efficiency histogram
  c1->cd(2);
  gPad->SetTicks();
  gPad->SetGrid();
  if (MacropEff) {
    MacropEff->Draw("E1");
    MacropEff->SetMarkerStyle(21);
    MacropEff->SetMarkerSize(1.5);
    MacropEff->SetMarkerColor(4.0);
    MacropEff->SetAxisRange(0., 1.,"Y");
    MacropEff->GetYaxis()->SetTitleOffset(1.26);
    Double_t TWA=0;
    Double_t sumE=0;
    Double_t Final=0; 
    Double_t error=0.;
    Double_t BC=0.;
    Double_t WA=0.;
    //Double_t Final=0.;
    for (int i = 0; i < 30; i++)
      {
	error =   MacropEff->GetBinError(i+2);
	sumE = sumE+error;
	BC =   MacropEff->GetBinContent(i+2);
	WA = BC*error;
	TWA = TWA + WA ;
	Final = TWA/sumE;
	//	cout << "error =  "<< error << endl;
	//	cout << "BC =  "<< BC << endl;
	//	cout << "Final =  "<< Final << endl;
      } 
    TLine *line = new TLine(1,Final,30,Final);
    line->SetLineWidth(3);
    line->SetLineColor(2);
    //Write the eff value on the histogram 
   char tFinal[40];
   char terror[40];
   sprintf(tFinal,"Hit Efficiency (%%) = %g",Final*100);
   sprintf(terror,"Hit Efficiency error (%%) = %g",error*100);
   line->Draw();
   TPaveLabel *p = new TPaveLabel(0.3,0.6,0.7,0.7,tFinal,"brNDC");
   p->Draw();
   TPaveLabel *p1 = new TPaveLabel(0.3,0.5,0.7,0.6,terror,"brNDC");
   p1->Draw();
  }
}
Esempio n. 2
0
mainClass(int luminosity=5000){ // luminosity is in /pb unit



  cutname[0]="nocut";cutname[1]="Njet_4";cutname[2]="ht_500" ;cutname[3]="mht_200";
  cutname[4]="delphi";cutname[5]="iso";
  cutname[6]="CSVM_0";
  cutname[7]="CSVM_1";
  cutname[8]="CSVM_2";
  cutname[9]="CSVM_3";

  WJtype[0]="EventsWith_1RecoMuon_0RecoElectron";
  TTbartype[0]="EventsWith_1RecoMuon_0RecoElectron";



// .....................................................................................................................................................//
// WJ Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> WJ_xs_vec;

  WJ_xs_vec.push_back(1817.0); // HT 100-200
  WJ_xs_vec.push_back(471.6);  // HT 200-400
  WJ_xs_vec.push_back(55.61);  // HT 400-600
  WJ_xs_vec.push_back(18.81);  // HT 600-Inf

  const int wjnHT = (int) WJ_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"../Results/results_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"../Results/results_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"../Results/results_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*WJ_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,WJ_xs_vec[i-1]);

    WJ_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "WJ normalization scale factor determination done \n " << std::endl;




//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=wjnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_WJ_HT-100to200_.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_HT-200to400_.root");
    else if(i==3)sprintf(tempname,"HadTauEstimation_WJ_HT-400to600_.root");
    else if(i==4)sprintf(tempname,"HadTauEstimation_WJ_HT-600toInf_.root");
    else{cout << " Error!! There are only 4 WJet ht binned sample " << endl;}
    WJ_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<wjnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) WJ_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(WJ_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);

        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("WJ main histograms stacked \n ");






// .....................................................................................................................................................//
// TTbar Section
// .....................................................................................................................................................//

  //build a vector of scale factors
  //first load the cross sections into a vector
  vector<double> TTbar_xs_vec;

  TTbar_xs_vec.push_back(806.1); // 

  const int ttbarnHT = (int) TTbar_xs_vec.size();   // Total number of HT bin samples

  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"../Results/results_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    file = new TFile(tempname, "R");
    sprintf(tempname,"allEvents/nocut/MHT_nocut_allEvents");
    tempvalue = (luminosity*TTbar_xs_vec[i-1])/((* (TH1D* ) file->Get(tempname)).GetEntries());

printf("Scale: %g, N: %g, Lum: %d, XS: %g \n ",tempvalue,((* (TH1D* ) file->Get(tempname)).GetEntries()),luminosity,TTbar_xs_vec[i-1]);

    TTbar_scalevec.push_back(tempvalue);
  }//end of loop over HTbins 
  std::cout << "TTbar normalization scale factor determination done \n " << std::endl;
  



//..........................................//
// main histograms like HT, MHT, ...
//..........................................//

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=ttbarnHT ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_.root");
    else{cout << " Error!! There are only 1 TTbaret ht binned sample " << endl;}
    TTbar_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=TTbartype.begin(); itt!=TTbartype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();

      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<ttbarnHT ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", TTbartype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          temphist = (TH1D *) TTbar_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist->Scale(TTbar_scalevec[i]);
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("TTbar main histograms stacked \n ");



// ..................................................................................................................................................... //
// Stack main histograms from TTbar and WJet
// ..................................................................................................................................................... //

  // There are two contributors 1-TTbar and 2-WJ
  int NSamples=2;

  // A vector that contains all the samples
  vector<TFile*> sample_inputfilevec;

  THStack * tempstack2 = new THStack("stack","Binned Sample Stack");

  // Load the files to a vector 
  // These are the HT, MHT, .. variables
  for(int i=1; i<=NSamples ; i++){
    if(i==1)sprintf(tempname,"HadTauEstimation_TTbar_stacked.root");
    else if(i==2)sprintf(tempname,"HadTauEstimation_WJ_stacked.root");
    else{cout << " Error!! There are only 2 contributors! " << endl;}
    sample_inputfilevec.push_back(TFile::Open(tempname,"R"));
  }//end of loop over HTbins 

  // Stack
  delete tempstack;
  tempstack = new THStack("stack","Binned Sample Stack");
  sprintf(tempname,"HadTauEstimation_stacked.root");
  file = new TFile(tempname,"RECREATE");
  histname.clear();
  histname[0]="weight";
  histname[1]="HT";
  histname[2]="MHT";
  histname[3]="NJet";
  histname[4]="NBtag";
  histname[5]="MuonPt";
  histname[6]="MtW";

  for(map<int , string >::iterator itt=WJtype.begin(); itt!=WJtype.end();itt++){        // loop over different event types

    cdtoitt = file->mkdir((itt->second).c_str());
    cdtoitt->cd();

    for(map<int , string >::iterator it=cutname.begin(); it!=cutname.end();it++){   // loop over different cutnames

      cdtoit =  cdtoitt->mkdir((it->second).c_str());
      cdtoit->cd();


      for(int j=0; j<histname.size(); j++){                                        // loop over different histograms

        for(int i=0; i<NSamples ; i++){                                                  // loop over different HT bins

          //cout << "================================" << endl;
          //cout << "HT#: " <<i << ", WJtype: " << itt->second << ", cutname: " << it->second << ", hist#: " << j << endl;  
          sprintf(tempname,"%s/%s/%s_%s_%s",(itt->second).c_str(),(it->second).c_str(),(histname[j]).c_str(),(it->second).c_str(),(itt->second).c_str());
          tempstack2 = (THStack *) sample_inputfilevec.at(i)->Get(tempname)->Clone();
          temphist = (TH1D*)tempstack2->GetStack()->Last(); 
          
          temphist->SetFillColor(i+2);
          tempstack->Add(temphist);

        }//end of loop over HTbins 1..7

        sprintf(tempname,"%s_%s_%s",histname[j].c_str(),(it->second).c_str(),(itt->second).c_str());
        tempstack->Write(tempname);
        delete tempstack;
        tempstack = new THStack("stack","Binned Sample Stack");

      }//end of loop over histograms

    }//end of loop over cutnames 

  }//end of loop over event types

  file->Close();
  printf("All samples main histograms stacked \n ");






} // End of the constructor 
Esempio n. 3
0
void getResvsub(int ispt=1){

	double theta[ntheta];
	TFile *f[nFileAll];
		
	for(int itheta=0;itheta<ntheta;itheta++)
        	theta[itheta]=itheta*TMath::Pi()/ntheta/nn;

        int nvv;
        const double *binv;

        if(ispt){             nvv = nptv;       binv = ptbinv;}
            else{             nvv = netav;          binv = etabinv;}

	string SumorProd = getenv("SUMORPROD");
	string mdir = getenv("DIR");
	ofstream fstrv;
        if(ispt){
	if(SumorProd=="Sum")fstrv.open("v_sub.txt");
	else fstrv.open("v_2_sub.txt");
        }
        else{
	if(SumorProd=="Sum")fstrv.open("v_eta_sub.txt");
	else fstrv.open("v_2_coarse_eta_sub.txt");
        }
	
	TVectorD Nevent[nbin], totmultall[nbin], totmultall_[nbin];
	TVectorD totmult[nbin], totpt[nbin],toteta[nbin];
	TVectorD totmulthisto[nbin], totmulthistocorr[nbin];
	TVectorD V_int[nbin], V_interr[nbin];
	TVectorD V_intcorr[nbin], V_intcorrerr[nbin];
	TVectorD* V_mean;
	TVectorD* deltaV_mean;
	TVectorD vmeanmean[nbin], deltavmeanmean[nbin], sigmavmeanmean[nbin], avgavgpt[nbin], avgavgeta[nbin];
	TVectorD* V[nbin]; TVectorD* chi[nbin];
	TVectorD* dDRe[nbin]; TVectorD* dDIm[nbin];
	TVectorD* dNRe[nbin][ntheta]; TVectorD* dNIm[nbin][ntheta];
	TComplex dD[nbin][ntheta], dN[nbin][ntheta][nvv];
	TVectorD avgmult[nbin];	TVectorD avgmultall;
	TVectorD avgpt[nbin],avgeta[nbin];
	TVectorD v[nbin][ntheta],vmean[nbin],deltav[nbin][ntheta],deltavmean[nbin];
	TVectorD IFILE[nbin];
	if(SumorProd=="Sum")	TFile *infile = TFile::Open("mergedV_Sum.root");
	else	TFile *infile = TFile::Open("mergedV_Prod.root");
        if(ispt){
	if(SumorProd=="Sum")TFile *fout = new TFile("mergedv_Prod_sub.root","Recreate");
	else TFile *fout = new TFile("mergedv_Prod2_sub.root","Recreate");
        }
        else{
	if(SumorProd=="Sum")TFile *fout = new TFile("mergedv_Prod_eta_sub.root","Recreate");
	else TFile *fout = new TFile("mergedv_Prod2_coarse_eta_sub.root","Recreate");
        }

	TVectorD Nevent_;       Nevent_.ResizeTo(nbin);  Nevent_.Zero();
	TH1D* hpt[nbin];
	TH1D* hpteffcorr[nbin];
	for(int ibin=0;ibin<nbin;ibin++){
        for(int ifile=0; ifile<nFileAll; ifile++){
            if(ispt){
        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod_%d.root",mdir.c_str(),ifile));
        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod2_%d.root",mdir.c_str(),ifile));
            }
            else{
        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6c/coarsebins/%s/Anaveta_Prod_%d.root",mdir.c_str(),ifile));
        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod2_%d.root",mdir.c_str(),ifile));
            }
        TVectorD* Nevent_t =  (TVectorD*)f[ifile]->Get(Form("Nevent"));
        Nevent_[ibin]+=(*Nevent_t)[ibin];
        f[ifile]->Close();
        }
	IFILE[ibin].ResizeTo(nsamples);
        Nevent[ibin].ResizeTo(nsamples);  Nevent[ibin].Zero();
        totmultall[ibin].ResizeTo(nsamples);      totmultall[ibin].Zero();
        totmultall_[ibin].ResizeTo(nsamples);      totmultall_[ibin].Zero();
        TDirectory *dir0 = fout->mkdir(Form("D_%d",ibin));


      	vmeanmean[ibin].ResizeTo(nvv);  vmeanmean[ibin].Zero();
        deltavmeanmean[ibin].ResizeTo(nvv);  deltavmeanmean[ibin].Zero();
       	sigmavmeanmean[ibin].ResizeTo(nvv);  sigmavmeanmean[ibin].Zero();
	avgavgpt[ibin].ResizeTo(nvv);	avgavgpt[ibin].Zero();
	avgavgeta[ibin].ResizeTo(nvv);	avgavgeta[ibin].Zero();
	V_interr[ibin].ResizeTo(nsamples);	V_interr[ibin].Zero();
	V_int[ibin].ResizeTo(nsamples);	V_int[ibin].Zero();
        if(ispt){
	V_intcorr[ibin].ResizeTo(nsamples);	V_intcorr[ibin].Zero();
	V_intcorrerr[ibin].ResizeTo(nsamples);	V_intcorrerr[ibin].Zero();
        }
        for(int isample=0;isample<nsamples;isample++){

	TVectorD Nevent0; Nevent0.ResizeTo(nbin);	Nevent0.Zero();
	avgmultall.ResizeTo(nbin);
		totmult[ibin].ResizeTo(nvv);	totmult[ibin].Zero();
                if(ispt){
		totmulthisto[ibin].ResizeTo(nvv); totmulthisto[ibin].Zero();
		totmulthistocorr[ibin].ResizeTo(nvv);totmulthistocorr[ibin].Zero();
                }
		avgmult[ibin].ResizeTo(nvv);	avgpt[ibin].ResizeTo(nvv);  avgeta[ibin].ResizeTo(nvv);
		totpt[ibin].ResizeTo(nvv);	totpt[ibin].Zero();
		toteta[ibin].ResizeTo(nvv);	toteta[ibin].Zero();
		vmean[ibin].ResizeTo(nvv);	deltavmean[ibin].ResizeTo(nvv);
		V[ibin] = (TVectorD*) infile->Get(Form("D_%d/V",ibin,isample));
		chi[ibin] = (TVectorD*) infile->Get(Form("chi",ibin,isample));
		V_mean = (TVectorD*) infile->Get(Form("Vmean",ibin,isample));
		deltaV_mean = (TVectorD*) infile->Get(Form("deltaVmean",ibin,isample));
		for(int itheta=0;itheta<ntheta;itheta++){
			v[ibin][itheta].ResizeTo(nvv);	deltav[ibin][itheta].ResizeTo(nvv);
			dD[ibin][itheta]=0;
			for(int ivbin=0;ivbin<nvv;ivbin++){
				dN[ibin][itheta][ivbin]=0;
			}
		}

        for(int ifile=0; ifile<nFileAll; ifile++){
            if(ispt){
	        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod__%d.root",mdir.c_str(),ifile));
	        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/%s/Anav_Prod2_%d.root",mdir.c_str(),ifile));
            }
            else{
	        if(SumorProd=="Sum") f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod_%d.root",mdir.c_str(),ifile));
	        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/tracknormcpt03to6/coarsebins/%s/Anaveta_Prod2_%d.root",mdir.c_str(),ifile));
            }
		TVectorD* Nevent_t = (TVectorD*)f[ifile]->Get("Nevent");	
		TVectorD* totmultall_t = (TVectorD*)f[ifile]->Get("totmultall");
		Nevent0[ibin] += (*Nevent_t)[ibin];
                double start=isample*Nevent_[ibin]/nsamples;
                double end=(isample+1)*Nevent_[ibin]/nsamples;
                if(Nevent0[ibin]>start && Nevent0[ibin]<=end){
                        IFILE[ibin][isample]=(double)ifile;
                        Nevent[ibin][isample] += (*Nevent_t)[ibin];
			TVectorD* totmult_t = (TVectorD*)f[ifile]->Get(Form("totmult_%d",ibin));
			TVectorD* totpt_t = (TVectorD*)f[ifile]->Get(Form("totpt_%d",ibin));
			TVectorD* toteta_t = (TVectorD*)f[ifile]->Get(Form("toteta_%d",ibin));
			dDRe[ibin] = (TVectorD*)f[ifile]->Get(Form("dDRe_%d",ibin));
			dDIm[ibin] = (TVectorD*)f[ifile]->Get(Form("dDIm_%d",ibin));
			totmultall[ibin][isample]+=(*totmultall_t)[ibin];
			for(int ivbin=0;ivbin<nvv;ivbin++){
				totmult[ibin][ivbin]+=(*totmult_t)[ivbin];
				totpt[ibin][ivbin]+=(*totpt_t)[ivbin];
				toteta[ibin][ivbin]+=(*toteta_t)[ivbin];
			}
			for(int itheta=0;itheta<ntheta;itheta++){
				dNRe[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNRe_%d_%d",ibin,itheta));
				dNIm[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNIm_%d_%d",ibin,itheta));
				dD[ibin][itheta]+=TComplex((*dDRe[ibin])[itheta],(*dDIm[ibin])[itheta]);
				for(int ivbin=0;ivbin<nvv;ivbin++){
					if(ifile<188) dN[ibin][itheta][ivbin]+=TComplex((*dNRe[ibin][itheta])[ivbin],(*dNIm[ibin][itheta])[ivbin]);
                                        else dN[ibin][itheta][nvv-ivbin-1]+=TComplex((*dNRe[ibin][itheta])[ivbin],(*dNIm[ibin][itheta])[ivbin]);
                                }
			}
		}
	f[ifile]->Close();
	}
	
	TFile *fhisto = TFile::Open("histomerged.root");
	TFile *feff = TFile::Open("/home/xuq7/HI/flow/LYZ/v2/TrackCorrections_HIJING_538_OFFICIAL_Mar24.root");
	TH2F* heff = (TH2F*)feff->Get("rTotalEff3D");
      	TH1D* hpteff = (TH1D*)heff->ProjectionY("hpteff",heff->GetXaxis()->FindBin(-2.4),heff->GetXaxis()->FindBin(2.4)-1,"o");
	TArrayD *ptarr = (TArrayD*)heff->GetYaxis()->GetXbins();
	double *ptbinhisto = ptarr->GetArray();
	int NbinX = heff->GetXaxis()->GetNbins();
	int NbinY = heff->GetYaxis()->GetNbins();
	hpteff->Scale(1.0/NbinX);
        
		for(int itheta=0;itheta<ntheta;itheta++)
			dD[ibin][itheta]*=TComplex::Power(TComplex::I(),mm-1)/(Double_t)Nevent[ibin][isample];
	
		avgmultall[ibin]=1.0*totmultall[ibin][isample]/Nevent[ibin][isample];
                hpt[ibin] = (TH1D*)fhisto->Get(Form("D_%d/hpt",ibin));
                //TH1D* hptre = (TH1D*)hpt[ibin]->Rebin(NbinY,"hptre",ptbinhisto);
                //hpteffcorr[ibin] = (TH1D*)hptre->Clone(Form("hpteffcorr_%d",ibin));
                //hpteffcorr[ibin]->Divide(hpteff);
		for(int ivbin=0;ivbin<nvv; ivbin++){
			vmean[ibin][ivbin]=0;
			deltavmean[ibin][ivbin]=0;
			avgmult[ibin][ivbin]=1.0*totmult[ibin][ivbin]/Nevent[ibin][isample];
			avgpt[ibin][ivbin]=1.0*totpt[ibin][ivbin]/totmult[ibin][ivbin];
			avgeta[ibin][ivbin]=1.0*toteta[ibin][ivbin]/totmult[ibin][ivbin];
			for(int itheta=0;itheta<ntheta;itheta++){
				dN[ibin][itheta][ivbin]/=totmult[ibin][ivbin];
				TComplex Res=dN[ibin][itheta][ivbin]/dD[ibin][itheta];
				v[ibin][itheta][ivbin]=(*V[ibin])[itheta]*avgmultall[ibin]*TMath::BesselJ1(j01)/Besselj01(mm)*Res.Re();
				vmean[ibin][ivbin]+=v[ibin][itheta][ivbin];
				deltav[ibin][itheta][ivbin]=TMath::Cos(mm*nn*theta[itheta])/totmult[ibin][ivbin]*(TMath::Exp(j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Power(-1,mm)*TMath::Exp(-j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.)));
				deltavmean[ibin][ivbin]+=deltav[ibin][itheta][ivbin];
			//	fstrv<<itheta<<"\t"<<v[ibin][itheta][ivbin]<<"\t"<<deltav[ibin][itheta][ivbin]<<endl;
			}
		deltavmean[ibin][ivbin]=TMath::Sqrt(deltavmean[ibin][ivbin])/2./Besselj01(mm);
		//fstrv<<endl;
		vmean[ibin][ivbin]/=ntheta;
		deltavmean[ibin][ivbin]/=TMath::Sqrt(ntheta);
		fstrv<<binv[ivbin]<<"-"<<binv[ivbin+1]<<"\t"<<vmean[ibin][ivbin]<<"\t"<<deltavmean[ibin][ivbin]<<endl;
                if(ispt){
		if(binv[ivbin+1]>3.0) continue;
                totmulthisto[ibin][ivbin]=hpt[ibin]->Integral(hpt[ibin]->GetXaxis()->FindBin(binv[ivbin]),hpt[ibin]->GetXaxis()->FindBin(binv[ivbin+1])-1);
//                totmulthistocorr[ibin][ivbin]=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[ivbin]),hpteffcorr[ibin]->GetXaxis()->FindBin(binv[ivbin+1])-1);
                totmulthistocorr[ibin][ivbin]=totmulthisto[ibin][ivbin]/hpteff->GetBinContent(hpteff->FindBin((binv[ivbin]+binv[ivbin+1])/2));
		V_int[ibin][isample]+=vmean[ibin][ivbin]*totmult[ibin][ivbin];
		V_interr[ibin][isample]+=deltavmean[ibin][ivbin]*totmult[ibin][ivbin];
		V_intcorr[ibin][isample]+=vmean[ibin][ivbin]*totmulthistocorr[ibin][ivbin];
		V_intcorrerr[ibin][isample]+=deltavmean[ibin][ivbin]*totmulthistocorr[ibin][ivbin];
                }
		totmultall_[ibin][isample]+=totmult[ibin][ivbin];
		}
		V_int[ibin][isample]/=totmultall_[ibin][isample];
		V_interr[ibin][isample]/=totmultall_[ibin][isample];
		//V_intcorr[ibin][isample]/=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1);
		//V_intcorr[ibin][isample]/=totmulthistocorr[ibin];
		//V_intcorrerr[ibin][isample]/=hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1);

                if(ispt){
        fstrv<<endl<<"pt range\t\t"<<"totmult"<<"\t\t"<<"totmult from histo"<<"\t"<<"totmult corrected"<<endl;
		for(int ivbin=0;ivbin<nvv; ivbin++){
                fstrv<<binv[ivbin]<<"-"<<binv[ivbin+1]<<"\t\t"<<totmult[ibin][ivbin]<<"\t"<<totmulthisto[ibin][ivbin]<<"\t"<<totmulthistocorr[ibin][ivbin]<<endl;
		}
		//fstrv<<"Integral\t\t"<<totmultall[ibin][isample]<<"\t"<<hpt[ibin]->Integral(hpt[ibin]->GetXaxis()->FindBin(binv[0]),hpt[ibin]->GetXaxis()->FindBin(3.0)-1)<<"\t"<<hpteffcorr[ibin]->Integral(hpteffcorr[ibin]->GetXaxis()->FindBin(binv[0]),hpteffcorr[ibin]->GetXaxis()->FindBin(3.0)-1)<<endl;
		fstrv<<"V ref="<<(*V_mean)[ibin]<<"\t"<<"V int="<<V_int[ibin][isample]<<"\t"<<"V int corr="<<V_intcorr[ibin][isample]<<endl;
		fstrv<<"V ref err="<<(*deltaV_mean)[ibin]<<"\t"<<"V int err="<<V_interr[ibin][isample]<<"\t"<<"V int corr err="<<V_intcorrerr[ibin][isample]<<endl;
                }
	TDirectory *dirsample = dir0->mkdir(Form("s_%d",isample));
        dirsample->cd();
	avgpt[ibin].Write("avgpt");
	avgeta[ibin].Write("avgeta");
	totmult[ibin].Write("totmult");
	vmean[ibin].Write("vmean");
	deltavmean[ibin].Write("deltavmean");
	for(int ivbin=0;ivbin<nvv; ivbin++){
		avgavgpt[ibin][ivbin]+=avgpt[ibin][ivbin]*Nevent[ibin][isample];
		avgavgeta[ibin][ivbin]+=avgeta[ibin][ivbin]*Nevent[ibin][isample];
		vmeanmean[ibin][ivbin]+=vmean[ibin][ivbin]/nsamples;
        	deltavmeanmean[ibin][ivbin]+=deltavmean[ibin][ivbin]/nsamples;
	        sigmavmeanmean[ibin][ivbin]+=TMath::Power(vmean[ibin][ivbin]/nsamples,2);
	}
	}//subsample loop
	dir0->cd();
        IFILE[ibin].Write("IFILE");
	V_int[ibin].Write("V_int");
	V_interr[ibin].Write("V_interr");
	V_intcorr[ibin].Write("V_intcorr");
	V_intcorrerr[ibin].Write("V_intcorrerr");
	Nevent[ibin].Write("Nevent");
	totmultall[ibin].Write("totmultall");
	for(int ivbin=0;ivbin<nvv; ivbin++){
		avgavgpt[ibin][ivbin]/=Nevent_[ibin];
		avgavgeta[ibin][ivbin]/=Nevent_[ibin];
        	sigmavmeanmean[ibin][ivbin]=TMath::Sqrt(sigmavmeanmean[ibin][ivbin]*nsamples-vmeanmean[ibin][ivbin]*vmeanmean[ibin][ivbin])/TMath::Sqrt(nsamples);
		}
	avgavgpt[ibin].Write("avgavgpt");
	avgavgeta[ibin].Write("avgavgeta");
        vmeanmean[ibin].Write("vmeanmean");
	deltavmeanmean[ibin].Write("deltavmeanmean");
        sigmavmeanmean[ibin].Write("sigmavmeanmean");
	}//ntrk bin loop
	infile->Close();
	fout->Close();
}
Esempio n. 4
0
int InputForLimits(){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;

  Int_t NBR = 3;
  Float_t BR[] = { 1., 0.75, 0.5};

  TFile* bkgFile = new TFile( "../../BkgPrediction/BkgPrediction.root", "READ"); 
  TTree* bkgTree;
  bkgFile->GetObject( "ElAndMu", bkgTree);
  
  Float_t bkg = 0.;
  Float_t bkgTotUnc = 0.;

  Float_t obs = 0.;

  bkgTree->SetBranchAddress( "srData", &obs);
  bkgTree->SetBranchAddress( "srAllBkgCorr", &bkg);
  bkgTree->SetBranchAddress( "TotUnc", &bkgTotUnc);

  TFile* sigFile = new TFile( "../../SignalSystematics/SignalSys.root", "READ"); 

  std::vector<std::vector<TString> > sysColl;
  std::vector<TString> sys;
  sys.push_back(TString("JES_Up"));
  sys.push_back(TString("JES_Down"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpBC"));
  sys.push_back(TString("BTagReweight_DownBC"));
  sysColl.push_back(sys);

  sys.clear();
  sys.push_back(TString("BTagReweight_UpLight"));
  sys.push_back(TString("BTagReweight_DownLight"));
  sysColl.push_back(sys);

  std::vector<TString> decayMode;
  decayMode.push_back(TString("tt"));
  decayMode.push_back(TString("tb"));
  decayMode.push_back(TString("bb"));
		      
  Systematics* systematics[3];
  TString dirname;
  TString histoname;

  TDirectory* srDir;
  TDirectory* histoDir;

  TFile* outFile = new TFile( "InputForLimits.root", "RECREATE");
  TDirectory* outBRDir;
  TDirectory* outSRDir;

  TH1F* datah = new TH1F( "data", "data", 1, 0., 1.);
  TH1F* bkgh = new TH1F( "bkg", "bkg", 1, 0., 1.);

  TH2F* sigh;
  TH2F* sig_toth;
  TH2F* effh;
  
  TH2F* sigLh;
  TH2F* effLh;

  TH2F* sigRh;
  TH2F* effRh;
  
  TH2F* jesh;
  TH2F* btagBCh;
  TH2F* btagLighth;
  TH2F* btagh;
  
  TH2F* sysh;

  TH2F* unch;

  TH2F* jesPercenth;
  TH2F* btagBCPercenth;
  TH2F* btagLightPercenth;
  TH2F* btagPercenth;
  
  TH2F* sysPercenth;

  TH2F* uncPercenth;

  Float_t sig = 0.;
  Float_t stat = 0.;

  Float_t jes = 0.;
  Float_t bc = 0.;
  Float_t light = 0.;
  
  Float_t unc = 0.;

  int N = bkgTree->GetEntries();

  for ( int ibr = 0; ibr < NBR; ibr++){
    dirname = ""; dirname += BR[ibr];
    outFile->mkdir(dirname);
    outBRDir = outFile->GetDirectory(dirname);

    for ( int iSR = 0; iSR < 9; iSR++){
      bkgTree->GetEntry(iSR);      
      datah->SetBinContent( 1, obs);
      bkgh->SetBinContent( 1, bkg);
      bkgh->SetBinError( 1, bkgTotUnc);

      dirname = ""; dirname += iSR;
      outBRDir->mkdir(dirname);
      outSRDir = outBRDir->GetDirectory(dirname);
      
      dirname = ""; dirname += iSR; dirname += ".root";      
      srDir = sigFile->GetDirectory( dirname);
      for ( int isys = 0; isys < (int) sysColl.size(); isys++){
	systematics[isys] = new Systematics();
	systematics[isys]->BR = BR[ibr];

	histoDir = srDir->GetDirectory( "NoSystematic");
	for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	  histoDir->GetObject( decayMode.at(idecay), systematics[isys]->h[idecay]);
	  histoDir->GetObject( decayMode.at(idecay) + "l", systematics[isys]->Lh);
	  histoDir->GetObject( decayMode.at(idecay) + "r", systematics[isys]->Rh);
	}
	histoDir->GetObject( decayMode.at(0) + "l", systematics[isys]->Lh);
	histoDir->GetObject( decayMode.at(0) + "r", systematics[isys]->Rh);
	histoDir->GetObject( "sig_tot", systematics[isys]->sig_toth);

	for ( int ishift = 0; ishift < 2; ishift++){
	  histoDir = srDir->GetDirectory(sysColl.at(isys).at(ishift));
	  for ( int idecay = 0; idecay < (int) decayMode.size(); idecay++){
	    histoDir->GetObject( decayMode.at(idecay), systematics[isys]->shifth[ishift][idecay]);
	  }
	}
	systematics[isys]->Calc();
      }
      sig_toth = new TH2F( *systematics[0]->sig_toth);
      sig_toth->SetName("sig_tot");
      sig_toth->SetTitle("sig_tot");    

      sigh = new TH2F( *systematics[0]->sigh);
      sigh->SetName("sig");
      sigh->SetTitle("sig");

      effh = new TH2F( *systematics[0]->effh);
      effh->SetName("eff");
      effh->SetTitle("eff");

      sigLh = new TH2F( *systematics[0]->sigRh);
      sigLh->SetName("sigL");
      sigLh->SetTitle("sigL");

      effLh = new TH2F( *systematics[0]->effLh);
      effLh->SetName("effL");
      effLh->SetTitle("effL");

      sigRh = new TH2F( *systematics[0]->sigRh);
      sigRh->SetName("sigR");
      sigRh->SetTitle("sigR");

      effRh = new TH2F( *systematics[0]->effRh);
      effRh->SetName("effR");
      effRh->SetTitle("effR");

      jesh = new TH2F( *systematics[0]->sysh);
      jesh->SetName("jes");
      jesh->SetTitle("jes");

      btagBCh = new TH2F( *systematics[1]->sysh);
      btagBCh->SetName("btagBC");
      btagBCh->SetTitle("btagBC");
      
      btagLighth = new TH2F( *systematics[2]->sysh);
      btagLighth->SetName("btagLight");
      btagLighth->SetTitle("btagLight");
      
      btagh = new TH2F( *btagBCh);
      btagh->Reset();
      btagh->SetName("btag");
      btagh->SetTitle("btag");
 
      sysh = new TH2F( *jesh);
      sysh->Reset();
      sysh->SetName("sys");
      sysh->SetTitle("sys");

      unch = new TH2F( *jesh);
      unch->Reset();
      unch->SetName("unc");
      unch->SetTitle("unc");


      jesPercenth = new TH2F( *systematics[0]->sysh);
      jesPercenth->SetName("jesPercent");
      jesPercenth->SetTitle("jesPercent");
      jesPercenth->Divide( sigh);
      jesPercenth->Scale( 100.);      

      btagBCPercenth = new TH2F( *systematics[1]->sysh);
      btagBCPercenth->SetName("btagBCPercent");
      btagBCPercenth->SetTitle("btagBCPercent");
      btagBCPercenth->Divide( sigh);
      btagBCPercenth->Scale( 100.);   

      btagLightPercenth = new TH2F( *systematics[2]->sysh);
      btagLightPercenth->SetName("btagLightPercent");
      btagLightPercenth->SetTitle("btagLightPercent");
      btagLightPercenth->Divide( sigh);
      btagLightPercenth->Scale( 100.);   

      btagPercenth = new TH2F( *btagBCh);
      btagPercenth->Reset();
      btagPercenth->SetName("btagPercent");
      btagPercenth->SetTitle("btagPercent");
 
      sysPercenth = new TH2F( *jesh);
      sysPercenth->Reset();
      sysPercenth->SetName("sysPercent");
      sysPercenth->SetTitle("sysPercent");

      uncPercenth = new TH2F( *jesh);
      uncPercenth->Reset();
      uncPercenth->SetName("uncPercent");
      uncPercenth->SetTitle("uncPercent");

      for (int ibin = 0; ibin < sigh->GetSize(); ibin++){	
	sig = sigh->GetBinContent( ibin);
	stat = sigh->GetBinError( ibin);

	jes = jesh->GetBinContent(ibin);
	bc = btagBCh->GetBinContent(ibin);
	light = btagLighth->GetBinContent(ibin);
    
	unc = sqrt( bc * bc + light * light);
	btagh->SetBinContent( ibin, unc);
	btagPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light +
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );       
	sysh->SetBinContent( ibin, unc);
	sysPercenth->SetBinContent( ibin, unc / sig * 100.);
	
	unc = sqrt( jes * jes + bc * bc + light * light + stat * stat +  
		    sig * sig * (0.044 * 0.044 + // Lumi
				 0.03  * 0.03  + // Trigger
				 0.05  * 0.05    // Lep Id
				 )
		    );	
	unch->SetBinContent( ibin, unc);
	uncPercenth->SetBinContent( ibin, unc / sig * 100.);
      }
      outSRDir->cd();

      datah->Write();
      bkgh->Write();

      sig_toth->Write();
      sigh->Write();
      effh->Write();
      
      sigLh->Write();
      effLh->Write();

      sigRh->Write();
      effRh->Write();

      jesh->Write();
      btagBCh->Write(); 
      btagLighth->Write();
      btagh->Write();
      
      sysh->Write();
      unch->Write();

      jesPercenth->Write();
      btagBCPercenth->Write(); 
      btagLightPercenth->Write();
      btagPercenth->Write();
      
      sysPercenth->Write();
      uncPercenth->Write();
    }
  }

  delete systematics[0];
  delete systematics[1];
  delete systematics[2];

  outFile->Close();
  sigFile->Close();
  bkgFile->Close();

  return 0;
}
Esempio n. 5
0
//_____________________________________________________________________________
Int_t ProofAux::GenerateTree(const char *fnt, Long64_t ent, TString &fn)
{
   // Generate the main tree for the 'friends' tutorial; the tree is called
   // 'Tmain', has 'ent' entries and is saved to file 'fnt'.
   // The full file path is returned in 'fn'.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;

   // Check the filename
   fn = fnt;
   if (fn.IsNull()) {
      Error("GenerateTree", "file name undefined!");
      return rc;
   }
   TUrl uu(fn, kTRUE);
   if (!strcmp(uu.GetProtocol(), "file") && !fn.BeginsWith("/")) {
      // Local file with relative path: create under the data directory
      if (!gProofServ ||
          !(gProofServ->GetDataDir()) || strlen(gProofServ->GetDataDir()) <= 0) {
         Error("GenerateTree", "data directory undefined!");
         return rc;
      }
      // Insert data directory
      fn.Insert(0, TString::Format("%s/", gProofServ->GetDataDir()));
      // Make sure the directory exists
      TString dir = gSystem->DirName(fn);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateTree", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   }

   // Create the file
   TDirectory* savedir = gDirectory;
   TFile *f = new TFile(fn, "RECREATE");
   if (!f || f->IsZombie()) {
      Error("GenerateTree", "problems opening file %s", fn.Data());
      return rc;
   }
   savedir->cd();
   rc = 0;

   // Create the tree
   TTree *T = new TTree("Tmain","Main tree for tutorial friends");
   T->SetDirectory(f);
   Int_t Run = 1;
   T->Branch("Run",&Run,"Run/I");
   Long64_t Event = 0;
   T->Branch("Event",&Event,"Event/L");
   Float_t x = 0., y = 0., z = 0.;
   T->Branch("x",&x,"x/F");
   T->Branch("y",&y,"y/F");
   T->Branch("z",&z,"z/F");
   TRandom r;
   for (Long64_t i = 0; i < ent; i++) {
      if (i > 0 && i%1000 == 0) Run++;
      Event = i;
      x = r.Gaus(10,1);
      y = r.Gaus(20,2);
      z = r.Landau(2,1);
      T->Fill();
   }
   T->Print();
   f->cd();
   T->Write();
   T->SetDirectory(0);
   f->Close();
   delete f;
   delete T;

   // Notify success
   Info("GenerateTree", "file '%s' successfully created", fn.Data());

   // Add to the list
   TString fds(fn);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fds.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fds.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fMainList->Add(new TObjString(fds));

   // Done
   return rc;
}
Esempio n. 6
0
void combineDataCardsSM(Int_t channel, Int_t cat, TString mass){

  TString ChannelName;
  if(channel==1)ChannelName="muTau";
  else if(channel==2)ChannelName="eleTau";
  else return;
  

  TFile nominal(ChannelName+"_SM"+(long)cat+"_"+mass+"_.root","read");
  TFile nominaltUp(ChannelName+"_SM"+(long)cat+"_"+mass+"_tUp.root","read");
  TFile nominaltDown(ChannelName+"_SM"+(long)cat+"_"+mass+"_tDown.root","read");


  TString scaleUp="CMS_scale_t_mutau_8TeVUp";
  TString scaleDown="CMS_scale_t_mutau_8TeVDown";
  if(channel==2)scaleUp="CMS_scale_t_etau_8TeVUp";
  if(channel==2)scaleDown="CMS_scale_t_etau_8TeVDown";


  TFile output(ChannelName+"_SM"+(long)cat+"_"+mass+".root","recreate");
  for(long sm=0;sm<NCAT;sm++){
    if(cat==13 && (sm==2 || sm==4))continue;//skip boost_low and vbf
    if(cat==20 && (sm==3 || sm==4))continue;//skip boost_high and vbf
    if(cat==23 && (sm==4))continue;//skip vbf
    if(cat==15 && (sm==2 || sm==3))continue;//skip boost_low and boost_high
    
    cout<<catdirname[sm]<<endl;

    TDirectory* dir = output.mkdir(ChannelName+"_"+catdirname[sm]);  
    dir->cd();


    /////////////Nominal histos:
    TH1F* ZTT = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZTT");
    TH1F* QCD = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/QCD");
    TH1F* W = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/W");
    TH1F* TT = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/TT");
    TH1F* ZL = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZL");
    TH1F* ZJ = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZJ");
    TH1F* VV = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/VV");
    TH1F* ZLL = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ZLL");
    TH1F* data_obs = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/data_obs");

    ZTT->Write();
    ZL->Write();
    ZJ->Write();
    ZLL->Write();
    W->Write();
    TT->Write();
    VV->Write();
    QCD->Write();
    data_obs->Write();

    /////////////tUp histos
    TH1F* ZTT_CMS_scale_tUp =  (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/ZTT");
    ZTT_CMS_scale_tUp->SetName(TString("ZTT_")+scaleUp);

    TH1F* QCD_CMS_scale_tUp = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/QCD");
    QCD_CMS_scale_tUp->SetName(TString("QCD_")+scaleUp);

    TH1F* W_CMS_scale_tUp =  (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/W");
    W_CMS_scale_tUp->SetName(TString("W_")+scaleUp);

    TH1F* TT_CMS_scale_tUp = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/TT");
    TT_CMS_scale_tUp->SetName(TString("TT_")+scaleUp);

    TH1F* ZL_CMS_scale_tUp = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/ZL");
    ZL_CMS_scale_tUp->SetName(TString("ZL_")+scaleUp);

    TH1F* ZJ_CMS_scale_tUp = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/ZJ");
    ZJ_CMS_scale_tUp->SetName(TString("ZJ_")+scaleUp);

    TH1F* VV_CMS_scale_tUp = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/VV");
    VV_CMS_scale_tUp->SetName(TString("VV_")+scaleUp);

    TH1F* ZLL_CMS_scale_tUp= (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/ZLL");
    ZLL_CMS_scale_tUp->SetName(TString("ZLL_")+scaleUp);

    ZTT_CMS_scale_tUp->Write();
    ZL_CMS_scale_tUp->Write();
    ZJ_CMS_scale_tUp->Write();
    ZLL_CMS_scale_tUp->Write();
    W_CMS_scale_tUp->Write();
    TT_CMS_scale_tUp->Write();
    VV_CMS_scale_tUp->Write();
    QCD_CMS_scale_tUp->Write();


    /////////////tDown histos
    TH1F* ZTT_CMS_scale_tDown =  (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/ZTT");
    ZTT_CMS_scale_tDown->SetName(TString("ZTT_")+scaleDown);

    TH1F* QCD_CMS_scale_tDown = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/QCD");
    QCD_CMS_scale_tDown->SetName(TString("QCD_")+scaleDown);

    TH1F* W_CMS_scale_tDown =  (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/W");
    W_CMS_scale_tDown->SetName(TString("W_")+scaleDown);

    TH1F* TT_CMS_scale_tDown = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/TT");
    TT_CMS_scale_tDown->SetName(TString("TT_")+scaleDown);

    TH1F* ZL_CMS_scale_tDown = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/ZL");
    ZL_CMS_scale_tDown->SetName(TString("ZL_")+scaleDown);

    TH1F* ZJ_CMS_scale_tDown = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/ZJ");
    ZJ_CMS_scale_tDown->SetName(TString("ZJ_")+scaleDown);

    TH1F* VV_CMS_scale_tDown = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/VV");
    VV_CMS_scale_tDown->SetName(TString("VV_")+scaleDown);

    TH1F* ZLL_CMS_scale_tDown= (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/ZLL");
    ZLL_CMS_scale_tDown->SetName(TString("ZLL_")+scaleDown);


    ZTT_CMS_scale_tDown->Write();
    ZL_CMS_scale_tDown->Write();
    ZJ_CMS_scale_tDown->Write();
    ZLL_CMS_scale_tDown->Write();
    W_CMS_scale_tDown->Write();
    TT_CMS_scale_tDown->Write();
    VV_CMS_scale_tDown->Write();
    QCD_CMS_scale_tDown->Write();


    for(Int_t m=0;m<NMASS;m++){
      long ma=massValues[m];
      
      cout<<ChannelName+"_"+catdirname[sm]<<" "<<ma<<endl;

      //Nominal histos
      TH1F* SM = (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/ggH"+ma);
      SM->SetName(TString("ggH")+ma);

      TH1F* VBF =  (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/qqH"+ma);
      VBF->SetName(TString("qqH")+ma);
      
      TH1F* VH =  (TH1F*)nominal.Get(ChannelName+"_"+catdirname[sm]+"/VH"+ma);
      VH->SetName(TString("VH")+ma);
     
      //tUp histos
      TH1F* SM_CMS_scale_tUp  = (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/ggH"+ma);
      SM_CMS_scale_tUp->SetName(TString("ggH")+ma+"_"+scaleUp);
      
      TH1F* VBF_CMS_scale_tUp  =  (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/qqH"+ma);
      VBF_CMS_scale_tUp->SetName(TString("qqH")+ma+"_"+scaleUp);

      TH1F* VH_CMS_scale_tUp  =  (TH1F*)nominaltUp.Get(ChannelName+"_"+catdirname[sm]+"/VH"+ma);
      VH_CMS_scale_tUp->SetName(TString("VH")+ma+"_"+scaleUp);

     
      //tDown histos
      TH1F* SM_CMS_scale_tDown  = (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/ggH"+ma);
      SM_CMS_scale_tDown->SetName(TString("ggH")+ma+"_"+scaleDown);
      
      TH1F* VBF_CMS_scale_tDown  =  (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/qqH"+ma);
      VBF_CMS_scale_tDown->SetName(TString("qqH")+ma+"_"+scaleDown);

      TH1F* VH_CMS_scale_tDown  =  (TH1F*)nominaltDown.Get(ChannelName+"_"+catdirname[sm]+"/VH"+ma);
      VH_CMS_scale_tDown->SetName(TString("VH")+ma+"_"+scaleDown);


      SM->Write();
      VBF->Write();
      VH->Write();

      SM_CMS_scale_tUp->Write();
      VBF_CMS_scale_tUp->Write();
      VH_CMS_scale_tUp->Write();

      SM_CMS_scale_tDown->Write();
      VBF_CMS_scale_tDown->Write();
      VH_CMS_scale_tDown->Write();


    }


  }
  


  //for 1Jet_low need to add a shape systematic for QCD 
  TH1F* QCD = (TH1F*)nominal.Get(ChannelName+"_boost_low/QCD");
  if(QCD){
    TH1F* QCDUp=(TH1F*)QCD->Clone("QCD_CMS_htt_QCDShape_mutau_boost_low_8TeVUp");
    TH1F* QCDDown=(TH1F*)QCD->Clone("QCD_CMS_htt_QCDShape_mutau_boost_low_8TeVDown");
    for(Int_t b=1;b<=QCD->GetNbinsX();b++){
      if(QCD->GetBinCenter(b)<=70.){
	QCDUp->SetBinContent(b,1.15*QCDUp->GetBinContent(b));
	QCDDown->SetBinContent(b,0.85*QCDDown->GetBinContent(b));
      }
    }
    output.cd("muTau_boost_low");
    QCDUp->Write();
    QCDDown->Write();
  }

  output.ls();
  output.Close();


  gROOT->ProcessLine(".q");
}
Esempio n. 7
0
void recurseFile(TDirectory *indir, TDirectory *outdir,
                 double etawid, double etamid) {

  TDirectory *curdir = gDirectory;

  // Automatically go through the list of keys (directories)
  TList *keys = indir->GetListOfKeys();
  TListIter itkey(keys);
  TObject *key, *obj;
  TDirectory *dir;

  while ( (key = itkey.Next()) ) {

    if (_debug) cout << key->GetName() << endl << flush;
    obj = ((TKey*)key)->ReadObj(); assert(obj);
    dir = indir;

    // Found a subdirectory: copy it to output and go deeper
    if (obj->InheritsFrom("TDirectory")) {

      //assert(outdir->mkdir(obj->GetName()));
      outdir->mkdir(obj->GetName());
      assert(outdir->cd(obj->GetName()));
      TDirectory *outdir2 = outdir->GetDirectory(obj->GetName()); assert(outdir2);
      outdir2->cd();

      assert(indir->cd(obj->GetName()));
      TDirectory *indir2 = indir->GetDirectory(obj->GetName());
      indir2->cd();

      // Check if directory name contains information on eta bin width
      float etamin, etamax;
      if ( (sscanf(indir->GetName(),"Eta_%f-%f",&etamin,&etamax)==2)
           && (etamax>etamin) ) {
        etawid = 2.*(etamax-etamin);
        etamid = 0.5*(etamax+etamin);
        //cout << "Eta bin width: " << etawid << flush << endl;
      }

      recurseFile(indir2, outdir2, etawid, etamid);
      //outdir2->Write(); // does this speedup or slow down?
    } // inherits from TDirectory

    // Found a plot: normalize if hpt, then copy to output
    if (obj->InheritsFrom("TH1")) {

      outdir->cd();
      TObject *obj2 = obj->Clone(obj->GetName());

      // Normalize hpt and hselpt histograms
      // Same for hbpt
      if (string(obj2->GetName())=="hpt" ||
          string(obj2->GetName())=="hpt_evt" ||
          string(obj2->GetName())=="hpt_jet" ||
          string(obj2->GetName())=="hpt_pre" ||
          string(obj2->GetName())=="hpt0" ||
          string(obj2->GetName())=="hpt1" ||
          string(obj2->GetName())=="hpt2" ||
          string(obj2->GetName())=="hpt3" ||
          string(obj2->GetName())=="hpt_jk1" ||
          string(obj2->GetName())=="hpt_jk2" ||
          string(obj2->GetName())=="hpt_jk3" ||
          string(obj2->GetName())=="hpt_jk4" ||
          string(obj2->GetName())=="hpt_jk5" ||
          string(obj2->GetName())=="hpt_jk6" ||
          string(obj2->GetName())=="hpt_jk7" ||
          string(obj2->GetName())=="hpt_jk8" ||
          string(obj2->GetName())=="hpt_jk9" ||
          string(obj2->GetName())=="hpt_jk10" ||
          string(obj2->GetName())=="hpt_l1off" ||
          string(obj2->GetName())=="hpt_l1fast" ||
          string(obj2->GetName())=="hpt_plus" ||
          string(obj2->GetName())=="hpt_minus" ||
          string(obj2->GetName())=="hpt0_plus" ||
          string(obj2->GetName())=="hpt0_minus" ||
          string(obj2->GetName())=="hpt_noid" ||
          string(obj2->GetName())=="hpt_noevtid" ||
          string(obj2->GetName())=="hpt_nojetid" ||
          string(obj2->GetName())=="hpt_ak5calo" ||
          string(obj2->GetName())=="hpt_ak5pf" ||
          string(obj2->GetName())=="hpt_evt_ak5pf" ||
          string(obj2->GetName())=="hpt_jet_ak5pf" ||
          string(obj2->GetName())=="hselpt" ||
          string(obj2->GetName())=="hpt_r" ||
          string(obj2->GetName())=="hpt_g" ||
          string(obj2->GetName())=="hpt_gg" ||
          string(obj2->GetName())=="hpt_g0" ||
          string(obj2->GetName())=="hpt_g0tw" ||
          string(obj2->GetName())=="hdjmass" ||
          string(obj2->GetName())=="hdjmass0" ||
          string(obj2->GetName())=="hdjmass0_hgg") {

          cout << "." << flush;

        TH1D *hpt = (TH1D*)obj2;
        bool isgen = TString(obj2->GetName()).Contains("pt_g");
        bool isoth = (TString(obj2->GetName()).Contains("pt_no") ||
                      TString(obj2->GetName()).Contains("djmass") ||
                      TString(obj2->GetName()).Contains("hpt0") ||
                      TString(obj2->GetName()).Contains("l1off") ||
                      TString(obj2->GetName()).Contains("l1fast"));
        bool iscalo = (TString(obj2->GetName()).Contains("_ak5calo"));
        bool ispf5 = (TString(obj2->GetName()).Contains("_ak5pf"));
        bool ispre = (TString(obj2->GetName()).Contains("_pre"));
        bool isjk = (TString(obj2->GetName()).Contains("hpt_jk"));
        bool isjet = (TString(obj2->GetName()).Contains("hpt_jet"));

        TProfile *peff = (TProfile*)dir->Get("peff"); assert(peff);

        TH1D *hlumi = (TH1D*)dir->Get("hlumi"); assert(hlumi);
        TH1D *hlumi0 = (TH1D*)dir->Get("../jt450/hlumi"); assert(hlumi0);
        if (_jp_usetriglumi) {

          TH1D *hlumi_orig = (TH1D*)outdir->FindObject("hlumi_orig");
          if (!hlumi_orig) hlumi_orig = (TH1D*)hlumi->Clone("hlumi_orig");

          // regular prescaled luminosity
          TH1D *hlumi_new = (TH1D*)outdir->FindObject("hlumi");
          if (hlumi_new) hlumi = hlumi_new;
          string strg = dir->GetName();
          double lumi = triglumi[strg];
          for (int i = 1; i != hlumi->GetNbinsX()+1; ++i) {
            hlumi->SetBinContent(i, lumi);
          }

          // unprescaled luminosity
          double lumi0 = triglumi["jt450"];
          for (int i = 1; i != hlumi0->GetNbinsX()+1; ++i) {
            hlumi0->SetBinContent(i, lumi0);
          }
        } // _jp_usetriglumi

        // Test MC-based normalization for trigger efficiency
        bool dotrigeff = ((string(obj2->GetName())=="hpt") || isjk || isjet);
        TH1D *htrigeff = (TH1D*)outdir->FindObject("htrigeff");
        TH1D *htrigeffmc = (TH1D*)outdir->FindObject("htrigeffmc");
        TH1D *htrigeffsf = (TH1D*)outdir->FindObject("htrigeffsf");
        TH1D *hpt_notrigeff = 0;

        if (!htrigeff && _jp_dotrigeff) {

          TFile *fmc = new TFile("output-MC-1.root","READ");
          assert(fmc && !fmc->IsZombie());
          assert(fmc->cd("Standard"));
          fmc->cd("Standard");
          TDirectory *dmc0 = fmc->GetDirectory("Standard");
          //assert(gDirectory->cd(Form("Eta_%1.1f-%1.1f",
          //                 etamid-0.25*etawid,etamid+0.25*etawid)));
          //TDirectory *dmc = gDirectory;
          TDirectory *dmc = dmc0->GetDirectory(Form("Eta_%1.1f-%1.1f",
                                                    etamid-0.25*etawid,etamid+0.25*etawid));
          assert(dmc);
          dmc->cd();

          // Add MC truth based trigger efficiency
          if(!htrigeffmc && dmc->cd(dir->GetName())) {

            TDirectory *dir1 = dmc->GetDirectory(dir->GetName()); assert(dir1);
            TH1D *hpty = (TH1D*)dir1->Get("hpt"); assert(hpty);
            assert(dmc->cd("mc"));
            dmc->cd("mc");
            TDirectory *dir2 = dmc->GetDirectory("mc"); assert(dir2);
            TH1D *hptx = (TH1D*)dir2->Get(Form("hpt_%s",dir->GetName()));

            outdir->cd();
            if (hpty && hptx) htrigeffmc = (TH1D*)hpty->Clone("htrigeffmc");
            if (hpty && hptx) htrigeffmc->Divide(hpty,hptx,1,1,"B");
          }

          // Add data/MC scale factor for trigger efficiency
          if (_nh_dt && !htrigeffsf) {

            assert(dmc->cd(dir->GetName()));
            dmc->cd(dir->GetName());
            TDirectory *dirmc = dmc->GetDirectory(dir->GetName()); assert(dirmc);
            TProfile *pm = (TProfile*)dirmc->Get("ptrigefftp");
            TProfile *pd = (TProfile*)dir->Get("ptrigefftp");

            outdir->cd();
            if (pm && pd) htrigeffsf = pm->ProjectionX("htrigeffsf");
            if (pm && pd) htrigeffsf->Divide(pd,pm,1);
          }

          // Combine MC trigger efficiency and scalefactor
          if (htrigeffmc) { // not available for 'mc' directory
            outdir->cd();
            htrigeff = (TH1D*)htrigeffmc->Clone("htrigeff");
            assert(!_nh_dt || htrigeffsf);
            if (_nh_dt) htrigeff->Multiply(htrigeffsf);

            TH1D *h = (TH1D*)dir->Get("hpt");
            assert(outdir->FindObject("hpt_notrigeff")==0);
            outdir->cd();
            hpt_notrigeff = (TH1D*)h->Clone("hpt_notrigeff");
          }

          fmc->Close();
        } // dotrigeff


        // Scale data to account for time dependence
        bool dotimedep = ((string(obj2->GetName())=="hpt") || isjk || isjet);
        TH1D *htimedep = (TH1D*)outdir->FindObject("htimedep");
        TH1D *htimefit = (TH1D*)outdir->FindObject("htimefit");
        TH1D *hpt_notimedep = 0, *hpt_withtimedep = 0;
        double ktime = 1.;

        if (!htimedep) {

          TH1D *h = (TH1D*)dir->Get("hpt");
          TH1D *hsel = (TH1D*)dir->Get("hselpt");
          TH1D *hpre = (TH1D*)dir->Get("hpt_pre");
          //TH1D *hlumi0 = (TH1D*)dir->Get("../jt450/hlumi");

          // Fix luminosity for unprescaled trigger
          //string strg = dir->GetName();
          //double lum0 = triglumi["jt450"];
          //for (int i = 1; i != hlumi0->GetNbinsX()+1; ++i) {
          //hlumi0->SetBinContent(i, lum0);
          //}

          outdir->cd();
          if (h) hpt_notimedep = (TH1D*)h->Clone("hpt_notimedep");
          if (hpre && h) htimedep = (TH1D*)hpre->Clone("htimedep");
          if (hpre && h) htimedep->Divide(hpre,h);//,1,1,"B");

          // Figure out trigger luminosities
          double lumi = 0;
          if (hlumi) lumi = hlumi->GetBinContent(1);
          double lumi0 = 0;
          if (hlumi0) lumi0 = hlumi0->GetBinContent(1);
          if (htimedep && lumi && lumi0) {
            htimedep->Scale(lumi / lumi0);
          }

          // Find proper pT range and fit
          double minpt = 0.;
          double maxpt = 6500.;
          if (hsel) {
            for (int i = 1; i != hsel->GetNbinsX()+1; ++i) {
              if (hsel->GetBinContent(i)!=0 &&
                  hsel->GetBinLowEdge(i)>=_jp_xmin57) {
                if (minpt<20) minpt = hsel->GetBinLowEdge(i);
                maxpt = hsel->GetBinLowEdge(i+1);
              }
            }
          }
          TF1 *ftmp = new TF1("ftmp","[0]",minpt,maxpt);
          ftmp->SetParameter(0,1);
          if (htimedep && htimedep->Integral()>0) htimedep->Fit(ftmp,"QRN");

          if (htimedep && ftmp->GetParameter(0)>0)
            ktime = 1./ftmp->GetParameter(0);

          if (htimedep) {
            outdir->cd();
            htimefit = (TH1D*)hsel->Clone("htimefit");
            hpt_withtimedep = (TH1D*)h->Clone("hpt_withtimedep");

            for (int i = 1; i != htimefit->GetNbinsX()+1; ++i) {

              if (hsel->GetBinContent(i)!=0) {
                htimefit->SetBinContent(i, ftmp->GetParameter(0));
                htimefit->SetBinError(i, ftmp->GetParError(0));
              }

              // Calculate with time dependence here to add ktime fit error
              hpt_withtimedep->SetBinContent(i, hpt_notimedep->GetBinContent(i)
                                             * htimefit->GetBinContent(i));
              double err1 = hpt_notimedep->GetBinError(i)
                / hpt_notimedep->GetBinContent(i);
              double err2 = htimefit->GetBinError(i)
                / htimefit->GetBinContent(i);
              hpt_withtimedep->SetBinError(i, hpt_notimedep->GetBinContent(i)
                                           * sqrt(pow(err1,2) + pow(err2,2)));
            }
          }
        } // dotimedep


        if (!(hpt->GetNbinsX()==peff->GetNbinsX() || isoth || isgen) ||
            !(hpt->GetNbinsX()==hlumi->GetNbinsX() || isoth || isgen)) {
          cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
               << " Nbins=" << hpt->GetNbinsX() << endl << flush;
          assert(hpt->GetNbinsX()==peff->GetNbinsX() || isoth);
          assert(hpt->GetNbinsX()==hlumi->GetNbinsX() || isoth);
        }

        for (int i = 1; i != hpt->GetNbinsX()+1; ++i) {

          // Normalization for bin width in y, pT
          double norm = hpt->GetBinWidth(i) * etawid;
          double trigeff = 1.;
          double pt = hpt->GetBinCenter(i);
          // Normalization for all the common efficiencies
          if (peff->GetBinContent(i)!=0 && !isgen)
            norm *= peff->GetBinContent(i);
          // Test MC-based normalization for trigger efficiency
          if (dotrigeff && htrigeff && _jp_dotrigeff) {
            if (htrigeff->GetBinContent(i)!=0) {
              trigeff = min(1.,max(0.,htrigeff->GetBinContent(i)));
              if (_jp_dotrigefflowptonly && pt>=114) trigeff = 1;
              norm *= trigeff;
            }
          }

          // Normalization for luminosity
          if (hlumi->GetBinContent(i)!=0 && !isoth && !isgen && !ispre)
            norm *= hlumi->GetBinContent(i);
          if (hlumi->GetBinContent(1)!=0 && isoth && !isgen && !ispre)
            norm *= hlumi->GetBinContent(1);
          if (hlumi0->GetBinContent(1)!=0 && !isoth && !isgen && ispre)
            norm *= hlumi0->GetBinContent(1);

          // Fix luminosity from .csv VTX to lumiCalc vdM
          if (!_nh_mc) norm *= _lumiscale;
          // Scale normalization for jackknife
          if (isjk) norm *= 0.9;

          if (_nh_mc && _jp_pthatbins) norm *= 1.;
          if (_nh_mc && !_jp_pthatbins) {
            norm /= 2500.; //(xsecw / (sumw * adhocw) ); // equals 2551.;
          }

          // Correct data for time-dependence
          double norm_notime = norm;
          if (dotimedep && htimedep && _jp_dotimedep) {
            norm *= ktime;
          }

          if (!(peff->GetBinContent(i)!=0||hpt->GetBinContent(i)==0 || isgen ||
                iscalo || ispf5 || isoth || hpt->GetBinCenter(i)<_jp_recopt
                || hpt->GetBinCenter(i)*cosh(etamid)>3500.)) {
            cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
                 << " pt=" << hpt->GetBinCenter(i)
                 << " etamid = " << etamid << endl << flush;
            assert(peff->GetBinContent(i)!=0||hpt->GetBinContent(i)==0||isgen||
                   hpt->GetBinCenter(i)<_jp_recopt);
          }
          /*
          if (!(hlumi->GetBinContent(i)!=0 || hpt->GetBinContent(i)==0
                || isoth || isgen || hpt->GetBinCenter(i)<_jp_recopt)) {
            cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
                 << " pt=" << hpt->GetBinCenter(i) << endl << flush;
            assert(hlumi->GetBinContent(i)!=0 || hpt->GetBinContent(i)==0
                   || isoth || hpt->GetBinCenter(i)<_jp_recopt);
          }
          */

          assert(norm!=0);
          hpt->SetBinContent(i, hpt->GetBinContent(i) / norm);
          hpt->SetBinError(i, hpt->GetBinError(i) / norm);
          if (hpt_notrigeff) {
            hpt_notrigeff->SetBinContent(i, hpt_notrigeff->GetBinContent(i)
                                         / norm * trigeff);
            hpt_notrigeff->SetBinError(i, hpt_notrigeff->GetBinError(i)
                                       / norm * trigeff);
          }
          if (hpt_notimedep) {
            hpt_notimedep->SetBinContent(i, hpt_notimedep->GetBinContent(i)
                                         / norm_notime);
            hpt_notimedep->SetBinError(i, hpt_notimedep->GetBinError(i)
                                       / norm_notime);
          }
          if (hpt_withtimedep) { // ktime already applied => use norm_notime
            hpt_withtimedep->SetBinContent(i, hpt_withtimedep->GetBinContent(i)
                                           / norm_notime);
            hpt_withtimedep->SetBinError(i, hpt_withtimedep->GetBinError(i)
                                         / norm_notime);
          }
        } // for i

      } // hpt

      dir->cd();
    } // inherits from TH1

  } // while key

  curdir->cd();
} // recurseFile
Esempio n. 8
0
void makeVictorTemplates::ScanChain (TChain* chain){

  
  int npass = 0;
  bookHistos();
  
  TObjArray *listOfFiles = chain->GetListOfFiles();

  unsigned int nEventsChain = 0;

  unsigned int nEvents = chain->GetEntries();
  nEventsChain = nEvents;
  unsigned int nEventsTotal = 0;

  if(debug) cout << "Begin file loop" << endl;

  // file loop
  TIter fileIter(listOfFiles);

  TFile* currentFile = 0;

  while ((currentFile = (TFile*)fileIter.Next())){

    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("jetTree");
    //cms2.Init(tree);
    setBranches(tree);

    // event loop
    //unsigned int nEvents = tree->GetEntries();
    nEvents = tree->GetEntries();

    for (unsigned int event = 0 ; event < nEvents; ++event){
   
      tree->GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEventsChain*0.01));
          fflush(stdout);
        }
      }

      if( nJets_ < 2 )        continue;
      if( maxjetpt_ < 30. )   continue;

      int iJetBin          = getJetBin( nJets_ );
      int iSumJetPtBin     = getSumJetPtBin( sumJetPt_ );
      //int iBosonPtBin      = getBosonPtBin( etg_ );
      int iVtxBin          = getVtxBin( nvtx_ );
      float templateWeight = 1;//jet15U_L1Prescale_ * jet15U_HLTPrescale_;

      //fill templates binned by njets, sumjetpt, boson pt        
      //fillUnderOverFlow( tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  tcmet_    , templateWeight );
      //fillUnderOverFlow( pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ]    ,  pfmet_    , templateWeight );
      
      //fill templates binned by njets, sumjetpt, nVtx
      fillUnderOverFlow( tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ]    ,  pfmet_    , templateWeight );
    
      //fill templates binned by njets, sumjetpt
      fillUnderOverFlow( tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
      fillUnderOverFlow( pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );
      
      ++npass;

      int iTrigBin = -1;

      if( firedJet15U_ == 1 ){
        
        templateWeight = jet15U_L1Prescale_ * jet15U_HLTPrescale_;
        iTrigBin = 0;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt15 , maxjetpt_ , templateWeight );
      }

      if( firedJet30U_ == 1 ){
        
        templateWeight = jet30U_L1Prescale_ * jet30U_HLTPrescale_;
        iTrigBin = 1;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt30 , maxjetpt_ , templateWeight );
      }
      
      if( firedJet50U_ == 1 ){
        
        templateWeight = jet50U_L1Prescale_ * jet50U_HLTPrescale_;
        iTrigBin = 2;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt50 , maxjetpt_ , templateWeight );
      }

      if( firedJet100U_ == 1 ){
        
        templateWeight = jet100U_L1Prescale_ * jet100U_HLTPrescale_;
        iTrigBin = 3;

        fillUnderOverFlow( tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  tcmet_    , templateWeight );
        fillUnderOverFlow( pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ]    ,  pfmet_    , templateWeight );

        fillUnderOverFlow( hleadJetPt100 , maxjetpt_ , templateWeight );
      }


    } // end loop over events
  } // end loop over files
      
  cout << npass << " events passing selection" << endl;
  if (nEventsChain != nEventsTotal)
    std::cout << "ERROR: number of events from files is not equal to total number of events" << std::endl;
 

    
    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iBosonPtBin = 0 ; iBosonPtBin < nBosonPtBins ; iBosonPtBin++ ){
          
          float scale = tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate[ iJetBin ][ iSumJetPtBin ][ iBosonPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        for( int iVtxBin = 0 ; iVtxBin < nVtxBins ; iVtxBin++ ){
          
          float scale = tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_njets_ht_nvtx[ iJetBin ][ iSumJetPtBin ][ iVtxBin ] -> Scale ( 1. / scale );
          
        }
      }
    }

    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        
        float scale = tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  tcmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
      
        scale = pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Integral();
        if( scale > 0 )  pfmetTemplate_combined[ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
        
        
      }
    }

    for( int iTrigBin = 0 ; iTrigBin < 4 ; ++iTrigBin ){
      for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
        for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
          
          float scale = tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  tcmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
          scale = pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Integral();
          if( scale > 0 )  pfmetTemplate_qcd[ iTrigBin ][ iJetBin ][ iSumJetPtBin ] -> Scale ( 1. / scale );
          
        }
      }
    }


    // make histos rootfile
    TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
    rootdir->cd();
    saveHist("qcd-mini-ntuple/victor_templates_2.root");
    deleteHistos();
  
} // end ScanChain
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
	RooMsgService::instance().setSilentMode(true);


  
	system(Form("mkdir -p %s",outdir_.c_str()));

	vector<string> procs;
	split(infilenames_,infilenamesStr_,boost::is_any_of(","));
  
   TPython::Exec("import os,imp,re");
   for (unsigned int i =0 ; i<infilenames_.size() ; i++){
     TFile *infile =  TFile::Open(infilenames_[i].c_str());
	   string outname  =(string) TPython::Eval(Form("'%s'.split(\"/\")[-1].replace('root','_reduced.root')",infilenames_[i].c_str())); 
     TFile *outfile = TFile::Open(outname.c_str(),"RECREATE") ;
    TDirectory* saveDir = outfile->mkdir("tagsDumper");
    saveDir->cd();

    RooWorkspace *inWS = (RooWorkspace*) infile->Get("tagsDumper/cms_hgg_13TeV");
    RooRealVar *intLumi = (RooRealVar*)inWS->var("IntLumi");
    RooWorkspace *outWS = new RooWorkspace("cms_hgg_13TeV");
    outWS->import(*intLumi);
    std::list<RooAbsData*> data =  (inWS->allData()) ;
    std::cout <<" [INFO] Reading WS dataset contents: "<< std::endl;
        for (std::list<RooAbsData*>::const_iterator iterator = data.begin(), end = data.end(); iterator != end; ++iterator )  {
              RooDataSet *dataset = dynamic_cast<RooDataSet *>( *iterator );
              if (dataset) {
              RooDataSet *datasetReduced = (RooDataSet*) dataset->emptyClone(dataset->GetName(),dataset->GetName());
                TRandom3 r;
                r.Rndm();
                double x[dataset->numEntries()];
                r.RndmArray(dataset->numEntries(),x);
                int desiredEntries = floor(0.5+ dataset->numEntries()*fraction_);
                int modFraction = floor(0.5+ 1/fraction_);
                int finalEventCount=0;
                for (int j =0; j < dataset->numEntries() ; j++){
                    if( j%modFraction==0){
                      finalEventCount++;
                    }
                 }
                float average_weight= dataset->sumEntries()/finalEventCount;
                for (int j =0; j < dataset->numEntries() ; j++){
                    if( j%modFraction==0){
                    dataset->get(j);
                    datasetReduced->add(*(dataset->get(j)),average_weight);
                    }
                }
              float entriesIN =dataset->sumEntries();
              float entriesOUT =datasetReduced->sumEntries();
           if(verbose_){
              std::cout << "Original dataset " << *dataset <<std::endl;
              std::cout << "Reduced       dataset " << *datasetReduced <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "fraction (obs) : " << entriesOUT/entriesIN << std::endl;
              std::cout << "fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datasetReduced);
                }
                
             RooDataHist *datahist = dynamic_cast<RooDataHist *>( *iterator );

              if (datahist) {
              RooDataHist *datahistOUT = (RooDataHist*) datahist->emptyClone(datahist->GetName(),datahist->GetName());
                TRandom3 r;
                r.Rndm();
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistOUT->add(*(datahist->get(j)),datahist->weight());
                }
              float w =datahistOUT->sumEntries();
              float z =datahist->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "Reduced  datahist " << *datahistOUT<<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : " << w/(z) <<std::endl;
              std::cout << "WH fraction (exp) : " << fraction_ << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistOUT);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
Esempio n. 10
0
File: getResv.C Progetto: XuQiao/HI
void getResv(){

	double theta[ntheta];
	TFile *f[nFileAll];
		
	for(int itheta=0;itheta<ntheta;itheta++)
        	theta[itheta]=itheta*TMath::Pi()/ntheta/nn;


	ofstream fstrv;
	if(isSum)fstrv.open("v.txt");
	else fstrv.open("v_2.txt");
	TVectorD totmult[nbin], totpt[nbin];	TVectorD Nevent, totmultall;
	TVectorD V_int;
	TVectorD* V_mean;
	TVectorD* V[nbin]; TVectorD* chi[nbin];
	TVectorD* dDRe[nbin]; TVectorD* dDIm[nbin];
	TVectorD* dNRe[nbin][ntheta]; TVectorD* dNIm[nbin][ntheta];
	TComplex dD[nbin][ntheta], dN[nbin][ntheta][nptv];
	TVectorD avgmult[nbin];	TVectorD avgmultall;
	TVectorD avgpt[nbin];
	TVectorD v[nbin][ntheta],vmean[nbin],deltav[nbin][ntheta],deltavmean[nbin];
	if(isSum)	TFile *infile = TFile::Open("mergedV_Sum.root");
	else	TFile *infile = TFile::Open("mergedV_Prod.root");
	Nevent.ResizeTo(nbin);	Nevent.Zero();
	totmultall.ResizeTo(nbin);	totmultall.Zero();
	avgmultall.ResizeTo(nbin);
	V_int.ResizeTo(nbin);	V_int.Zero();
	for(int ibin=0;ibin<nbin;ibin++){
		totmult[ibin].ResizeTo(nptv);	totmult[ibin].Zero();
		avgmult[ibin].ResizeTo(nptv);	avgpt[ibin].ResizeTo(nptv);
		totpt[ibin].ResizeTo(nptv);	totpt[ibin].Zero();
		vmean[ibin].ResizeTo(nptv);	deltavmean[ibin].ResizeTo(nptv);
		V[ibin] = (TVectorD*) infile->Get(Form("D_%d/D_0/V",ibin));
		chi[ibin] = (TVectorD*) infile->Get(Form("D_%d/chi",ibin));
		V_mean = (TVectorD*) infile->Get(Form("D_%d/Vmean",ibin));
		for(int itheta=0;itheta<ntheta;itheta++){
			v[ibin][itheta].ResizeTo(nptv);	deltav[ibin][itheta].ResizeTo(nptv);
			dD[ibin][itheta]=0;
			for(int iptbin=0;iptbin<nptv;iptbin++){
				dN[ibin][itheta][iptbin]=0;
			}
		}
	}

        for(int ifile=0; ifile<nFileAll; ifile++){
	        if(isSum) f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/theta8/pPbDataV205m150/Anav_Prod_%d.root",ifile));
	        else f[ifile] = TFile::Open(Form("/scratch/xuq7/flow/pbsjoboutput/theta8/pPbDataV205m150/Anav_Prod2_%d.root",ifile));
		TVectorD* Nevent_t = (TVectorD*)f[ifile]->Get("Nevent");	
		TVectorD* totmultall_t = (TVectorD*)f[ifile]->Get("totmultall");
		for(int ibin=0;ibin<nbin;ibin++){
			TVectorD* totmult_t = (TVectorD*)f[ifile]->Get(Form("totmult_%d",ibin));
			TVectorD* totpt_t = (TVectorD*)f[ifile]->Get(Form("totpt_%d",ibin));
			dDRe[ibin] = (TVectorD*)f[ifile]->Get(Form("dDRe_%d",ibin));
			dDIm[ibin] = (TVectorD*)f[ifile]->Get(Form("dDIm_%d",ibin));
			Nevent[ibin]+=(*Nevent_t)[ibin];
			totmultall[ibin]+=(*totmultall_t)[ibin];
			for(int iptbin=0;iptbin<nptv;iptbin++){
				totmult[ibin][iptbin]+=(*totmult_t)[iptbin];
				totpt[ibin][iptbin]+=(*totpt_t)[iptbin];
			}
			for(int itheta=0;itheta<ntheta;itheta++){
				dNRe[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNRe_%d_%d",ibin,itheta));
				dNIm[ibin][itheta] = (TVectorD*)f[ifile]->Get(Form("dNIm_%d_%d",ibin,itheta));
				dD[ibin][itheta]+=TComplex((*dDRe[ibin])[itheta],(*dDIm[ibin])[itheta]);
				for(int iptbin=0;iptbin<nptv;iptbin++)
					dN[ibin][itheta][iptbin]+=TComplex((*dNRe[ibin][itheta])[iptbin],(*dNIm[ibin][itheta])[iptbin]);
			}
		}
	f[ifile]->Close();
	}

	for(int ibin=0;ibin<nbin;ibin++)
		for(int itheta=0;itheta<ntheta;itheta++)
			dD[ibin][itheta]*=TComplex::Power(TComplex::I(),mm-1)/(Double_t)Nevent[ibin];
	
	for(int ibin=0;ibin<nbin;ibin++){
			avgmultall[ibin]=1.0*totmultall[ibin]/Nevent[ibin];
		for(int iptbin=0;iptbin<nptv; iptbin++){
			vmean[ibin][iptbin]=0;
			deltavmean[ibin][iptbin]=0;
			avgmult[ibin][iptbin]=1.0*totmult[ibin][iptbin]/Nevent[ibin];
			avgpt[ibin][iptbin]=1.0*totpt[ibin][iptbin]/totmult[ibin][iptbin];
			for(int itheta=0;itheta<ntheta;itheta++){
				dN[ibin][itheta][iptbin]/=totmult[ibin][iptbin];
				TComplex Res=dN[ibin][itheta][iptbin]/dD[ibin][itheta];
				v[ibin][itheta][iptbin]=(*V[ibin])[itheta]*avgmultall[ibin]*TMath::BesselJ1(j01)/Besselj01(mm)*Res.Re();
				vmean[ibin][iptbin]+=v[ibin][itheta][iptbin];
				deltav[ibin][itheta][iptbin]=TMath::Cos(mm*nn*theta[itheta])/totmult[ibin][iptbin]*(TMath::Exp(j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Sin(nn*theta[itheta]/2.))+TMath::Power(-1,mm)*TMath::Exp(-j01*j01/2./(*chi[ibin])[0]/(*chi[ibin])[0]*TMath::Cos(nn*theta[itheta]))*TMath::BesselJ0(2*j01*TMath::Cos(nn*theta[itheta]/2.)));
				deltavmean[ibin][iptbin]+=deltav[ibin][itheta][iptbin];
			//	fstrv<<itheta<<"\t"<<v[ibin][itheta][iptbin]<<"\t"<<deltav[ibin][itheta][iptbin]<<endl;
			}
		deltavmean[ibin][iptbin]=TMath::Sqrt(deltavmean[ibin][iptbin])/2./Besselj01(mm);
		//fstrv<<endl;
		vmean[ibin][iptbin]/=ntheta;
		deltavmean[ibin][iptbin]/=ntheta;
		fstrv<<ptbinv[iptbin]<<"-"<<ptbinv[iptbin+1]<<"\t"<<vmean[ibin][iptbin]<<"\t"<<deltavmean[ibin][iptbin]<<endl;
		V_int[ibin]+=vmean[ibin][iptbin]*totmult[ibin][iptbin];
		}
		V_int[ibin]/=totmultall[ibin];
		fstrv<<endl<<"V ref="<<(*V_mean)[ibin]<<"\t"<<"V int="<<V_int[ibin]<<endl;
	}
	
	if(isSum)TFile *fout = new TFile("mergedv_Prod.root","Recreate");
	else TFile *fout = new TFile("mergedv_Prod2.root","Recreate");
	for(ibin=0;ibin<nbin;ibin++){
	Nevent.Write("Nevent");
	V_int.Write("V_int");
	TDirectory *dir = fout->mkdir(Form("D_%d",ibin));
	dir->cd();
	avgpt[ibin].Write("avgpt");
	totmult[ibin].Write("totmult");
	vmean[ibin].Write("vmean");
	deltavmean[ibin].Write("deltavmean");
	}
	
	infile->Close();
	fout->Close();
	
}
Esempio n. 11
0
void makeVictorTemplates::bookHistos(){

  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();

  hleadJetPt15  = new TH1F("hleadJetPt15", "",100,0,1000);
  hleadJetPt30  = new TH1F("hleadJetPt30", "",100,0,1000);
  hleadJetPt50  = new TH1F("hleadJetPt50", "",100,0,1000);
  hleadJetPt100 = new TH1F("hleadJetPt100","",100,0,1000);

  int maxmet = 200;

  for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
    for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
      for( int iBosonPtBin = 0 ; iBosonPtBin < nBosonPtBins ; iBosonPtBin++ ){
        
        tcmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin] = new TH1F(Form("tcmetTemplate_%i_%i_%i",iJetBin,iSumJetPtBin,iBosonPtBin),
                                                                     Form("%s, %s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str(),
                                                                          bosonPtString(iBosonPtBin).c_str()),maxmet,0,maxmet);
        
        pfmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin] = new TH1F(Form("pfmetTemplate_%i_%i_%i",iJetBin,iSumJetPtBin,iBosonPtBin),
                                                                     Form("%s, %s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str(),
                                                                          bosonPtString(iBosonPtBin).c_str()),maxmet,0,maxmet);
        
        tcmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin]->Sumw2();
        pfmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin]->Sumw2();
        
        tcmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin]->GetXaxis()->SetTitle("tcmet (GeV)");
        pfmetTemplate[iJetBin][iSumJetPtBin][iBosonPtBin]->GetXaxis()->SetTitle("pfmet (GeV)");          
        
      }
    }
  }

  for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
    for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
      for( int iVtxBin = 0 ; iVtxBin < nVtxBins ; iVtxBin++ ){
        
        tcmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin] = new TH1F(Form("tcmetTemplate_njets_ht_nvtx_%i_%i_%i",iJetBin,iSumJetPtBin,iVtxBin),
                                                                               Form("%s, %s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str(),
                                                                                    nVTXString(iVtxBin).c_str()),maxmet,0,maxmet);
                
        pfmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin] = new TH1F(Form("pfmetTemplate_njets_ht_nvtx_%i_%i_%i",iJetBin,iSumJetPtBin,iVtxBin),
                                                                               Form("%s, %s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str(),
                                                                                    nVTXString(iVtxBin).c_str()),maxmet,0,maxmet);
        
        tcmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin]->Sumw2();
        pfmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin]->Sumw2();
        
        tcmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin]->GetXaxis()->SetTitle("tcmet (GeV)");
        pfmetTemplate_njets_ht_nvtx[iJetBin][iSumJetPtBin][iVtxBin]->GetXaxis()->SetTitle("pfmet (GeV)");          
        
      }
    }
  }
  
  
  for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
    for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
      
      
      tcmetTemplate_combined[iJetBin][iSumJetPtBin] = new TH1F(Form("tcmetTemplate_combined_%i_%i",iJetBin,iSumJetPtBin),
                                                               Form("%s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str()),maxmet,0,maxmet);
      
      pfmetTemplate_combined[iJetBin][iSumJetPtBin] = new TH1F(Form("pfmetTemplate_combined_%i_%i",iJetBin,iSumJetPtBin),
                                                               Form("%s, %s",jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str()),maxmet,0,maxmet);
      
      tcmetTemplate_combined[iJetBin][iSumJetPtBin]->Sumw2();
      pfmetTemplate_combined[iJetBin][iSumJetPtBin]->Sumw2();
      
      tcmetTemplate_combined[iJetBin][iSumJetPtBin]->GetXaxis()->SetTitle("tcmet (GeV)");
      pfmetTemplate_combined[iJetBin][iSumJetPtBin]->GetXaxis()->SetTitle("pfmet (GeV)");          
      
    }
  }
  
  char* trigName[4]={"15U","30U","50U","100U"};

  for( int iTrigBin = 0 ; iTrigBin < 4 ; iTrigBin++ ){
    for( int iJetBin = 0 ; iJetBin < nJetBins ; iJetBin++ ){
      for( int iSumJetPtBin = 0 ; iSumJetPtBin < nSumJetPtBins ; iSumJetPtBin++ ){
        
        
        tcmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin] = new TH1F(Form("tcmetTemplate_qcd_%i_%i_%i",iTrigBin,iJetBin,iSumJetPtBin),
                                                                      Form("%s, %s, %s",trigName[iTrigBin],
                                                                           jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str()),maxmet,0,maxmet);

        pfmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin] = new TH1F(Form("pfmetTemplate_qcd_%i_%i_%i",iTrigBin,iJetBin,iSumJetPtBin),
                                                                      Form("%s, %s, %s",trigName[iTrigBin],
                                                                           jetString(iJetBin).c_str(),sumJetPtString(iSumJetPtBin).c_str()),maxmet,0,maxmet);
        
 
        
        tcmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin]->Sumw2();
        pfmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin]->Sumw2();
        
        tcmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin]->GetXaxis()->SetTitle("tcmet (GeV)");
        pfmetTemplate_qcd[iTrigBin][iJetBin][iSumJetPtBin]->GetXaxis()->SetTitle("pfmet (GeV)");          
        
      }
    }
  }

}
Esempio n. 12
0
void plotMergedHisto(TString outputFileName = "plotMergedOutput.root") {

  // general root setting
  gROOT->Reset(); 
  //  gROOT->SetBatch(kTRUE);
  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(0.1);
  gStyle->SetLabelSize(0.04,"X");
  gStyle->SetLabelSize(0.04,"Y");
  gStyle->SetPadBorderMode(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0);

  // ************************************************************
  std::vector<TString> sgnFileSuffix;
  sgnFileSuffix.push_back("VBFH160ZZ");
  sgnFileSuffix.push_back("VBFH200ZZ");
  sgnFileSuffix.push_back("VBFH400ZZ");
  sgnFileSuffix.push_back("VBFH800ZZ");
  std::vector<TString> bkgZZFileSuffix;
  bkgZZFileSuffix.push_back("ZZ0Jets");
  bkgZZFileSuffix.push_back("ZZ1Jets");
  bkgZZFileSuffix.push_back("ZZ2Jets");
  std::vector<TString> bkgZbbFileSuffix;
  bkgZbbFileSuffix.push_back("Zbb0Jets");
  bkgZbbFileSuffix.push_back("Zbb1Jets");
  bkgZbbFileSuffix.push_back("Zbb2Jets");
  // ************************************************************
  // List of Files
  TList * sgnFileList    = new TList();
  std::vector<TString>::const_iterator sgnFileSuffix_itr = sgnFileSuffix.begin();
  for ( ; sgnFileSuffix_itr != sgnFileSuffix.end(); ++sgnFileSuffix_itr )
    sgnFileList->Add( TFile::Open(*sgnFileSuffix_itr+"output.root"  ) );
  TList * bkgZZFileList  = new TList();
  std::vector<TString>::const_iterator bkgZZFileSuffix_itr = bkgZZFileSuffix.begin();
  for ( ; bkgZZFileSuffix_itr != bkgZZFileSuffix.end(); ++bkgZZFileSuffix_itr )
    bkgZZFileList->Add( TFile::Open(*bkgZZFileSuffix_itr+"output.root"  ) );
  TList * bkgZbbFileList = new TList();
  std::vector<TString>::const_iterator bkgZbbFileSuffix_itr = bkgZbbFileSuffix.begin();
  for ( ; bkgZbbFileSuffix_itr != bkgZbbFileSuffix.end(); ++bkgZbbFileSuffix_itr )
    bkgZbbFileList->Add( TFile::Open(*bkgZbbFileSuffix_itr+"output.root"  ) );
    // ************************************************************
  // List of xSec (in pb)
  // stored in 
  // "HiggsAnalysis/VBFHiggsToZZto2l2bs/interface/xSecLO.h"
  // "HiggsAnalysis/VBFHiggsToZZto2l2bs/interface/xSecNLO.h"
  // "HiggsAnalysis/VBFHiggsToZZto2l2bs/interface/BR.h"
  std::vector<double> sgnCrossSections;
  std::vector<double> bkgZZCrossSections;
  std::vector<double> bkgZbbCrossSections;
  sgnCrossSections.push_back(1000*xSec_VBFH160_*BR_H160ZZ_);
  sgnCrossSections.push_back(1000*xSec_VBFH200_*BR_H200ZZ_);
  sgnCrossSections.push_back(1000*xSec_VBFH400_*BR_H400ZZ_);
  sgnCrossSections.push_back(1000*xSec_VBFH800_*BR_H800ZZ_);
  bkgZZCrossSections.push_back(1000*xSec_ZZ0Jets_);
  bkgZZCrossSections.push_back(1000*xSec_ZZ1Jets_);
  bkgZZCrossSections.push_back(1000*xSec_ZZ2Jets_);
  bkgZbbCrossSections.push_back(1000*xSec_Zbb0Jets_);
  bkgZbbCrossSections.push_back(1000*xSec_Zbb1Jets_);
  bkgZbbCrossSections.push_back(1000*xSec_Zbb2Jets_);
  // *************************************************************************
  std::vector<TString> varNameVector;
  varNameVector.push_back("recZllMass_leptonicZcutsAFTERZdileptonMass"      );
  varNameVector.push_back("recZllMass_leptonicZcutsAFTERZleptonDeltaR"      );
  varNameVector.push_back("recZllDeltaR"                                    );
  varNameVector.push_back("recJetsInvMass"                                  );
  varNameVector.push_back("recZjjMass_hadronicZcutsAFTERZdijetMass"         );
  varNameVector.push_back("recZjjMass_hadronicZcutsAFTERZjetDeltaR"         );
  varNameVector.push_back("recZjjDeltaR"                                    );
  varNameVector.push_back("forwardDiJetMass"                                );
  varNameVector.push_back("recFWDjj_hadronicZcutsAFTERjetDeltaR"            );
  varNameVector.push_back("recZllShiftedEta"                                );
  varNameVector.push_back("recZleptonsShitedEta_hadronicZcutsAFTERjetDeltaR");
  varNameVector.push_back("pTbalance"                                       );
  varNameVector.push_back("recFWDjjPtBalance_hadronicZcutsAFTERjetDeltaR"   );
  varNameVector.push_back("recHZZdeltaR"                                    );
  varNameVector.push_back("recHZZdeltaR_FWDcutsAFTERpTbalance"              );
  varNameVector.push_back("recHlljj"                                        );
  varNameVector.push_back("recHlljj_final"                                  );
  varNameVector.push_back("recHlljj_forwardDiJetMass"                       );
  // *************************************************************************

  int indexSample = 0;
  std::vector<TH1*> sgnEventsNumberTH1vector;
  if (sgnFileSuffix.size() != 0) {
    findObj( sgnEventsNumberTH1vector, 
	     sgnFileList, 
	     "eventsNumber", 
	     &sgnFileSuffix
	     );
    indexSample = 0;
    std::vector<TH1*>::const_iterator sgnEventsNumberTH1vector_itr = sgnEventsNumberTH1vector.begin();  
    for ( ; sgnEventsNumberTH1vector_itr != sgnEventsNumberTH1vector.end(); ++sgnEventsNumberTH1vector_itr,
	    indexSample++) { 
      double sampleEvents = (*sgnEventsNumberTH1vector_itr)->GetMaximum(); 
      if(sampleEvents!=0.) sgnCrossSections[indexSample] = sgnCrossSections[indexSample]/sampleEvents;
    }
  }
  std::vector<TH1*> bkgZZEventsNumberTH1vector;
  findObj( bkgZZEventsNumberTH1vector, 
	   bkgZZFileList, 
	   "eventsNumber", 
	   &bkgZZFileSuffix
	   );
  std::vector<TH1*>::const_iterator bkgZZEventsNumberTH1vector_itr = bkgZZEventsNumberTH1vector.begin();  
  indexSample = 0;
  for ( ; bkgZZEventsNumberTH1vector_itr != bkgZZEventsNumberTH1vector.end(); ++bkgZZEventsNumberTH1vector_itr,
	                                                                      indexSample++) { 
    double sampleEvents = (*bkgZZEventsNumberTH1vector_itr)->GetMaximum();
    bkgZZCrossSections[indexSample] = bkgZZCrossSections[indexSample]/sampleEvents;
  }
  std::vector<TH1*> bkgZbbEventsNumberTH1vector;
  findObj( bkgZbbEventsNumberTH1vector, 
	   bkgZbbFileList, 
	   "eventsNumber", 
	   &bkgZbbFileSuffix
	   );
  std::vector<TH1*>::const_iterator bkgZbbEventsNumberTH1vector_itr = bkgZbbEventsNumberTH1vector.begin();  
  indexSample = 0;
  for ( ; bkgZbbEventsNumberTH1vector_itr != bkgZbbEventsNumberTH1vector.end(); ++bkgZbbEventsNumberTH1vector_itr,
	                                                                        indexSample++) { 
    double sampleEvents = (*bkgZbbEventsNumberTH1vector_itr)->GetMaximum();
    bkgZbbCrossSections[indexSample] = bkgZbbCrossSections[indexSample]/sampleEvents;
  }


  TFile * outputFile = TFile::Open( outputFileName, "RECREATE" );

  std::vector<TString>::const_iterator varNameVector_itr = varNameVector.begin();
  for ( ; varNameVector_itr != varNameVector.end(); ++varNameVector_itr ) {
    std::vector<TH1*> TH1vector;
    std::vector<TH1*> bkgZZTH1vector;
    std::vector<TH1*> bkgZbbTH1vector;
    findObj( TH1vector, 
	     sgnFileList, 
	     *varNameVector_itr, 
	     &sgnFileSuffix,
	     "TH1",
	     &sgnCrossSections
	     );
    findObj( bkgZZTH1vector, 
	     bkgZZFileList, 
	     *varNameVector_itr, 
	     &bkgZZFileSuffix,
	     "TH1",
	     &bkgZZCrossSections
	     );
    findObj( bkgZbbTH1vector, 
	     bkgZbbFileList, 
	     *varNameVector_itr, 
	     &bkgZbbFileSuffix,
	     "TH1",
	     &bkgZbbCrossSections
	     );

    //    TH1vector.push_back(mergeObj((*varNameVector_itr)+"_ZZNjets", bkgZZTH1vector, &bkgZZCrossSections, "kTRUE","kTRUE"));
    //    TH1vector.push_back(mergeObj((*varNameVector_itr)+"_ZbbNjets",bkgZbbTH1vector,&bkgZbbCrossSections,"kTRUE","kTRUE"));
    TH1vector.push_back(mergeObj((*varNameVector_itr)+"_ZZNjets", bkgZZTH1vector));
    TH1vector.push_back(mergeObj((*varNameVector_itr)+"_ZbbNjets",bkgZbbTH1vector));

    std::cout << "TH1vector.size(): " << TH1vector.size() << std::endl;

    // THStackLegend histogram
    TString Stack( "Stack_" );
    THStackLegend<TH1> * StackLegend_ = new THStackLegend<TH1>( *varNameVector_itr, 0.6,0.68,0.98,0.97 );

    outputFile->cd();
    TDirectory * directory = outputFile->mkdir( *varNameVector_itr, *varNameVector_itr );
    directory->cd();
    std::vector<TH1*>::const_iterator TH1vector_itr = TH1vector.begin();
    for ( ; TH1vector_itr != TH1vector.end(); ++TH1vector_itr ) {
      TH1 * histo = (TH1*)(*TH1vector_itr)->Clone();
      TString histoName = histo->GetName();
      TString sample = histoName.Remove(0,(*varNameVector_itr).Length()+1);
      FashionAttributedHisto<TH1D> * dressedHisto;
      bool dressed = false;
      if (      sample.Contains("VBFH160ZZ") ) { dressedHisto = new H160<TH1D>((TH1D*)histo);       dressed = true; }
      else if ( sample.Contains("VBFH200ZZ") ) { dressedHisto = new H200<TH1D>((TH1D*)histo);	    dressed = true; }
      else if ( sample.Contains("VBFH400ZZ") ) { dressedHisto = new H400<TH1D>((TH1D*)histo);	    dressed = true; }
      else if ( sample.Contains("VBFH800ZZ") ) { dressedHisto = new H800<TH1D>((TH1D*)histo);	    dressed = true; }
      else if ( sample.Contains("ZZ" ) && sample.Contains("jets") ) { dressedHisto = new ZZNjets<TH1D>((TH1D*)histo);  dressed = true; }
      else if ( sample.Contains("Zbb") && sample.Contains("jets") ) { dressedHisto = new ZbbNjets<TH1D>((TH1D*)histo); dressed = true; }
      else if ( sample.Contains("WZ" ) && sample.Contains("jets") ) { dressedHisto = new WZNjets<TH1D>((TH1D*)histo);  dressed = true; }
      else if ( sample.Contains("tt" ) && sample.Contains("jets") ) { dressedHisto = new ttNjets<TH1D>((TH1D*)histo);  dressed = true; }
      else dressedHisto = new FashionAttributedHisto<TH1D>((TH1D*)histo);
      char nev[50];
      sprintf(nev,sample+": %.2f",dressedHisto->Integral());
      StackLegend_->Add(dressedHisto,nev,false,"lf",false,dressed);
      //      StackLegend_->Add(dressedHisto,sample,false,"fl",false,dressed);

      dressedHisto->Write();
    }
    StackLegend_->SetLogY();
    StackLegend_->Print("nostack",*varNameVector_itr+"MergedMultiPlot.jpg");
    StackLegend_->Write("nostackhisto");
    StackLegend_->Draw("nostackhisto");
    //    StackLegend_->SavePrimitive(Stack+*varNameVector_itr+".C","nostackhisto");

    //    TH1vector.clear();
    //    bkgZZTH1vector.clear();
    //    bkgZbbTH1vector.clear();
  }

}
Esempio n. 13
0
void SanityCheck() { 
    
    // 
    // Get tree 
    // 
    //TFile *f = TFile::Open("cfA/cfA_QCD_HT-1000ToInf_TuneZ2star_8TeV-madgraph-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1_AODSIM_UCSB2029_v71_f1_1_YWH_Test.root", "READ");
    //TFile *f = TFile::Open("cfA/cfA_JetHT_Run2012D-PromptReco-v1_AOD_UCSB2030_v71_f1_1_fip_Test.root", "READ");
    TFile *f = TFile::Open("cfA/NopT10Cut/cfA_QCD_HT-1000ToInf_TuneZ2star_8TeV-madgraph-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1_AODSIM_UCSB2048_v71_f1_1_DGh_Test.root", "READ");
    //TFile *f = TFile::Open("cfA/NopT10Cut/cfA_JetHT_Run2012D-PromptReco-v1_AOD_UCSB2049_v71_f1000_1_473_Test.root", "READ");
    TDirectory* dir = f->GetDirectory("configurableAnalysis");
    dir->cd();
    TTree *eventB = (TTree*)dir->Get("eventB");
    
    // 
    // set address of variables to read 
    // 

    // event info
    UInt_t   event_ = 0;
    eventB->SetBranchAddress("event", &event_);
    UInt_t   run_ = 0;
    eventB->SetBranchAddress("run", &run_);
    UInt_t   lumiblock_ = 0;
    eventB->SetBranchAddress("lumiblock", &lumiblock_);
    // jets
    vector<float>   *jets_AK5PFclean_px_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_px", &jets_AK5PFclean_px_);
    vector<float>   *jets_AK5PFclean_py_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_py", &jets_AK5PFclean_py_);
    vector<float>   *jets_AK5PFclean_pz_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_pz", &jets_AK5PFclean_pz_);
    vector<float>   *jets_AK5PFclean_energy_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_energy", &jets_AK5PFclean_energy_);
    vector<float>   *jets_AK5PFclean_phi_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_phi", &jets_AK5PFclean_phi_);
    vector<float>   *jets_AK5PFclean_eta_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_eta", &jets_AK5PFclean_eta_);
    vector<float>   *jets_AK5PFclean_rawPt_ = 0;
    eventB->SetBranchAddress("jets_AK5PFclean_rawPt", &jets_AK5PFclean_rawPt_);
    vector<float>   *jets_AK5PF_rawPt_ = 0;
    eventB->SetBranchAddress("jets_AK5PF_rawPt", &jets_AK5PF_rawPt_);
    // fastjets
    vector<float>   *fastjets_AK5PF_px_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_px", &fastjets_AK5PF_px_);
    vector<float>   *fastjets_AK5PF_py_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_py", &fastjets_AK5PF_py_);
    vector<float>   *fastjets_AK5PF_pz_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_pz", &fastjets_AK5PF_pz_);
    vector<float>   *fastjets_AK5PF_energy_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_energy", &fastjets_AK5PF_energy_);
    vector<float>   *fastjets_AK5PF_phi_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_phi", &fastjets_AK5PF_phi_);
    vector<float>   *fastjets_AK5PF_eta_ = 0;
    eventB->SetBranchAddress("fastjets_AK5PF_eta", &fastjets_AK5PF_eta_);
   
    // 
    //  loop over entries
    // 
    Int_t nentries = (Int_t)eventB->GetEntries();
    cout<<"The number of entries is: "<<nentries<<endl;

    TH1F *h1_pT_jets            = new TH1F("h1_pT_jets","h1_pT_jets", 100, 0, 1000);
    TH1F *h1_pT_fastjets        = new TH1F("h1_pT_fastjets","h1_pT_fastjets", 100, 0, 1000);
    TH1F *h1_eta_jets           = new TH1F("h1_eta_jets","h1_eta_jets", 100, -5, 5);
    TH1F *h1_eta_fastjets       = new TH1F("h1_eta_fastjets","h1_eta_fastjets", 100, -5, 5);
    TH1F *h1_phi_jets           = new TH1F("h1_phi_jets","h1_phi_jets", 100, -0.5, 0.5);
    TH1F *h1_phi_fastjets       = new TH1F("h1_phi_fastjets","h1_phi_fastjets", 100, -0.5, 0.5);
    TH1F *h1_njets_jets         = new TH1F("h1_njets_jets","h1_njets_jets", 15, -0.5, 14.5);
    TH1F *h1_njets_fastjets     = new TH1F("h1_njets_fastjets","h1_njets_fastjets", 15, -0.5, 14.5);
    
    TH1F *h1_pT_diff       = new TH1F("h1_pT_diff","h1_pT_diff", 100, -10, 10);
    //TH1F *h1_pT_diff       = new TH1F("h1_pT_diff","h1_pT_diff", 100, -0.5, 0.5);
    TH1F *h1_eta_diff      = new TH1F("h1_eta_diff","h1_eta_diff", 100, -0.1, 0.1);
    TH1F *h1_phi_diff      = new TH1F("h1_phi_diff","h1_phi_diff", 100, -0.1, 0.1);

    // pT threshold for Njets counting
    const float JetpTthres=30;

    // main event loop
    for(int ib = 0; ib<nentries; ib++) {
    //for(int ib = 0; ib<10; ib++) { // DEBUG
       
        if(ib%500==0) cout << "Entry : " << ib << endl; 

        // get entry of an event 
        eventB->GetEntry(ib);
        // 
        // Before matching 
        // 
        // Number of jets 
        int Njets=0;
        for(int ijet=0; ijet<(int)jets_AK5PFclean_rawPt_->size(); ijet++) {
            if(jets_AK5PFclean_rawPt_->at(ijet)>JetpTthres) Njets++;
        }
        int Nfastjets=0;
        for(int ifastjet=0; ifastjet<(int)fastjets_AK5PF_px_->size(); ifastjet++) {
            float pT = TMath::Sqrt( fastjets_AK5PF_px_->at(ifastjet)*fastjets_AK5PF_px_->at(ifastjet)
                                   +fastjets_AK5PF_py_->at(ifastjet)*fastjets_AK5PF_py_->at(ifastjet));
            if(pT>JetpTthres) Nfastjets++; 
        }
        
        // pT
        for(int ifastjet=0; ifastjet<(int)fastjets_AK5PF_px_->size(); ifastjet++) {
            float fastpT = TMath::Sqrt( fastjets_AK5PF_px_->at(ifastjet)*fastjets_AK5PF_px_->at(ifastjet)
                                       +fastjets_AK5PF_py_->at(ifastjet)*fastjets_AK5PF_py_->at(ifastjet));   
                h1_pT_fastjets->Fill( fastpT );
        }
        
        for(int ijet=0; ijet<(int)jets_AK5PFclean_rawPt_->size(); ijet++) {
                h1_pT_jets->Fill( jets_AK5PFclean_rawPt_->at(ijet) );
        }
        
        //
        // After matching 
        //
        for(int ifastjet=0; ifastjet<(int)fastjets_AK5PF_px_->size(); ifastjet++) {
            float fastpT = TMath::Sqrt( fastjets_AK5PF_px_->at(ifastjet)*fastjets_AK5PF_px_->at(ifastjet)
                                       +fastjets_AK5PF_py_->at(ifastjet)*fastjets_AK5PF_py_->at(ifastjet));   
            bool matched = false;
            int imatchedjet = 0;
            int imatchedetajet = 0;
            int imatchedphijet = 0;
            float detamin = 999.;
            float deta = 999.;
            float dphimin = 999.;
            float dphi = 999.;
            for(int ijet=0; ijet<(int)jets_AK5PFclean_rawPt_->size(); ijet++) {
                deta = TMath::Abs(jets_AK5PFclean_eta_->at(ijet) - fastjets_AK5PF_eta_->at(ifastjet));
                dphi = TMath::Abs(jets_AK5PFclean_phi_->at(ijet) - fastjets_AK5PF_phi_->at(ifastjet));

                if(deta<detamin){  
                    imatchedetajet = ijet;
                    detamin = deta;
                }
                if(dphi<dphimin){  
                    imatchedphijet = ijet;
                    dphimin = dphi;
                }

            }
            
            if( imatchedetajet==imatchedphijet //&& 
                //dphimin < 0.01 && detamin < 0.05
              ) { 
                matched = true; 
                imatchedjet=imatchedphijet;
            }

            if (matched) {  
                h1_eta_jets->Fill( jets_AK5PFclean_eta_->at(imatchedjet) );
                h1_eta_fastjets->Fill( fastjets_AK5PF_eta_->at(ifastjet) );
                h1_phi_jets->Fill( jets_AK5PFclean_phi_->at(imatchedjet) );
                h1_phi_fastjets->Fill( fastjets_AK5PF_phi_->at(ifastjet) );
                //h1_pT_diff->Fill( (fastpT-jets_AK5PFclean_rawPt_->at(imatchedjet))/jets_AK5PFclean_rawPt_->at(imatchedjet) );
                h1_pT_diff->Fill( (fastpT-jets_AK5PFclean_rawPt_->at(imatchedjet))/1.);
                h1_eta_diff->Fill( (fastjets_AK5PF_eta_->at(ifastjet)-jets_AK5PFclean_eta_->at(imatchedjet))/TMath::Abs(jets_AK5PFclean_eta_->at(imatchedjet)));
                h1_phi_diff->Fill( (fastjets_AK5PF_phi_->at(ifastjet)-jets_AK5PFclean_phi_->at(imatchedjet))/jets_AK5PFclean_phi_->at(imatchedjet) );

            } else {
                h1_eta_jets->Fill( -999. );
                h1_eta_fastjets->Fill( fastjets_AK5PF_eta_->at(ifastjet) );
                h1_phi_jets->Fill( -999. );
                h1_phi_fastjets->Fill( fastjets_AK5PF_phi_->at(ifastjet) );
                h1_pT_diff->Fill( -999. );
                h1_eta_diff->Fill( -999. );
                h1_phi_diff->Fill( -999.); 
            }
        } //if(matched)

        // njets needs to be outside of for loop
        h1_njets_jets->Fill( TMath::Min((Float_t)Njets,(Float_t)14.499) );
        h1_njets_fastjets->Fill( TMath::Min((Float_t)Nfastjets,(Float_t)14.999) );
    
    } // event loop

    h1cosmetic(h1_pT_jets, (char*)"pT", kBlack, 1, 0, "pT (GeV)");
    h1cosmetic(h1_pT_fastjets, (char*)"CMS fastjets", kRed, 1, 0, "pT (GeV)");
    h1cosmetic(h1_njets_jets, Form("Njets pT>%i GeV",(int)JetpTthres), kBlack, 1, 0, "Njets");
    h1cosmetic(h1_njets_fastjets, (char*)"Njets", kRed, 1, 0, "Njets");
    h1cosmetic(h1_pT_diff, (char*)"pT difference(Fastjet - cfA)", kBlack, 1, 0, "#Delta pT (GeV)");
    
    TCanvas *c = new TCanvas("c","c",1000,500);
    c->Divide(2,1);
    c->cd(1);
    c->cd(1)->SetLogy(1);
    h1_pT_jets->SetMaximum(h1_pT_jets->GetMaximum()*2);
    h1_pT_jets->Draw();
    h1_pT_fastjets->Draw("HIST SAME");
    c->cd(2);
    h1_pT_diff->SetMaximum(h1_pT_diff->GetMaximum()*1.2);
    h1_pT_diff->Draw();
    h1_pT_diff->Draw("HIST SAME");
    c->SaveAs(Form("SanityCheckpT.pdf")); 

    // njet distribution
    TCanvas *c_njets = new TCanvas();
    c_njets->cd(1);
    h1_njets_jets->SetMaximum(h1_njets_jets->GetMaximum()*1.4);
    h1_njets_jets->Draw();
    h1_njets_fastjets->Draw("HIST SAME");
    c_njets->SaveAs(Form("SanityCheckNjetsPT%i.pdf", (int)JetpTthres)); 
   
    // cleanup
    //delete f;
}
Esempio n. 14
0
void TagAndProbeAnalysis::Loop()
{
  if (fChain == 0) return;

  readR9Weights();
  
  // output file
  TFile *outFile[5];
  outFile[0] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+".root","RECREATE");
  outFile[1] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"30.root","RECREATE");
  outFile[2] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"50.root","RECREATE");
  outFile[3] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"75.root","RECREATE");
  outFile[4] = new TFile(outFileNamePrefix+"_tag"+tagTightnessLevel+(mcMatch==0 ? "" : "_mcMatch"+TString::Format("%d",mcMatch))+"_HLT"+"90.root","RECREATE");

  // output trees declaration
  TTree *myTree[5];
  for (int ii=0; ii<5; ii++) {
    outFile[ii]->cd();
    TDirectory* outputDirectory = outFile[ii]->mkdir("myTaPDir");
    outputDirectory->cd();
    myTree[ii] = new TTree();
    myTree[ii] -> SetName("myTree");
  }

  float mass;
  float probe_eta, probe_abseta, probe_phi, probe_pt, probe_r9;
  int numvtx;
  float rho;
  float r9weight_EB;
  float r9weight_EE;
  float puW;
  float puW30, puW50, puW75, puW90;  
  int okLooseElePtEta,  okLooseEleID;
  int okMediumElePtEta, okMediumEleID; 
  int okTightElePtEta,  okTightEleID; 
  int okMVA_005, okMVA_01, okMVA_02;
  int hasPromptElectronMatched;
  

  for (int ii=0; ii<5; ii++) {
    myTree[ii] -> Branch("mass",&mass,"mass/F");
    myTree[ii] -> Branch("probe_eta",&probe_eta,"probe_eta/F");
    myTree[ii] -> Branch("probe_abseta",&probe_abseta,"probe_abseta/F");
    myTree[ii] -> Branch("probe_phi",&probe_phi,"probe_phi/F");
    myTree[ii] -> Branch("probe_pt",&probe_pt,"probe_pt/F");
    myTree[ii] -> Branch("probe_r9",&probe_r9,"probe_r9/F");
    myTree[ii] -> Branch("numvtx",&numvtx,"numvtx/I");
    myTree[ii] -> Branch("rho",&rho,"rho/F");
    myTree[ii] -> Branch("puW",  &puW,  "puW/F");
    myTree[ii] -> Branch("r9WeightEB",  &r9weight_EB,  "r9WeightEB/F");
    myTree[ii] -> Branch("r9WeightEE",  &r9weight_EE,  "r9WeightEE/F");
    myTree[ii] -> Branch("puW30",&puW30,"puW30/F");
    myTree[ii] -> Branch("puW50",&puW50,"puW50/F");
    myTree[ii] -> Branch("puW75",&puW75,"puW75/F");
    myTree[ii] -> Branch("puW90",&puW90,"puW90/F");
    myTree[ii] -> Branch("okLooseElePtEta",&okLooseElePtEta,"okLooseElePtEta/I");
    myTree[ii] -> Branch("okLooseEleID",&okLooseEleID,"okLooseEleID/I");
    myTree[ii] -> Branch("okMediumElePtEta",&okMediumElePtEta,"okMediumElePtEta/I");
    myTree[ii] -> Branch("okMediumEleID",&okMediumEleID,"okMediumEleID/I");
    myTree[ii] -> Branch("okTightElePtEta",&okTightElePtEta,"okTightElePtEta/I");
    myTree[ii] -> Branch("okTightEleID",&okTightEleID,"okTightEleID/I");
    myTree[ii] -> Branch("okMVA_005",&okMVA_005,"okMVA_005/I");
    myTree[ii] -> Branch("okMVA_01",&okMVA_01,"okMVA_01/I");
    myTree[ii] -> Branch("okMVA_02",&okMVA_02,"okMVA_02/I");
    myTree[ii] -> Branch("hasPromptElectronMatched",&hasPromptElectronMatched,"hasPromptElectronMatched/I");
  }

  // Loop over events
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;

  cout << "Going to loop over " << nentries << " events" << endl;
  cout << endl;
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    Long64_t ientry = LoadTree(jentry);

    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    if (jentry%5000==0) cout << "Read entry " << jentry << endl;

    for (int iEle=0; iEle<nEle; iEle++) {
      if (isMC && mcMatch)
	if (!isGenMatchEle[iEle])
	  continue;

      if (tagTightnessLevel=="Tight")
	{
	  if (!isTagTightEle[iEle])
	    continue;
	}
      else if (tagTightnessLevel=="Medium")
	{
	  if (!isTagMediumEle[iEle])
	    continue;
	}
      else if (tagTightnessLevel=="Loose")
	{
	  if (!isTagLooseEle[iEle])
	    continue;
	}
      else
	{
	  std::cout << "Tag Selection undefined" << std::endl;
	  exit(-1);
	}

      TLorentzVector theEle;
      //      theEle.SetPtEtaPhiE(electron_pt[iEle], electron_eta[iEle], electron_phi[iEle], electron_energy[iEle]);
      theEle.SetPtEtaPhiM(electron_pt[iEle], electron_eta[iEle], electron_phi[iEle], 0.);

      for (int iPho=0; iPho<nPhot; iPho++) {
	if (isMC && mcMatch)
	  if (!isGenMatchPhot[iPho])
	    continue;

	//apply preselection as probe selection for photons (should be loosened to measure preselection SF)
	if (!isProbePreselPhot[iPho])
	  continue;

	TLorentzVector thePho;
	thePho.SetPtEtaPhiE(ptPhot[iPho], etaPhot[iPho], phiPhot[iPho], ePhot[iPho]);
      
	TLorentzVector theTaP = theEle + thePho;
	float theMass = theTaP.M();
      
	if (fabs(theMass-91.181)>DeltaMZ)
	  continue;

	// filling the tree
	mass = theMass;
	
	probe_eta    = etascPhot[iPho];
	probe_abseta = fabs(etascPhot[iPho]);
	probe_phi    = phiPhot[iPho];
	probe_pt     = ptPhot[iPho];
	probe_r9     = r9Phot[iPho];
	
	numvtx = nvtx;
	rho=rhoAllJets;

	if(isMC) {
	  puW   = pu_weight;
	  puW30 = pu_weight30;
	  puW50 = pu_weight50;
	  puW75 = pu_weight75;
	  puW90 = pu_weight90;
	} else {
	  puW   = 1.;
	  puW30 = 1.;
	  puW50 = 1.;
	  puW75 = 1.;
	  puW90 = 1.;
	}
	

	if (r9Reweight)
	  {
	    r9weight_EB=r9weights_EB->GetBinContent(r9weights_EB->FindBin(r9Phot[iPho]));
	    r9weight_EE=r9weights_EE->GetBinContent(r9weights_EE->FindBin(r9Phot[iPho]));
	  }
	else
	  {
	    r9weight_EB=1.;
	    r9weight_EE=1.;
	  }


	okLooseElePtEta  = 1;
	okLooseEleID     = isProbeLoosePhot[iPho];
	okMediumElePtEta = 1;
	okMediumEleID    = isProbeMediumPhot[iPho];
	okTightElePtEta  = 1;
	okTightEleID     = isProbeTightPhot[iPho];

	hasPromptElectronMatched = hasMatchedPromptElePhot[iPho];

	// MVA WPs
	okMVA_005 = 0;
	okMVA_01  = 0;
	okMVA_02  = 0;
	if (isEBPhot[iPho]) {
	  if ( mvaIDPhot[iPho]>0.711099 ) okMVA_005 = 1;
	  if ( mvaIDPhot[iPho]>0.812948 ) okMVA_01  = 1;
	  if ( mvaIDPhot[iPho]>0.878893 ) okMVA_02  = 1;
	} else {
	  if ( mvaIDPhot[iPho]>0.581733 ) okMVA_005 = 1;
	  if ( mvaIDPhot[iPho]>0.73721  ) okMVA_01  = 1;
	  if ( mvaIDPhot[iPho]>0.850808 ) okMVA_02  = 1;
	}
	
	// check HLT and pT range
	if (!isMC) {
	  if ( isHLT_TandP() )                                           myTree[0]->Fill();
	  if ( isHLT_30() && ptPhot[iPho]>=40 && ptPhot[iPho]<65 )       myTree[1]->Fill();
	  if ( isHLT_50() && ptPhot[iPho]>=65 && ptPhot[iPho]<90 )       myTree[2]->Fill();
	  if ( isHLT_75() && ptPhot[iPho]>=90 && ptPhot[iPho]<105 )      myTree[3]->Fill();
	  if ( isHLT_90() && ptPhot[iPho]>=105 && ptPhot[iPho]<200000 )  myTree[4]->Fill();
	}
	if (isMC) {
	  myTree[0]->Fill();
	  if ( ptPhot[iPho]>=40 && ptPhot[iPho]<65 )       myTree[1]->Fill();
	  if ( ptPhot[iPho]>=65 && ptPhot[iPho]<90 )       myTree[2]->Fill();
	  if ( ptPhot[iPho]>=90 && ptPhot[iPho]<105 )      myTree[3]->Fill();
	  if ( ptPhot[iPho]>=105 && ptPhot[iPho]<200000 )  myTree[4]->Fill();
	}
	
      
      } // loop over photons
    }   // loop over electrons
  }

  for (int ii=0; ii<5; ii++) {
    outFile[ii]->cd("myTaPDir");
    myTree[ii]->Write();
    outFile[ii]->Close();
  }
}
Esempio n. 15
0
void doAll(bool skipFWLite = true)
{

  //---------------------------------------------------------------
  // choose version, output will be written to output/[version]
  //---------------------------------------------------------------
  
  const char* version    = "V00-00-10";
  const char* jsonfile   = "jsons/Cert_190456-202305_8TeV_PromptReco_Collisions12_JSON_goodruns.txt";
  const bool  useMCSkims = true;

  cout << "Version : " << version     << endl;
  cout << "json    : " << jsonfile    << endl;

  // Load various tools  
  gROOT->ProcessLine(Form(".x setup.C(%d)", skipFWLite));

  // Load FWLite
  gSystem->Load("../Tools/MiniFWLite/libMiniFWLite.so");

  // Load and compile the looping code
  gSystem->CompileMacro("looper.C","++k", "liblooper");
  
  looper* looper = new looper();

  //set looper parameters
  looper->set_susybaseline(0);
  //make baby ntuple
  looper->set_createTree(1);
  //use bitmask selection
  looper->set_useBitMask(0);
  //set version
  looper->set_version(version);
  //set json
  looper->set_json( jsonfile );
 
  //----------------------------------------
  // flags for files to run over
  //----------------------------------------

  bool runData          = 0;
  bool runElData        = 0;
  bool runMuData        = 0;
  bool runSingleElData  = 0;
  bool runSingleMuData  = 0;
  bool runElHadData     = 0;
  bool runDoubleElData  = 0;
  bool runDoubleMuData  = 0;
  bool runMuHadData     = 0;
  bool runPhotonData    = 0;
  bool runData2012A     = 0;
  bool runData2012B     = 1;
  bool runData2012C     = 1;

  //----------------------------------------------------------------------------------------------------------
  // muon trigger skim: 2012A
  //----------------------------------------------------------------------------------------------------------

  TChain* chData2012A = new TChain("Events");

  if( runData2012A ){
    cout << "Adding all 2012A data muon trigger skim" << endl;

    pickSkimIfExists(chData2012A,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012A-13Jul2012-v1_AOD/V05-03-13/merged_ntuple_999999_12_2_skim.root");
    //pickSkimIfExists(chData,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012A-13Jul2012-v1_AOD/V05-03-13/merged*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // muon trigger skim: 2012B
  //----------------------------------------------------------------------------------------------------------

  TChain* chData2012B = new TChain("Events");

  if( runData2012B ){
    cout << "Adding all 2012B data muon trigger skim" << endl;

    //pickSkimIfExists(chData2012B,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012B-13Jul2012-v1_AOD/V05-03-13/merged_ntuple_999999_21_6_skim.root");
    pickSkimIfExists(chData2012B,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012B-13Jul2012-v1_AOD/V05-03-13/merged*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // muon trigger skim: 2012C
  //----------------------------------------------------------------------------------------------------------

  TChain* chData2012C = new TChain("Events");

  if( runData2012C ){
    cout << "Adding all 2012C data muon trigger skim" << endl;

    //pickSkimIfExists(chData2012C,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012C-PromptReco-v2_AOD/V05-03-13/merged_ntuple_199572_0_skim.root");
    pickSkimIfExists(chData2012C,"/home/users/benhoob/CondorSkim/MuonTrigger/MuHad_Run2012C-PromptReco-v2_AOD/V05-03-13/merged*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // all data
  //----------------------------------------------------------------------------------------------------------

  TChain* chData = new TChain("Events");

  if( runData ){
    cout << "Adding all data" << endl;

    pickSkimIfExists(chData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");  	  	 
    pickSkimIfExists(chData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root"); 	  	 
    pickSkimIfExists(chData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/MuEG_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    pickSkimIfExists(chData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/SingleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    pickSkimIfExists(chData,"/hadoop/cms/store/user/macneill/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");	 
    pickSkimIfExists(chData,"/hadoop/cms/store/user/macneill/CMSSW_5_2_3_patch3_V05-02-07/Photon_Run2012A-PromptReco-v1_AOD/unmerged/*root");	 
    pickSkimIfExists(chData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/MuHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");	  	 
    pickSkimIfExists(chData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // all electron data
  //----------------------------------------------------------------------------------------------------------

  TChain* chElData = new TChain("Events");

  if( runElData ){
    cout << "Adding all electron data" << endl;
    pickSkimIfExists(chElData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root"); 	  	 
    pickSkimIfExists(chElData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/SingleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    pickSkimIfExists(chElData,"/hadoop/cms/store/user/macneill/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");	     
  }

  //----------------------------------------------------------------------------------------------------------
  // all muon data
  //----------------------------------------------------------------------------------------------------------

  TChain* chMuData = new TChain("Events");

  if( runMuData ){
    cout << "Adding all muon data" << endl;
    //pickSkimIfExists(chMuData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_SingleMu_AOD_PromptReco-v1_000_190_663_125F6FAA-C382-E111-8D4A-003048F1110E.root");
    //pickSkimIfExists(chMuData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_SingleMu_AOD_PromptReco-v1_000_190_663_BE881788-D182-E111-86AB-001D09F2462D.root");
    // pickSkimIfExists(chMuData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/MuEG_Run2012A-PromptReco-v1_AOD/unmerged/*root");

    pickSkimIfExists(chMuData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");  	  	 
    pickSkimIfExists(chMuData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/MuHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");	  	 
    pickSkimIfExists(chMuData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // single electron data
  //----------------------------------------------------------------------------------------------------------

  TChain* chSingleElData = new TChain("Events");

  if( runSingleElData ){
    cout << "Adding single electron data" << endl;
    pickSkimIfExists(chSingleElData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/SingleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // single muon data
  //----------------------------------------------------------------------------------------------------------

  TChain* chSingleMuData = new TChain("Events");

  if( runSingleMuData ){
    cout << "Adding single muon data" << endl;
    //pickSkimIfExists(chSingleMuData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    //pickSkimIfExists(chSingleMuData,"/tas/benhoob/testFiles/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_SingleMu_AOD_PromptReco-v1_000_191_718_1031CF12-DC8B-E111-9983-003048F117EC.root");
    //pickSkimIfExists(chSingleMuData,"/tas/benhoob/testFiles/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store*root");
    pickSkimIfExists(chSingleMuData,"/tas/benhoob/testFiles/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store*191_718*root");
    //pickSkimIfExists(chSingleMuData,"/tas/benhoob/testFiles/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store*191_830*root");
    //pickSkimIfExists(chSingleMuData,"/tas/benhoob/testFiles/SingleMu_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_SingleMu_AOD_PromptReco-v1_000_191_830_5E887D82-A98C-E111-9455-003048F117F6.root");
  }

  //----------------------------------------------------------------------------------------------------------
  // ElHad data
  //----------------------------------------------------------------------------------------------------------

  TChain* chElHadData = new TChain("Events");

  if( runElHadData ){
    cout << "Adding electronhad data" << endl;
    //pickSkimIfExists(chElHadData,"/hadoop/cms/store/user/cwelke/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_ElectronHad_AOD_PromptReco-v1_000_191_718_C448B8E1-028C-E111-9E99-003048F110BE.root");
    //pickSkimIfExists(chElHadData,"/hadoop/cms/store/user/cwelke/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/*191_718*root");
    pickSkimIfExists(chElHadData,"/hadoop/cms/store/user/cwelke/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/*191_830*root");
    //pickSkimIfExists(chElHadData,"/hadoop/cms/store/user/macneill/CMSSW_5_2_3_patch3_V05-02-07/ElectronHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");	     
  }

  //----------------------------------------------------------------------------------------------------------
  // doubleElectron data
  //----------------------------------------------------------------------------------------------------------

  TChain* chDoubleElData = new TChain("Events");

  if( runDoubleElData ){
    cout << "Adding double electron data" << endl;
    pickSkimIfExists(chDoubleElData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // doubleMu data
  //----------------------------------------------------------------------------------------------------------

  TChain* chDoubleMuData = new TChain("Events");

  if( runDoubleMuData ){
    cout << "Adding double muon data" << endl;
    pickSkimIfExists(chDoubleMuData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleMu_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    //pickSkimIfExists(chDoubleMuData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleMu_Run2012A-PromptReco-v1_AOD/unmerged/store_data_Run2012A_DoubleMu_AOD_PromptReco-v1_000_191_090_7C2A77D9-2087-E111-877A-003048D2BC4C.root");
  }

  //----------------------------------------------------------------------------------------------------------
  // MuHad data
  //----------------------------------------------------------------------------------------------------------

  TChain* chMuHadData = new TChain("Events");

  if( runMuHadData ){
    cout << "Adding muhad data" << endl;
    pickSkimIfExists(chMuHadData,"/hadoop/cms/store/user/jaehyeok/CMSSW_5_2_3_patch3_V05-02-07/MuHad_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }


  //----------------------------------------------------------------------------------------------------------
  // photon data
  //----------------------------------------------------------------------------------------------------------

  TChain* chPhotonData = new TChain("Events");

  if( runPhotonData ){
    cout << "Adding all photon data" << endl;

    pickSkimIfExists(chPhotonData,"/hadoop/cms/store/user/yanjuntu/CMSSW_5_2_3_patch3_V05-02-07/DoubleElectron_Run2012A-PromptReco-v1_AOD/unmerged/*root");
    pickSkimIfExists(chPhotonData,"/hadoop/cms/store/user/macneill/CMSSW_5_2_3_patch3_V05-02-07/Photon_Run2012A-PromptReco-v1_AOD/unmerged/*root");
  }

  //----------------------------------------------------------------------------------------------------------
  // run on samples
  //----------------------------------------------------------------------------------------------------------

  if (runData2012A) {
    cout << "Processing all 2012A muon trigger data" << endl;
    looper->ScanChain(chData2012A,"data2012A_mutrig");
    cout << "Done processing all 2012A muon trigger data" << endl;
  }

  if (runData2012B) {
    cout << "Processing all 2012B muon trigger data" << endl;
    looper->ScanChain(chData2012B,"data2012B_mutrig");
    cout << "Done processing all 2012B muon trigger data" << endl;
  }

  if (runData2012C) {
    cout << "Processing all 2012C muon trigger data" << endl;
    looper->ScanChain(chData2012C,"data2012C_mutrig");
    cout << "Done processing all 2012C muon trigger data" << endl;
  }

  if (runData) {
    cout << "Processing all data" << endl;
    looper->ScanChain(chData,"allData");
    cout << "Done processing all data" << endl;
  }

  if (runDoubleMuData) {
    cout << "Processing double muon data" << endl;
    looper->ScanChain(chDoubleMuData,"doubleMuData");
    cout << "Done processing double muon data" << endl;
  }

  if (runSingleMuData) {
    cout << "Processing single muon data" << endl;
    looper->ScanChain(chSingleMuData,"singleMuData");
    cout << "Done processing single muon data" << endl;
  }

  if (runSingleElData) {
    cout << "Processing single electron data" << endl;
    looper->ScanChain(chSingleElData,"singleElData");
    cout << "Done processing single electron data" << endl;
  }

  if (runElHadData) {
    cout << "Processing elhad data" << endl;
    looper->ScanChain(chElHadData,"elHadData");
    cout << "Done processing elhad data" << endl;
  }

  if (runDoubleElData) {
    cout << "Processing double electron data" << endl;
    looper->ScanChain(chDoubleElData,"doubleElData");
    cout << "Done processing double electron data" << endl;
  }

  if (runMuHadData) {
    cout << "Processing muhad data" << endl;
    looper->ScanChain(chMuHadData,"muHadData");
    cout << "Done processing muhad data" << endl;
  }

  if (runElData) {
    cout << "Processing all electron data" << endl;
    looper->ScanChain(chElData,"elData");
    cout << "Done processing all electron data" << endl;
  }

  if (runMuData) {
    cout << "Processing all muon data" << endl;
    looper->ScanChain(chMuData,"muData");
    cout << "Done processing all muon data" << endl;
  }

  if (runPhotonData) {
    cout << "Processing all photon data" << endl;
    looper->ScanChain(chPhotonData,"photonData");
    cout << "Done processing all photon data" << endl;
  }

  //----------------------------------------
  // save all the histograms
  //----------------------------------------

  const char* outFile  = Form("../output/%s/singleLepton.root", version );
  TDirectory *rootdir = gDirectory->GetDirectory("Rint:");
  rootdir->cd();
  saveHist(outFile);
  deleteHistos();
  
  gSystem->Exit(0);
}
void bcal_hist_eff_summary(void)
{
// read in histograms plotting BCAL efficiencies and print history to file.
//

gROOT->Reset();
//TTree *Bfield = (TTree *) gROOT->FindObject("Bfield");
gStyle->SetPalette(1,0);
gStyle->SetOptStat(kFALSE);
// gStyle->SetOptStat(11111111);
gStyle->SetPadRightMargin(0.15);
gStyle->SetPadLeftMargin(0.15);
gStyle->SetPadBottomMargin(0.15);
//

   char string[256];
   Int_t j,jj;
   Int_t ndx;
   // Int_t npts=7;   // run 1506
   // Int_t npts=42;   // run 2400
   // Int_t npts=423;    // run 2439
   // Int_t npts=205;    // run 2439
   Int_t npts=18;    // run 2179

   // define history histogram

   Double_t xmin=0;
   Double_t xmax=npts;
   //Double_t ymin=0.5;
   // Double_t ymax=1.1;
   Double_t ymin=0.;
   Double_t ymax=1.2;
  TH1F *hsummary_layer1 = new TH1F("hsummary_layer1","Summary layer 1",npts,xmin,xmax);
  TH1F *hsummary_layer2 = new TH1F("hsummary_layer2","Summary layer 2",npts,xmin,xmax);
  TH1F *hsummary_layer3 = new TH1F("hsummary_layer3","Summary layer 3",npts,xmin,xmax);
  TH1F *hsummary_layer4 = new TH1F("hsummary_layer4","Summary layer 4",npts,xmin,xmax);

  TH1F *hsummary2_layer1 = new TH1F("hsummary2_layer1","Summary layer 1",npts,xmin,xmax);
  TH1F *hsummary2_layer2 = new TH1F("hsummary2_layer2","Summary layer 2",npts,xmin,xmax);
  TH1F *hsummary2_layer3 = new TH1F("hsummary2_layer3","Summary layer 3",npts,xmin,xmax);
  TH1F *hsummary2_layer4 = new TH1F("hsummary2_layer4","Summary layer 4",npts,xmin,xmax);

   // read histograms from file

   for (ndx=0; ndx < npts; ndx++) {

   sprintf(string,"hd_rawdata_002179_%03d_.root",ndx);


   // if (ndx == 1) continue;  // run 1506
   /*if (ndx == 2) continue;
   if (ndx == 6) continue;
   if (ndx == 12) continue;;
   if (ndx == 39) continue;*/ 

   /*if (ndx == 10) continue;     // file #3 is empty
   if (ndx == 92) continue;     // file #3 is empty
   if (ndx == 95) continue;     // file #3 is empty
   if (ndx == 141) continue;     // file #3 is empty
   if (ndx == 176) continue;     // file #3 is empty
   if (ndx == 225) continue;     // file #3 is empty
   if (ndx == 226) continue;     // file #3 is empty
   if (ndx == 227) continue;     // file #3 is empty
   if (ndx >= 230 && ndx<=254 ) continue;     // file #3 is empty
   if (ndx == 257) continue;     // file #3 is empty
   if (ndx == 258) continue;     // file #3 is empty
   if (ndx == 260) continue;     // file #3 is empty
   if (ndx == 262) continue;     // file #3 is empty
   if (ndx == 264) continue;     // file #3 is empty
   if (ndx == 278) continue;     // file #3 is empty
   if (ndx == 281) continue;     // file #3 is empty
   if (ndx == 284) continue;     // file #3 is empty
   if (ndx == 285) continue;     // file #3 is empty
   if (ndx == 286) continue;     // file #3 is empty
   if (ndx == 287) continue;     // file #3 is empty
   if (ndx == 289) continue;     // file #3 is empty
   if (ndx == 290) continue;     // file #3 is empty
   if (ndx == 291) continue;     // file #3 is empty
   if (ndx == 293) continue;     // file #3 is empty
   if (ndx == 294) continue;     // file #3 is empty
   if (ndx == 295) continue;     // file #3 is empty
   if (ndx == 298) continue;     // file #3 is empty
   if (ndx == 299) continue;     // file #3 is empty
   if (ndx == 304) continue;     // file #3 is empty
   if (ndx == 306) continue;     // file #3 is empty*/

   TFile *in=NULL;
   in = new TFile(string,"read");
   if (!in) {
     printf ("Histogram input filename=%s does not open\n",string);
     continue;
   }
   else {
     printf ("Histogram input filename=%s OK\n",string);
   }

   // cd into bcal_eff directory
   TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("bcal_eff");
   if(dir) dir->cd();

   TH1F *h1eff_eff= NULL;
   h1eff_eff = (TH1F*)gDirectory->FindObjectAny("h1eff_eff");
   TH1F *h1eff_cellideff = (TH1F*)gDirectory->FindObjectAny("h1eff_cellideff");
   TH1F *h1eff2_eff2 = (TH1F*)gDirectory->FindObjectAny("h1eff2_eff2");
   TH1F *h1eff2_cellideff2 = (TH1F*)gDirectory->FindObjectAny("h1eff2_cellideff2");

   if ( (h1eff_eff == NULL) ||  (h1eff_eff->GetEntries() <=0)) continue;

   // retrieving information from the histogram

   Int_t ndim = h1eff_eff->GetNbinsX();
   Double_t xlo = h1eff_eff->GetBinLowEdge(1);
   Double_t width = h1eff_eff->GetBinWidth(1);
   Double_t xhi = xlo + width*ndim;
   printf ("\nbcal_hist_eff_summary: ndx=%d, ndim=%d, xlo=%f, width=%f, xhi=%d\n\n",ndx,ndim,xlo,width,xhi);

      for(j=0;j<ndim;j++) {
      Double_t xbin = xlo + j*width;
      Double_t content = h1eff_eff->GetBinContent(j+1);
      Double_t error = h1eff_eff->GetBinError(j+1);
      printf ("j=%d, xbin=%f, content=%f\n",j,xbin,content);

     // fill summary histogram

          if (j == 1) {
	hsummary_layer1->SetBinContent(ndx+1,content);
                    hsummary_layer1->SetBinError(ndx+1,error);
	}
         if (j == 2) {
	hsummary_layer2->SetBinContent(ndx+1,content);
                    hsummary_layer2->SetBinError(ndx+1,error);
	}
         if (j == 3) {
	hsummary_layer3->SetBinContent(ndx+1,content);
                    hsummary_layer3->SetBinError(ndx+1,error);
	}
         if (j == 4) {
	hsummary_layer4->SetBinContent(ndx+1,content);
                    hsummary_layer4->SetBinError(ndx+1,error);
	}
    
   }



   // retrieving information from the histogram

   ndim = h1eff2_eff2->GetNbinsX();
   xlo = h1eff2_eff2->GetBinLowEdge(1);
   width = h1eff2_eff2->GetBinWidth(1);
   xhi = xlo + width*ndim;
   printf ("\nbcal_hist_eff2_summary: ndx=%d, ndim=%d, xlo=%f, width=%f, xhi=%f\n\n",ndx,ndim,xlo,width,xhi);

      for(j=0;j<ndim;j++) {
      Double_t xbin = xlo + j*width;
      Double_t content = h1eff2_eff2->GetBinContent(j+1);
      Double_t error = h1eff2_eff2->GetBinError(j+1);
      printf ("j=%d, xbin=%f, content=%f\n",j,xbin,content);

     // fill summary histogram

          if (j == 1) {
	hsummary2_layer1->SetBinContent(ndx+1,content);
                    hsummary2_layer1->SetBinError(ndx+1,error);
	}
         if (j == 2) {
	hsummary2_layer2->SetBinContent(ndx+1,content);
                    hsummary2_layer2->SetBinError(ndx+1,error);
	}
         if (j == 3) {
	hsummary2_layer3->SetBinContent(ndx+1,content);
                    hsummary2_layer3->SetBinError(ndx+1,error);
	}
         if (j == 4) {
	hsummary2_layer4->SetBinContent(ndx+1,content);
                    hsummary2_layer4->SetBinError(ndx+1,error);
	}
    
   }

      in->Close();
   
   }   // end loop over histogram files

   //
   TCanvas *c1 = new TCanvas("c1","c1 bcal_hist_eff_summary ",200,10,700,700);
   c1->SetBorderMode(0);
   c1->SetFillColor(0);

   c1->SetGridx();
   c1->SetGridy();
   c1->SetBorderMode(0);
   c1->SetFillColor(0);

  TLegend *leg = new TLegend(0.6,0.8,0.85,0.95);
  leg->AddEntry(hsummary_layer1,"Layer 1","p");
  leg->AddEntry(hsummary_layer2,"Layer 2","p");
  leg->AddEntry(hsummary_layer3,"Layer 3","p");
  leg->AddEntry(hsummary_layer4,"Layer 4","p");

   hsummary_layer1->SetTitle("");
   //hsummary_layer1->GetXaxis()->SetRangeUser(xmin,xmax);
   hsummary_layer1->GetYaxis()->SetRangeUser(ymin,ymax);
   hsummary_layer1->GetXaxis()->SetTitleSize(0.05);
   hsummary_layer1->GetYaxis()->SetTitleSize(0.05);
   hsummary_layer1->GetXaxis()->SetTitle("File Number");
   hsummary_layer1->GetYaxis()->SetTitle("Efficiency Clusters");
   hsummary_layer1->SetLineColor(2);
   hsummary_layer1->SetMarkerColor(2);
   hsummary_layer1->SetMarkerStyle(20);
   hsummary_layer1->Draw("p");

   hsummary_layer2->SetLineColor(4);
   hsummary_layer2->SetMarkerColor(4);
   hsummary_layer2->SetMarkerStyle(20);
   hsummary_layer2->Draw("samep");

   hsummary_layer3->SetLineColor(1);
   hsummary_layer3->SetMarkerColor(1);
   hsummary_layer3->SetMarkerStyle(20);
   hsummary_layer3->Draw("samep");

   hsummary_layer4->SetLineColor(3);
   hsummary_layer4->SetMarkerColor(3);
   hsummary_layer4->SetMarkerStyle(20);
   hsummary_layer4->Draw("samep");

   sprintf(string,"hd_rawdata_002179");
   printf ("Histogram input filename=%s\n",string);
   TLatex *t1 = new TLatex(0.15,0.92,string);
   t1->SetNDC();
   t1->SetTextSize(0.03);
   t1->Draw();

  leg->Draw();

   //
   TCanvas *c2 = new TCanvas("c2","c2 bcal_hist_eff_summary ",200,10,700,700);
   c2->SetBorderMode(0);
   c2->SetFillColor(0);

   c2->SetGridx();
   c2->SetGridy();
   c2->SetBorderMode(0);
   c2->SetFillColor(0);

   leg = new TLegend(0.6,0.80,0.85,0.95);
  leg->AddEntry(hsummary2_layer1,"Layer 1","p");
  leg->AddEntry(hsummary2_layer2,"Layer 2","p");
  leg->AddEntry(hsummary2_layer3,"Layer 3","p");
  leg->AddEntry(hsummary2_layer4,"Layer 4","p");

   hsummary2_layer1->SetTitle("");
   //hsummary2_layer1->GetXaxis()->SetRangeUser(xmin,xmax);
   hsummary2_layer1->GetYaxis()->SetRangeUser(ymin,ymax);
   hsummary2_layer1->GetXaxis()->SetTitleSize(0.05);
   hsummary2_layer1->GetYaxis()->SetTitleSize(0.05);
   hsummary2_layer1->GetXaxis()->SetTitle("File Number");
   hsummary2_layer1->GetYaxis()->SetTitle("Efficiency Enhanced Hits");
   hsummary2_layer1->SetLineColor(2);
   hsummary2_layer1->SetMarkerColor(2);
   hsummary2_layer1->SetMarkerStyle(20);
   hsummary2_layer1->Draw("p");

   hsummary2_layer2->SetLineColor(4);
   hsummary2_layer2->SetMarkerColor(4);
   hsummary2_layer2->SetMarkerStyle(20);
   hsummary2_layer2->Draw("samep");

   hsummary2_layer3->SetLineColor(1);
   hsummary2_layer3->SetMarkerColor(1);
   hsummary2_layer3->SetMarkerStyle(20);
   hsummary2_layer3->Draw("samep");

   hsummary2_layer4->SetLineColor(3);
   hsummary2_layer4->SetMarkerColor(3);
   hsummary2_layer4->SetMarkerStyle(20);
   hsummary2_layer4->Draw("samep");

   sprintf(string,"hd_rawdata_002179");
   printf ("Histogram input filename=%s\n",string);
   t1 = new TLatex(0.15,0.92,string);
   t1->SetNDC();
   t1->SetTextSize(0.03);
   t1->Draw();

  leg->Draw();



   sprintf(string,"bcal_hist_eff_summary_002179.pdf(");
   c1->SaveAs(string);

   sprintf(string,"bcal_hist_eff_summary_002179.pdf)");
   c2->SaveAs(string);

}
Esempio n. 17
0
int MakeHistos(int iSample = 0, int iSR = 6){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;
    
  TString mainDir = "/home/fcostanz/Bonsai/ControlPlots/";

  TFile* cutFile = new TFile( "Optimization-2Step.root", "READ"); 
  TTree* cutTree;  
  cutFile->GetObject( "Optimization", cutTree);

  Float_t mtCut = 0.;
  Float_t nJetCut = 0.;
  Float_t topnessCut = 0.;
  Float_t mt2wCut = 0.;
  Float_t yCut = 0.;
  Float_t dphiCut = 0.;
  Float_t drlblCut = 0.;
  Float_t drlbgCut = 0.;
  Float_t chi2Cut = 0.;
  Float_t metCut = 0.;
  Float_t m3Cut = 0.;
  Float_t centralityCut = 0.;
  Float_t mlbCut = 0.;

  cutTree->SetBranchAddress( "mtCut", &mtCut);
  cutTree->SetBranchAddress( "njetCut", &nJetCut);
  cutTree->SetBranchAddress( "topnessCut", &topnessCut);
  cutTree->SetBranchAddress( "mt2wCut", &mt2wCut);
  cutTree->SetBranchAddress( "yCut", &yCut);
  cutTree->SetBranchAddress( "dphiCut", &dphiCut);
  cutTree->SetBranchAddress( "drlblCut", &drlblCut);
  cutTree->SetBranchAddress( "drlbgCut", &drlbgCut);
  cutTree->SetBranchAddress( "chi2Cut", &chi2Cut);
  cutTree->SetBranchAddress( "metCut", &metCut);
  cutTree->SetBranchAddress( "m3Cut", &m3Cut);
  cutTree->SetBranchAddress( "centralityCut", &centralityCut);
  cutTree->SetBranchAddress( "mlbCut", &mlbCut);

  cutTree->GetEntry(iSR);
  /*
  mtCut = 120.;
  nJetCut = 3;
  topnessCut = -20;
  mt2wCut = 200;
  yCut = 0.;
  dphiCut = 1.;
  drlblCut = 5.;
  drlbgCut = 0.;
  chi2Cut = 9999999999.;
  metCut = 250.;
  m3Cut = 0.;
  centralityCut = 0.6;
  mlbCut =9999999999. ;*/

  cout<<"mtCut = "<<mtCut<<endl;
  cout<<"nJetCut = "<<nJetCut<<endl;
  cout<<"topnessCut = "<<topnessCut<<endl;
  cout<<"mt2wCut = "<<mt2wCut<<endl;
  cout<<"yCut = "<<yCut<<endl;
  cout<<"dphiCut = "<<dphiCut<<endl;
  cout<<"drlblCut = "<<drlblCut<<endl;
  cout<<"drlbgCut = "<<drlbgCut<<endl;
  cout<<"chi2Cut = "<<chi2Cut<<endl;
  cout<<"metCut = "<<metCut<<endl;
  cout<<"m3Cut = "<<m3Cut<<endl;
  cout<<"centralityCut = "<<centralityCut<<endl;
  cout<<"mlbCut = "<<mlbCut<<endl;

  const int NSamples = 11;  
  const int NSignals = 4;
  const int NControlRegions = 6;
  const int NLeps = 3;
  const int NDirs = NControlRegions * NLeps;

  TString sample[NSamples];
  sample[0] = "Data";
  sample[1] = "DiLep";
  sample[2] = "OneLep";
  sample[3] = "WJets";
  sample[4] = "Rare";
  sample[5] = "QCD";
  sample[6] = "DrellYan";
  sample[7] = "T2tb-mStop175mLSP50";
  sample[8] = "T2tb-mStop200mLSP25";
  sample[9] = "T2tb-mStop325mLSP100";
  sample[10] = "T2tb-mStop550mLSP1";

  double lumi=19500.;
  double weight = 1.;

  bool lepFlag;
  TString lep[NLeps];
  lep[0] = "El";
  lep[1] = "Mu";
  lep[2] = "ElAndMu";

  TString controlRegion[NControlRegions];
  controlRegion[0] = "Preselection";
  controlRegion[1] = "SearchRegionPreIsoTrackVeto";
  controlRegion[2] = "SearchRegionPostIsoTrackVeto";
  controlRegion[3] = "CR1";
  controlRegion[4] = "CR4";
  controlRegion[5] = "CR5";

  bool flag[NDirs];
  TString controlDirName[NDirs];
  TDirectory* controlDir[NDirs];

  for (int ilep = 0; ilep < NLeps; ilep++){
    for ( int iControlRegion = 0; iControlRegion < NControlRegions; iControlRegion++){
      controlDirName[ilep * NControlRegions + iControlRegion ] = lep[ilep];
      controlDirName[ilep * NControlRegions + iControlRegion ] += "-";
      controlDirName[ilep * NControlRegions + iControlRegion ] += controlRegion[iControlRegion];
    }
  }

  /////////////////////////////////////////////////////
  //  Input Definition
  /////////////////////////////////////////////////////  
  std::cout<<"Running over Sample "<<sample[iSample]<<std::endl;

  TString inFileName = mainDir; inFileName += sample[iSample]; inFileName +=".root";
  TFile* inFile = new TFile(inFileName,"READ");
  if (!inFile->IsOpen()){
    std::cout<<"not open"<<std::endl;
  }

  /////////////////////////////////////////////////////
  //  Tree Definition
  /////////////////////////////////////////////////////  
  TTree* tree;
  tree= (TTree*)inFile->Get("NoSystematic/bonsai");
  int N = tree->GetEntries();  cout<<"THERE ARE "<<N<<" EVENTS IN "<<inFileName<<endl;
  
  Float_t globalWeight = 0.;
  Float_t triggerWeight = 0.;
  Float_t npv = 0.;
  Float_t ngoodpv = 0.;
  Float_t puWeight = 0.;
  Float_t isrWeight = 0.;
  Float_t topPtWeight = 0.;

  Float_t lepFromTop = 0.;
  Float_t charginos = 0.;

  Float_t njets = 0.;
  Float_t jet1 = 0.;
  Float_t jet2 = 0.;
  Float_t jet3 = 0.;
  Float_t jet4 = 0.;

  Float_t nbjets = 0.;
  Float_t bjet1 = 0.;
  Float_t bjetHighestDisc = 0.;
  Float_t bdiscH = 0.;

  Float_t lPt = 0.;
  Float_t lEta = 0.;
  Float_t lRelIso = 0.;

  Float_t isoTrack = 0.;
  Float_t tauVeto = 0.;
  
  Float_t rawmet = 0.;
  Float_t typeImet = 0.;
  Float_t phiCorrMet = 0.;
  
  Float_t ht = 0.;
  Float_t ht3 = 0.;
  Float_t ht4 = 0.;
  Float_t ht5 = 0.;
  Float_t htRatio = 0.;
  Float_t meff = 0.;
  Float_t y = 0.;
  
  Float_t mt = 0.;
  Float_t mlb1 = 0.;
  Float_t mlb = 0.;
  Float_t m3b = 0.;
  Float_t m3 = 0.;
  Float_t centrality = 0.;  
  Float_t mt2w = 0.;
  Float_t hadChi2 = 0.;
  Float_t topness = 0.;

  Float_t dphimin = 0.;
  Float_t drlb1 = 0.;
  Float_t drlbmin = 0.;

  Int_t pdgIdLep1 = 0;
  Int_t pdgIdLep2 = 0;

  Char_t kinRegion = false;
  Char_t searchRegionPre = false;
  Char_t searchRegionPost = false;
  Char_t CR1 = false;
  Char_t CR4 = false;
  Char_t CR5 = false;

  tree->SetBranchAddress( "GlobalWeight", &globalWeight);
  tree->SetBranchAddress( "TriggerWeight", &triggerWeight);
  tree->SetBranchAddress( "NPV", &npv);
  tree->SetBranchAddress( "NgoodPV", &ngoodpv);
  tree->SetBranchAddress( "PUWeight", &puWeight);
  tree->SetBranchAddress( "isrWeight", &isrWeight);
  tree->SetBranchAddress( "topPtWeight", &topPtWeight);

  tree->SetBranchAddress( "LepFromTop", &lepFromTop);
  tree->SetBranchAddress( "Charginos", &charginos);

  tree->SetBranchAddress( "njets", &njets);
  tree->SetBranchAddress( "jet1", &jet1);
  tree->SetBranchAddress( "jet2", &jet2);
  tree->SetBranchAddress( "jet3", &jet3);
  tree->SetBranchAddress( "jet4", &jet4);

  tree->SetBranchAddress( "nbjets", &nbjets);
  tree->SetBranchAddress( "bjet1", &bjet1);
  tree->SetBranchAddress( "bjetHighestDisc", &bjetHighestDisc);
  tree->SetBranchAddress( "discH", &bdiscH);

  tree->SetBranchAddress( "lPt", &lPt);
  tree->SetBranchAddress( "lEta", &lEta);
  tree->SetBranchAddress( "lRelIso", &lRelIso);

  tree->SetBranchAddress( "phiCorrMet", &phiCorrMet);
  
  tree->SetBranchAddress( "ht", &ht);
  tree->SetBranchAddress( "ht3", &ht3);
  tree->SetBranchAddress( "ht4", &ht4);
  tree->SetBranchAddress( "ht5", &ht5);
  tree->SetBranchAddress( "htRatio", &htRatio);
  tree->SetBranchAddress( "meff", &meff);
  tree->SetBranchAddress( "y", &y);

  tree->SetBranchAddress( "mt", &mt);
  tree->SetBranchAddress( "mlb1", &mlb1);
  tree->SetBranchAddress( "mlb", &mlb);
  tree->SetBranchAddress( "m3b", &m3b);
  tree->SetBranchAddress( "m3", &m3);
  tree->SetBranchAddress( "centrality", &centrality);
  tree->SetBranchAddress( "mt2w", &mt2w);
  tree->SetBranchAddress( "hadChi2", &hadChi2);
  tree->SetBranchAddress( "topness", &topness);

  tree->SetBranchAddress( "dphimin", &dphimin);
  tree->SetBranchAddress( "drlb1", &drlb1);
  tree->SetBranchAddress( "drlbmin", &drlbmin);

  tree->SetBranchAddress("pdgIdLep1",&pdgIdLep1);
  tree->SetBranchAddress("pdgIdLep2",&pdgIdLep2);

  tree->SetBranchAddress("kinRegion",&kinRegion);
  tree->SetBranchAddress("searchRegionPre",&searchRegionPre);
  tree->SetBranchAddress("searchRegionPost",&searchRegionPost);
  tree->SetBranchAddress("CR1",&CR1);
  tree->SetBranchAddress("CR4",&CR4);
  tree->SetBranchAddress("CR5",&CR5);

  /////////////////////////////////////////////////////
  //  Output Definition
  /////////////////////////////////////////////////////

  //Branching Ratio
 
  TFile* outFile = new TFile( "./MakeHistos/"+sample[iSample]+".root", "Update");
  outFile->cd();

  TH1D* npvh[NDirs];
  TH1D* ngoodpvh[NDirs];

  TH1D* lpth[NDirs];
  TH1D* letah[NDirs];
  TH1D* lrelisoh[NDirs];

  TH1D* njetsh[NDirs];
  TH1D* jet1h[NDirs];
  TH1D* jet2h[NDirs];
  TH1D* jet3h[NDirs];
  TH1D* jet4h[NDirs];

  TH1D* nbjetsh[NDirs];
  TH1D* bjet1h[NDirs];
  TH1D* bjetHighDh[NDirs];
  TH1D* bdiscHh[NDirs];
  
  TH1D* hth[NDirs];
  TH1D* ht3h[NDirs];
  TH1D* ht4h[NDirs];
  TH1D* ht5h[NDirs];
  TH1D* htratioh[NDirs];
  TH1D* meth[NDirs];
  TH1D* meffh[NDirs];
  TH1D* yh[NDirs];

  TH1D* mth[NDirs];
  TH1D* mlb1h[NDirs];
  TH1D* mlbh[NDirs];
  TH1D* m3bh[NDirs];
  TH1D* m3h[NDirs];
  TH1D* centralityh[NDirs];
  TH1D* mt2wh[NDirs];
  TH1D* hadchi2h[NDirs];
  TH1D* topnessh[NDirs];

  TH1D* dphiminh[NDirs];
  TH1D* drlb1h[NDirs];
  TH1D* drlbminh[NDirs];

  TString dirName = ""; dirName += iSR;
  if (outFile->GetDirectory(dirName)) outFile->Delete(dirName + ";*");
  outFile->mkdir( dirName);
  TDirectory* SRDir = outFile->GetDirectory( dirName);
  SRDir->cd();
  
  for ( int iDir = 0; iDir < NDirs; iDir++){    
    SRDir->mkdir( controlDirName[iDir]);
    controlDir[iDir] = SRDir->GetDirectory( controlDirName[iDir]);
    controlDir[iDir]->cd();

    npvh[iDir] = new TH1D( "npv", "NPV", 51, -0.5, 50.5);
    ngoodpvh[iDir] = new TH1D( "ngoodpv", "NgoodPV", 51, -0.5, 50.5);

    lpth[iDir]     = new TH1D( "lpt", "lep p_{T} [GeV]",  12, 25., 500.);
    letah[iDir]    = new TH1D( "leta", "lep #Eta", 30, -3., 3.);
    lrelisoh[iDir] = new TH1D( "lRelIso", "lep RelIso", 30, 0., 1.);
    
    njetsh[iDir] = new TH1D(  "njets", "jets multiplicity",    10, -0.5, 9.5);
    jet1h[iDir]  = new TH1D(  "jet1", "1st jet p_{T} [GeV]",   25, 0., 500.);
    jet2h[iDir]  = new TH1D(  "jet2", "2nd jet p_{T} [GeV]",   25, 0., 500.);
    jet3h[iDir]  = new TH1D(  "jet3", "3rd jet p_{T} [GeV]",   25, 0., 500.);
    jet4h[iDir]  = new TH1D(  "jet4", "4th jet p_{T} [GeV]",   25, 0., 500.);
    
    nbjetsh[iDir]    = new TH1D( "nbjets", "b jets multiplicity",  6, -0.5, 5.5);  
    bjet1h[iDir]     = new TH1D(     "bjet1", "Leading b jet p_{T} [GeV]", 25, 0., 500.);
    bjetHighDh[iDir] = new TH1D( "bjetHighD", "p_{T} of the highest b disc jet [GeV]",  12, 0., 500.);
    bdiscHh[iDir]    = new TH1D( "bdisc", "bdisc",  20, 0., 1.);  

    meth[iDir] = new TH1D( "MET", "MET [GeV]", 12, 0., 400.);
    
    hth[iDir]      = new TH1D(   "Ht",   "Ht [GeV]",  20, 0., 1000.);
    ht3h[iDir]     = new TH1D(   "Ht3",   "Ht3 [GeV]",  20, 0., 1000.);
    ht4h[iDir]     = new TH1D(   "Ht4",   "Ht4 [GeV]",  20, 0., 1000.);
    ht5h[iDir]     = new TH1D(   "Ht5",   "Ht5 [GeV]",  20, 0., 1000.);
    htratioh[iDir] = new TH1D(   "HtRatio",   "HtRatio",  20, 0., 1.);
    meffh[iDir]    = new TH1D( "Meff", "Meff [GeV]",  40, 0., 1000.);
    yh[iDir]       = new TH1D(    "Y",    "Y [GeV^{1/2}]",  15, 0.,   30.);
    
    mth[iDir]      = new TH1D(  "Mt",  "Mt [GeV]", 30, 0., 300.);
    mlb1h[iDir]    = new TH1D(      "mlb1",     "Mlb1 [GeV]", 10, 0., 500.);
    mlbh[iDir]     = new TH1D(  "mlb", "Mlb [GeV]", 10, 0., 500.);
    m3bh[iDir]     = new TH1D(       "m3b",      "M3b [GeV]", 15, 0., 500.);
    m3h[iDir]      = new TH1D(        "m3",       "M3 [GeV]", 15, 0., 500.);
    centralityh[iDir] = new TH1D( "centrality", "centrality", 10, 0., 1.);
    mt2wh[iDir]    = new TH1D(      "mt2w",     "MT2W [GeV]", 15, 0.,  500.);
    hadchi2h[iDir] = new TH1D(      "hadChi2",     "hadChi2 [GeV]", 20, 0., 10.);
    topnessh[iDir] = new TH1D(      "topness",     "topness [GeV]", 30, -15., 15.);
    
    dphiminh[iDir] = new TH1D( "dphimin", "min dPhi (MET, jet1/2)", 17, 0., TMath::Pi() * 17./16.);
    drlb1h[iDir]   = new TH1D(    "drlb1", "dR(lep, bjet1)", 20, 0., 5.);
    drlbminh[iDir] = new TH1D(    "drlbmin", "min dR(lep, bjet)", 20, 0., 5.);
  }
  outFile->cd();

  for (int ievt=0;ievt<N;++ievt){    
    tree->GetEntry(ievt);
    
    //if (ievt%13453 == 0) cout<<"Event number "<<ievt<<"\r"<<flush;    

    if (iSample == 0) weight = 1.;
    else weight = globalWeight * triggerWeight * puWeight * topPtWeight * lumi;

    if ( (iSample - NSamples + NSignals) > -0.01 ) weight *= isrWeight;

    if (lRelIso > 0.1) continue;
    
    for (int ilep = 0; ilep < NLeps; ilep++){
      lepFlag = true;
      if (ilep == 0) lepFlag = (abs(pdgIdLep1) == 11);
      if (ilep == 1) lepFlag = (abs(pdgIdLep1) == 13);

      flag[ilep * NControlRegions + 0] = (searchRegionPost || CR1) && lepFlag;
      flag[ilep * NControlRegions + 1] = searchRegionPre && lepFlag;
      flag[ilep * NControlRegions + 2] = searchRegionPost && lepFlag;
      flag[ilep * NControlRegions + 3] = CR1 && lepFlag;
      flag[ilep * NControlRegions + 4] = CR4 && lepFlag;
      flag[ilep * NControlRegions + 5] = CR5 && lepFlag;
    }
    
    for ( int iDir = 0; iDir < NDirs; iDir++){
      if (!flag[iDir])
	continue;
      
      /////////////////////////////////////////////////////
      //  Histo Filling
      /////////////////////////////////////////////////////
      
      bool allCuts    = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButMt2w = (njets - nJetCut) > -0.0001 &&                   y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButY    = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut &&             dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButDphi = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut &&                      drlb1 < drlblCut && phiCorrMet > metCut && m3 > m3Cut;
      bool allButDrlb = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut &&                     phiCorrMet > metCut && m3 > m3Cut;
      bool allButMet  = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut &&                        m3 > m3Cut;
      bool allButM3   = (njets - nJetCut) > -0.0001 && mt2w > mt2wCut && y > yCut && dphimin > dphiCut && drlb1 < drlblCut && phiCorrMet > metCut              ;

      bool allButCentrality = allCuts && mlb1 < mlbCut;
      bool allButMlb        = allCuts && centrality > centralityCut;

      allCuts    &= centrality > centralityCut && mlb1 < mlbCut;
      allButMt2w &= centrality > centralityCut && mlb1 < mlbCut;
      allButY    &= centrality > centralityCut && mlb1 < mlbCut; 
      allButDphi &= centrality > centralityCut && mlb1 < mlbCut; 
      allButDrlb &= centrality > centralityCut && mlb1 < mlbCut; 
      allButMet  &= centrality > centralityCut && mlb1 < mlbCut;
      allButM3   &= centrality > centralityCut && mlb1 < mlbCut; 
    
      if (iDir%NControlRegions == 0 || iDir%NControlRegions == 1 || iDir%NControlRegions == 2 ){
 	if ( mt > 80.){
	  if (iSample != 0 && allCuts) mth[iDir]->Fill( mt, weight);
          continue;
	}
	if (mt < 50.) {
	  if (allCuts) mth[iDir]->Fill( mt, weight);
	  continue;
	}
      }
      
      if (allButMt2w) mt2wh[iDir]->Fill( mt2w, weight);
      if (allButY) yh[iDir]->Fill( y, weight);
      if (allButDphi) dphiminh[iDir]->Fill( dphimin, weight);
      if (allButDrlb) drlb1h[iDir]->Fill( drlb1, weight);
      if (allButMet) meth[iDir]->Fill( phiCorrMet, weight);
      if (allButM3) m3h[iDir]->Fill( m3, weight);
      if (allButCentrality) centralityh[iDir]->Fill( centrality, weight);
      if (allButMlb) mlb1h[iDir]->Fill( mlb1, weight);
  
      if (allCuts) {
	npvh[iDir]->Fill( npv, weight);
	ngoodpvh[iDir]->Fill( ngoodpv, weight);

	lpth[iDir]->Fill( lPt, weight);
	letah[iDir]->Fill( lEta, weight);
	lrelisoh[iDir]->Fill( lRelIso, weight);
	
	njetsh[iDir]->Fill( njets, weight);
	jet1h[iDir]->Fill( jet1, weight);
	jet2h[iDir]->Fill( jet2, weight);
	jet3h[iDir]->Fill( jet3, weight);
	jet4h[iDir]->Fill( jet4, weight);
	
	nbjetsh[iDir]->Fill( nbjets, weight);
	bjet1h[iDir]->Fill( bjet1, weight);
	bjetHighDh[iDir]->Fill( bjetHighestDisc, weight);
	bdiscHh[iDir]->Fill( bdiscH, weight);
	
	hth[iDir]->Fill( ht, weight);
	ht3h[iDir]->Fill( ht3, weight);
	ht4h[iDir]->Fill( ht4, weight);
	ht5h[iDir]->Fill( ht5, weight);
	htratioh[iDir]->Fill( htRatio, weight);
	meffh[iDir]->Fill( meff, weight);
      
	mth[iDir]->Fill( mt, weight);
	mlb1h[iDir]->Fill( mlb1, weight);
	m3bh[iDir]->Fill( m3b, weight);
	hadchi2h[iDir]->Fill( hadChi2, weight);
	topnessh[iDir]->Fill( topness, weight);
      
	drlbminh[iDir]->Fill( drlbmin, weight);
      }
    }
  }
  
  outFile->Write();
  outFile->Close();
  
  inFile->Close();
  
  return 0;
}
Esempio n. 18
0
void compare()
{
	msglvl[DBG] = SILENT;
	msglvl[INF] = VISUAL;
	msglvl[WRN] = VISUAL;
	msglvl[ERR] = VISUAL;
	msglvl[FAT] = VISUAL;

	TDirectory* oldDir = gDirectory;

	style();

	TFile* f2ds = NULL;
	TFile* f2d  = NULL;
	TH2D* h2ds  = NULL;
	TH2D* h2d   = NULL;
	TH1D* h1s   = NULL;
	TH1D* h1    = NULL;
	TH1D* h1dy  = NULL;

	Int_t g4bin = 50;
	TString model = "ZP";

	int imassmin = 330;
	int imassmax = 4930;
	int dimass   = 100;
	for(int imass=imassmin ; imass<=imassmax ; imass+=dimass)
	{
		TString mass = (TString)_s(imass);
		_INFO("enter "+(string)mass);

		TString modeltmp = (model=="ZP") ? "P" : "KK";

		oldDir->cd();
		f2ds = new TFile("~yiftahsi/KK_analysis_t301/2dtemplates_FEB1/templates2d_Xmass"+mass+".root","READ");
		h2ds = (TH2D*)f2ds->Get("h2"+model+"/Z"+modeltmp+"_mXp"+mass)->Clone();

		f2d  = new TFile("~yiftahsi/KK_analysis_t301/2dtemplates_FEB2/templates2d_Xmass"+mass+".root","READ");
		h2d = (TH2D*)f2d->Get("h2"+model+"/Z"+modeltmp+"_mXp"+mass)->Clone();
                oldDir->cd();

		//------------------------------------------------------------
		const Int_t nbins = h2d->GetNbinsX();
		Double_t bins[nbins+1];
		TAxis* xaxis = (TAxis*)h2d->GetXaxis();
		for(int i=0 ; i<nbins ; i++) bins[i] = xaxis->GetBinLowEdge(i+1);
		bins[nbins] = xaxis->GetBinUpEdge(nbins);
		//------------------------------------------------------------
		
		Double_t g4 = h2d->GetYaxis()->GetBinLowEdge(g4bin);
		TString g = (TString)_s(sqrt(sqrt(g4)),2);
	
		TString modelname = (model=="ZP") ? "Z'" : "KK";
	
		h1s  = new TH1D(mass+"_subtracted","g="+g+", m_{"+modelname+"} = "+mass+" GeV;m_{ee} TeV;Events",nbins,bins);
		h1   = new TH1D(mass+"_inamplitude","g="+g+", m_{"+modelname+"} = "+mass+" GeV;m_{ee} TeV;Events",nbins,bins);
		h1dy = new TH1D(mass+"_dy","g="+g+", m_{"+modelname+"} = "+mass+" GeV;m_{ee} TeV;Events",nbins,bins);
		for(Int_t bin=0 ; bin<=nbins+1 ; bin++)
		{
			h1s->SetBinContent(bin, h2ds->GetBinContent(bin,g4bin));
			h1->SetBinContent(bin, h2d->GetBinContent(bin,g4bin));
			h1dy->SetBinContent(bin, h2d->GetBinContent(bin,1));
		}

		TLegend* leg = new TLegend(0.55,0.72,0.85,0.85,NULL,"brNDC");
		leg->SetFillStyle(4000); //will be transparent
		leg->SetFillColor(0);
		leg->SetTextFont(42);
		
		TCanvas* c = new TCanvas("c"+mass,"c"+mass,600,400);
		c->Draw();
		c->cd();
		c->SetTicks(1,1);
		c->SetLogy();
		c->SetLogx();
		c->SetGridy();	
		c->cd();

		double ymin = getYmin(h1s);
		ymin = (getYmin(h1dy)<ymin) ? getYmin(h1dy): ymin;
		h1dy->SetMinimum( ymin*0.1);
		TLine* l = new TLine(0.12805,h1dy->GetMinimum(),0.12805,h1dy->GetMaximum());
		l->SetLineColor(kGreen+2);
		
		h1dy->SetLineColor(kBlue);
		h1dy->SetLineStyle(1);
		h1dy->SetLineWidth(2);
		leg->AddEntry(h1dy,"DY, in-amplitude k_{F}","l");
		h1dy->DrawCopy();

		h1s->SetLineColor(kBlack);
		h1s->SetLineStyle(1);
		h1s->SetLineWidth(2);
		leg->AddEntry(h1s,modelname+", subtracted k_{F}","l");
		h1s->DrawCopy("SAMES");

		h1->SetLineColor(kRed);
		h1->SetLineStyle(3);
		h1->SetLineWidth(2);
		leg->AddEntry(h1,modelname+", in-amplitude k_{F}","l");
		h1->DrawCopy("SAMES");
		l->Draw("SAMES");
		leg->Draw("SAMES");
	
		_INFO("done "+(string)mass);

		c->RedrawAxis();
		c->Update();
		g.ReplaceAll(".","");
		if(imass==imassmin)      c->SaveAs("kfactors_g"+model+g+".pdf(");
		else if(imass==imassmax) c->SaveAs("kfactors_g"+model+g+".pdf)");
		else                     c->SaveAs("kfactors_g"+model+g+".pdf");
	}
}
Esempio n. 19
0
void ResultPlot(TString expectation="skims/13TeV/reduced_trees/TTJets_MSDecaysCKM_central_Tune4C_13TeV-madgraph-tauola_Phys14DR-PU20bx25_PHYS14_25_V1-v1_MINIAODSIM_UCSB2406_v78.root",
		TString prediction="macros/junews/lostleptons/arne/Prediction/Prediction.root")
{
	

  //Reset ROOT and connect tree file
  gROOT->Reset();
  TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(expectation.Data());
  if (!f) {
    f = new TFile(expectation.Data());
  }
  // output tree
  TFile *outPutFile = new TFile("macros/junews/lostleptons/arne/Closure/Closure.root","RECREATE"); 
  outPutFile->cd();
  TTree* OutPutTreeExp_ = new TTree("ResultExp","Result Lost-Lepton Tree for plotting tool");
  TTree* OutPutTreePre_ = new TTree("ResultPre","Result Lost-Lepton Tree for plotting tool");
  UShort_t Bin=0;
  Float_t Weight_=0, PredictionWeight_=0; 
	
  OutPutTreeExp_->Branch("Weight", &Weight_, "Weight/F");
  OutPutTreePre_->Branch("totalWeightDiLep", &PredictionWeight_, "totalWeightDiLep/F");
  OutPutTreeExp_->Branch("Bin",&Bin,"Bin/s");
  //
  UShort_t muAcc_=0, muIso_=0, muReco_=0;
  OutPutTreeExp_->Branch("muAcc",&muAcc_,"muAcc/s");
  OutPutTreeExp_->Branch("muReco",&muReco_,"muReco/s");
  OutPutTreeExp_->Branch("muIso",&muIso_,"muIso/s");
	
  UShort_t elAcc_=0, elIso_=0, elReco_=0;
  OutPutTreeExp_->Branch("elAcc",&elAcc_,"elAcc/s");
  OutPutTreeExp_->Branch("elReco",&elReco_,"elReco/s");
  OutPutTreeExp_->Branch("elIso",&elIso_,"elIso/s");
  //
  Float_t muIsoWeight_=0, muRecoWeight_=0, muAccWeight_=0;
  OutPutTreePre_->Branch("muIsoWeight", &muIsoWeight_, "muIsoWeight/F");
  OutPutTreePre_->Branch("muRecoWeight", &muRecoWeight_, "muRecoWeight/F");
  OutPutTreePre_->Branch("muAccWeight", &muAccWeight_, "muAccWeight/F");
	
  Float_t elIsoWeight_=0, elRecoWeight_=0, elAccWeight_=0;
  OutPutTreePre_->Branch("elIsoWeight", &elIsoWeight_, "elIsoWeight/F");
  OutPutTreePre_->Branch("elRecoWeight", &elRecoWeight_, "elRecoWeight/F");
  OutPutTreePre_->Branch("elAccWeight", &elAccWeight_, "elAccWeight/F");
	
  UShort_t num_veto_mus_=0, num_veto_els_=0;
  OutPutTreePre_->Branch("num_veto_mus",&num_veto_mus_,"num_veto_mus/s");
  OutPutTreePre_->Branch("num_veto_els",&num_veto_els_,"num_veto_els/s");
	
  TTree* LostLeptonExpectation = (TTree*) f->Get("reduced_tree");

	
  SearchBinEventCount * ControlSampleMu_ = new SearchBinEventCount("ControlSampleMu");
  SearchBinEventCount * ControlSampleEl_ = new SearchBinEventCount("ControlSampleEl");
	
  SearchBinEventCount * totalExpectation_ = new SearchBinEventCount("TotalLostLeptonExpecation");
  SearchBinEventCount * totalPrediction_ = new SearchBinEventCount("TotalLostLeptonPrediction");
  SearchBinEventCount * totalPredictionMu_ = new SearchBinEventCount("TotalLostLeptonPredictionMu");
  SearchBinEventCount * totalPredictionEl_ = new SearchBinEventCount("TotalLostLeptonPredictionEl");
	
  // SearchBinEventCount * totalExpectationIsoTrackReduction_ = new SearchBinEventCount("TotalLostLeptonExpecationIsoTrackReduction");
  // SearchBinEventCount * totalPredictionIsoTrackReduction_ = new SearchBinEventCount("TotalLostLeptonPredictionIsoTrackReduction");
  // SearchBinEventCount * totalPredictionMuIsoTrackReduction_ = new SearchBinEventCount("TotalLostLeptonPredictionMuIsoTrackReduction");
  // SearchBinEventCount * totalPredictionElIsoTrackReduction_ = new SearchBinEventCount("TotalLostLeptonPredictionElIsoTrackReduction");
	
  // separted closure
  SearchBinEventCount * totalExpectationMuAcc_ = new SearchBinEventCount("TotalLostLeptonExpecationMuAcc");
  SearchBinEventCount * totalPredictionMuCSMuAcc_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSMuAcc");
  SearchBinEventCount * totalPredictionElCSMuAcc_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSMuAcc");
	
  SearchBinEventCount * totalExpectationMuReco_ = new SearchBinEventCount("TotalLostLeptonExpecationMuReco");
  SearchBinEventCount * totalPredictionMuCSMuReco_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSMuReco");
  SearchBinEventCount * totalPredictionElCSMuReco_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSMuReco");
	
  SearchBinEventCount * totalExpectationMuIso_ = new SearchBinEventCount("TotalLostLeptonExpecationMuIso");
  SearchBinEventCount * totalPredictionMuCSMuIso_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSMuIso");
  SearchBinEventCount * totalPredictionElCSMuIso_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSMuIso");
	
	
	
  SearchBinEventCount * totalExpectationElAcc_ = new SearchBinEventCount("TotalLostLeptonExpecationElAcc");
  SearchBinEventCount * totalPredictionMuCSElAcc_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSElAcc");
  SearchBinEventCount * totalPredictionElCSElAcc_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSElAcc");
	
  SearchBinEventCount * totalExpectationElReco_ = new SearchBinEventCount("TotalLostLeptonExpecationElReco");
  SearchBinEventCount * totalPredictionMuCSElReco_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSElReco");
  SearchBinEventCount * totalPredictionElCSElReco_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSElReco");
	
  SearchBinEventCount * totalExpectationElIso_ = new SearchBinEventCount("TotalLostLeptonExpecationElIso");
  SearchBinEventCount * totalPredictionMuCSElIso_ = new SearchBinEventCount("TotalLostLeptonPredictionMuCSElIso");
  SearchBinEventCount * totalPredictionElCSElIso_ = new SearchBinEventCount("TotalLostLeptonPredictionElCSElIso");
	
  double totalExp=0, totalPre=0;
  double totalExpError=0, totalPreError=0;
  double totalPreMu=0, totalPreMuError=0;
  double totalPreEl=0, totalPreElError=0;
	
  double totalExpMuAcc=0, totalExpMuReco=0, totalExpMuIso=0;
	
  double totalPreMuAcc=0, totalPreMuReco=0, totalPreMuIso=0;
	
	
  double totalExpElAcc=0, totalExpElReco=0, totalExpElIso=0;
	
  double totalPreElAcc=0, totalPreElReco=0, totalPreElIso=0;
	
  //Declaration of leaves types
  Float_t         HT;
  Float_t         MHT;
  UShort_t        NJets;
  UShort_t        BTags;

  Float_t         min_delta_phi_met_N;
  Float_t         Weight;
	
  UShort_t        Expectation;
  UShort_t        muAcc;
  UShort_t        muReco;
  UShort_t        muIso;
  UShort_t        elAcc;
  UShort_t        elReco;
  UShort_t        elIso;
  UShort_t        ExpectationDiLep;

  bool passesBadJetFilter;
  Int_t PBNRcode;
  //	UShort_t        ExpectationReductionIsoTrack;
	
  // Set branch addresses.
  LostLeptonExpectation->SetBranchAddress("ht30",&HT);
  LostLeptonExpectation->SetBranchAddress("mht30",&MHT);
  LostLeptonExpectation->SetBranchAddress("num_jets_pt30",&NJets);
  LostLeptonExpectation->SetBranchAddress("num_csvm_jets30",&BTags);
  LostLeptonExpectation->SetBranchAddress("min_delta_phi_met_N",&min_delta_phi_met_N);
  LostLeptonExpectation->SetBranchAddress("weightppb",&Weight);
	
  LostLeptonExpectation->SetBranchAddress("Expectation",&Expectation);
  //	LostLeptonExpectation->SetBranchAddress("ExpectationReductionIsoTrack",&ExpectationReductionIsoTrack);
  LostLeptonExpectation->SetBranchAddress("muAcc",&muAcc);
  LostLeptonExpectation->SetBranchAddress("muReco",&muReco);
  LostLeptonExpectation->SetBranchAddress("muIso",&muIso);
	
  LostLeptonExpectation->SetBranchAddress("elAcc",&elAcc);
  LostLeptonExpectation->SetBranchAddress("elReco",&elReco);
  LostLeptonExpectation->SetBranchAddress("elIso",&elIso);
	
  //LostLeptonExpectation->SetBranchAddress("IsolatedTracksNum",&IsolatedTracksNum);
  LostLeptonExpectation->SetBranchAddress("ExpectationDiLep",&ExpectationDiLep);

  LostLeptonExpectation->SetBranchAddress("passesBadJetFilter",&passesBadJetFilter);
  LostLeptonExpectation->SetBranchAddress("PBNRcode",&PBNRcode);

  LostLeptonExpectation->SetBranchStatus("jet_*", 0);
  LostLeptonExpectation->SetBranchStatus("fat*", 0);
  LostLeptonExpectation->SetBranchStatus("*track*", 0);
	
	
  Long64_t nentries = LostLeptonExpectation->GetEntries();
	
  SearchBins *SearchBins_ = new SearchBins();

	
  Long64_t nbytes = 0;
  for (Long64_t i=0; i<nentries;i++) {
    nbytes += LostLeptonExpectation->GetEntry(i);
    Weight*=10000;
    //cout << "Expectation weight: " << Weight << endl;
    // total expectation
    if(NJets<4) continue;
    if(BTags<2) continue;
    if(HT<500) continue;
    if(MHT<200) continue;
    if(min_delta_phi_met_N<6) continue;
    // if (!passesBadJetFilter || PBNRcode<1) continue;
    //if (num_true_mus+num_true_els==1&&num_true_had_taus==0)
     if(Expectation==1 && NJets>3.1)
      {
	totalExpectation_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExp+=Weight;
	totalExpError+= Weight*Weight;
	Bin = SearchBins_->GetBinNumber(HT,MHT,NJets,BTags);
	Weight_=Weight;
	muAcc_=muAcc; muReco_=muReco; muIso_=muIso; elAcc_=elAcc; elReco_=elReco; elIso_=elIso;
	OutPutTreeExp_->Fill();
      }
    // if(Expectation==1 && ExpectationReductionIsoTrack==0)
    // {
    // 	totalExpectationIsoTrackReduction_->Fill(HT,MHT,NJets,BTags,Weight);
    // }
    if(muAcc==0)
      {
	totalExpectationMuAcc_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpMuAcc+=Weight;
      }
    if(muReco==0)
      {
	totalExpectationMuReco_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpMuReco+=Weight;
      }
    if(muIso==0)
      {
	totalExpectationMuIso_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpMuIso+=Weight;
      }
					
    if(elAcc==0)
      {
	totalExpectationElAcc_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpElAcc+=Weight;
      }
    if(elReco==0)
      {
	totalExpectationElReco_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpElReco+=Weight;
      }
    if(elIso==0)
      {
	totalExpectationElIso_->Fill(HT,MHT,NJets,BTags,Weight);
	totalExpElIso+=Weight;
      }
  }
	   
  // loop on prediction
  gROOT->Reset();
  TFile *f1 = (TFile*)gROOT->GetListOfFiles()->FindObject(prediction.Data());
  if (!f1) {
    f1 = new TFile(prediction.Data());
  }
  TTree* LostLeptonPrediction = (TTree*) f1->Get("LostLeptonPrediction");
	
  Float_t         MTW;
  UShort_t        num_veto_mus;
  UShort_t        num_veto_els;
	
  Float_t         totalWeightDiLep;
  //	Float_t         totalWeightDiLepIsoTrackReduced;
	
  Float_t         muIsoWeight;
  Float_t         muRecoWeight;
  Float_t         muAccWeight;

  Float_t         elAccWeight;
  Float_t         elRecoWeight;
  Float_t         elIsoWeight;
	
	
	
  LostLeptonPrediction->SetBranchAddress("HT",&HT);
  LostLeptonPrediction->SetBranchAddress("MHT",&MHT);
  LostLeptonPrediction->SetBranchAddress("NJets",&NJets);
  LostLeptonPrediction->SetBranchAddress("BTags",&BTags);
  LostLeptonPrediction->SetBranchAddress("min_delta_phi_met_N",&min_delta_phi_met_N);
  LostLeptonPrediction->SetBranchAddress("Weight",&Weight);
	
  LostLeptonPrediction->SetBranchAddress("MTW",&MTW);
  LostLeptonPrediction->SetBranchAddress("num_veto_mus",&num_veto_mus);
  LostLeptonPrediction->SetBranchAddress("num_veto_els",&num_veto_els);
  LostLeptonPrediction->SetBranchAddress("totalWeightDiLep",&totalWeightDiLep);
  //	LostLeptonPrediction->SetBranchAddress("totalWeightDiLepIsoTrackReduced",&totalWeightDiLepIsoTrackReduced);
	
  LostLeptonPrediction->SetBranchAddress("muIsoWeight",&muIsoWeight);
  LostLeptonPrediction->SetBranchAddress("muRecoWeight",&muRecoWeight);
  LostLeptonPrediction->SetBranchAddress("muAccWeight",&muAccWeight);
	
  LostLeptonPrediction->SetBranchAddress("elAccWeight",&elAccWeight);
  LostLeptonPrediction->SetBranchAddress("elRecoWeight",&elRecoWeight);
  LostLeptonPrediction->SetBranchAddress("elIsoWeight",&elIsoWeight);

	
  nentries = LostLeptonPrediction->GetEntries();
  nbytes = 0;
  for (Long64_t i=0; i<nentries;i++) {
    nbytes += LostLeptonPrediction->GetEntry(i);
    // total expectation
    Weight*=10000;
    //    // cout << "Prediction weight: " << Weight << endl;
    if(MTW>100 || NJets<3.7 || BTags<1.6)continue;
    // cout << "NJets = " << NJets << endl;
    if(NJets<4) continue;
    // cout << "BTags = " << BTags << endl;
    if(BTags<2) continue;
    // cout << "HT = " << HT << endl;
    if(HT<500) continue;
    // cout << "MHT = " << MHT << endl;
    if(MHT<200) continue;
    // cout << "min_delta_phi_met_N = " << min_delta_phi_met_N << endl;
    if(min_delta_phi_met_N<6) continue;
    Bin = SearchBins_->GetBinNumber(HT,MHT,NJets,BTags);
    Weight_=Weight;
    num_veto_mus_=num_veto_mus;
    num_veto_els_=num_veto_els;
    if(num_veto_mus==1 && num_veto_els==0)
      {
	// cout << "Single muon event..." << endl;
	ControlSampleMu_->Fill(HT,MHT,NJets,BTags,Weight);
			
	totalPrediction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLep/2);
	totalPredictionMu_->Fill(HT,MHT,NJets,BTags,totalWeightDiLep);
	totalPre+=totalWeightDiLep;
	totalPreError+= totalWeightDiLep*totalWeightDiLep;
	totalPreMu+=totalWeightDiLep;
	totalPreMuError+= totalWeightDiLep*totalWeightDiLep;
	// isotrackveto applied
	// totalPredictionIsoTrackReduction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLepIsoTrackReduced/2);
	// totalPredictionMuIsoTrackReduction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLepIsoTrackReduced);
	// separted closure
	totalPredictionMuCSMuAcc_->Fill(HT,MHT,NJets,BTags,muAccWeight);
	totalPreMuAcc+=muAccWeight;
	totalPredictionMuCSMuReco_->Fill(HT,MHT,NJets,BTags,muRecoWeight);
	totalPreMuReco+=muRecoWeight;
	totalPredictionMuCSMuIso_->Fill(HT,MHT,NJets,BTags,muIsoWeight);
	totalPreMuIso+=muIsoWeight;
			
	totalPredictionMuCSElAcc_->Fill(HT,MHT,NJets,BTags,elAccWeight);
	totalPreElAcc+=elAccWeight;
	totalPredictionMuCSElReco_->Fill(HT,MHT,NJets,BTags,elRecoWeight);
	totalPreElReco+=elRecoWeight;
	totalPredictionMuCSElIso_->Fill(HT,MHT,NJets,BTags,elIsoWeight);
	totalPreElIso+=elIsoWeight;
	muIsoWeight_=muIsoWeight; muRecoWeight_=muRecoWeight; muAccWeight_=muAccWeight;  elIsoWeight_=elIsoWeight; elRecoWeight_=elRecoWeight; elAccWeight_=elAccWeight; 
	PredictionWeight_= totalWeightDiLep;
	OutPutTreePre_->Fill();
      }
    if(num_veto_mus==0 && num_veto_els==1)
      {
	ControlSampleEl_->Fill(HT,MHT,NJets,BTags,Weight);
			
	totalPrediction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLep/2);
	totalPredictionEl_->Fill(HT,MHT,NJets,BTags,totalWeightDiLep);
	totalPre+=totalWeightDiLep;
	totalPreError+= totalWeightDiLep*totalWeightDiLep;
	totalPreEl+=totalWeightDiLep;
	totalPreElError+= totalWeightDiLep*totalWeightDiLep;
	// isotrackveto applied
	// totalPredictionIsoTrackReduction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLepIsoTrackReduced/2);
	// totalPredictionElIsoTrackReduction_->Fill(HT,MHT,NJets,BTags,totalWeightDiLepIsoTrackReduced);
	// separted closure
	totalPredictionElCSMuAcc_->Fill(HT,MHT,NJets,BTags,muAccWeight);
	totalPredictionElCSMuReco_->Fill(HT,MHT,NJets,BTags,muRecoWeight);
	totalPredictionElCSMuIso_->Fill(HT,MHT,NJets,BTags,muIsoWeight);
			
	totalPredictionElCSElAcc_->Fill(HT,MHT,NJets,BTags,elAccWeight);
	totalPredictionElCSElReco_->Fill(HT,MHT,NJets,BTags,elRecoWeight);
	totalPredictionElCSElIso_->Fill(HT,MHT,NJets,BTags,elIsoWeight);
	PredictionWeight_= totalWeightDiLep;
	OutPutTreePre_->Fill();
      }
  }
	
  TH1D* expectationTH1 = (TH1D*) totalExpectation_->getFullTH1D();
  TH1D* predictionTH1 = (TH1D*) totalPrediction_->getFullTH1D();
  TH1D* FullClosure = (TH1D*) expectationTH1->Clone();
  FullClosure->Divide(predictionTH1,expectationTH1,1,1,"B");
  FullClosure->SetName("LostLeptonClosure");
  FullClosure->SetTitle("Closure of lost-lepton method");
	
  TH1D* predictionTH1Mu = (TH1D*) totalPredictionMu_->getFullTH1D();
  TH1D* FullClosureMu = (TH1D*) expectationTH1->Clone();
  FullClosureMu->Divide(predictionTH1Mu,expectationTH1,1,1,"B");
  FullClosureMu->SetName("LostLeptonClosureMuCS");
  FullClosureMu->SetTitle("Closure of lost-lepton method #mu control-sample");
	
  TH1D* predictionTH1El = (TH1D*) totalPredictionEl_->getFullTH1D();
  TH1D* FullClosureEl = (TH1D*) expectationTH1->Clone();
  FullClosureEl->Divide(predictionTH1El,expectationTH1,1,1,"B");
  FullClosureEl->SetName("LostLeptonClosureElCS");
  FullClosureEl->SetTitle("Closure of lost-lepton method el control-sample");

  std::cout<<"Result:\n TotalExpectation: "<<totalExp<<" +- " << sqrt(totalExpError)<<"\n TotalPrediction: "<<totalPre/2<<" +- "<<sqrt(totalPreError)/2<<std::endl;
  std::cout<<"TotalExpectation: "<<totalExp<<" +- " << sqrt(totalExpError)<<"\n TotalPredictionMu: "<<totalPreMu<<" +- "<<sqrt(totalPreMuError)<<std::endl;
  std::cout<<"TotalExpectation: "<<totalExp<<" +- " << sqrt(totalExpError)<<"\n TotalPredictionEl: "<<totalPreEl<<" +- "<<sqrt(totalPreElError)<<std::endl;
  std::cout<<"--------------------------------------------------------------------------------------------------------------------------\n";
  std::cout<<"MuAccExp: "<<totalExpMuAcc<<"\n MuAccPre: "<<totalPreMuAcc<<std::endl;
  std::cout<<"MuRecoExp: "<<totalExpMuReco<<"\n MuRecoPre: "<<totalPreMuReco<<std::endl;
  std::cout<<"MuIsoExp: "<<totalExpMuIso<<"\n MuIsoPre: "<<totalPreMuIso<<std::endl;
  std::cout<<"ElAccExp: "<<totalExpElAcc<<"\n ElAccPre: "<<totalPreElAcc<<std::endl;
  std::cout<<"ElRecoExp: "<<totalExpElReco<<"\n ElRecoPre: "<<totalPreElReco<<std::endl;
  std::cout<<"ElIsoExp: "<<totalExpElIso<<"\n ElIsoPre: "<<totalPreElIso<<std::endl;
	
  outPutFile->cd();
  OutPutTreeExp_->Write();
  OutPutTreePre_->Write();
  FullClosure->Write();
  FullClosureMu->Write();
  FullClosureEl->Write();
  outPutFile->mkdir("Closures");
  TDirectory *dClosures = (TDirectory*)outPutFile->Get("Closures");
  SaveClosure(totalPredictionMuCSMuAcc_->getFullTH1D(), totalExpectationMuAcc_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionMuCSMuReco_->getFullTH1D(), totalExpectationMuReco_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionMuCSMuIso_->getFullTH1D(), totalExpectationMuIso_->getFullTH1D(), dClosures);
	
  SaveClosure(totalPredictionMuCSElAcc_->getFullTH1D(), totalExpectationElAcc_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionMuCSElReco_->getFullTH1D(), totalExpectationElReco_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionMuCSElIso_->getFullTH1D(), totalExpectationElIso_->getFullTH1D(), dClosures);
	
  SaveClosure(totalPredictionElCSMuAcc_->getFullTH1D(), totalExpectationMuAcc_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionElCSMuReco_->getFullTH1D(), totalExpectationMuReco_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionElCSMuIso_->getFullTH1D(), totalExpectationMuIso_->getFullTH1D(), dClosures);
	
  SaveClosure(totalPredictionElCSElAcc_->getFullTH1D(), totalExpectationElAcc_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionElCSElReco_->getFullTH1D(), totalExpectationElReco_->getFullTH1D(), dClosures);
  SaveClosure(totalPredictionElCSElIso_->getFullTH1D(), totalExpectationElIso_->getFullTH1D(), dClosures);
	
  // SaveClosure(totalPredictionIsoTrackReduction_->getFullTH1D(), totalExpectationIsoTrackReduction_->getFullTH1D(), dClosures);
  // SaveClosure(totalPredictionMuIsoTrackReduction_->getFullTH1D(), totalExpectationIsoTrackReduction_->getFullTH1D(), dClosures);
  // SaveClosure(totalPredictionElIsoTrackReduction_->getFullTH1D(), totalExpectationIsoTrackReduction_->getFullTH1D(), dClosures);
	
	
  outPutFile->mkdir("Expectation");
  TDirectory *dExpectation = (TDirectory*)outPutFile->Get("Expectation");
  dExpectation->cd();
  totalExpectation_->saveResults(dExpectation);
  outPutFile->mkdir("Prediction");
  TDirectory *dPrediction = (TDirectory*)outPutFile->Get("Prediction");
  dPrediction->cd();
  totalPrediction_->saveResults(dPrediction);
  totalPredictionMu_->saveResults(dPrediction);
  totalPredictionEl_->saveResults(dPrediction);
	
  outPutFile->mkdir("ControlSample");
  TDirectory *dControlSample = (TDirectory*)outPutFile->Get("ControlSample");
  SaveClosure(ControlSampleEl_->getFullTH1D(), ControlSampleMu_->getFullTH1D(), dControlSample);
  dControlSample->cd();
  ControlSampleMu_->saveResults(dControlSample);
  ControlSampleEl_->saveResults(dControlSample);
	
}
void TnPDrawMass_test_5eta5()
{
    char *infile;
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_2G_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_Multi_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_PAMu7_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_merge_v1.root";
    //char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/mc/out/gputEveryCut_mc_allDirection_v24_nominalCond_5etaBins_cutG_all_narrow_v1.root";
    char *files = "/afs/cern.ch/work/g/goni/cms760pre4/src/test_TNP/TnP/data/outputEveryCut_data_allDirection_v24_nominalCond_5etaBins_cutG_all_nominal_v8_oldeta.root";

    TString outname_in, outname_mid, outname_out;
    TString middle_name, middle_name2;

    gROOT->SetStyle("Plain");
    gStyle->SetOptStat(0);
    gStyle->SetTitle(0);

    gStyle->SetPaperSize(20,26);
    TCanvas *c1 = new TCanvas();
    Int_t type = 112;
    TString out1 = outfile_ + "[";
		c1->SetLogy();
    c1->Print(out1);

    infile = files;
    TFile *f = new TFile(infile);

    outname_in = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps[";
    outname_mid = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps";
    outname_out = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps]";


    cout<<" Out Name : "<<outname_in<<" "<<outname_mid<<" "<<outname_in<<endl;
        

    TString tot_dir; //dir_suffix;
    
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
		//								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_",};//1
    //TString ptbins1[ptBins1] = {"3.3 - 3.8 GeV", "3.8 - 4.3  GeV", "4.3 - 5 GeV", "5 - 6 GeV", "6 - 7 GeV",
		//								"7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//1
    TString dir_pt[ptBins] = {"tpTree/ptBin_eta5_0/", "tpTree/ptBin_eta5_1/", "tpTree/ptBin_eta5_2/", "tpTree/ptBin_eta5_3/", "tpTree/ptBin_eta5_4/", "tpTree/ptBin_eta5_5/", "tpTree/ptBin_eta5_6/", "tpTree/ptBin_eta5_7/"};//5
    TString ptbins1[ptBins1] = {"1.3 - 1.6 GeV", "1.6 - 1.8 GeV", "1.8 - 2.0  GeV", "2.0 - 2.6 GeV", "2.6 - 3.4 GeV", "3.4 - 4.8 GeV", "4.8 -6.0 GeV", "6.0 - 30 GeV"};//5
   

    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//3
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//3
    
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//4
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//4
     
    //TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
	  //								"pt_bin5_", "pt_bin6_", "pt_bin7_", "pt_bin8_", "pt_bin9_"};//5
    //TString ptbins1[ptBins1] = {"0 - 3.3 GeV", "3.3 - 3.8  GeV", "3.8 - 4.3 GeV", "4.3 - 5 GeV", "5 -6 GeV",
		//								"6 - 7 GeV", "7 - 8 GeV", "8 - 10 GeV", "10 - 13 GeV", "13 - 30 GeV"};//5

    //dir_pt = "tpTree/ptBin_eta1/";
    //dir_pt = "tpTree/ptBin_eta3/";
    //dir_pt = "tpTree/ptBin_eta3/";
    //dir_pt = "tpTree/ptBin_eta5/";
    //dir_pt = "tpTree/ptBin_eta5/";

    //dir_suffix = "_cbGaussPlusPoly1";
    //dir_suffix = "_cbGaussPlusPoly4";
    TString dir_suffix[ptBins]= {"_cbGaussPlusExpo5_0","_cbGaussPlusExpo5_1","_cbGaussPlusExpo5_2","_cbGaussPlusExpo5_3","_cbGaussPlusExpo5_4","_cbGaussPlusExpo5_5", "_cbGaussPlusExpo5_6", "_cbGaussPlusExpo5_7"};   
    //dir_suffix = "_GaussPlusExpo";
    //dir_suffix = "_twoGaussPlusExpo";
    gStyle->SetPaperSize(20,26);

    c1->Print(outname_in);
    int cnt = 0;

    TCanvas *tmp1 = new TCanvas();
    tmp1->cd();

    TString title;
    title = "J/#psi Efficiency Heavy Ion TnP Result (" + middle_name2 + ")";

    c1 = (TCanvas *)tmp1->Clone();
    c1->Print(outname_mid);
    c1->Print(outfile_);

    TString mid_title = "Centrality : (" + middle_name2 + ")";
    TString leg_title = Cat2 + " Efficiency (" + middle_name2 + ")";

    // pt
    for(int j = 0; j < ptBins; j++){
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsi_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;
        TString tot_dir = dir_pt[j] + "abseta_bin0__event_PrimaryVertex_z_bin0__pt_bin0__tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix[j];//2G,PAMu3,merge
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu7_standard_pass_" + dir_suffix;//PAMu7
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__pair_probeMultiplicity_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsiG_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;//multi
        //TString tot_dir = dir_pt + "abseta_bin0__event_PrimaryVertex_z_bin0__" + ptbins[j] + "_tag_eta_bin0__tag_pt_bin0__Acc_JPsi_pass__Calo_pass__tag_PAMu3_standard_pass_" + dir_suffix;//merge
        //
      
  
        f->cd(tot_dir);
        cout<<" tot_dir : "<<tot_dir<<endl;
        TDirectory *root_dir = gDirectory;
        TIter rootnextkey( root_dir->GetListOfKeys() );
        root_dir->cd();
        TKey *rootkey;
        TCanvas *ctmp = new TCanvas();
        ctmp->cd();

        TLatex l;
        l.SetTextAlign(13);
        l.SetTextSize(0.06);
        l.DrawLatex(0.1,0.8,mid_title);
        l.DrawLatex(0.1,0.6,"Bin : ");
        l.SetTextSize(0.04);
        //l.DrawLatex(0.1,0.5,tot_dir);
        l.DrawLatex(0.1,0.5,ptbins1[j]);
        

        ctmp->Update();
        c1 = (TCanvas *)ctmp->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        while( rootkey = (TKey*)rootnextkey() )
        {
            TObject *rootobj = rootkey->ReadObj();
            TDirectory *rdir = gDirectory;
            TIter rdirnextkey(rdir->GetListOfKeys());
            rdir->cd();
            TKey *dir_key;
            while( dir_key = (TKey*)rdirnextkey())
            {
                if (rootobj->IsA()->InheritsFrom("TCanvas")){
                    c1 = (TCanvas *)rootobj;
		c1->SetLogy();
		c1->Modified();
		c1->Update();
                    c1->Print(outname_mid);
                    c1->Print(outfile_);
                    cnt++;
                    cout<<"Count : "<<cnt<<endl;
                    if(cnt > 0) break;
                }
            }
        }
    }
    c1->Print(outname_out);
    TString out2 = outfile_ + "]";
    c1->Print(out2);
}
Esempio n. 21
0
// Soft radiation corrections for L3Res
void softrad(double etamin=0.0, double etamax=1.3, bool dodijet=false) {

  setTDRStyle();
  writeExtraText = false; // for JEC paper CWR

  TDirectory *curdir = gDirectory;

  // Open jecdata.root produced by reprocess.C
  TFile *fin = new TFile("rootfiles/jecdata.root","UPDATE");
  assert(fin && !fin->IsZombie());
  
  const int ntypes = 3;
  const char* types[ntypes] = {"data", "mc", "ratio"};
  const int nmethods = 2;
  const char* methods[nmethods] = {"mpfchs1", "ptchs"};
  const int nsamples = (dodijet ? 4 : 3);
  const char* samples[4] = {"gamjet", "zeejet", "zmmjet", "dijet"};
  string sbin = Form("eta%02.0f-%02.0f",10*etamin,10*etamax);
  const char* bin = sbin.c_str();
  const int nalphas = 4;
  const int alphas[nalphas] = {30, 20, 15, 10};

  // Z+jet bins
  const double ptbins1[] = {30, 40, 50, 60, 75, 95, 125, 180, 300, 1000};
  const int npt1 = sizeof(ptbins1)/sizeof(ptbins1[0])-1;
  TH1D *hpt1 = new TH1D("hpt1","",npt1,&ptbins1[0]);
  TProfile *ppt1 = new TProfile("ppt1","",npt1,&ptbins1[0]);

  // gamma+jet bins
  const double ptbins2[] = {30, 40, 50, 60, 75, 100, 125, 155, 180,
			    210, 250, 300, 350, 400, 500, 600, 800};
  const int npt2 = sizeof(ptbins2)/sizeof(ptbins2[0])-1;
  TH1D *hpt2 = new TH1D("hpt2","",npt2,&ptbins2[0]);
  TProfile *ppt2 = new TProfile("ppt2","",npt2,&ptbins2[0]);

  // dijet bins
  const double ptbins4[] = {20, 62, 107, 175, 242, 310, 379, 467,
			    628, 839, 1121, 1497, 2000};
  const int npt4 = sizeof(ptbins4)/sizeof(ptbins4[0])-1;
  TH1D *hpt4 = new TH1D("hpt4","",npt4,&ptbins4[0]);
  TProfile *ppt4 = new TProfile("ppt4","",npt4,&ptbins4[0]);

  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.045);

  map<string,const char*> texlabel;
  texlabel["gamjet"] = "#gamma+jet";
  texlabel["zeejet"] = "Z#rightarrowee+jet";
  texlabel["zmmjet"] = "Z#rightarrow#mu#mu+jet";
  texlabel["dijet"] = "Dijet";
  texlabel["ptchs"] = "p_{T} balance (CHS)";
  texlabel["mpfchs"] = "MPF raw (CHS)";
  texlabel["mpfchs1"] = "MPF type-I (CHS)";

  // overlay of various alpha values
  TCanvas *c1 = new TCanvas("c1","c1",ntypes*400,nmethods*400);
  c1->Divide(ntypes,nmethods);

  TH1D *h1 = new TH1D("h1",";p_{T} (GeV);Response",1270,30,1300);

  // extrapolation vs alpha for each pT bin
  vector<TCanvas*> c2s(ntypes*nmethods);
  for (unsigned int icanvas = 0; icanvas != c2s.size(); ++icanvas) {
    TCanvas *c2 = new TCanvas(Form("c2_%d",icanvas),Form("c2_%d",icanvas),
			      1200,1200);
    c2->Divide(3,3);
    c2s[icanvas] = c2;
  }

  TH1D *h2 = new TH1D("h2",";#alpha;Response",10,0.,0.4);
  h2->SetMaximum(1.08);
  h2->SetMinimum(0.88);

  // krad corrections
  TCanvas *c3 = new TCanvas("c3","c3",ntypes*400,nmethods*400);
  c3->Divide(ntypes,nmethods);

  TH1D *h3 = new TH1D("h3",";p_{T,ref} (GeV);FSR sensitivity: -dR/d#alpha [%]",
		      1270,30,1300);

  cout << "Reading in data" << endl << flush;
  // Read in plots vs pT (and alpha)
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gemap;
  map<string, map<string, map<string, map<int, TGraphErrors*> > > > gamap;
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      for (int  isample = 0; isample != nsamples; ++isample) {

	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  fin->cd();
	  assert(gDirectory->cd(types[itype]));
	  assert(gDirectory->cd(bin));
	  TDirectory *d = gDirectory;

	  const char *ct = types[itype];
	  const char *cm = methods[imethod];
	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  // Get graph made vs pT
	  string s = Form("%s/%s/%s_%s_a%d",types[itype],bin,cm,cs,a);
	  TGraphErrors *g = (TGraphErrors*)fin->Get(s.c_str());
	  if (!g) cout << "Missing " << s << endl << flush;
	  assert(g);

	  // Clean out empty points
	  // as well as trigger-biased ones for dijets
	  // as well as weird gamma+jet high pT point
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetY()[i]==0 || g->GetEY()[i]==0 ||
		(string(cs)=="dijet" && g->GetX()[i]<70.) ||
		(string(cs)=="gamjet" && g->GetX()[i]>600. && etamin!=0))
	      g->RemovePoint(i);
	  }

	  gemap[ct][cm][cs][a] = g;
	  
	  // Sort points into new graphs vs alpha
	  TH1D *hpt = (isample==0 ? hpt2 : hpt1);
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { hpt = hpt4; ppt = ppt4; } // pas-v6
	  for (int i = 0; i != g->GetN(); ++i) {
	    
	    double pt = g->GetX()[i];
	    ppt->Fill(pt, pt);
	    int ipt = int(hpt->GetBinLowEdge(hpt->FindBin(pt))+0.5);
	    //int ipt = int(pt+0.5);
	    TGraphErrors *ga = gamap[ct][cm][cs][ipt];
	    if (!ga) {
	      ga = new TGraphErrors(0);
	      ga->SetMarkerStyle(g->GetMarkerStyle());
	      ga->SetMarkerColor(g->GetMarkerColor());
	      ga->SetLineColor(g->GetLineColor());
	      gamap[ct][cm][cs][ipt] = ga;
	    }
	    int n = ga->GetN();
	    ga->SetPoint(n, 0.01*a, g->GetY()[i]);
	    ga->SetPointError(n, 0, g->GetEY()[i]);
	  } // for i 

	} // for ialpha

      } // for isample
    } // for imethod
  } // for itype

  cout << "Drawing plots vs pT for each alpha" << endl << flush;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c1->cd(ipad);
      gPad->SetLogx();
      h1->SetMaximum(itype<2 ? 1.15 : 1.08);
      h1->SetMinimum(itype<2 ? 0.85 : 0.93);
      h1->SetYTitle(Form("Response (%s)",ct));
      h1->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3, #alpha=0.1--0.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {
	for (int  ialpha = 0; ialpha != nalphas; ++ialpha) {

	  const char *cs = samples[isample];
	  const int a = alphas[ialpha];
	  TGraphErrors *g = gemap[ct][cm][cs][a]; assert(g);

	  // Clean out points with very large uncertainty for plot readability
	  for (int i = g->GetN()-1; i != -1; --i) {
	    if (g->GetEY()[i]>0.02) g->RemovePoint(i);
	  }

	  g->Draw("SAME Pz");

	  if (ialpha==0) leg->AddEntry(g,texlabel[cs],"P");
	}
      } // for isample

      // Individual plots for JEC paper
      if ( true ) { // paper

	TH1D *h = new TH1D(Form("h_5%s_%s",ct,cm),
			   Form(";p_{T} (GeV);Response (%s)",ct),
			   1270,30,1300);
	h->GetXaxis()->SetMoreLogLabels();
	h->GetXaxis()->SetNoExponent();
	h->SetMinimum(0.88);
	h->SetMaximum(1.13);

	writeExtraText = true;
	extraText = (string(ct)=="mc" ? "Simulation" : "");
	lumi_8TeV = (string(ct)=="mc" ? "" : "19.7 fb^{-1}");
	TCanvas *c0 = tdrCanvas(Form("c0_%s_%s",cm,ct), h, 2, 11, true);
	c0->SetLogx();
	

	TLegend *leg = tdrLeg(0.55,0.68,0.85,0.83);
	tex->DrawLatex(0.55,0.85,texlabel[cm]);
	tex->DrawLatex(0.55,0.18,"|#eta| < 1.3, #alpha=0.3");
	//tex->DrawLatex(0.55,0.18,"Anti-k_{T} R=0.5");

	// Loop over Z+jet and gamma+jet (only, no dijet/multijet)
	for (int  isample = 0; isample != min(3,nsamples); ++isample) {
	  
	  const char *cs = samples[isample];
	  TGraphErrors *g = gemap[ct][cm][cs][30]; assert(g);
	  g->Draw("SAME Pz");
	  
	  leg->AddEntry(g,texlabel[cs],"P");
	} // for isample

	if (etamin==0) {
	  c0->SaveAs(Form("pdf/paper_softrad_%s_%s_vspt.pdf",ct,cm));
	  c0->SaveAs(Form("pdfC/paper_softrad_%s_%s_vspt.C",ct,cm));
	}
	else {
	  c0->SaveAs(Form("pdf/an_softrad_%s_%s_eta%1.0f-%1.0f_vspt.pdf",
			  ct,cm,10*etamin,10*etamax));
	}
      } // paper

    } // for imethod
  } // for itype
  
  c1->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c1, 2, 33);
  c1->SaveAs("pdf/softrad_2x6_vspt.pdf");


  cout << "Drawing plots vs alpha for each pT" << endl << flush;
  cout << "...and fitting slope vs alpha" << endl << flush;

  map<string, map<string, map<string, TGraphErrors* > > > gkmap;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {
      
      int icanvas = nmethods*imethod + itype; assert(icanvas<=6);
      TCanvas *c2 = c2s[icanvas]; assert(c2);

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      const int npads = 9;
      for (int ipad = 0; ipad != npads; ++ipad) {
	c2->cd(ipad+1);
	h2->SetYTitle(Form("Response (%s)",ct));
	h2->DrawClone("AXIS");
	tex->DrawLatex(0.20,0.85,texlabel[cm]);
	tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
	tex->DrawLatex(0.20,0.75,Form("%1.0f < p_{T} < %1.0f GeV",
				      hpt1->GetBinLowEdge(ipad+1),
				      hpt1->GetBinLowEdge(ipad+2)));
	TLegend *leg = tdrLeg(0.65,0.75,0.90,0.90);
	leg->AddEntry(gemap[ct][cm]["gamjet"][30], texlabel["gamjet"], "P");
	leg->AddEntry(gemap[ct][cm]["zeejet"][30], texlabel["zeejet"], "P");
	leg->AddEntry(gemap[ct][cm]["zmmjet"][30], texlabel["zmmjet"], "P");
	leg->AddEntry(gemap[ct][cm]["dijet"][30], texlabel["dijet"], "P");
      }

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];

	map<int, TGraphErrors*> &gam = gamap[ct][cm][cs];
	map<int, TGraphErrors*>::iterator itpt;
	for (itpt = gam.begin(); itpt != gam.end(); ++itpt) {

	  int ipt = itpt->first;
	  int jpt = hpt1->FindBin(ipt);
	  if (jpt>npads) continue;
	  assert(jpt<=npads);
	  c2->cd(jpt);
	  
	  TGraphErrors *ga = itpt->second; assert(ga);
	  
	  ga->Draw("SAME Pz");

	  // Fit slope
	  TF1 *f1 = new TF1(Form("f1_%s_%s_%s_%d",ct,cm,cs,ipt),
			    "(x<1)*([0]+[1]*x) + (x>1 && x<2)*[0] +"
			    "(x>2)*[1]",-1,1);
	  f1->SetLineColor(ga->GetLineColor());
	  f1->SetParameters(1,0);
	  const double minalpha = (isample==0 ? 10./ipt : 5./ipt);
	  // Constrain slope to within reasonable values
	  // in the absence of sufficient data using priors
	  if (true) { // use priors
	    int n = ga->GetN();
	    // For response, limit to 1+/-0.02 (we've corrected for L3Res
	    ga->SetPoint(n, 1.5, 1);
	    ga->SetPointError(n, 0, 0.02);
	    n = ga->GetN();
	    if (imethod==1) { // pT balance
	      // For pT balance, estimate slope of <vecpT2>/alpha from data
	      // => 7.5%/0.30 = 25%
	      // Approximate uncertainty on this to be
	      // 0.5%/0.30 ~ 1.5% for data, 0.5%/0.30 ~ 1.5% for Z+jet MC, and
	      // 2%/0.30 ~ 6% for gamma+jet MC (same as slope)
	      if (itype==0)               ga->SetPoint(n, 2.5, -0.250); // DT
	      if (itype==1 && isample!=0) ga->SetPoint(n, 2.5, -0.250); // MC
	      if (itype==1 && isample==0) ga->SetPoint(n, 2.5, -0.190);
	      if (itype==2 && isample!=0) ga->SetPoint(n, 2.5, -0.000); // rt
	      if (itype==2 && isample==0) ga->SetPoint(n, 2.5, -0.060); 
	      //
	      // BUG: found 2015-01-08 (no effect on ratio)
	      //if (itype==1)               ga->SetPointError(n, 0, -0.015);
	      if (itype==0)               ga->SetPointError(n, 0, -0.015); // DT
	      if (itype==1 && isample!=0) ga->SetPointError(n, 0, -0.015); // MC
	      if (itype==1 && isample==0) ga->SetPointError(n, 0, -0.060);
	      if (itype==2 && isample!=0) ga->SetPointError(n, 0, -0.015); // rt
	      if (itype==2 && isample==0) ga->SetPointError(n, 0, -0.060); 
	    }
	    if (imethod==0) { // MPF
	      // For MPF, expectation is no slope
	      // Maximal slope would be approximately
	      // (<vecpT2>/alpha ~ 25% from pT balance) times
	      // (response difference between pT1 and vecpT2~10%)
	      // => 0.25*0.10 = 2.5%
	      // For data/MC, estimate uncertainty as half of this
	      // => 1.25%
	      ga->SetPoint(n, 2.5, 0.);
	      if (itype!=2) ga->SetPointError(n, 0, 0.025);
	      if (itype==2) ga->SetPointError(n, 0, 0.0125);
	    } // MPF
	  } // use priors

	  if (ga->GetN()>2) {

	    f1->SetRange(minalpha, 3.);
	    ga->Fit(f1,"QRN");

	    if (f1->GetNDF()>=0) {
	      f1->DrawClone("SAME");
	      f1->SetRange(0,0.4);
	      f1->SetLineStyle(kDashed);
	      f1->DrawClone("SAME");

	      // Store results
	      TGraphErrors *gk = gkmap[ct][cm][cs];
	      if (!gk) {
		gk = new TGraphErrors(0);
		gk->SetMarkerStyle(ga->GetMarkerStyle());
		gk->SetMarkerColor(ga->GetMarkerColor());
		gk->SetLineColor(ga->GetLineColor());
		gkmap[ct][cm][cs] = gk;
	      }
	      int n = gk->GetN();
	      TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	      if (isample==3) { ppt = ppt4; } // pas-v6
	      double pt = ppt->GetBinContent(ppt->FindBin(ipt));
	      gk->SetPoint(n, pt, f1->GetParameter(1));
	      gk->SetPointError(n, 0, f1->GetParError(1));
	    } // f1->GetNDF()>=0
	  } // ga->GetN()>2
	} // for itpt
	
      } // for isample
      
      c2->SaveAs(Form("pdf/softrad_3x3_%s_%s_vsalpha.pdf",ct,cm));
      
    }
  }


  cout << "Drawing plots of kFSR vs pT" << endl;

  // 2x6 plots
  for (int itype = 0; itype != ntypes; ++itype) {
    for (int  imethod = 0; imethod != nmethods; ++imethod) {

      const char *ct = types[itype];
      const char *cm = methods[imethod];

      TMultiGraph *mgk = new TMultiGraph();

      int ipad = ntypes*imethod + itype + 1; assert(ipad<=6);
      c3->cd(ipad);
      gPad->SetLogx();
      h3->SetMaximum(imethod==0 ? 0.05 : (itype!=2 ? 0.1 : 0.25));
      h3->SetMinimum(imethod==0 ? -0.05 : (itype!=2 ? -0.4 : -0.25));
      h3->SetYTitle(Form("k_{FSR} = dR/d#alpha (%s)",ct));
      h3->DrawClone("AXIS");
      tex->DrawLatex(0.20,0.85,texlabel[cm]);
      tex->DrawLatex(0.20,0.80,"|#eta| < 1.3");
      TLegend *leg = tdrLeg(0.60,0.75,0.90,0.90);

      for (int  isample = 0; isample != nsamples; ++isample) {

	const char *cs = samples[isample];
	TGraphErrors *gk = gkmap[ct][cm][cs]; assert(gk);
	
	leg->AddEntry(gk,texlabel[cs],"P");

	// Fit each sample separately for pT balance
	if (true) {

	  TF1 *fk = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			    "[0]+[1]*log(0.01*x)+[2]*pow(log(0.01*x),2)",
			    30,1300);
	  fk->SetParameters(-0.25,-0.5);
	  fk->SetLineColor(gk->GetLineColor());
	  gk->Fit(fk, "QRN");

	  tex->SetTextColor(fk->GetLineColor());
	  tex->DrawLatex(0.55,0.27-0.045*isample,
			 Form("#chi^{2}/NDF = %1.1f / %d",
			      fk->GetChisquare(), fk->GetNDF()));
	  tex->SetTextColor(kBlack);

	  // Error band
	  const int n = fk->GetNpar();
	  TMatrixD emat(n,n);
	  gMinuit->mnemat(emat.GetMatrixArray(), n);
	  TF1 *fke = new TF1(Form("fk_%s_%s_%s",ct,cm,cs),
			     sr_fitError, 30, 1300, 1);
	  _sr_fitError_func = fk;
	  _sr_fitError_emat = &emat;

	  fke->SetLineStyle(kSolid);
	  fke->SetLineColor(fk->GetLineColor()-10);
	  fke->SetParameter(0,-1);
	  fke->DrawClone("SAME");
	  fke->SetParameter(0,+1);
	  fke->DrawClone("SAME");

	  fk->DrawClone("SAME");
	  gk->DrawClone("SAME Pz");

	  // Store soft radiation corrections in fsr subdirectory
	  assert(fin->cd(ct));
	  assert(gDirectory->cd(bin));
	  if (!gDirectory->FindObject("fsr")) gDirectory->mkdir("fsr");
	  assert(gDirectory->cd("fsr"));

	  TH1D *hk = (TH1D*)(isample==0 ? hpt2->Clone() : hpt1->Clone());
	  hk->SetName(Form("hkfsr_%s_%s",cm,cs));
	  TProfile *ppt = (isample==0 ? ppt2 : ppt1);
	  if (isample==3) { ppt = ppt4; } // pas-v6
	  for (int i = 1; i != hk->GetNbinsX()+1; ++i) {
	    double pt = ppt->GetBinContent(i);
	    if (pt>30 && pt<1300) {
	      hk->SetBinContent(i, fk->Eval(pt));
	      hk->SetBinError(i, fabs(fke->Eval(pt)-fk->Eval(pt)));
	    }
	    else {
	      hk->SetBinContent(i, 0);
	      hk->SetBinError(i, 0);
	    }
	  }
	  
	  hk->Write(hk->GetName(), TObject::kOverwrite);

	  // Factorize error matrix into eigenvectors
	  // Remember: A = Q*Lambda*Q^-1, where
	  // A is emat, Q is eigmat, and Lambda is a diagonal matrix with
	  // eigenvalues from eigvec on the diagonal. For eigenmatrix
	  // Q^-1 = Q^T, i.e. inverse matrix is the original transposed
	  TVectorD eigvec(n);
	  TMatrixD eigmat = emat.EigenVectors(eigvec);

	  // Eigenvectors are the columns and sum of eigenvectors squared
	  // equals original uncertainty. Calculate histograms from the
	  // eigenvectors and store them
	  TF1 *fkeig = (TF1*)fk->Clone(Form("%s_eig",fk->GetName()));
	  fkeig->SetLineStyle(kDotted);
	  for (int ieig = 0; ieig != n; ++ieig) {

	    // Eigenvector functions
	    for (int i = 0; i != n; ++i) {
	      fkeig->SetParameter(i, fk->GetParameter(i)
				  + eigmat[i][ieig] * sqrt(eigvec[ieig]));
	    }
	    fkeig->DrawClone("SAMEL");

	    // Eigenvector histograms evaluated at bin mean pT
	    TH1D *hke = (TH1D*)hk->Clone(Form("%s_eig%d",hk->GetName(),ieig));
	    hke->Reset();

	    for (int i = 0; i != gk->GetN(); ++i) {

	      double pt = gk->GetX()[i];
	      int ipt = hke->FindBin(pt);
	      // Need to store central value as well, because
	      // uncertainty sources are signed
	      hke->SetBinContent(ipt, fkeig->Eval(pt)-fk->Eval(pt));
	      hke->SetBinError(ipt, fabs(fkeig->Eval(pt)-fk->Eval(pt)));
	    }
	    hke->Write(hke->GetName(), TObject::kOverwrite);
	  }

	  cout << "." << flush;
	} // if tree
      } // for isample
    } // for imethod
  } // for itype
  
  c3->cd(0);
  //cmsPrel(_lumi, true);
  CMS_lumi(c3, 2, 33);
  c3->SaveAs("pdf/softrad_2x6_kfsr.pdf");

  fin->Close();
  curdir->cd();
} // softrad
Esempio n. 22
0
void fsr(int ins = -1, double pt = 200., std::string sample = "dijet") {

  setTDRStyle();

  TDirectory *curdir = gDirectory;

  const char *cs = sample.c_str();
  map<string, const char *> title;
  title["dijet"] = "Dijet";
  title["gamjet"] = "#gamma+jet";

  TFile *fp8 = new TFile("alphafracs_p8.root","READ");
  assert(fp8 && !fp8->IsZombie());

  TFile *fp6 = new TFile("alphafracs_p6.root","READ");
  assert(fp6 && !fp6->IsZombie());

  TFile *fhw = new TFile("alphafracs_hwpp.root","READ");
  assert(fhw && !fhw->IsZombie());

  curdir->cd();

  TProfile *p8_10 = (TProfile*)fp8->Get("prof10"); assert(p8_10);
  TProfile *p8_15 = (TProfile*)fp8->Get("prof15"); assert(p8_15);
  TProfile *p8_20 = (TProfile*)fp8->Get("prof20"); assert(p8_20);
  TProfile *p8_30 = (TProfile*)fp8->Get("prof30"); assert(p8_30);
  TH1D *h8_0 = p8_10->ProjectionX("h8_10");

  TProfile *p6_10 = (TProfile*)fp6->Get("prof10"); assert(p6_10);
  TProfile *p6_15 = (TProfile*)fp6->Get("prof15"); assert(p6_15);
  TProfile *p6_20 = (TProfile*)fp6->Get("prof20"); assert(p6_20);
  TProfile *p6_30 = (TProfile*)fp6->Get("prof30"); assert(p6_30);
  TH1D *h6_0 = p6_10->ProjectionX("h6_10");

  TProfile *hw_10 = (TProfile*)fhw->Get("prof10"); assert(hw_10);
  TProfile *hw_15 = (TProfile*)fhw->Get("prof15"); assert(hw_15);
  TProfile *hw_20 = (TProfile*)fhw->Get("prof20"); assert(hw_20);
  TProfile *hw_30 = (TProfile*)fhw->Get("prof30"); assert(hw_30);
  TH1D *hw_0 = hw_10->ProjectionX("hw_10");

  TH1D *dt_0 = (TH1D*)hw_0->Clone("dt_0");
  TH1D *dt_10 = hw_10->ProjectionX("dt_10");
  TH1D *dt_15 = hw_15->ProjectionX("dt_15");
  TH1D *dt_20 = hw_20->ProjectionX("dt_20");
  TH1D *dt_30 = hw_30->ProjectionX("dt_30");

  const int ns = 3;//4;
  const int np = 5;
  TH1D* ps[ns][np] = {{h8_0, p8_10, p8_15, p8_20, p8_30},
		      {h6_0, p6_10, p6_15, p6_20, p6_30},
		      {hw_0, hw_10, hw_15, hw_20, hw_30}};//,
  //{dt_0, dt_10, dt_15, dt_20, dt_30}};
  double alpha[np] = {0, 0.10, 0.15, 0.20, 0.30};
  int markers[ns][2] = {{kFullSquare, kFullCircle},
			{kOpenSquare, kOpenCircle},
			{kOpenDiamond, kOpenStar}};//,
  //{kDot, kDot}};
  int colors[np] = {kBlack, kRed, kOrange+2, kGreen+2, kBlue};

  assert(ins>=-1 && ins<ns);

  // Approximate data as 1:1 mixture of P6 and Herwig++
  /*
  double whw = 0.5;
  for (int j = 0; j != np; ++j) {
    for (int k = 1; k != hw_0->GetNbinsX()+1; ++k) {
      ps[ns-1][j]->SetBinContent(k, (1-whw)*ps[1][j]->GetBinContent(k) +
				 whw*ps[2][j]->GetBinContent(k));
      ps[ns-1][j]->SetBinError(k, (1-whw)*ps[1][j]->GetBinError(k) +
			       whw*ps[2][j]->GetBinError(k));
    }
  }
  */

  TGraphErrors *gas[ns];
  TGraphErrors *ga = new TGraphErrors(4);
  TF1 *f1 = new TF1("f1","[0]+[1]*x",0,0.35);
  
  for (int i = 0; i != ns; ++i) {
    for (int k = 1; k != p8_10->GetNbinsX()+1; ++k) {
      for (int j = 1; j != np; ++j) {
	ga->SetPoint(j, alpha[j], ps[i][j]->GetBinContent(k));
	ga->SetPointError(j, 0., ps[i][j]->GetBinError(k));
      }
      ga->Fit(f1, "QRN");
      ps[i][0]->SetBinContent(k, f1->GetParameter(0));
      ps[i][0]->SetBinError(k, f1->GetParError(0));

      if (p8_10->FindBin(pt)==k) {
	gas[i] = (TGraphErrors*)ga->Clone(Form("ga_%d",i));
      }
    }
  }

  TH1D *h = new TH1D("h",";p_{T,parton} (GeV);"
		     "#LTp_{T,gen} / p_{T,parton}#GT", 100, 0, 900);
  h->SetMaximum(1.06);//1.03);
  h->SetMinimum(0.91);//0.96);

  TLatex *tex = new TLatex();
  tex->SetNDC(); tex->SetTextSize(0.045);

  extraText = "Simulation";
  //extraText2 = "Preliminary";
  if (ins==0) lumi_13TeV = "Pythia8";
  if (ins==1) lumi_13TeV = "Pythia6";
  if (ins==2) lumi_13TeV = "Herwig++";
  if (ins==-1) lumi_13TeV = "Herwig++ / Pythia8 / Pythia6";

  TCanvas *c1 = tdrCanvas("c1",h,2,0,kSquare);
  tex->DrawLatex(0.18,0.87,title[cs]);
  tex->DrawLatex(0.18,0.80,"Anti-k_{T} R=0.5");
  tex->DrawLatex(0.18,0.75,"|#eta| < 1.3");
  tex->DrawLatex(0.0,0.01,"#copyright Hannu Siikonen");

  for (int i = 0; i != ns; ++i) {
    for (int j = 0; j != np; ++j) {
      if ((ins == -1 && (j==0 || j==np-1)) || i == ins)
	tdrDraw(ps[i][j], "P", markers[i][j==0 ? 0 : 1], colors[j]);
    }
  }
  //tdrDraw(h8_0,"P",kFullSquare,kBlack);
  //tdrDraw(p8_10,"P",kFullCircle,kRed);
  //tdrDraw(p8_15,"P",kFullCircle,kOrange+2);
  //tdrDraw(p8_20,"P",kFullCircle,kGreen+1);
  //tdrDraw(p8_30,"P",kFullCircle,kBlue);

  TF1 *f2 = new TF1("f2","[0] + [1]*pow(x,[2])",100,840);
  f2->SetParameters(1,-0.1,-0.5);
  for (int i = 0; i != ns; ++i) {
    for (int j = 0; j != np; ++j) {
      ps[i][j]->Fit(f2,"QRN");
      f2->SetLineColor(ps[i][j]->GetMarkerColor());
      if ((ins == -1 && (j==0 || j==np-1)) || i == ins)
	f2->DrawClone("SAME");
    }
  }

  if (ins!=-1) {
    TLegend *leg = tdrLeg(0.70,0.65,0.90,0.90);
    leg->AddEntry(ps[ins][0],"#alpha_{max}#rightarrow0","PL");
    leg->AddEntry(ps[ins][1],"#alpha<0.10","PL");
    leg->AddEntry(ps[ins][2],"#alpha<0.15","PL");
    leg->AddEntry(ps[ins][3],"#alpha<0.20","PL");
    leg->AddEntry(ps[ins][4],"#alpha<0.30","PL");
  }
  if (ins==-1) {
    TLegend *ll = tdrLeg(0.50,0.70,0.70,0.90);
    ll->SetHeader("#alpha#rightarrow0");
    ll->AddEntry(ps[0][0],"","PL");
    ll->AddEntry(ps[1][0],"","PL");
    ll->AddEntry(ps[2][0],"","PL");
    //ll->AddEntry(ps[3][0],"","PL");
    TLegend *lr = tdrLeg(0.60,0.70,0.80,0.90);
    lr->SetHeader("#alpha<0.30");
    lr->AddEntry(ps[0][np-1],"   Pythia 8","PL");
    lr->AddEntry(ps[1][np-1],"   Pythia 6","PL");
    lr->AddEntry(ps[2][np-1],"   Herwig++","PL");
    //lr->AddEntry(ps[3][np-1],"   \"DATA\"","PL");
  }

  c1->SaveAs(Form("pdf/fsr_ins%d_%s.pdf",ins,cs));


  TH1D *h2 = new TH1D("h2",";#alpha_{max};#LTp_{T,gen} / p_{T,parton}#GT",
		      10,0,0.4);
  h2->SetMinimum(0.91);
  h2->SetMaximum(1.05);

  lumi_13TeV = "Herwig++ / Pythia8 / Pythia6";  
  TCanvas *c2 = tdrCanvas("c2",h2,2,0,kSquare);
  tex->DrawLatex(0.18,0.87,title[cs]);
  tex->DrawLatex(0.18,0.80,"Anti-k_{T} R=0.5");
  tex->DrawLatex(0.18,0.75,"|#eta| < 1.3");
  tex->DrawLatex(0.0,0.01,"#copyright Hannu Siikonen");

  TF1 *f3 = new TF1("f3","[0]+[1]*x+[2]*x*x",0,0.35);
  f3->SetLineStyle(kDashed);

  for (int i = 0; i != ns; ++i) {
    
    tdrDraw(gas[i], "P", markers[i][1], colors[i]);

    gas[i]->Fit(f1,"QRN");
    f1->SetLineColor(gas[i]->GetLineColor());
    f1->DrawClone("SAME");

    gas[i]->Fit(f3,"QRN");
    f3->SetLineColor(gas[i]->GetLineColor());
    f3->DrawClone("SAME");
  }

  int ipt = dt_0->FindBin(pt);
  double ptmin = dt_0->GetBinLowEdge(ipt);
  double ptmax = dt_0->GetBinLowEdge(ipt+1);
  tex->DrawLatex(0.18, 0.18, Form("%1.0f<p_{T}<%1.0f GeV",
				  ptmin, ptmax));

  TLegend *leg = tdrLeg(0.70,0.70,0.90,0.90);
  leg->AddEntry(gas[0], "Pythia 8", "PL");
  leg->AddEntry(gas[1], "Pythia 6", "PL");
  leg->AddEntry(gas[2], "Herwig++", "PL");
  //leg->AddEntry(gas[3], "\"DATA\"", "PL");

  c2->SaveAs(Form("pdf/fsr_vsalpha_%s.pdf",cs));
}
Esempio n. 23
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 4;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fOut;
  TDirectory * SubEvt_0;
  TDirectory * SubEvt_1;
  TDirectory * FullEvt;

  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  double VNRawX_0[NCENT][NEPSymm][NQN];
  double VNRawY_0[NCENT][NEPSymm][NQN];
  double VNRawX_1[NCENT][NEPSymm][NQN];
  double VNRawY_1[NCENT][NEPSymm][NQN];
  double VNRawX_full[NCENT][NEPSymm][NQN];
  double VNRawY_full[NCENT][NEPSymm][NQN];

  double sumw_0[NCENT][NEPSymm][NQN];
  double sumw_1[NCENT][NEPSymm][NQN];
  double sumw_full[NCENT][NEPSymm][NQN];

  int evtMult_0[NCENT][NEPSymm][NQN];
  int evtMult_1[NCENT][NEPSymm][NQN];
  int evtMult_full[NCENT][NEPSymm][NQN];
 
  double VNDetX_0[NCENT][NEPSymm][NQN];
  double VNDetY_0[NCENT][NEPSymm][NQN];
  double VNDetX_1[NCENT][NEPSymm][NQN];
  double VNDetY_1[NCENT][NEPSymm][NQN];
  double VNDetX_full[NCENT][NEPSymm][NQN];
  double VNDetY_full[NCENT][NEPSymm][NQN];

  int Nevents[NCENT][NEPSymm][NQN];
  int NFails[NCENT][NEPSymm][NQN];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_pixel_tight.root");

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms                                                                                                                                                                                             
  fQNDet = new TFile( Form("../../../../../../v%i/eta2.4/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../../../../v%i/eta2.4/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  SubEvt_0 = fOut->mkdir("SubEvt_0");
  SubEvt_1 = fOut->mkdir("SubEvt_1");
  FullEvt  = fOut->mkdir("FullEvt");
    
  for(int iqn = 0; iqn < NQN; iqn++){
    SubEvt_0->cd();
    hVNDetX_0[iqn]    = new TH2D( Form("hVNDetX_0_qbin%i", iqn),    Form("hVNDetX_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_0[iqn]->SetOption("colz");
    
    hVNDetY_0[iqn]    = new TH2D( Form("hVNDetY_0_qbin%i", iqn),    Form("hVNDetY_0_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_0[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_0[iqn]->SetOption("colz");
    
    SubEvt_1->cd();
    hVNDetX_1[iqn]    = new TH2D( Form("hVNDetX_1_qbin%i", iqn),    Form("hVNDetX_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_1[iqn]->SetOption("colz");
    
    hVNDetY_1[iqn]    = new TH2D( Form("hVNDetY_1_qbin%i", iqn),    Form("hVNDetY_1_qbin%i", iqn),    NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_1[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_1[iqn]->SetOption("colz");
  
    FullEvt->cd();
    hVNDetX_full[iqn] = new TH2D( Form("hVNDetX_full_qbin%i", iqn), Form("hVNDetX_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetX_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetX_full[iqn]->SetOption("colz");
    
    hVNDetY_full[iqn] = new TH2D( Form("hVNDetY_full_qbin%i", iqn), Form("hVNDetY_full_qbin%i", iqn), NCENT, centbinsDefault, NEPSymm, epbinsDefault );
    hVNDetY_full[iqn]->GetXaxis()->SetTitle("Centrality %");
    hVNDetY_full[iqn]->SetOption("colz");
    
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      hVNDetX_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_0[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_1[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetX_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
      hVNDetY_full[iqn]->GetYaxis()->SetBinLabel(iEP+1, EPSymmNames[iEP].data());
    }

  }
    
  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      for(int iqn = 0; iqn < NQN; iqn++){

	VNDetX_0[icent][iEP][iqn]     = 0.;
	VNDetY_0[icent][iEP][iqn]     = 0.;
	VNDetX_1[icent][iEP][iqn]     = 0.;
	VNDetY_1[icent][iEP][iqn]     = 0.;
	VNDetX_full[icent][iEP][iqn]  = 0.;
	VNDetY_full[icent][iEP][iqn]  = 0.;

	evtMult_0[icent][iEP][iqn]    = 0;
	evtMult_1[icent][iEP][iqn]    = 0;
	evtMult_full[icent][iEP][iqn] = 0;

	Nevents[icent][iEP][iqn]      = 0;
	NFails[icent][iEP][iqn]       = 0;

      }
    }
  }
    
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();


  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    tree->GetEntry(ievent);
      
    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset Raw and sumw values
      VNRawX_0[icent][EPbin][iqn]     = 0.;
      VNRawY_0[icent][EPbin][iqn]     = 0.;
      VNRawX_1[icent][EPbin][iqn]     = 0.;
      VNRawY_1[icent][EPbin][iqn]     = 0.;
      VNRawX_full[icent][EPbin][iqn]  = 0.;
      VNRawY_full[icent][EPbin][iqn]  = 0.;            
	
      sumw_0[icent][EPbin][iqn]       = 0.;
      sumw_1[icent][EPbin][iqn]       = 0.;
      sumw_full[icent][EPbin][iqn]    = 0.;
      
      evtMult_0[icent][EPbin][iqn]    = 0;
      evtMult_1[icent][EPbin][iqn]    = 0;
      evtMult_full[icent][EPbin][iqn] = 0;
      
      Nevents[icent][EPbin][iqn]++;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VNRawX_0[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_0[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_0[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VNRawX_1[icent][EPbin][iqn]   += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VNRawY_1[icent][EPbin][iqn]   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	      sumw_1[icent][EPbin][iqn]     += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1[icent][EPbin][iqn]  += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VNRawX_full[icent][EPbin][iqn]  += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_full[icent][EPbin][iqn]  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	    sumw_full[icent][EPbin][iqn]    += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full[icent][EPbin][iqn] += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  
	} //-- End eta loop
	
      } //-- End pt loop
      
      //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
      if( sumw_0[icent][EPbin][iqn] == 0 || sumw_1[icent][EPbin][iqn] == 0 || evtMult_0[icent][EPbin][iqn] < 2 || evtMult_1[icent][EPbin][iqn] < 2 ){
	NFails[icent][EPbin][iqn]++;
      }
      else{      
	VNDetX_0[icent][EPbin][iqn]    += VNRawX_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetY_0[icent][EPbin][iqn]    += VNRawY_0[icent][EPbin][iqn]    / sumw_0[icent][EPbin][iqn];
	VNDetX_1[icent][EPbin][iqn]    += VNRawX_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetY_1[icent][EPbin][iqn]    += VNRawY_1[icent][EPbin][iqn]    / sumw_1[icent][EPbin][iqn];
	VNDetX_full[icent][EPbin][iqn] += VNRawX_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
	VNDetY_full[icent][EPbin][iqn] += VNRawY_full[icent][EPbin][iqn] / sumw_full[icent][EPbin][iqn];
      }

    } //-- End EP loop

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){
	if( iEP != EPSymmBin ) continue;

	double  Neffective = (double) Nevents[icent][iEP][iqn] - (double) NFails[icent][iEP][iqn];
	if( Neffective == 0) continue;

	VNDetX_0[icent][iEP][iqn]    /= Neffective;
	VNDetY_0[icent][iEP][iqn]    /= Neffective;
	VNDetX_1[icent][iEP][iqn]    /= Neffective;
	VNDetY_1[icent][iEP][iqn]    /= Neffective;
	VNDetX_full[icent][iEP][iqn] /= Neffective;
	VNDetY_full[icent][iEP][iqn] /= Neffective;

	//-- Populate histograms that will be used by ReadTree_normDet.C
	hVNDetX_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_0[icent][iEP][iqn]);
	hVNDetX_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetX_1[icent][iEP][iqn]);
	hVNDetX_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetX_full[icent][iEP][iqn]);
        
	hVNDetY_0[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_0[icent][iEP][iqn]);
	hVNDetY_1[iqn]    -> SetBinContent(icent+1, iEP+1, VNDetY_1[icent][iEP][iqn]);
	hVNDetY_full[iqn] -> SetBinContent(icent+1, iEP+1, VNDetY_full[icent][iEP][iqn]);

      }
    }
  } //-- END TRIPLE LOOP

  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
Esempio n. 24
0
//________________________________________________________________________________
void MergeComplexHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) 
{
  if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) {
    printf(" An experimental version of macro.\n");
    TStopwatch time;
    Int_t fileCounter = 0;
    Int_t dirCounter = 0;
    Int_t treeCounter = 0;
    Int_t histogramCounter = 0;
     // Create the output file
     TFile *outFile = TFile::Open(TargetName,"RECREATE");
     TDirectory *outDir = outFile;
     TDirIter listOfFiles(inputFilesPattern);
     const char *fileName = 0;
     while ( (fileName =  listOfFiles.NextFile() ) ) {
        Int_t currentDirDepth = 0;
        printf(".");
        fileCounter++;
        StFileIter file(fileName);
        TObject *obj = 0;
        while ( (obj = *file) ) {
           Int_t depth = file.GetDepth();
           while (depth < currentDirDepth) {
                outDir = outDir->GetMotherDir();
                currentDirDepth--;
           }
           if ( obj->IsA()->InheritsFrom(TH1::Class()) ) {
              // descendant of TH1 -> merge it
              // printf("Merging histogram: %s\n",obj->GetName() ); 
//              std::cout << "Merging histogram " << obj->GetName() << std::endl;
              TH1 *h1 = (TH1*)obj;
              TH1 *dstHistogram = 0;
              // Check whether we found the new histogram
              if ( (dstHistogram = (TH1 *)outDir->FindObject(h1->GetName()))) {
                 // Accumulate  the  histogram
                  dstHistogram->Add(h1);
                  delete h1;  // Optional, to reduce the memory consumption
                  printf("h");
              } else {
                // First time - move the histogram
                h1->SetDirectory(outDir);
                printf(" The new Histogram found: %s \n", h1->GetName() );
                histogramCounter++;
              }
           } else  if ( obj->IsA()->InheritsFrom(TTree::Class()) ) {
              // descendant of TTree  -> merge it
              // printf("Merging Tree %p:%s\n",obj, obj->GetName() ); 
              TTree *tree = (TTree*)obj;
              TTree *dstTree = 0;
              // Check whether we found the new histogram
              if ( (dstTree = (TTree *)outDir->FindObject(tree->GetName()))) {
                   // printf("Merging %p:%s with the existing Tree %p:%s\n"
                   //       ,tree,tree->GetName(),dstTree, dstTree->GetName() ); 
                  // Merge  the  tree
                  TList *nextTree = new TList(); nextTree->Add(tree); 
                  dstTree->Merge(nextTree);
                  delete tree;  // Optional, to reduce the memory consumption
                  delete nextTree;
                  printf("t");
              } else {
                // First time - move the TTree
                TDirectory *saveDir = 0;
                if (outDir != gDirectory) {
                   saveDir = gDirectory;
                   outDir->cd();
                }
                TList *nextTree = new TList(); nextTree->Add(tree);               
                dstTree = TTree::MergeTrees(nextTree);
                if (saveDir) saveDir->cd();
                // printf(" The new TTree found: %p:%s \n",tree, tree->GetName() );
                // printf(" Create the destination Tree %p:%s\n\n",dstTree, dstTree->GetName() );
                delete tree;  // Optional, to reduce the memory consumption
                delete nextTree;
                treeCounter++;
              }
           } else if ( obj->IsA()->InheritsFrom(TDirectory::Class()) ) {
               printf("The input sub-TDirectory object: %s depth=%d\n",obj->GetName(), depth); 
               TDirectory *d =  (TDirectory *)outDir->FindObject(obj->GetName());
               if (!d) {
                  d = outDir->mkdir(obj->GetName());
                  dirCounter++;
                  printf("The new TDirectory object: %s depth=%d\n",d->GetPathStatic(), depth); 
               }
               if (d) {
                  outDir = d;                  
                  printf("The output sub-TDirectory object: %s depth=%d\n",outDir->GetPathStatic(), depth); 

               }
           } else {
              printf("I have no idea how to merge the %s objects of the %s class. Skipping .... \n",obj->GetName(), obj->ClassName() ); 
           }
           ++file;
        }
              
     }
     printf("\n Finishing  . . . \n");
     outFile->Write();  // this creates a second copy of the TTree ???
     outFile->Close();     
     delete outFile;
     if (fileCounter)      printf(" Total files merged: %d \n", fileCounter);
     if (dirCounter)       printf(" Total TDirectory objects merged: %d \n", dirCounter);
     if (histogramCounter) printf(" Total histograms merged: %d \n", histogramCounter);
     if (treeCounter)      printf(" Total TTree\'s merged: %d \n",treeCounter);
     if (dirCounter || treeCounter) printf(" You have used the experimental version of the program. Please check the output file\n");
        
     time.Print("Merge");
  } else {
     printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\")\n");     
     printf("------        where InputFilesPattern  ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n");
     printf("                    indirect_file_list ::= a text file with the list of the files\n");
     printf("                    indirect_file_list can be create by the shell command:\n");
     printf("                         ls -1 *.root>indirect_file_list \n\n");
  }
}
Esempio n. 25
0
//_____________________________________________________________________________
Int_t ProofAux::GenerateFriend(const char *fnt, const char *fnf)
{
   // Generate the friend tree for the main tree in the 'friends' tutorial fetched
   // from 'fnt'.
   // the tree is called 'Tfriend', has the same number of entries as the main
   // tree and is saved to file 'fnf'. If 'fnf' is not defined the filename is
   // derived from 'fnt' either replacing 'tree' with 'friend', or adding '_friend'
   // before the '.root' extension.
   // Return 0 on success, -1 on error.

   Int_t rc = -1;
   // Check the input filename
   TString fin(fnt);
   if (fin.IsNull()) {
      Error("GenerateFriend", "file name for the main tree undefined!");
      return rc;
   }
   // Make sure that the file can be read
   if (gSystem->AccessPathName(fin, kReadPermission)) {
      Error("GenerateFriend", "input file does not exist or cannot be read: %s", fin.Data());
      return rc;
   }

   // File handlers
   Bool_t sameFile = kTRUE;
   const char *openMain = "UPDATE";

   // The output filename
   TString fout(fnf);
   if (!fout.IsNull()) {
      sameFile = kFALSE;
      openMain = "READ";
      // Make sure the directory exists
      TString dir = gSystem->DirName(fout);
      if (gSystem->AccessPathName(dir, kWritePermission)) {
         if (gSystem->mkdir(dir, kTRUE) != 0) {
            Error("GenerateFriend", "problems creating directory %s to store the file", dir.Data());
            return rc;
         }
      }
   } else {
      // We set the same name
      fout = fin;
   }

   // Get main tree
   TFile *fi = TFile::Open(fin, openMain);
   if (!fi || fi->IsZombie()) {
      Error("GenerateFriend", "problems opening input file %s", fin.Data());
      return rc;
   }
   TTree *Tin = (TTree *) fi->Get("Tmain");
   if (!Tin) {
      Error("GenerateFriend", "problems getting tree 'Tmain' from file %s", fin.Data());
      delete fi;
      return rc;
   }
   // Set branches
   Float_t x, y, z;
   Tin->SetBranchAddress("x", &x);
   Tin->SetBranchAddress("y", &y);
   Tin->SetBranchAddress("z", &z);
   TBranch *b_x = Tin->GetBranch("x");
   TBranch *b_y = Tin->GetBranch("y");
   TBranch *b_z = Tin->GetBranch("z");

   TDirectory* savedir = gDirectory;
   // Create output file
   TFile *fo = 0;
   if (!sameFile) {
      fo = new TFile(fout, "RECREATE");
      if (!fo || fo->IsZombie()) {
         Error("GenerateFriend", "problems opening file %s", fout.Data());
         delete fi;
         return rc;
      }
      savedir->cd();
   } else {
      // Same file
      fo = fi;
   }
   rc = 0;

   // Create the tree
   TTree *Tfrnd = new TTree("Tfrnd", "Friend tree for tutorial 'friends'");
   Tfrnd->SetDirectory(fo);
   Float_t r = 0;
   Tfrnd->Branch("r",&r,"r/F");
   Long64_t ent = Tin->GetEntries();
   for (Long64_t i = 0; i < ent; i++) {
      b_x->GetEntry(i);
      b_y->GetEntry(i);
      b_z->GetEntry(i);
      r = TMath::Sqrt(x*x + y*y + z*z);
      Tfrnd->Fill();
   }
   if (!sameFile) {
      fi->Close();
      delete fi;
   }
   Tfrnd->Print();
   fo->cd();
   Tfrnd->Write();
   Tfrnd->SetDirectory(0);
   fo->Close();
   delete fo;
   delete Tfrnd;

   // Notify success
   Info("GenerateFriend", "friend file '%s' successfully created", fout.Data());

   // Add to the list
   TUrl uu(fout);
   if (!strcmp(uu.GetProtocol(), "file")) {
      if (gSystem->Getenv("LOCALDATASERVER")) {
         if (strcmp(TUrl(gSystem->Getenv("LOCALDATASERVER"), kTRUE).GetProtocol(), "file"))
            fout.Insert(0, TString::Format("%s/", gSystem->Getenv("LOCALDATASERVER")));
      } else {
         fout.Insert(0, TString::Format("root://%s/", gSystem->HostName()));
      }
   }
   fFriendList->Add(new TObjString(fout));

   // Done
   return rc;
}
Esempio n. 26
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fVNDet;
  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub0[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub1[NCENT][NEPSymm][NQN];
  TH2D * hVn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * hVnFull[NCENT][NEPSymm][NQN];
  TH1D * hVnSub0[NCENT][NEPSymm][NQN];
  TH1D * hVnSub1[NCENT][NEPSymm][NQN];
  TH1I * Mult[NCENT][NEPSymm][NQN];
  TH2D * h2Vn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * h2Vn2D0v1Magnitude[NCENT][NEPSymm][NQN];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms
  fQNDet = new TFile( Form("../../../v%i/eta2.4/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../v%i/eta2.4/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  for(int iqn = 0; iqn < NQN; iqn++){
    hVNDetX_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetX_0_qbin%i",   iqn) );
    hVNDetY_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetY_0_qbin%i",   iqn) );
    hVNDetX_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetX_1_qbin%i",   iqn) );
    hVNDetY_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetY_1_qbin%i",   iqn) );
    hVNDetX_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetX_full_qbin%i", iqn) );
    hVNDetY_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetY_full_qbin%i", iqn) );
  }

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){    
	if( iEP != EPSymmBin ) continue;

	qwebye->cd();
	hVn2Dfull[icent][iEP][iqn]          = new TH2D(Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dfull[icent][iEP][iqn]->SetOption("colz");
	hVn2Dfull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
	hVn2Dfull[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

	hVn2Dsub0[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub0[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
	hVn2Dsub0[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

	hVn2Dsub1[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub1[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
	hVn2Dsub1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

	hVn2D0v1[icent][iEP][iqn]           = new TH2D( Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2D0v1[icent][iEP][iqn]->SetOption("colz");
	hVn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
	hVn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

	hVnFull[icent][iEP][iqn]            = new TH1D( Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnFull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
	hVnFull[icent][iEP][iqn]->GetYaxis()->SetTitle( "Events" );

	hVnSub0[icent][iEP][iqn]            = new TH1D( Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

	hVnSub1[icent][iEP][iqn]            = new TH1D( Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );

	Mult[icent][iEP][iqn]               = new TH1I( Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 300, 1, 1500 );
	Mult[icent][iEP][iqn]->GetXaxis()->SetTitle("Multiplicity");

	h2Vn2D0v1[icent][iEP][iqn]          = new TH2D( Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	h2Vn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->SetOption("colz");

	h2Vn2D0v1Magnitude[icent][iEP][iqn] = new TH1D( Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	h2Vn2D0v1Magnitude[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

      }
    } 
  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset raw and sumw values
      VnRaw_x_0    = 0;
      VnRaw_y_0    = 0;
      VnRaw_x_1    = 0;
      VnRaw_y_1    = 0;
      VnRaw_x_full = 0;
      VnRaw_y_full = 0;                

      sumw_0       = 0;
      sumw_1       = 0;
      sumw_full    = 0;

      evtMult_0    = 0;
      evtMult_1    = 0;
      evtMult_full = 0;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	  }

	} //-- End eta loop
      } //-- End pt loop

      //-- Fill Histograms, only use events that have at least two tracks in each SE
      if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

      VnRaw_x_full /= sumw_full;
      VnRaw_y_full /= sumw_full;
	
      VnRaw_x_0 /= sumw_0;
      VnRaw_y_0 /= sumw_0;
	
      VnRaw_x_1 /= sumw_1;
      VnRaw_y_1 /= sumw_1;
                
      //-- Full Tracker
      VnCorrected_x_full = VnRaw_x_full - hVNDetX_full[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_full = VnRaw_y_full - hVNDetY_full[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

      hVnFull[icent][EPbin][iqn]   -> Fill( vn_full );
      hVn2Dfull[icent][EPbin][iqn] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

      Mult[icent][EPbin][iqn]->Fill(evtMult_full);

      //-- SubEvt 0 (Eta > 0)
      VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

      hVnSub0[icent][EPbin][iqn]   -> Fill( vn_0 );
      hVn2Dsub0[icent][EPbin][iqn] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
      //-- SubEvt 1 (Eta < 0)
      VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

      hVnSub1[icent][EPbin][iqn]   -> Fill( vn_1 );
      hVn2Dsub1[icent][EPbin][iqn] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

      //-- SubEvt Difference
      double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
      double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
      hVn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x, vn0m1_y);	

      //-- SubEvt Difference for DD response
      double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
      double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
      h2Vn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x2, vn0m1_y2);

      double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
      h2Vn2D0v1Magnitude[icent][EPbin][iqn]->Fill(vn0m12);

    } //-- End EP loop        

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
    
}
Esempio n. 27
0
void dataCardSM(Int_t channel, Int_t cat, Int_t year, Int_t dataset, TString mass, TString path, TString tag, Int_t option=0){

  if(tag!="")path=path+"_"+tag;

  TString ChannelName;
  if(channel==1)ChannelName="muTau";
  else if(channel==2)ChannelName="eleTau";
  else return;
  cout<<"ChannelName "<<ChannelName<<endl;
  
  if(channel==1){
    TauMuPlotter * analysis=0;
    
    if(year==2011){
      analysis=configTauMu2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauMu2012AB("analysis",path);
      if(dataset==2)analysis=configTauMu2012ABC("analysis",path);
      if(dataset==3)analysis=configTauMu2012D("analysis",path);
      if(dataset==4)analysis=configTauMu2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauMu2012Summer13("analysis",path);
      if(dataset==6)analysis=configTauMu2012Summer13ReReco("analysis",path);
    }
  }
  if(channel==2){
    TauElePlotter * analysis=0;

    if(year==2011){
      analysis=configTauEle2011("analysis",path);
    }
    if(year==2012){
      if(dataset==1)analysis=configTauEle2012AB("analysis",path);
      if(dataset==2)analysis=configTauEle2012ABC("analysis",path);
      if(dataset==3)analysis=configTauEle2012D("analysis",path);
      if(dataset==4)analysis=configTauEle2012ABCD("analysis",path);
      if(dataset==5)analysis=configTauEle2012Summer13("analysis",path);
    }
  }
  
 
  bool Blind=0;
  analysis->nbins_=0;
  analysis->Isocat_=1;
  analysis->MTcat_=1; 
  analysis->Chcat_=1; 

  cout<<endl<<"optimizaion with option "<<option<<endl;

//   ///Simple isolation scan
//   char isocutoption[100];
//   if(option<10){
//     sprintf(isocutoption,"(tauisomva2raw>%.3f)",0.80+0.02*option);
//     analysis->tauIsoCutQCD_="(tauisomva2raw>0.5)";
//   }else if(option<20){
//     sprintf(isocutoption,"(tauiso3hitraw<%.3f)",2.2-0.2*(option-10));
//     analysis->tauIsoCutQCD_="(tauiso3hitraw<6.0)";
//   }
//   analysis->tauIsoCut_=isocutoption;

  
//   ////////////////////////optimization of mT cut
//   if(option>0){
//     //use the digits of the option for each variable
//     analysis->mTCut_=5+abs(option)*5;
//   }
//   //////////////////////////////////////////////////

  ////////////////////////optimization of 1Jet : with 2 tau pT categories
  if(option>0){

    //optimize tau pT without higgs pT cut
    if((option/10)==0)analysis->taupTCut_ = 20+(option)*5;//1->6
    ///optimize higgs pT cut at low Tau pT
    if((option/10)==1)analysis->higgspTCutLow_=(option%10-1)*20;//11->18
    ///optimize higgs pT cut at high Tau pT
    if((option/10)==2)analysis->higgspTCutHigh_=(option%10-1)*20;//21->28

    //optimize tau and higgs pT cuts at the same time
    if((option/100)==1){
      analysis->taupTCut_ = 20+((option%100)/10 - 1)*5;//first digit: 1->6
      analysis->higgspTCutHigh_=(option%10-1)*20;//second digit: 1->8
    }

  }
  //////////////////////////////////////////////////

  analysis->scaleSamplesLumi();
  TFile output(ChannelName+"_SM"+(long)cat+"_"+mass+"_"+tag+".root","recreate");
  for(long sm=0; sm<NCAT; sm++){
    if(cat==9)continue;
    if(cat==13 && (sm==2 || sm==4))continue;//skip boost_low and vbf
    if(cat==20 && (sm==3 || sm==4))continue;//skip boost_high and vbf
    if(cat==23 && (sm==4))continue;//skip vbf
    if(cat==15 && (sm==2 || sm==3))continue;//skip boost_low and boost_high

    TDirectory* dir = output.mkdir(ChannelName+"_"+catdirname[sm]);  
    gROOT->cd();

//     if(sm==0 || sm==1){
//       analysis->plotvar_="ditaumass";//switch to visible mass for 0jet
//       analysis->setVariableBinning(NXBINS0JET,xbinsValues0Jet);
//     }else{
    analysis->plotvar_=mass;
    if(sm==4)analysis->setVariableBinning(NXBINSVBF,xbinsValuesVBF);
    else analysis->setVariableBinning(NXBINS,xbinsValues);
    //    }
    
      ///Category definition
    analysis->extrasel_ = analysis->getSMcut(sm);
    //analysis->extrasel_ = analysis->getSMcutOpt(sm);//possible higgs pT cuts
    //analysis->extrasel_ = analysis->getSMcutSummer13(sm);//use higgs pT < 20 in control regions


//     if(option==0)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==0)";
//     if(option==1)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==1)";
//     if(option==10)analysis->extrasel_ = analysis->getSMcut(sm) + "*(taudecaymode==10)";

//     //for ZTT decaymode ratios
//     analysis->mTCut_=40;
//     if(20<=option&&option<30) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==0)"+"*("+(long)(20+(option-20)*5)+"<taupt&&taupt<"+(long)(20+(option-20+1)*5)+")";
//     if(30<=option&&option<40) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==1)"+"*("+(long)(20+(option-30)*5)+"<taupt&&taupt<"+(long)(20+(option-30+1)*5)+")";
//     if(40<=option&&option<50) analysis->extrasel_ = TString("(metpt<40&&njet<=2)*")+"(taudecaymode==10)"+"*("+(long)(20+(option-40)*5)+"<taupt&&taupt<"+(long)(20+(option-40+1)*5)+")";


    TH1F* QCD = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==2 ) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3 ) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)           QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==2) QCD=analysis->getQCDIncLowPt(); 
	if(sm==3) QCD=analysis->getQCDMuIsoSM(); 
	if(sm==4) QCD=analysis->getQCDVBFHCP();
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==2) QCD=analysis->getQCDInc();
	if(sm==1 || sm==3) QCD=analysis->getQCDIncLooseShape();
	if(sm==4)          QCD=analysis->getQCDMike();
      }
      if(year==2012){
	if(sm==0) QCD=analysis->getQCDIncWNJet(); 
	if(sm==1) QCD=analysis->getQCDMuIsoSM();
	if(sm==2) QCD=analysis->getQCDIncLowPt();//getQCDIncWNJet(); //
	if(sm==3) QCD=analysis->getQCDIncHighPt();
	if(sm==4) QCD=analysis->getQCDVBFHCP2();
      }
    }
    QCD->SetName("QCD");


    TH1F* W = 0;
    if(channel==1){//mu-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4) W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJet();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    if(channel==2){//e-tau
      if(year==2011){
	if(sm==0 || sm==1) W = analysis->getWJetsInc();
	if(sm==2 || sm==3) W = analysis->getWJetsInc();
	if(sm==4)  W = analysis->getW3JetsVBF();
      }
      if(year==2012){
	if(sm==0) W = analysis->getWJetsNJet();
	if(sm==1) W = analysis->getWJetsNJetNoChCut();
	if(sm==2) W = analysis->getWJetsNJetNoChCut();
	if(sm==3) W = analysis->getWJetsNJetNoChCut();
	if(sm==4) W = analysis->getWJetsNJetVBFHCP(); 
      }
    }
    W->SetName("W");
    
    TH1F* ZTT = 0;
    ZTT = analysis->getZToTauTau();
    ZTT->SetName("ZTT");

    TH1F* TT = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        TT=analysis->getTTJetsInc(); 
    if(sm==4)                                   TT=analysis->getTTJetsVBFHCP(); 
    TT->SetName("TT");

    TH1F* ZL =0;
    if(channel==1){//mu-Tau
      if(sm==0 || sm==2 || sm==1 || sm==3) 	ZL =analysis->getZLInc();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    if(channel==2){//e-Tau
      if(sm==0 || sm==2 || sm==1) 	        ZL =analysis->getZL2012();//analysis->getZL2012Type2();//
      if(sm==3)                            	ZL =analysis->getZLBoost();
      if(sm==4)                            	ZL =analysis->getZLVBFHCP();
    }
    ZL->SetName("ZL");

    TH1F* ZJ = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        ZJ=analysis->getZToLJetInc();
    if(sm==4)                                   ZJ=analysis->getZToLJetVBFHCP();                   
    ZJ->SetName("ZJ");

    TH1F* VV = 0;
    if(sm==0 || sm==2 || sm==1 || sm==3)        VV=analysis->getDiBoson();
    if(sm==4)                                   VV=analysis->getDiBosonVBFHCP();
    VV->SetName("VV");

    TH1F* ZLL=(TH1F*)ZL->Clone("ZLL");
    ZLL->SetName("ZLL");
    ZLL->Add(ZJ);

    //blind
    TString tmpsel=analysis->extrasel_;
    if(Blind)analysis->extrasel_ += "*(svfitmass<100||160<svfitmass)"; 
    TH1F* data_obs = analysis->getTotalData();
    data_obs->SetName("data_obs");
    analysis->extrasel_ =tmpsel;



    TH1F* MC=(TH1F*)ZTT->Clone("MC");//needed below
    MC->Add(ZL);
    MC->Add(ZJ);
    MC->Add(W);
    MC->Add(TT);
    MC->Add(VV);
    MC->Add(QCD);


    dir->cd();
  
    
    fix0Bins(ZTT); ZTT->Write(); 
    ZTT->SetName("ZTT125"); ZTT->Write();//needed for ZTT fits
    fix0Bins(ZL);  ZL->Write();
    fix0Bins(ZJ);  ZJ->Write();
    fix0Bins(ZLL); ZLL->Write();
    fix0Bins(W);   W->Write();
    fix0Bins(TT);  TT->Write();
    fix0Bins(VV);  VV->Write();
    fix0Bins(QCD); QCD->Write();
    data_obs->Write();
 
    gROOT->cd();
    
    delete ZTT ;
    delete ZL;
    delete ZJ;
    delete ZLL;
    delete W;
    delete TT;
    delete VV;
    delete QCD;

 
    for(Int_t m=0;m<NMASS;m++){
      long ma=massValues[m];

      //Nominal h 
      TH1F* SM = analysis->getSample(TString("HiggsGG")+ma);
      SM->SetName(TString("ggH")+ma);

      TH1F* VBF = analysis->getSample(TString("HiggsVBF")+ma);
      VBF->SetName(TString("qqH")+ma);

      TH1F* VH = analysis->getSample(TString("HiggsVH")+ma);
      VH->SetName(TString("VH")+ma);

      SM->Scale(1./analysis->findSample(TString("HiggsGG")+ma)->getCrossection());
      VBF->Scale(1./analysis->findSample(TString("HiggsVBF")+ma)->getCrossection());
      VH->Scale(1./analysis->findSample(TString("HiggsVH")+ma)->getCrossection());
      
      //check for empty histos
      if( SM->Integral()<=0.){  SM->SetBinContent(SM->GetNbinsX()/2,1e-4);    SM->SetBinError(SM->GetNbinsX()/2,1e-4); }
      if( VBF->Integral()<=0.){ VBF->SetBinContent(VBF->GetNbinsX()/2,1e-4);  VBF->SetBinError(VBF->GetNbinsX()/2,1e-4); }
      if( VH->Integral()<=0.){  VH->SetBinContent(VH->GetNbinsX()/2,1e-4);    VH->SetBinError(VH->GetNbinsX()/2,1e-4); }

      dir->cd();
      
     
      
      fixSignal(data_obs,MC,VH);  fix0Bins(VH);   VH->Write();
      fixSignal(data_obs,MC,SM);  fix0Bins(SM);   SM->Write();
      fixSignal(data_obs,MC,VBF); fix0Bins(VBF);  VBF->Write();
      gROOT->cd();

      delete VH;
      delete SM;
      delete VBF;

    }

    delete MC;
    delete data_obs;

  }
  
  output.ls();
  output.Close();
  gROOT->ProcessLine(".q");
}
Esempio n. 28
0
void MassPlotterSingleTop::singleTopAnalysis(TList* allCuts, Long64_t nevents ,TString myfileName ){

  TopUtilities topUtils ;

  int lumi = 0;

  TIter nextcut(allCuts); 
  TObject *objcut; 

  std::vector<TString> alllabels;
  while( objcut = nextcut() ){
    ExtendedCut* thecut = (ExtendedCut*)objcut ;
    alllabels.push_back( thecut->Name );
  }  
  //alllabels.push_back( "NoCut" );
  alllabels.push_back( "Trigger" );
  //alllabels.push_back( "MuonSelection" );
  //alllabels.push_back( "MuonVeto1" );
  //alllabels.push_back( "MuonVeto" );
  alllabels.push_back( "== 1#mu" );
  alllabels.push_back( "== 2-Jets" );
  alllabels.push_back( "== 1-bJet" );
  alllabels.push_back( "MT >50 GeV" );
  //alllabels.push_back( "j'-bVeto" );
  alllabels.push_back( "mtop" );
  //cout << alllabels.size() << endl;

  ExtendedObjectProperty cutflowtable("" , "cutflowtable" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  ExtendedObjectProperty cutflowtablew1("" , "cutflowtablew1" , "1" , alllabels.size() ,  0 , alllabels.size() , "2", {}, &alllabels );  
  

  TString fileName = fOutputDir;
  if(!fileName.EndsWith("/")) fileName += "/";
  Util::MakeOutputDir(fileName);

  bool printEventIds = false;
  vector< ofstream* > EventIdFiles;
  if(printEventIds){
    for( int i = 0 ; i < alllabels.size() ; i++ ){
      ofstream* filetxt = new ofstream(fileName + "/IPM_" + myfileName  + "_step" + boost::lexical_cast<string>(i) + ".txt" );
      EventIdFiles.push_back( filetxt );
    }
  }


  ExtendedObjectProperty nJetsBeforeCut("LeptonVeto" , "nJets" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_47("OneBjet" , "nJets20_47" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nJets20_24("OneBjet" , "nJets20_24" , "1" , 8 , 0 , 8 , "2", {});
  ExtendedObjectProperty nbJets("Jets" , "nbJets" , "1" , 3 , 0 , 3 , "2", {});

  ExtendedObjectProperty MTBeforeCut("OneBjetNoMT" , "MT" , "1" , 30 , 0 , 300 , "2", {});

  ExtendedObjectProperty nPVBeforeCutsUnCorr("nPVBeforeCutsUnCorr" , "nPVBeforeCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVBeforeCuts("nPVBeforeCuts" , "nPVBeforeCuts" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCutsUnCorr("nPVAfterCutsUnCorr" , "nPVAfterCutsUnCorr" , "1" , 100 , 0 , 100 , "2", {});
  ExtendedObjectProperty nPVAfterCuts("nPVAfterCuts" , "nPVAfterCuts" , "1" , 100 , 0 , 100 , "2", {});

  ExtendedObjectProperty TopMass("OneBjet" , "TopMass" , "1" , 30 , 100 , 400 , "2", {});
  ExtendedObjectProperty jprimeEta("OneBjet" , "jPrimeEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimeEtaSB("SideBand" , "jPrimeEtaSB" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty jprimePt("OneBjet" , "jPrimePt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty muPtOneB("OneBjet" , "muPt" , "1" , 20 , 20 , 120 , "2", {});
  ExtendedObjectProperty muCharge("OneBjet" , "muCharge" , "1" , 40 , -2 , 2 , "2", {});
  ExtendedObjectProperty muEtaOneB("OneBjet" , "muEta" , "1" , 10 , -2.5 , 2.5 , "2", {});
  ExtendedObjectProperty METOneBSR("OneBjet" , "MET_SR" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBSB("OneBjet" , "MET_SB" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty METOneBAll("OneBjet" , "MET_ALL" , "1" , 20 , 0 , 200 , "2", {});
  ExtendedObjectProperty bPtOneB("OneBjet" , "bPt" , "1" , 30 , 30 , 330 , "2", {});
  ExtendedObjectProperty bEtaOneB("OneBjet" , "bEta" , "1" , 10 , 0 , 5.0 , "2", {});
  ExtendedObjectProperty nonbCSV("OneBjet" , "jpCSV" , "1" , 20 , 0 , 1.0 , "2", {});

  ExtendedObjectProperty nLbjets1EJ24("1EJ24" , "nLbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ24("1EJ24" , "nTbJets_1EJ24" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ24("2EJ24" , "nLbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ24("2EJ24" , "nTbJets_2EJ24" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ24("3EJ24" , "nLbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ24("3EJ24" , "nTbJets_3EJ24" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ24("4EJ24" , "nLbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ24("4EJ24" , "nTbJets_4EJ24" , "1" , 5 , 0 , 5  , "2", {});

  ExtendedObjectProperty nLbjets1EJ47("1EJ47" , "nLbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});
  ExtendedObjectProperty nTbjets1EJ47("1EJ47" , "nTbJets_1EJ47" , "1" , 2 , 0 , 2  , "2", {});

  ExtendedObjectProperty nLbjets2EJ47("2EJ47" , "nLbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});
  ExtendedObjectProperty nTbjets2EJ47("2EJ47" , "nTbJets_2EJ47" , "1" , 3 , 0 , 3  , "2", {});

  ExtendedObjectProperty nLbjets3EJ47("3EJ47" , "nLbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});
  ExtendedObjectProperty nTbjets3EJ47("3EJ47" , "nTbJets_3EJ47" , "1" , 4 , 0 , 4  , "2", {});

  ExtendedObjectProperty nLbjets4EJ47("4EJ47" , "nLbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});
  ExtendedObjectProperty nTbjets4EJ47("4EJ47" , "nTbJets_4EJ47" , "1" , 5 , 0 , 5  , "2", {});

  TH1* hTopMass = new TH1D("hTopMass" , "Top Mass" , 500 , 0 , 500 );
  TH1* hTopMassEtaJ = new TH2D( "hTopMassEtaJ" , "Top Mass" , 500 , 0 , 500 , 20 , 0 , 5.0 );

  TH1* hEtajPDFScales[102];
  double ScalesPDF[102];
  double CurrentPDFWeights[102];
  for(int i=0 ; i < 102 ; i++){
    TString s(to_string(i));
    hEtajPDFScales[i] = new TH1D( TString("hEtaJp_PDF")+s , "" , 10 , 0 , 5.0 );
    ScalesPDF[i] = 0 ;
    CurrentPDFWeights[i] = 0;
  }

  TH1* hEtajWScales[9];
  double WScalesTotal[9];
  double CurrentLHEWeights[9];
  for(int i=0; i < 9; i++){
    TString s(to_string(i));
    hEtajWScales[i] = new TH1D( TString("hEtaJp_")+s , "" , 10 , 0 , 5.0 );
    WScalesTotal[i] = 0 ;
    CurrentLHEWeights[i] = 0;
  }

  std::vector<ExtendedObjectProperty*> allProps = {&cutflowtable, &cutflowtablew1 , &nJetsBeforeCut , &nbJets , &MTBeforeCut, &TopMass , &jprimeEta , &jprimeEtaSB , &jprimePt , &muPtOneB, &muCharge, &muEtaOneB , &METOneBSR ,&METOneBSB , &METOneBAll , & bPtOneB , &bEtaOneB , &nonbCSV ,&nJets20_24, &nJets20_47,&nPVAfterCuts, &nPVBeforeCuts , &nPVAfterCutsUnCorr , &nPVBeforeCutsUnCorr};

  std::vector<ExtendedObjectProperty*> JbJOptimizationProps = {&nLbjets1EJ24,&nTbjets1EJ24,&nLbjets2EJ24,&nTbjets2EJ24,&nLbjets3EJ24,&nTbjets3EJ24,&nLbjets4EJ24,&nTbjets4EJ24,&nLbjets1EJ47,&nTbjets1EJ47,&nLbjets2EJ47,&nTbjets2EJ47,&nLbjets3EJ47,&nTbjets3EJ47,&nLbjets4EJ47,&nTbjets4EJ47};
  nextcut.Reset();


  //codes for 2j0t selection
  TFile *theTreeFile = NULL;
  if(IsQCD==1)
    theTreeFile = new TFile( (fileName+ myfileName + "_Trees.root" ).Data(), "RECREATE");    

  double MT_QCD_Tree , TOPMASS_QCD_Tree , MuIso_QCD_Tree , Weight_QCD_Tree;

  TTree* theQCD_Tree = NULL;
  //end of 2j0t

  for(int ii = 0; ii < fSamples.size(); ii++){

    int data = 0;
    sample Sample = fSamples[ii];

    TEventList* list = 0;
   
    if(Sample.type == "data"){
      data = 1;
    }else
      lumi = Sample.lumi; 

    if( theTreeFile ){
      TString treename = Sample.sname ;
      if( data )
	treename = "Data";
      if( theTreeFile->Get( treename ) ){
	theQCD_Tree = (TTree*) (theTreeFile->Get( treename )) ; 
      }else{
	theTreeFile->cd();
	theQCD_Tree = new TTree( treename , treename + " tree for QCD shape/normalization studies" );
	theQCD_Tree->Branch( "MT/D" , &MT_QCD_Tree );
	theQCD_Tree->Branch( "TOPMASS/D" , &TOPMASS_QCD_Tree );
	theQCD_Tree->Branch( "MuIso/D" , &MuIso_QCD_Tree );
	theQCD_Tree->Branch( "Weight/D" , &Weight_QCD_Tree );
      }
    }


    double Weight = Sample.xsection * Sample.kfact * Sample.lumi / (Sample.nevents*Sample.PU_avg_weight);
    //Weight = 1.0;
    if(data == 1)
      Weight = 1.0;

    Sample.Print(Weight);

    SingleTopTree fTree( Sample.tree );
    Sample.tree->SetBranchStatus("*", 1);

    string lastFileName = "";

    Long64_t nentries =  Sample.tree->GetEntries();
    Long64_t maxloop = min(nentries, nevents);

    int counter = 0;
    double EventsIsPSeudoData ;
    int cutPassCounter = 0;
    for (Long64_t jentry=0; jentry<maxloop;jentry++, counter++) {
      Sample.tree->GetEntry(jentry);
      // //cout << fTree.Event_EventNumber << endl;
      // if(  !(fTree.Event_EventNumber == 11112683 || fTree.Event_EventNumber == 11112881 ) ){
      // 	//cout << " " ;
      // 	continue;
      // }
      // else{
      // 	cutPassCounter ++ ;
      // 	cout << cutPassCounter << " : " << fTree.Event_EventNumber << " : " << endl;
      // }
      EventsIsPSeudoData = PSeudoDataRandom->Uniform();

      if( lastFileName.compare( ((TChain*)Sample.tree)->GetFile()->GetName() ) != 0 ) {
	for(auto prop : allProps)
	  prop->SetTree( Sample.tree , Sample.type, Sample.sname );
	for(auto prop2 : JbJOptimizationProps ) 
	  prop2->SetTree( Sample.tree , Sample.type, Sample.sname );

	nextcut.Reset();
	while( objcut = nextcut() ){
	  ExtendedCut* thecut = (ExtendedCut*)objcut ;
	  thecut->SetTree( Sample.tree ,  Sample.name , Sample.sname , Sample.type , Sample.xsection, Sample.nevents, Sample.kfact , Sample.PU_avg_weight);
	}

	lastFileName = ((TChain*)Sample.tree)->GetFile()->GetName() ;
	cout << "new file : " << lastFileName << endl;
      }

      if ( counter == 100000 ){  
	fprintf(stdout, "\rProcessed events: %6d of %6d ", jentry + 1, nentries);
	fflush(stdout);
	counter = 0;
      }
 
      nextcut.Reset();
      double weight = Weight;

      if( !data ){
	weight *= fTree.Event_puWeight ;
      }

      if( Sample.UseLHEWeight ){
	//cout << "SIGNAL" << endl;
	weight *= fTree.Event_LHEWeightSign ;
	// if(fTree.Event_LHEWeightSign < 0.0)
	//   cout << fTree.Event_LHEWeightSign << endl;
      }

      #ifdef SingleTopTreeLHEWeights_h
      for( int i = 0 ; i < 102 ; i++ ){
	CurrentPDFWeights[i] = fTree.GetPDFWeight(i)/fabs(fTree.Event_LHEWeight) ;
	ScalesPDF[i] += CurrentPDFWeights[i] ;
      }

      if( Sample.name == "WJets" || Sample.name == "Signal" ){

	
	if(fTree.GetLHEWeight(0) != fTree.Event_LHEWeight0) cout << "Wrong GetLHEWeight(0) Value" << endl;
	if(fTree.GetLHEWeight(1) != fTree.Event_LHEWeight1) cout << "Wrong GetLHEWeight(1) Value" << endl;
	if(fTree.GetLHEWeight(2) != fTree.Event_LHEWeight2) cout << "Wrong GetLHEWeight(2) Value" << endl;
	if(fTree.GetLHEWeight(3) != fTree.Event_LHEWeight3) cout << "Wrong GetLHEWeight(3) Value" << endl;
	if(fTree.GetLHEWeight(4) != fTree.Event_LHEWeight4) cout << "Wrong GetLHEWeight(4) Value" << endl;
	if(fTree.GetLHEWeight(5) != fTree.Event_LHEWeight5) cout << "Wrong GetLHEWeight(5) Value" << endl;
	if(fTree.GetLHEWeight(6) != fTree.Event_LHEWeight6) cout << "Wrong GetLHEWeight(6) Value" << endl;
	if(fTree.GetLHEWeight(7) != fTree.Event_LHEWeight7) cout << "Wrong GetLHEWeight(7) Value" << endl;
	if(fTree.GetLHEWeight(8) != fTree.Event_LHEWeight8) cout << "Wrong GetLHEWeight(8) Value" << endl;
	
	// CurrentLHEWeights[0] = fTree.Event_LHEWeight /fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[1] = fTree.Event_LHEWeight1/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[2] = fTree.Event_LHEWeight2/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[3] = fTree.Event_LHEWeight3/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[4] = fTree.Event_LHEWeight4/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[5] = fTree.Event_LHEWeight5/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[6] = fTree.Event_LHEWeight6/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[7] = fTree.Event_LHEWeight7/fabs(fTree.Event_LHEWeight) ;
	// CurrentLHEWeights[8] = fTree.Event_LHEWeight8/fabs(fTree.Event_LHEWeight) ;
	
	for(int i = 0 ; i<9 ;i++){
	  CurrentLHEWeights[i] = fTree.GetLHEWeight(i)/fabs(fTree.Event_LHEWeight) ;
	  WScalesTotal[i] += CurrentLHEWeights[i];
	}
      }
      #endif
      
      double cutindex = 0.5;
      bool pass=true;
      while( objcut = nextcut() ){
	ExtendedCut* thecut = (ExtendedCut*)objcut ;
	pass &= thecut->Pass(jentry , weight);
	if(! pass ){
	  break;
	}else{
	  if( isfinite (weight) ){
	    cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	    cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	  }
	  else
	    cout << "non-finite weight : " << weight << endl;
	}
	cutindex+=1.0;
      }

      if(! pass)
	continue;

      int cut = 0;

      //cout << alllabels[ int(cutindex) ] << endl;
//       cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
//       cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
//       cutindex ++ ;

      // if( data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v2 > 0.5) )
      // 	continue;
      
      // if( !data && !(fTree.Event_passesHLT_IsoMu20_eta2p1_v1 > 0.5) )
      // 	continue;

      nPVBeforeCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , false , true );
      nPVBeforeCuts.Fill( fTree.Event_nPV , weight , false, true);

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl; 
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;
      
      if( data && !(fTree.Event_passesHLT_IsoMu20_v2 > 0.5 || fTree.Event_passesHLT_IsoMu20_v1 > 0.5 || fTree.Event_passesHLT_IsoMu20_v3 > 0.5)  )
	continue;
      if(!data && !(fTree.Event_passesHLT_IsoMu20_v1 > 0.5) )
	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << fTree.Event_EventNumber << endl;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      

      //cout << "nMuons : " << fTree.muons_size << endl;
      int tightMuIndex =-1;
      int nonTightMuIndex = -1;
      int nLooseMuos   = 0;
      int nTightMuons = 0;
      int nTightNonIsoMuons = 0;

      for( int imu=0 ; imu < fTree.muons_size ; imu++ ){
	// cout << imu << " : " << fTree.muons_Pt[imu] << "-" << fTree.muons_Eta[imu] << "-"
	//      << fTree.muons_IsTightMuon[imu] << "-" << fTree.muons_Iso04[imu] << endl;
	
	bool isTight = false;
      	if( fTree.muons_Pt[imu] > 22.0 &&
	    fabs(fTree.muons_Eta[imu]) < 2.1 &&
	    fTree.muons_IsTightMuon[imu] > 0.5 ){


	  if( fTree.muons_Iso04[imu] < 0.06 ){ 
	    isTight = true;
	    nTightMuons ++;
	    if( tightMuIndex == -1 )
	      tightMuIndex = imu;
	  }else if( fTree.muons_Iso04[imu] < 0.15 ){
	    nTightNonIsoMuons ++;
	    if( nonTightMuIndex == -1 )
	      nonTightMuIndex = imu;
	  }
	}

	if( ! isTight )
	  if( fTree.muons_Pt[ imu ] > 10.0 &&
	      fTree.muons_IsLooseMuon[ imu ] > 0.5 &&
	      fabs(fTree.muons_Eta[imu]) < 2.5 && 
	      fTree.muons_Iso04[imu] < 0.20 ){
	    nLooseMuos++;
	  }
      }      

      if(IsQCD){
	nLooseMuos = nTightMuons ;	
	nTightMuons = nTightNonIsoMuons ;
	tightMuIndex = nonTightMuIndex ;
      }


      if( nTightMuons != 1 )
	  continue;

      bool isiso = true;

      if( nLooseMuos > 0 )
      	continue;

#ifdef MUONCHARGEP
      if(fTree.muons_Charge[tightMuIndex] < 0)
	continue;
#endif
#ifdef MUONCHARGEN
      if(fTree.muons_Charge[tightMuIndex] > 0)
	continue;
#endif

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      int nLooseElectrons = 0;
      for( int iele = 0 ; iele < fTree.electrons_size;iele ++ ){
      	if( fTree.electrons_Pt[iele] > 20 &&
	    fabs(fTree.electrons_Eta[iele]) < 2.5 && 
	    ( fabs(fTree.electrons_Eta[iele]) < 1.4442 || fabs(fTree.electrons_Eta[iele]) > 1.566) &&
	    fTree.electrons_vidVeto[iele] > 0.5 )
	  nLooseElectrons++;
      }
      
      if( nLooseElectrons > 0 )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      int j1index = -1;
      int j2index = -1;
      int j3index = -1;
      int nJets = 0 ;
      int howManyBJets = 0;
      int bjIndex = -1;
      int bj2Index = -1;
      int jprimeIndex ; 

      int nJetsPt20_47 = 0;

      int nJetsPt20_24 = 0;
      int nLbJetsPt20 = 0;
      int nTbJetsPt20 = 0;

      TLorentzVector muon;
      muon.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[tightMuIndex] , fTree.muons_E[tightMuIndex] );
      if( muon.Energy() == 0.0 )
	cout << "ZERO???" <<endl;
      for( int jid = 0 ; jid < fTree.jetsAK4_size ; jid++ ){

	float NHF = fTree.jetsAK4_JetID_neutralHadronEnergyFraction[jid] ;
	float NEMF = fTree.jetsAK4_JetID_neutralEmEnergyFraction[jid] ;
	float NumConst = fTree.jetsAK4_JetID_numberOfDaughters[jid] ;
	float eta = fTree.jetsAK4_Eta[jid] ;
	float CHF = fTree.jetsAK4_JetID_chargedHadronEnergyFraction[jid] ;
	float CHM = fTree.jetsAK4_JetID_chargedMultiplicity[jid] ;
	float CEMF = fTree.jetsAK4_JetID_chargedEmEnergyFraction[jid] ;
	float NumNeutralParticle = fTree.jetsAK4_JetID_neutralMultiplicity[jid] ;


	bool looseid ;
	if(  abs(eta)<=3.0 ) {
	  looseid = (NHF<0.99 && NEMF<0.99 && NumConst>1) && ((abs(eta)<=2.4 && CHF>0 && CHM>0 && CEMF<0.99) || abs(eta)>2.4) ;
	}
	else
	  looseid = (NEMF<0.90 && NumNeutralParticle>10) ;

      	if( fTree.jetsAK4_CorrPt[jid] > 20 &&
	    fabs( fTree.jetsAK4_Eta[jid] ) < 4.7 &&
	    looseid
	    ){
	  TLorentzVector jet;
	  jet.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[jid] , fTree.jetsAK4_Eta[jid] , fTree.jetsAK4_Phi[jid] , fTree.jetsAK4_CorrE[jid] );
	  double DR = muon.DeltaR( jet );

	  if ( DR > 0.3 ){

	    if( fTree.jetsAK4_CorrPt[jid] <= 40 ){
	      nJetsPt20_47 ++ ;
	      if( fabs( fTree.jetsAK4_Eta[jid] ) < 2.4 ){
		nJetsPt20_24 ++;
		if( fTree.jetsAK4_CSV[jid] > 0.97 )
		  nTbJetsPt20++;
		else if( fTree.jetsAK4_CSV[jid] > 0.605 )
		  nLbJetsPt20++;
	      }
	      
	      continue;
	    }	    
	    nJets++;
	    if( nJets == 1 )
	      j1index = jid ;
	    else if(nJets == 2 )
	      j2index = jid ;
	    else if( nJets == 3 )
	      j3index = jid ;
	    
	    if( fTree.jetsAK4_IsCSVT[jid] == true  && fabs( fTree.jetsAK4_Eta[jid] ) <= 2.4 ){
	      howManyBJets ++;
	      if(howManyBJets==1)
		bjIndex = jid ;
	      else if(howManyBJets==2)
		bj2Index = jid ;
	    }else
	      jprimeIndex = jid ;
	  }
	}
      }
      
      nJetsBeforeCut.Fill( nJets , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      if (nJets != NUMBEROFJETS)
	continue;


      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;
      
      nbJets.Fill( howManyBJets , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      if( howManyBJets != NUMBEROFBJETS )
	continue;

      if( !data ){
	if( NUMBEROFBJETS == 2 )
	  weight *= fTree.Event_bWeight2CSVT ;
	else if (NUMBEROFBJETS == 1 )
	  weight *= fTree.Event_bWeight1CSVT ;
      }

      //weight = 1.0;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

     
      double MT = sqrt( 2*fTree.met_Pt* fTree.muons_Pt[tightMuIndex]*(1-TMath::Cos( Util::DeltaPhi(fTree.met_Phi , fTree.muons_Phi[tightMuIndex]) ) )  ) ;
      MTBeforeCut.Fill( MT , weight , EventsIsPSeudoData < fabs(weight) , isiso );
      // if( fTree.met_Pt < 45 )
      // 	continue;
      if( MT < 50 && (NUMBEROFBJETS == 1 && NUMBEROFJETS == 2) && !IsQCD )
      	continue;

      if( printEventIds )
	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
     
      cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      cutindex ++ ;

      nonbCSV.Fill( fTree.jetsAK4_CSV[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);

//       if( fTree.jetsAK4_CSV[jprimeIndex] > 0.605 )
// 	continue;

      // if( printEventIds )
      // 	(*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
      // cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
      // cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
      // cutindex ++ ;

      nJets20_47.Fill( nJetsPt20_47 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      nJets20_24.Fill( nJetsPt20_24 , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(nJetsPt20_24 < 2){
	nLbjets1EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 3){
	nLbjets2EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 4){
	nLbjets3EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_24 < 5){
	nLbjets4EJ24.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ24.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      if(nJetsPt20_47 < 2){
	nLbjets1EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets1EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 3){
	nLbjets2EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets2EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 4){
	nLbjets3EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets3EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }
      if(nJetsPt20_47 < 5){
	nLbjets4EJ47.Fill( nLbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	nTbjets4EJ47.Fill( nTbJetsPt20 , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }


      if( NUMBEROFBJETS == 2 )
	if( fTree.jetsAK4_CSV[bj2Index] > fTree.jetsAK4_CSV[bjIndex] )
	  std::swap( bj2Index , bjIndex );

      //int jprimeIndex = (bjIndex == j1index) ? j2index : j1index ;
      TLorentzVector muLV;
      muLV.SetPtEtaPhiE( fTree.muons_Pt[tightMuIndex] , fTree.muons_Eta[tightMuIndex] , fTree.muons_Phi[ tightMuIndex ] , fTree.muons_E[tightMuIndex] );
      TLorentzVector bjetLV;
      bjetLV.SetPtEtaPhiE( fTree.jetsAK4_CorrPt[ bjIndex ] , fTree.jetsAK4_Eta[ bjIndex ] , fTree.jetsAK4_Phi[ bjIndex ] , fTree.jetsAK4_CorrE[ bjIndex ] ) ; 
      double topMass = topUtils.top4Momentum( muLV , bjetLV , fTree.met_Px , fTree.met_Py ).mass();
      TopMass.Fill( topMass , weight , EventsIsPSeudoData < fabs(weight) , isiso ); //fTree.resolvedTopSemiLep_Mass[0]

      MT_QCD_Tree = MT;
      TOPMASS_QCD_Tree = topMass ;
      MuIso_QCD_Tree = fTree.muons_Iso04[tightMuIndex];
      Weight_QCD_Tree = weight ;

      if( IsQCD )
	theQCD_Tree->Fill();



      if( (130. < topMass && topMass < 225.) || NUMBEROFBJETS == 2 ){

	nPVAfterCutsUnCorr.Fill( fTree.Event_nPV , weight/fTree.Event_puWeight , EventsIsPSeudoData < fabs(weight) , isiso );
	nPVAfterCuts.Fill( fTree.Event_nPV , weight , EventsIsPSeudoData < fabs(weight) , isiso );

#ifdef SingleTopTreeLHEWeights_h
	for(int i = 0 ; i< 102 ; i++){
	  hEtajPDFScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentPDFWeights[i] ) );
	}
	if( Sample.name == "WJets" || Sample.name == "Signal"){
	  for(int i=0;i<9;i++)
	    hEtajWScales[i]->Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight*fabs( CurrentLHEWeights[i] ) );
	}
#endif
	
	jprimeEta.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	jprimePt.Fill( fTree.jetsAK4_CorrPt[jprimeIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muPtOneB.Fill( fTree.muons_Pt[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muCharge.Fill( fTree.muons_Charge[tightMuIndex] , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	muEtaOneB.Fill( fabs(fTree.muons_Eta[tightMuIndex]) , weight , EventsIsPSeudoData < fabs(weight), isiso );
	METOneBSR.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
	bPtOneB.Fill( fTree.jetsAK4_CorrPt[bjIndex] , weight , EventsIsPSeudoData < fabs(weight), isiso );
	bEtaOneB.Fill(fabs( fTree.jetsAK4_Eta[bjIndex] ) , weight , EventsIsPSeudoData < fabs(weight), isiso );

	if( printEventIds )
	  (*(EventIdFiles[cutindex])) << (fTree.Event_EventNumber) << endl ;
	cutflowtable.Fill( cutindex , weight , EventsIsPSeudoData < fabs(weight) );
	cutflowtablew1.Fill( cutindex , weight/fabs(weight) , EventsIsPSeudoData < fabs(weight) );
	cutindex++;
      }else{
	jprimeEtaSB.Fill( fabs( fTree.jetsAK4_Eta[jprimeIndex] ) , weight , EventsIsPSeudoData < fabs(weight) , isiso );
	METOneBSB.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);
      }

      METOneBAll.Fill(  fTree.met_Pt , weight , EventsIsPSeudoData < fabs(weight) , isiso);

      if(Sample.name == "Signal" )
	hTopMass->Fill( topMass , weight );
      if(Sample.name == "WJets")
	hTopMassEtaJ->Fill( topMass ,fabs( fTree.jetsAK4_Eta[jprimeIndex] )  );
    }
    theQCD_Tree->Write();
    
  }

  theTreeFile->Close();
      

  // TString fileName = fOutputDir;
  // if(!fileName.EndsWith("/")) fileName += "/";
  // Util::MakeOutputDir(fileName);
  fileName += myfileName + ".root" ;

  TFile *theFile = new TFile(fileName.Data(), "RECREATE");

  nonbCSV.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nonbCSV.CalcSig( 0 , 4 , -1 , 0.1); 
  nonbCSV.CalcSig( 0 , 2 , -1 , 0 ) ; 

  nJets20_24.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_24.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_24.CalcSig( 0 , 2 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 0 , -1 , 0 ) ; 
  nJets20_47.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  nJets20_47.CalcSig( 0 , 2 , -1 , 0 ) ; 

  muCharge.CalcSig( 0 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 0 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 0 , 2 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 0 , -1 , 0 ) ; 
  muCharge.CalcSig( 1 , 4 , -1 , 0.1 ) ; 
  muCharge.CalcSig( 1 , 2 , -1 , 0 ) ; 

  for(auto prop : allProps)
    prop->Write( theFile , 1000  );

#ifdef SingleTopTreeLHEWeights_h
  TDirectory* dirWScales = theFile->mkdir("WJScales");
  dirWScales->cd();
  for(int i=0;i<9;i++){
    cout << "WScalesTotal[i]" << WScalesTotal[i] << "," << WScalesTotal[0]/WScalesTotal[i] << endl;
    hEtajWScales[i]->Scale( WScalesTotal[0]/WScalesTotal[i] );
    hEtajWScales[i]->Write();
  }

  TDirectory* dirPDFScales = theFile->mkdir("PDFScales");
  dirPDFScales->cd();
  for(int i=0;i<102;i++){
    cout << "PDFScales[i]" << ScalesPDF[i] << "," << WScalesTotal[0]/ScalesPDF[i] << endl;
    hEtajPDFScales[i]->Scale( WScalesTotal[0]/ScalesPDF[i] );
    hEtajPDFScales[i]->Write();
  }
#endif

  TDirectory* dir2 = theFile->mkdir("JbJOptimizationProps");
  dir2->cd();

  for(auto prop2 : JbJOptimizationProps){
    prop2->CalcSig( 0 , 0 , -1 , 0 ) ; 
    prop2->CalcSig( 0 , 4 , -1 , 0.1 ) ; 
    prop2->CalcSig( 0 , 2 , -1 , 0 ) ; 
    prop2->Write( dir2 , 1000  );
  }

  theFile->cd();
  hTopMass->Write();
  hTopMassEtaJ->Write();
  //cutflowtable.Print("cutflowtable");
  theFile->Close();
  if( printEventIds )
    for( auto a : EventIdFiles ){
      a->close();
    }
}
Esempio n. 29
0
void ProcessingTime(const char *inputFile)
{
  TChain *chain = new TChain("Delphes");
  chain->Add(inputFile);

  TH1F hist("time", "time", 50, 0, 0.01);
  Int_t i;

  TDirectory *currentDirectory = gDirectory;

  // Graphics style parameters to avoid grey background on figures
  gStyle->SetCanvasColor(kExRootBackgroundColor);
  gStyle->SetStatColor(kExRootBackgroundColor);
  //  gStyle->SetTitleColor(kExRootBackgroundColor);
  gStyle->SetPadColor(kExRootBackgroundColor);

  gStyle->SetPadTopMargin(0.10);
  gStyle->SetPadRightMargin(0.10);
  gStyle->SetPadBottomMargin(0.15);
  gStyle->SetPadLeftMargin(0.15);

  gStyle->SetStatFont(kExRootFont);
  gStyle->SetStatFontSize(kExRootFontSize);

  gStyle->SetTitleFont(kExRootFont, "");
  gStyle->SetTitleFont(kExRootFont, "X");
  gStyle->SetTitleFont(kExRootFont, "Y");
  gStyle->SetTitleFont(kExRootFont, "Z");
  gStyle->SetTitleSize(kExRootFontSize, "");
  gStyle->SetTitleSize(kExRootFontSize, "X");
  gStyle->SetTitleSize(kExRootFontSize, "Y");
  gStyle->SetTitleSize(kExRootFontSize, "Z");

  gStyle->SetLabelFont(kExRootFont, "X");
  gStyle->SetLabelFont(kExRootFont, "Y");
  gStyle->SetLabelFont(kExRootFont, "Z");
  gStyle->SetLabelSize(kExRootFontSize, "X");
  gStyle->SetLabelSize(kExRootFontSize, "Y");
  gStyle->SetLabelSize(kExRootFontSize, "Z");

  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

  gStyle->SetTextFont(kExRootFont);
  gStyle->SetTextSize(kExRootFontSize);

  gStyle->SetOptStat(111110);
  // gStyle->SetOptFit(101);

  canvas = static_cast<TCanvas*>(gROOT->FindObject("c1"));
  if(canvas)
  {
    canvas->Clear();
    canvas->UseCurrentStyle();
    canvas->SetWindowSize(800, 650);
  }
  else
  {
    canvas = new TCanvas("c1", "c1", 800, 650);
  }
  canvas->SetGrid();
  canvas->SetHighLightColor(kExRootBackgroundColor);

  currentDirectory->cd();

  for(i = 0; i < 9; ++i)
  {
    chain->Draw("Event.ProcTime >> time", TString::Format("Jet_size == %d", i+2));
    gr.SetPoint(i, i+2, hist.GetMean()*1000);
    grerr.SetPoint(i, i+2, hist.GetMean()*1000);
    grerr.SetPointError(i, 0, hist.GetRMS()*1000);
  }

  grerr.GetXaxis()->SetLimits(1.0, 11.0);
  grerr.GetXaxis()->SetTitleOffset(1.5);
  grerr.GetYaxis()->SetTitleOffset(1.75);
  grerr.GetXaxis()->SetTitle("jet multiplicity");
  grerr.GetYaxis()->SetTitle("processing time per event, ms");
  gr.SetMarkerStyle(kFullCircle);
  gr.SetMarkerColor(kBlack);
  gr.SetMarkerSize(1);
  gr.SetLineColor(kBlack);
  gr.SetLineWidth(2);
  grerr.SetFillStyle(1001);
  grerr.SetFillColor(17);
  grerr.Draw("A3");
  gr.Draw("P");

  comment.SetTextSize(kExRootFontSize);
  comment.SetTextFont(kExRootFont);
  comment.SetTextAlign(22);
  comment.SetFillColor(kExRootBackgroundColor);
  comment.SetBorderSize(0);
  comment.AddText("ttbar + jets events");
  comment.Draw();
}
int main () 
{
//open input file
 //TFile *f=TFile::Open("input_rootfile/PhotonJet_G_PFlowAK5chs.root");
   //TFile *f=TFile::Open("input_rootfile/PhotonJet_QCD_PFlowAK5chs.root");
   TFile *f=TFile::Open("input_rootfile/PhotonJet_MC_TOT_PFlowAK5chs.root");

 	
  	

//*****************************************************************************************************
//
//                                      histograms definition
//
//*****************************************************************************************************
	QGSyst qgsyst;
	//qgsyst.ReadDatabase("SystDatabase.txt");
	qgsyst.ReadDatabaseDoubleMin("SystDatabase_doubleMin.txt");
	qgsyst.SetTagger("QGLHisto");

	ptBinning myPtBinning;
	int isFor2DTagging = 1;
	ptBinning my2DTaggingPtBinning(isFor2DTagging);
	
//usefull variables
	Double_t xlow = getHistoXlow();
	Double_t xup = getHistoXup();
	//Double_t    binrange = 0.1;
	//Int_t    nbinsx = (xup - xlow)/binrange;
	Int_t    nbinsx = getHistoNbinsx();
	
	Double_t xlow2D = 0;
	Double_t xup2D = 1;
	Int_t    nbinsx2D = 20;
	Double_t ylow2D = 0;
	Double_t yup2D = 1;
	Int_t    nbinsy2D = 20;

	int nzones = getZoneNumber();
	int nflavours = getFlavourNumber(); //uds, g, c, b, noMatched, all
	int n2DTaggingPtBins = my2DTaggingPtBinning.getSize();

	vector<TMatrixF> v4x4MatrixPt = buildSquareMatrixPtVector(my2DTaggingPtBinning);
	vector<TMatrixF> v6x4MatrixPt = buildMatrixPtVector(my2DTaggingPtBinning);

//vectors for 2D tagging study
  // gammapt per flavour per zone
  std::vector<std::vector<TH1F*> > vGammaPt_ZoneFlavour = buildZoneFlavourVectorH1("Gammapt",30,0,800);
  std::vector<std::vector<TH1F*> > vFirstJetPt_ZoneFlavour = buildZoneFlavourVectorH1("FirstJetPt",160,0,800);

	//flavour fractions per pt
	vector<TH1F*> vFractionHisto_Pt = buildPtVectorH1(my2DTaggingPtBinning,"FractionHisto",nflavours-1,0,nflavours-1) ;

	//responses per zone per pt
	vector<vector<TH1F*> > vRmpf_ZonePt = buildZonePtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_ZonePt = buildZonePtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;


	//QG-likelihood per flavour per pt
	vector<vector<TH1F*> > vQGL_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"QGL",nbinsx2D,xlow2D,xup2D) ;

	//Btag-CSV per flavour per pt
	vector<vector<TH1F*> > vCSV_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"CSV",nbinsx2D,xlow2D,xup2D) ;

	//responses per flavour per pt
	vector<vector<TH1F*> > vRmpf_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;

	//responses per flavour per pt when we are in one of the 2D tagging zones
	vector<vector<TH1F*> > vRmpf_in2DTaggingZone_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf_in2DTaggingZone",nbinsx,xlow,xup) ;

	vector<vector<TH1F*> > vRtrue_in2DTaggingZone_FlavourPt = buildFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue_in2DTaggingZone",nbinsx,xlow,xup) ;

	
	//Gammapt per flavour 
	vector<TH1F*> vGammapt_Flavour = buildFlavourVectorH1("Gammapt",30,0,800);


	//responses per zone per flavour per pt
	vector<vector<vector<TH1F*> > > vRmpf_ZoneFlavourPt = buildZoneFlavourPtVectorH1(my2DTaggingPtBinning,"Rmpf",nbinsx,xlow,xup) ;

	vector<vector<vector<TH1F*> > > vRtrue_ZoneFlavourPt = buildZoneFlavourPtVectorH1(my2DTaggingPtBinning,"Rtrue",nbinsx,xlow,xup) ;

	
	//2D tagging plans per flavour per pt
	vector<vector<TH2F*> > v2DTaggingPlan_FlavourPt = buildFlavourPtVectorH2(my2DTaggingPtBinning,"2DTaggingPlan",nbinsx2D,xlow2D,xup2D,nbinsy2D,ylow2D,yup2D) ;

	vector<vector<TH2F*> > v2DTaggingPlan_FlavourPt_divided = buildFlavourPtVectorH2(my2DTaggingPtBinning,"2DTaggingPlan_divided",nbinsx2D,xlow2D,xup2D,nbinsy2D,ylow2D,yup2D) ;

	//flavour number per zone per flavour per pt
	vector<vector<vector<float> > > vFlavourNumber = build_fraction_ZoneFlavourPtVector(my2DTaggingPtBinning) ;

	//flavour number per zone per flavour per pt
	vector<vector<vector<float> > > vFlavourFraction = build_fraction_ZoneFlavourPtVector(my2DTaggingPtBinning) ;

	
	for(int j=0; j<n2DTaggingPtBins; j++) {
		vFractionHisto_Pt[j]->Sumw2();
		for(int i=0; i<nzones; i++) {
			vRmpf_ZonePt[i][j]->Sumw2();
			vRtrue_ZonePt[i][j]->Sumw2();
		}
		for(int k=0; k<nflavours; k++) {
			vRmpf_FlavourPt[k][j]->Sumw2();
			vRtrue_FlavourPt[k][j]->Sumw2();
			vRmpf_in2DTaggingZone_FlavourPt[k][j]->Sumw2();
			vRtrue_in2DTaggingZone_FlavourPt[k][j]->Sumw2();
			v2DTaggingPlan_FlavourPt[k][j]->Sumw2();
			vQGL_FlavourPt[k][j]->Sumw2();
			vCSV_FlavourPt[k][j]->Sumw2();
			for(int l=0; l<nzones; l++) {
				vRmpf_ZoneFlavourPt[l][k][j]->Sumw2();
				vRtrue_ZoneFlavourPt[l][k][j]->Sumw2();
			}
		}
	}
	
	for(int k=0; k<nflavours; k++) {
		vGammapt_Flavour[k]->Sumw2();
    for(int l=0; l<nzones; l++) {
		  vGammaPt_ZoneFlavour[l][k]->Sumw2();
		  vFirstJetPt_ZoneFlavour[l][k]->Sumw2();
		}
	}
	

	TH1F* hGammaPt=new TH1F("hGammaPt","hGammaPt",40,40,800);
	hGammaPt->SetXTitle("p_{T}^{#gamma} [GeV/c]");
	hGammaPt->Sumw2();

	TH1F* hFirstJetPt=new TH1F("hFirstJetPt","hFirstJetPt",50,0,1400);
	hFirstJetPt->SetXTitle("1^{st} jet p_{T} [GeV/c]");
	hFirstJetPt->Sumw2();

	TH1F* hSecondJetPt=new TH1F("hSecondJetPt","hSecondJetPt",50,0,200);
	hSecondJetPt->SetXTitle("2^{nd} jet p_{T} [GeV/c]");
	hSecondJetPt->Sumw2();
	
	TH1F* hMetPt=new TH1F("hMetPt","hMetPt",50,0,620);
	hMetPt->SetXTitle("MET p_{T} [GeV/c]");
	hMetPt->Sumw2();
	
	TH1F* hParalleleMetPt=new TH1F("hParalleleMetPt","hParalleleMetPt",50,-200,200);
	hParalleleMetPt->SetXTitle("parallele MET p_{T} [GeV/c]");
	hParalleleMetPt->Sumw2();
	
	TH1F* hPerpendicularMetPt=new TH1F("hPerpendicularMetPt","hPerpendicularMetPt",50,-140,140);
	hPerpendicularMetPt->SetXTitle("perpendicular MET p_{T} [GeV/c]");
	hPerpendicularMetPt->Sumw2();
	
	TH1F* hAlpha=new TH1F("hAlpha","hAlpha",10,0.,1.);
	hAlpha->SetXTitle("p_{T}^{2^{nd} jet}/p_{T}^{#gamma}");
	hAlpha->Sumw2();
	
	TH1F* hDeltaPhi_j1gamma=new TH1F("hDeltaPhi_j1gamma","hDeltaPhi_j1gamma",40,0,4);
	hDeltaPhi_j1gamma->SetXTitle("|#Delta#phi (#gamma,1^{st}jet)|");
	hDeltaPhi_j1gamma->Sumw2();

	TH1F* hDeltaPhi_j2gamma=new TH1F("hDeltaPhi_j2gamma","hDeltaPhi_j2gamma",40,0,4);
	hDeltaPhi_j2gamma->SetXTitle("|#Delta#phi (#gamma,2^{nd}jet)|");
	hDeltaPhi_j2gamma->Sumw2();
	
	TH1F* hDeltaPhi_j1j2=new TH1F("hDeltaPhi_j1j2","hDeltaPhi_j1j2",40,0,4);
	hDeltaPhi_j1j2->SetXTitle("|#Delta#phi (1^{st} jet,2^{nd} jet)|");
	hDeltaPhi_j1j2->Sumw2();
	
	TH1F* hDeltaR_j1gamma=new TH1F("hDeltaR_j1gamma","hDeltaR_j1gamma",40,0,8);
	hDeltaR_j1gamma->SetXTitle("|#DeltaR (#gamma,1^{st} jet)|");
	hDeltaR_j1gamma->Sumw2();
	
	TH1F* hDeltaR_j2gamma=new TH1F("hDeltaR_j2gamma","hDeltaR_j2gamma",40,0,8);
	hDeltaR_j2gamma->SetXTitle("|#DeltaR (#gamma,2^{nd} jet)|");
	hDeltaR_j2gamma->Sumw2();
	
	TH1F* hDeltaR_j1j2=new TH1F("hDeltaR_j1j2","hDeltaR_j1j2",40,0,8);
	hDeltaR_j1j2->SetXTitle("|#DeltaR (1^{st} jet,2^{nd} jet)|");
	hDeltaR_j1j2->Sumw2();




//*****************************************************************************************************
//
//                                      reading the root file 
//
//*****************************************************************************************************

//retrieve the trees
	TTree* t_firstjet=(TTree*)f->Get("first_jet");
	TTree* t_firstjetraw=(TTree*)f->Get("first_jet_raw");
	TTree* t_firstjetgen=(TTree*)f->Get("first_jet_gen");
	TTree* t_secondjetgen=(TTree*)f->Get("second_jet_gen");
	TTree* t_secondjet=(TTree*)f->Get("second_jet");
	TTree* t_electron=(TTree*)f->Get("electrons");
	TTree* t_muon=(TTree*)f->Get("muons");
	TTree* t_met=(TTree*)f->Get("met");
	TTree* t_gamma=(TTree*)f->Get("photon");
	TTree* t_gammagen=(TTree*)f->Get("photon_gen");
	TTree* t_misc=(TTree*)f->Get("misc");
	TTree* t_rho=(TTree*)f->Get("rho");
	//TTree* t_gen_particles=(TTree*)f->Get("gen_particles");

//retrieve the variables
	//First jet
	float firstjetpt;
	t_firstjet->SetBranchAddress("pt",&firstjetpt);
	float firstjetpx;
	t_firstjet->SetBranchAddress("px",&firstjetpx);
	float firstjetpy;
	t_firstjet->SetBranchAddress("py",&firstjetpy);
	float firstjetphi;
	t_firstjet->SetBranchAddress("phi",&firstjetphi);
	float firstjeteta;
	t_firstjet->SetBranchAddress("eta",&firstjeteta);
	float firstjetbtag_csv;
	t_firstjet->SetBranchAddress("btag_csv",&firstjetbtag_csv);
	float firstjetqg_tag_mlp;
	t_firstjet->SetBranchAddress("qg_tag_mlp",&firstjetqg_tag_mlp);
	float firstjetqg_tag_likelihood;
	t_firstjet->SetBranchAddress("qg_tag_likelihood",&firstjetqg_tag_likelihood);
	
	//First jet raw
	float firstjetrawpt;
	t_firstjetraw->SetBranchAddress("pt",&firstjetrawpt);
	float firstjetrawphi;
	t_firstjetraw->SetBranchAddress("phi",&firstjetrawphi);
	float firstjetraweta;
	t_firstjetraw->SetBranchAddress("eta",&firstjetraweta);
	
	//First jet generated
	gROOT->ProcessLine("#include <vector>"); 
	float firstjetgenpt;
	t_firstjetgen->SetBranchAddress("pt",&firstjetgenpt);
	float firstjetgenpx;
	t_firstjetgen->SetBranchAddress("px",&firstjetgenpx);
	float firstjetgenpy;
	t_firstjetgen->SetBranchAddress("py",&firstjetgenpy);
	float firstjetgenphi;
	t_firstjetgen->SetBranchAddress("phi",&firstjetgenphi);
	float firstjetgeneta;
	t_firstjetgen->SetBranchAddress("eta",&firstjetgeneta);
	int firstjetgenpdgid;
  t_firstjetgen->SetBranchAddress("parton_pdg_id",&firstjetgenpdgid); // physics definition
   //t_firstjetgen->SetBranchAddress("parton_flavour",&firstjetgenpdgid); // algorithmic definition
// 	TClonesArray *aneutrino_4vect = 0;
// 	t_firstjetgen->SetBranchAddress("neutrinos",&aneutrino_4vect);

	
	//Second jet generated
	float secondjetgenpt;
	t_secondjetgen->SetBranchAddress("pt",&secondjetgenpt);
	float secondjetgenphi;
	t_secondjetgen->SetBranchAddress("phi",&secondjetgenphi);
	float secondjetgeneta;
	t_secondjetgen->SetBranchAddress("eta",&secondjetgeneta);
	
	//misc
	float miscevent_weight;
	t_misc->SetBranchAddress("event_weight",&miscevent_weight);

	//Second jet
	float secondjetpt;
	t_secondjet->SetBranchAddress("pt",&secondjetpt);
	float secondjetphi;
	t_secondjet->SetBranchAddress("phi",&secondjetphi);
	float secondjeteta;
	t_secondjet->SetBranchAddress("eta",&secondjeteta);
	
	//Gamma (reco)
	float gammapt;
	t_gamma->SetBranchAddress("pt",&gammapt);
	float gammaphi;
	t_gamma->SetBranchAddress("phi",&gammaphi);
	float gammaeta;
	t_gamma->SetBranchAddress("eta",&gammaeta);
	float gammapx;
	t_gamma->SetBranchAddress("px",&gammapx);
	float gammapy;
	t_gamma->SetBranchAddress("py",&gammapy);
	float gammapz;
	t_gamma->SetBranchAddress("pz",&gammapz);
	bool gamma_has_pixel_seed;
	t_gamma->SetBranchAddress("has_pixel_seed",&gamma_has_pixel_seed);
	
	//Gamma gen
	float gammagenpt;
	t_gammagen->SetBranchAddress("pt",&gammagenpt);
	float gammagenpx;
	t_gammagen->SetBranchAddress("px",&gammagenpx);
	float gammagenpy;
	t_gammagen->SetBranchAddress("py",&gammagenpy);

	
	//electron
	float electronpt[100];
	t_electron->SetBranchAddress("pt",&electronpt);
	float electronphi[100];
	t_electron->SetBranchAddress("phi",&electronphi);
	float electroneta[100];
	t_electron->SetBranchAddress("eta",&electroneta);
	int electronn;
	t_electron->SetBranchAddress("n",&electronn);
	float electronisolation[100];
	t_electron->SetBranchAddress("isolation",&electronisolation);
	
	//muon
	float muonpt[100];
	t_muon->SetBranchAddress("pt",&muonpt);
	float muonphi[100];
	t_muon->SetBranchAddress("phi",&muonphi);
	float muoneta[100];
	t_muon->SetBranchAddress("eta",&muoneta);
	int muonn;
	t_muon->SetBranchAddress("n",&muonn);
	float muonisolation[100];
	t_muon->SetBranchAddress("relative_isolation",&muonisolation);
	
	//met
	float metpt;
	t_met->SetBranchAddress("pt",&metpt);
	float metpx;
	t_met->SetBranchAddress("px",&metpx);
	float metpy;
	t_met->SetBranchAddress("py",&metpy);
	float metpz;
	t_met->SetBranchAddress("pz",&metpz);
	float metphi;
	t_met->SetBranchAddress("phi",&metphi);
	
	//rho
	double rho;
	t_rho->SetBranchAddress("rho",&rho);
	

	
	//Usefull variables
	float Rmpf;
	float Rtrue;
	float alpha;
	float metParal;
	float metPerpend;
	Double_t DeltaPhi_j1gamma;
	Double_t DeltaPhi_j2gamma;
	Double_t DeltaPhi_j1j2;	
	Double_t DeltaPhi_j1met;
	Double_t DeltaR_j1gamma;
	Double_t DeltaR_j2gamma;
	Double_t DeltaR_j1j2;	
	Double_t DeltaEta_j1gamma;
	Double_t DeltaEta_j2gamma;
	Double_t DeltaEta_j1j2;
	Double_t DeltaPhi_j1j2_gen;
	Double_t DeltaEta_j1j2_gen;
	Double_t DeltaR_j1j2_gen;

	int binPt;//bin en pt
	int bin2DTaggingPt;//gros bins en pt pour l etude 2D tagging
	int binZone;// 2D tagging zone bin
	int binFlavour;
	
	bool dropEvent=false;
	
	//count events in the tree
	unsigned int nEvents = (int)t_firstjet->GetEntries();
	
	string type;
	
	//loop over them
	for(unsigned int ievt=0; ievt<nEvents; ievt++) {
		t_firstjet->GetEntry(ievt);
		t_firstjetraw->GetEntry(ievt);
		t_secondjet->GetEntry(ievt);
		t_electron->GetEntry(ievt);
		t_muon->GetEntry(ievt);
		t_gamma->GetEntry(ievt);
		t_gammagen->GetEntry(ievt);
		t_met->GetEntry(ievt);
		t_misc->GetEntry(ievt);
		t_firstjetgen->GetEntry(ievt);
		t_secondjetgen->GetEntry(ievt); 
		t_rho->GetEntry(ievt);   
		//t_gen_particles->GetEntry(ievt);
	
//*********************************************************************************************************
		
		dropEvent=false;
		
		if(gamma_has_pixel_seed == true) continue;
		  	
		binPt = myPtBinning.getPtBin(gammapt);
		if(binPt == -1) continue;

		bin2DTaggingPt = my2DTaggingPtBinning.getPtBin(gammapt);		

		if(TMath::Abs(firstjetgenpdgid) == 21) {
			type = "gluon";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 4) {//c
			type = "quark";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 5) {//b
			type = "quark";
		}
		else if(TMath::Abs(firstjetgenpdgid) == 1 || TMath::Abs(firstjetgenpdgid) == 2 || TMath::Abs(firstjetgenpdgid) == 3) {
			type = "quark";
		}
		else {
			type = "gluon";
		}
		
		firstjetqg_tag_likelihood = qgsyst.Smear(firstjetpt, firstjeteta, rho, firstjetqg_tag_likelihood, type);

		binZone = getZoneBin(firstjetbtag_csv, firstjetqg_tag_likelihood);
		//if(binZone == -1) continue;	
		binFlavour = getFlavourBin(firstjetgenpdgid);
		//if(binFlavour == -1) continue;
		
		Rmpf = 1 + (gammapx*metpx + gammapy*metpy)/(pow(gammapt,2));		
		alpha = (secondjetpt)/(gammapt);
		Rtrue = (firstjetpt)/(firstjetgenpt);

		
//*****************************************************************************************************
//
//                                      deltaPhi calculation
//
//*****************************************************************************************************


//DeltaPhi between the 1st jet and the gamma calculation
    	DeltaPhi_j1gamma = TMath::Abs((gammaphi) - (firstjetphi));
    	if(DeltaPhi_j1gamma>TMath::Pi()){
    	  DeltaPhi_j1gamma = 2*TMath::Pi()-DeltaPhi_j1gamma;
    	}
    	
//DeltaPhi between the 2nd jet and the gamma calculation
    	DeltaPhi_j2gamma = TMath::Abs((gammaphi) - (secondjetphi));
    	if(DeltaPhi_j2gamma>TMath::Pi()){
    	  DeltaPhi_j2gamma = 2*TMath::Pi()-DeltaPhi_j2gamma;
    	}


//DeltaPhi between the first jet and the second jet calculation
    	DeltaPhi_j1j2 = TMath::Abs((secondjetphi) - (firstjetphi));
    	if(DeltaPhi_j1j2>TMath::Pi()){
      	DeltaPhi_j1j2 = 2*TMath::Pi()-DeltaPhi_j1j2;
    	}
    	
//DeltaPhi between the first jetgen and the second jetgen calculation
    	DeltaPhi_j1j2_gen = TMath::Abs((secondjetgenphi) - (firstjetgenphi));
    	if(DeltaPhi_j1j2_gen>TMath::Pi()){
    	  DeltaPhi_j1j2_gen = 2*TMath::Pi()-DeltaPhi_j1j2_gen;
    	}
    	
 //DeltaPhi between the first jet and the met
    	DeltaPhi_j1met = TMath::Abs((metphi) - (firstjetphi));
    	
    	
//*****************************************************************************************************
//
//                                      deltaEta calculation 
//
//*****************************************************************************************************

//DeltaEta between the first jet and the gamma calculation
    	DeltaEta_j1gamma = TMath::Abs((gammaeta) - (firstjeteta));

//DeltaEta between the second jet and the gamma calculation
    	DeltaEta_j2gamma = TMath::Abs((gammaeta) - (secondjeteta));
    	
//DeltaEta between the first jet and the second jet calculation
    	DeltaEta_j1j2 = TMath::Abs((secondjeteta) - (firstjeteta));
    	
 //DeltaEta between the first jetgen and the second jetgen calculation
    	DeltaEta_j1j2_gen = TMath::Abs((secondjetgeneta) - (firstjetgeneta));
    	    	
//*****************************************************************************************************
//
//                                      deltaR calculation 
//
//*****************************************************************************************************


//DeltaR between the first jet and the gamma calculation
    	DeltaR_j1gamma = sqrt ( pow(DeltaEta_j1gamma,2) + pow(DeltaPhi_j1gamma,2) );
    	
//DeltaR between the second jet and the gamma calculation
    	DeltaR_j2gamma = sqrt ( pow(DeltaEta_j2gamma,2) + pow(DeltaPhi_j2gamma,2) );

//DeltaR between the first jet and the second jet calculation
    	DeltaR_j1j2 = sqrt ( pow(DeltaEta_j1j2,2) + pow(DeltaPhi_j1j2,2) );
    	
//DeltaR between the first jetgen and the second jetgen calculation
    	DeltaR_j1j2_gen = sqrt ( pow(DeltaEta_j1j2_gen,2) + pow(DeltaPhi_j1j2_gen,2) );
    	
//*****************************************************************************************************
//
//                                      met parallele calculation 
//
//*****************************************************************************************************

		metParal = metpt * TMath::Cos(DeltaPhi_j1met);

//*****************************************************************************************************
//
//                                      met perpendicular calculation 
//
//*****************************************************************************************************

		metPerpend = metpt * TMath::Sin(DeltaPhi_j1met);

//*****************************************************************************************************
//
//                                      filling histogramms 
//
//*****************************************************************************************************

	
		//if(fabs(firstjetpt)>12. && DeltaPhi_j1gamma>2.8 && fabs(firstjeteta)<1.3 && (alpha<0.3 || secondjetpt<10)) {
		if(fabs(firstjetpt)>12. && DeltaPhi_j1gamma>2.8 && fabs(firstjeteta)<1.3) {
			if(muonn==0){
				if(electronn==0) {
					if(gammapt>200.) {
						hAlpha->Fill(alpha,miscevent_weight);
					}
					if((alpha<0.3 || secondjetpt<10)) {
						vGammapt_Flavour[binFlavour]->Fill(gammapt,miscevent_weight);	
						vGammapt_Flavour[nflavours-1]->Fill(gammapt,miscevent_weight);
		
		
						hGammaPt->Fill(gammapt,miscevent_weight);
						hFirstJetPt->Fill(firstjetpt,miscevent_weight);
						hMetPt->Fill(metpt,miscevent_weight);
						hParalleleMetPt->Fill(metParal,miscevent_weight);
						hPerpendicularMetPt->Fill(metPerpend,miscevent_weight);
						hSecondJetPt->Fill(secondjetpt,miscevent_weight);
						hDeltaPhi_j1gamma->Fill(DeltaPhi_j1gamma,miscevent_weight);
						hDeltaPhi_j2gamma->Fill(DeltaPhi_j2gamma,miscevent_weight);
						hDeltaPhi_j1j2->Fill(DeltaPhi_j1j2,miscevent_weight);
						hDeltaR_j1gamma->Fill(DeltaR_j1gamma,miscevent_weight);
						hDeltaR_j2gamma->Fill(DeltaR_j2gamma,miscevent_weight);
						hDeltaR_j1j2->Fill(DeltaR_j1j2,miscevent_weight);	

		
						if((firstjetbtag_csv>=0 && firstjetbtag_csv<=1) && (firstjetqg_tag_likelihood>=0 && firstjetqg_tag_likelihood<=1)) { 
		//protection contre les jets non matches
	
							vQGL_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
							vCSV_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
							vQGL_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
							vCSV_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
	
							if(binZone!=-1) {
                vGammaPt_ZoneFlavour[binZone][binFlavour]->Fill(gammapt,miscevent_weight);
                vGammaPt_ZoneFlavour[binZone][nflavours-1]->Fill(gammapt,miscevent_weight);

                if(gammapt>200.) {
                  vFirstJetPt_ZoneFlavour[binZone][binFlavour]->Fill(firstjetpt,miscevent_weight);
                  vFirstJetPt_ZoneFlavour[binZone][nflavours-1]->Fill(firstjetpt,miscevent_weight);
                }

								vRmpf_ZonePt[binZone][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZonePt[binZone][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);

								vRmpf_ZoneFlavourPt[binZone][binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZoneFlavourPt[binZone][binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
								vRmpf_ZoneFlavourPt[binZone][nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_ZoneFlavourPt[binZone][nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	
								vRmpf_in2DTaggingZone_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_in2DTaggingZone_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
								vRmpf_in2DTaggingZone_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
								vRtrue_in2DTaggingZone_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	
								vFlavourNumber[binZone][binFlavour][bin2DTaggingPt] = vFlavourNumber[binZone][binFlavour][bin2DTaggingPt] + miscevent_weight;
								vFlavourNumber[binZone][nflavours-1][bin2DTaggingPt] = vFlavourNumber[binZone][nflavours-1][bin2DTaggingPt] + miscevent_weight;
							}
							vRmpf_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
							vRtrue_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
							vRmpf_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rmpf,miscevent_weight);
							vRtrue_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(Rtrue,miscevent_weight);
	// 						vQGL_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
	// 						vCSV_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
	// 						vQGL_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetqg_tag_likelihood,miscevent_weight);
	// 						vCSV_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,miscevent_weight);
							v2DTaggingPlan_FlavourPt[binFlavour][bin2DTaggingPt]->Fill(firstjetbtag_csv,firstjetqg_tag_likelihood,miscevent_weight);
							v2DTaggingPlan_FlavourPt[nflavours-1][bin2DTaggingPt]->Fill(firstjetbtag_csv,firstjetqg_tag_likelihood,miscevent_weight);//nflavours-1 : corresponds to total
						}
					}	
				}
			}
		}
	}
    
	

	
//*****************************************************************************************************
//
//                                      2D Tagging Plans
//
//*****************************************************************************************************

//v2DTaggingPlan_FlavourPt[binFlavour][bin2DTaggingPt]
	std::string name2DTaggingPlan; 
	std::string name2DTaggingPlan_check; 
	std::string nameHisto;
	std::string nameHisto_check;
	TCanvas *cLikelihood_vs_csv = new TCanvas();
	cLikelihood_vs_csv->cd();
	string histoName;
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nflavours-1; i++) {//divide flavour distri by total distri
			cLikelihood_vs_csv->Clear();
			histoName = "images2DTagging/2DTaggingZones/beforeDividing/" + getFlavourBinName(i) + "_" + my2DTaggingPtBinning.getName(j) + ".pdf";
			//name2DTaggingPlan_check = ("images2DTagging/2DTaggingZones/beforeDividing/");

			v2DTaggingPlan_FlavourPt[i][j]->Draw("colz");
			v2DTaggingPlan_FlavourPt[i][j]->SetStats(0);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetLabelSize(0.045);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleOffset(1.15);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleSize(0.04);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetXaxis()->SetTitle("btag_csv");
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetLabelSize(0.045);	
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleOffset(1.2);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitleSize(0.04);	
			v2DTaggingPlan_FlavourPt[i][j]->GetYaxis()->SetTitle("QG_likelihood");
			v2DTaggingPlan_FlavourPt[i][j]->GetZaxis()->SetLabelSize(0.03);
			//nameHisto_check = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			//name2DTaggingPlan_check += nameHisto;
			//name2DTaggingPlan_check += ".pdf";
			//cLikelihood_vs_csv->SaveAs(name2DTaggingPlan_check.c_str());
			cLikelihood_vs_csv->SaveAs(histoName.c_str());

			v2DTaggingPlan_FlavourPt_divided[i][j] = (TH2F*)v2DTaggingPlan_FlavourPt[i][j]->Clone(v2DTaggingPlan_FlavourPt[i][j]->GetTitle());

			v2DTaggingPlan_FlavourPt_divided[i][j]->Divide(v2DTaggingPlan_FlavourPt[nflavours-1][j]);

			name2DTaggingPlan = ("images2DTagging/2DTaggingZones/");

			cLikelihood_vs_csv->Clear();
	
			v2DTaggingPlan_FlavourPt_divided[i][j]->Draw("colz");
			v2DTaggingPlan_FlavourPt_divided[i][j]->SetStats(0);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetLabelSize(0.045);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleOffset(1.15);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleSize(0.04);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetXaxis()->SetTitle("btag_csv");
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetRangeUser(0.,1.);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelOffset(0.005);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetLabelSize(0.045);	
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleOffset(1.2);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleFont(42);
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitleSize(0.04);	
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetYaxis()->SetTitle("QG_likelihood");
			v2DTaggingPlan_FlavourPt_divided[i][j]->GetZaxis()->SetLabelSize(0.03);
			nameHisto = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			name2DTaggingPlan += nameHisto;
			name2DTaggingPlan += ".pdf";
			cLikelihood_vs_csv->SaveAs(name2DTaggingPlan.c_str());
			nameHisto = "";
			name2DTaggingPlan = "";

      name2DTaggingPlan = ("images2DTagging/2DTaggingZones/");
      nameHisto = v2DTaggingPlan_FlavourPt[i][j]->GetTitle();
			name2DTaggingPlan += nameHisto;
			name2DTaggingPlan += ".C";
			cLikelihood_vs_csv->SaveAs(name2DTaggingPlan.c_str());
			nameHisto = "";
			name2DTaggingPlan = "";
// 			nameHisto_check = "";
// 			name2DTaggingPlan_check = "";
			histoName = "";
				}
	}





//*****************************************************************************************************
//
//                                      Jet flavour fraction
//
//*****************************************************************************************************

	float Nuds,Ng,Nc,Nb,NnoMatched,Ntot;
	std::string nameFraction;
	std::string nameHistoFraction;
	
	for(int j=0;j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			nameFraction = ("images2DTagging/FlavourFractions/");
			Nuds       = vFlavourNumber[i][0][j];
			Ng         = vFlavourNumber[i][1][j];
			Nc         = vFlavourNumber[i][2][j];
			Nb         = vFlavourNumber[i][3][j];
			NnoMatched = vFlavourNumber[i][4][j];
			Ntot       = vFlavourNumber[i][5][j];
			//Ntot       = vFlavourNumber[i][0][j]+vFlavourNumber[i][1][j]+vFlavourNumber[i][2][j]+vFlavourNumber[i][3][j];
			nameHistoFraction = vFractionHisto_Pt[j]->GetName();
			nameFraction += nameHistoFraction ;
			nameFraction += ".pdf";
			computeFlavourRatio(Nuds, Ng, Nc, Nb, NnoMatched, Ntot,vFractionHisto_Pt[j], nameFraction, my2DTaggingPtBinning, i, j);
			nameFraction = "";
			nameHistoFraction = "";
		}
	} 

	for(int j=0;j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			Nuds       = vFlavourNumber[i][0][j];
			Ng         = vFlavourNumber[i][1][j];
			Nc         = vFlavourNumber[i][2][j];
			Nb         = vFlavourNumber[i][3][j];
			NnoMatched = vFlavourNumber[i][4][j];
			Ntot       = vFlavourNumber[i][5][j];
			printLatexTableFlavourRatio(Nuds, Ng, Nc, Nb, NnoMatched, Ntot,vFractionHisto_Pt[j], nameFraction, my2DTaggingPtBinning, i, j);
		}
	}

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours ; j++) {
			for(int i=0; i<nzones; i++) {
				vFlavourFraction[i][j][k] = vFlavourNumber[i][j][k];
			}
		}
	}

	cout<<""<<endl<<endl;

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours ; j++) {
			for(int i=0; i<nzones; i++) {
				//Ntot       = vFlavourNumber[i][0][k]+vFlavourNumber[i][1][k]+vFlavourNumber[i][2][k]+vFlavourNumber[i][3][k];
				//vFlavourFraction[i][j][k] = vFlavourFraction[i][j][k]/Ntot;
				vFlavourFraction[i][j][k] = vFlavourFraction[i][j][k]/vFlavourFraction[i][nflavours-1][k];
				cout<<"vFlavourFraction["<<i<<"]["<<j<<"]["<<k<<"] : "<<vFlavourFraction[i][j][k]*100.<<" %"<<endl;
			}
		}
	}

//**********************************************************************************************************
//
//                                      filling the matrix with the flavour fractions per zone
//
//**********************************************************************************************************

	cout<<""<<endl<<endl;

	//filling the matrices
	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours-2; j++) {
			for(int i=0; i<nzones-2; i++) {
				v4x4MatrixPt[k](i,j) = vFlavourFraction[i][j][k];
				cout<<"v4x4MatrixPt["<<k<<"]("<<i<<","<<j<<") :  "<<v4x4MatrixPt[k](i,j)*100.<<" %"<<endl;
			}
		}
	}

	cout<<""<<endl<<endl;

	for(int k=0; k<n2DTaggingPtBins; k++) {
		for(int j=0; j<nflavours-2; j++) {
			for(int i=0; i<nzones; i++) {
				v6x4MatrixPt[k](i,j) = vFlavourFraction[i][j][k];
				cout<<"v6x4MatrixPt["<<k<<"]("<<i<<","<<j<<") : "<<v6x4MatrixPt[k](i,j)*100.<<" %"<<endl;
			}
		}
	}

	//write into the output matrix rootfile
	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_G.root", "recreate");
// 	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_TOT.root", "recreate");
// 	TFile *out_matrix = new TFile("output_rootfile/outputMatrix2DTagging_MC_QCD.root", "recreate");

	out_matrix->cd();
	TDirectory *matrixDir = out_matrix->mkdir("matrix","matrix");
	matrixDir->cd();
	for(int k=0; k<n2DTaggingPtBins; k++) {
		string matrix6x4Name;
		string matrix4x4Name;
		matrix6x4Name = "matrix6x4_" + my2DTaggingPtBinning.getName(k);
		matrix4x4Name = "matrix4x4_" + my2DTaggingPtBinning.getName(k);
		v6x4MatrixPt[k].Write(matrix6x4Name.c_str());
		v4x4MatrixPt[k].Write(matrix4x4Name.c_str());
	}
	out_matrix->Close();

//*****************************************************************************************************
//
//                                      Output file
//
//*****************************************************************************************************

  //TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_G_forMikko_L5Corr_physics.root", "recreate");
  //TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_QCD_forMikko_L5Corr_physics.root", "recreate");
  TFile *out_mikko = new TFile("output_rootfile/output2DTagging_MC_TOT_forMikko_L5Corr_physics.root", "recreate");

	out_mikko->cd();	

  TDirectory *firstJetPtPtDir = out_mikko->mkdir("firstJetPtPerZonePerFlavour","firstJetPtPerZonePerFlavour");
  firstJetPtPtDir->cd();
  for(int k=0; k<nflavours; k++) {
    for(int l=0; l<nzones; l++) {
		  vFirstJetPt_ZoneFlavour[l][k]->Write();
		}
	}

 /* TDirectory *response_Zone_FlavourDir = out_mikko->mkdir("response_perZone_perFlavour","response_perZone_perFlavour");*/
	//TDirectory *Rmpf_Zone_FavourDir = response_Zone_FlavourDir->mkdir("Rmpf","Rmpf");
	//Rmpf_Zone_FavourDir->cd();
		//for(int k=0; k<nflavours; k++) {
			//for(int l=0; l<nzones; l++) {
				//vRmpf_ZoneFlavourPt[l][k][n2DTaggingPtBins-1]->Write();
			//}
		//}
	//TDirectory *Rtrue_Zone_FavourDir = response_Zone_FlavourDir->mkdir("Rtrue","Rtrue");
	//Rtrue_Zone_FavourDir->cd();
		//for(int k=0; k<nflavours; k++) {
			//for(int l=0; l<nzones; l++) {
				//vRtrue_ZoneFlavourPt[l][k][n2DTaggingPtBins-1]->Write();
			//}
		//}

//TDirectory *response_Zone_PtDir_mikko = out_mikko->mkdir("response_perZone","response_perZone");
	//TDirectory *Rmpf_Zone_PtDir_mikko = response_Zone_PtDir_mikko->mkdir("Rmpf","Rmpf");
	//Rmpf_Zone_PtDir_mikko->cd();
      //for(int i=0; i<nzones; i++) {
			//vRmpf_ZonePt[i][n2DTaggingPtBins-1]->Write();
		/*}*/
  out_mikko->Close();

	//write into the output file
  //TFile *out = new TFile("output_rootfile/output2DTagging_MC_G_physics.root", "recreate");
   TFile *out = new TFile("output_rootfile/output2DTagging_MC_TOT_physics.root", "recreate");
   //TFile *out = new TFile("output_rootfile/output2DTagging_MC_QCD_physics.root", "recreate");

	out->cd();	
	TDirectory *response_Zone_PtDir = out->mkdir("response_Zone_Pt","response_Zone_Pt");
	TDirectory *Rmpf_Zone_PtDir = response_Zone_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Zone_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			vRmpf_ZonePt[i][j]->Write();
		}
	}
	TDirectory *Rtrue_Zone_PtDir = response_Zone_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Zone_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nzones; i++) {
			vRtrue_ZonePt[i][j]->Write();
		}
	}


	TDirectory *response_Flavour_PtDir = out->mkdir("response_Flavour_Pt","response_Flavour_Pt");
	TDirectory *Rmpf_Flavour_PtDir = response_Flavour_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vRmpf_FlavourPt[k][j]->Write();
			vRmpf_in2DTaggingZone_FlavourPt[k][j]->Write();
		}
	}
	TDirectory *Rtrue_Flavour_PtDir = response_Flavour_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vRtrue_FlavourPt[k][j]->Write();
			vRtrue_in2DTaggingZone_FlavourPt[k][j]->Write();
		}
	}

	TDirectory *response_Zone_Flavour_PtDir = out->mkdir("response_Zone_Flavour_Pt","response_Zone_Flavour_Pt");
	TDirectory *Rmpf_Zone_Flavour_PtDir = response_Zone_Flavour_PtDir->mkdir("Rmpf","Rmpf");
	Rmpf_Zone_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			for(int l=0; l<nzones; l++) {
				vRmpf_ZoneFlavourPt[l][k][j]->Write();
			}
		}
	}
	TDirectory *Rtrue_Zone_Flavour_PtDir = response_Zone_Flavour_PtDir->mkdir("Rtrue","Rtrue");
	Rtrue_Zone_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			for(int l=0; l<nzones; l++) {
				vRtrue_ZoneFlavourPt[l][k][j]->Write();
			}
		}
	}

	TDirectory *tagger_Flavour_PtDir = out->mkdir("tagger_Flavour_Pt","tagger_Flavour_Pt");
	TDirectory *CSV_Flavour_PtDir = tagger_Flavour_PtDir->mkdir("CSV","CSV");
	CSV_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vCSV_FlavourPt[k][j]->Write();
		}
	}
	TDirectory *QGL_Flavour_PtDir = tagger_Flavour_PtDir->mkdir("QGL","QGL");
	QGL_Flavour_PtDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int k=0; k<nflavours; k++) {
			vQGL_FlavourPt[k][j]->Write();
		}
	}
	
	TDirectory *gammapt_FlavourDir = out->mkdir("gammapt_Flavour","gammapt_Flavour");
	gammapt_FlavourDir->cd();
	for(int k=0; k<nflavours; k++) {
		vGammapt_Flavour[k]->Write();
	}
	
	
	TDirectory *variablesDir = out->mkdir("variables","variables");
	variablesDir->cd();
	hGammaPt->Write();
	hFirstJetPt->Write();
	hSecondJetPt->Write();
	hMetPt->Write();
	hParalleleMetPt->Write();
	hPerpendicularMetPt->Write();
	hAlpha->Write();
	hDeltaPhi_j1gamma->Write();
	hDeltaPhi_j2gamma->Write();
	hDeltaPhi_j1j2->Write();
	hDeltaR_j1gamma->Write();
	hDeltaR_j2gamma->Write();
	hDeltaR_j1j2->Write();
  TDirectory *gammaPtDir = variablesDir->mkdir("gammaPtPerZonePerFlavour","gammaPtPerZonePerFlavour");
  gammaPtDir->cd();
  for(int k=0; k<nflavours; k++) {
    for(int l=0; l<nzones; l++) {
		  vGammaPt_ZoneFlavour[l][k]->Write();
		}
	}



	TDirectory *plan2DTaggingDir = out->mkdir("plan2DTagging","plan2DTagging");
	plan2DTaggingDir->cd();
	for(int j=0; j<n2DTaggingPtBins; j++) {
		for(int i=0; i<nflavours; i++) {//divide flavour distri by total distri
			v2DTaggingPlan_FlavourPt[i][j]->Write();
			v2DTaggingPlan_FlavourPt_divided[i][j]->Write();	
		}
	}
	
	out->Close();
	
	return 0;
}