Пример #1
0
void calccorr(int i=1,string t="ptfiner"){
float const PI = acos(-1.0);
const int ncent = 4;
const int npt = 10;
if(i==0) TString dire="north";
else TString dire="south";
TFile *f=TFile::Open("../../../work/200GeV/output_cntbbc.root");
TH1F* kforebbcw[ncent][npt];
TH1F* hforebbcw[ncent][npt];
TH1F* kbackbbcw2[ncent][npt];
TH1F* kforebbcw_In;
TH1F* hforebbcw_In;
TH1F* kbackbbcw2_In;
double ptbin[npt+1] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double centbin[ncent+1] = {0,0.05,0.2,0.6,1.0};
//double centbin[ncent+1] = {0,1,2};
TString type = t.c_str();
if(type=="ptIn25_4"){
double selptbin[] = {2.5,4.0};
double selcentbin[ncent+1] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptIn"){
double selptbin[] = {1.0,3.0};
double selcentbin[ncent+1] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptcoarser"){
double selptbin[] = {0.2,1.0,2.0,3.0,5.0};
double selcentbin[ncent+1] = {0,0.01,0.05,0.1,0.2,0.3,0.4,0.6,1.0};
}
else if(type=="ptfiner"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {0,0.05,0.2,0.6,1.0};
//double selcentbin[ncent+1] = {0,1,2};
}
else if(type=="centIn"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {0,1.0};
}
else if(type=="ptccentc"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selcentbin[] = {0,0.05};
}
else{exit(0);};

/*double ptmin = 1.0; double ptmax = 3.0;//has to be boundary
for(int ipt=0; ipt<npt; ipt++){
if(ptmin >= ptbin[ipt] && ptmin < ptbin[ipt+1]){int xptmin = ipt; continue;}
if(ptmax >= ptbin[ipt] && ptmax < ptbin[ipt+1]){int xptmax = ipt; continue;}
}*/
  ofstream fout(Form("c1_c2_central_%s_%s.dat",type.Data(),dire.Data()));
for(int icent=0; icent<ncent; icent++){
for(int ipt=0; ipt<npt; ipt++){
kforebbcw[icent][ipt] = (TH1F*)f->Get(Form("kfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kforenorthbbcw_%d_%d",icent,ipt));
//kforebbcw[icent][ipt]->Add(htemp,-1);
hforebbcw[icent][ipt] = (TH1F*)f->Get(Form("hfore%sbbcw_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("hforenorthbbcw_%d_%d",icent,ipt));
//hforebbcw[icent][ipt]->Add(htemp,-1);
kbackbbcw2[icent][ipt] = (TH1F*)f->Get(Form("kback%sbbcw2_%d_%d",dire.Data(),icent,ipt));
//htemp = (TH1F*)f->Get(Form("kbacknorthbbcw2_%d_%d",icent,ipt));
//kbackbbcw2[icent][ipt]->Add(htemp,-1);
}
}
int ncent_a = sizeof(selcentbin)/sizeof(double)-1;
int npt_a = sizeof(selptbin)/sizeof(double)-1;
for(int icent_a=0;icent_a<ncent+1;icent_a++){
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a] == centbin[icent_b]) break;
int xcentmin = icent_b;
for(int icent_b=0; icent_b<ncent+1; icent_b++)
if(selcentbin[icent_a+1] == centbin[icent_b]) break;
int xcentmax = icent_b;
if((xcentmin == ncent+1) || (xcentmax == ncent+1)) exit(0);
for(int ipt_a=0;ipt_a<npt_a;ipt_a++){
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a] == ptbin[ipt_b]) break;
int xptmin = ipt_b;
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a+1] == ptbin[ipt_b]) break;
int xptmax = ipt_b;
if((xptmin == npt+1) || (xptmax == npt+1)) exit(0);
cout<<xcentmin<<"\t"<<xcentmax<<"\t"<<endl;
cout<<xptmin<<"\t"<<xptmax<<"\t"<<endl;
kforebbcw_In = (TH1F*)kforebbcw[xcentmin][xptmin]->Clone();
hforebbcw_In = (TH1F*)hforebbcw[xcentmin][xptmin]->Clone();
kbackbbcw2_In = (TH1F*)kbackbbcw2[xcentmin][xptmin]->Clone();
kforebbcw_In->Reset();
hforebbcw_In->Reset();
kbackbbcw2_In->Reset();
for(int icent=xcentmin; icent<xcentmax; icent++){
for(int ipt=xptmin; ipt<xptmax; ipt++){
kforebbcw_In->Add(kforebbcw[icent][ipt]);
hforebbcw_In->Add(hforebbcw[icent][ipt]);
kbackbbcw2_In->Add(kbackbbcw2[icent][ipt]);
}
}
kforebbcw_In->Rebin(2);
hforebbcw_In->Rebin(2);
kbackbbcw2_In->Rebin(2);


TH1F* hpp;
TH1F* hbackpp;
  hpp = (TH1F*)kforebbcw_In->Clone();
  hbackpp = (TH1F*)kbackbbcw2_In->Clone();
  float nbackpp = hbackpp->Integral()/2.0/PI;
  float nforepp = hpp->Integral()/2.0/PI;
  //float ntrig0 = ptforedis_0->Integral(11,30);
   for(int i=0; i<20; i++){
     float pp_cont = 1.0*hpp->GetBinContent(i+1);
     //float pp0_err = 1.0*hpp->GetBinError(i+1);
     float weight2 = sqrt(1.0*hforebbcw_In->GetBinContent(i+1));

     float backpp_cont = 1.0*hbackpp->GetBinContent(i+1);
    
     float con = pp_cont/backpp_cont*nbackpp/nforepp;
     float err = weight2/backpp_cont*nbackpp/nforepp;

     hpp->SetBinContent(i+1, con);
     hpp->SetBinError(i+1, err);

   }
  TF1 *fun0 = new TF1("fun0","[0]*(1+2*[1]*cos(x)+2*[2]*cos(2*x)+2*[3]*cos(3*x)+2*[4]*cos(4*x))", -0.5*PI, 1.5*PI);

  fun0->SetLineColor(1);
  hpp->Fit("fun0","NORQ");

  TF1 *fun1 = new TF1("fun1","[0]*(1+2*[1]*cos(x))",   -0.5*PI, 1.5*PI);
  TF1 *fun2 = new TF1("fun2","[0]*(1+2*[1]*cos(2*x))", -0.5*PI, 1.5*PI);
  TF1 *fun3 = new TF1("fun3","[0]*(1+2*[1]*cos(3*x))", -0.5*PI, 1.5*PI);
  TF1 *fun4 = new TF1("fun4","[0]*(1+2*[1]*cos(4*x))", -0.5*PI, 1.5*PI);

const double ptmean[npt] = {0.360943, 0.691833, 1.1911, 1.69654, 2.20117, 2.70571, 3.2097, 3.71372, 4.21814, 4.72014};
  fout<<fun0->GetParameter(1)<<" "<<fun0->GetParError(1)<<" "
      <<fun0->GetParameter(2)<<" "<<fun0->GetParError(2)<<" "//<<0.05*fun0->GetParameter(2)<<" "<<endl;
      <<fun0->GetParameter(3)<<" "<<fun0->GetParError(3)<<endl;
}
}
  fout.close();

/*  
  cout<<"*************** v2 ***********"<<endl;
  float v2_0 = funvn0->GetParameter(1)/(zym_pp0 + funvn0->GetParameter(0));
  float v2_1 = funvn1->GetParameter(1)/(zym_pp1 + funvn1->GetParameter(0));
  float v2_2 = funvn2->GetParameter(1)/(zym_pp2 + funvn2->GetParameter(0));
  float v2_3 = funvn3->GetParameter(1)/(zym_pp3 + funvn3->GetParameter(0));
  

  cout<<v2_0<<" "<<v2_1<<" "<<v2_2<<" "<<v2_3<<endl;
 
  
  cout<<funvn0->GetParameter(0)*funvn0->GetParameter(1)<<" "
      <<funvn1->GetParameter(0)*funvn1->GetParameter(1)<<" "
      <<funvn2->GetParameter(0)*funvn2->GetParameter(1)<<" "
      <<funvn3->GetParameter(0)*funvn3->GetParameter(1)<<endl;
  

  cout<<"*************** v2 ***********"<<endl;
  cout<<funvn0->GetParameter(2)<<" "<<funvn1->GetParameter(2)<<" "<<funvn2->GetParameter(2)<<" "<<funvn3->GetParameter(2)<<endl;

  cout<<"*************** v3 ***********"<<endl;
  cout<<funvn0->GetParameter(3)<<" "<<funvn1->GetParameter(3)<<" "<<funvn2->GetParameter(3)<<" "<<funvn3->GetParameter(3)<<endl;
*/
}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001); 
  TH1F* EWK0   = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK0 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(100,182,232), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#else
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#endif
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK0 );
  ref->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK2 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK0 ->Integral();
  unscaled[1]+= EWK1 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK2 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK0 ->Integral()
					       +EWK1 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK2 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK0 ->Add(Fakes);
  EWK1 ->Add(EWK0 );
#ifdef EXTRA_SAMPLES
  EWK2 ->Add(EWK1 );
  EWK  ->Add(EWK2 );
#else
  EWK  ->Add(EWK1 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{max} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Z#rightarrow ee"                , "F" );
  leg->AddEntry(EWK1 , "W+jets"                         , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
    EWK  ->Write("Zee"     );
    EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Пример #3
0
void fitBjetJES(int ppPbPb=1, int cbinlo=12, int cbinhi=40){

  if(!ppPbPb){
    cbinlo=0;
    cbinhi=40;
  }

  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);

  TFile *fL;
  
  if(!ppPbPb)fL=new TFile("histos/ppMC_hiReco_jetTrig_highPurity_JEC.root");
  else     fL=new TFile("histos/PbPbQCDMC_pt30by3_ipHICalibCentWeight.root");

  // these are dummy files for pp
  TFile *fB=new TFile("histos/PbPbBMC_pt30by3_ipHICalibCentWeight.root");
  TFile *fC=new TFile("histos/PbPbCMC_pt30by3_ipHICalibCentWeight.root");


  TNtuple *tL = (TNtuple*) fL->Get("nt");
  TNtuple *tB = (TNtuple*) fB->Get("nt");
  TNtuple *tC = (TNtuple*) fC->Get("nt");
  
  float jtptL, refptL, jtetaL, weightL, refparton_flavorForBL, binL;

  tL->SetBranchAddress("jtpt",&jtptL);
  tL->SetBranchAddress("jteta",&jtetaL);
  tL->SetBranchAddress("refpt",&refptL);
  tL->SetBranchAddress("weight",&weightL);
  if(ppPbPb)tL->SetBranchAddress("bin",&binL);
  tL->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBL);

  float jtptB, refptB, jtetaB, weightB, refparton_flavorForBB, binB;

  tB->SetBranchAddress("jtpt",&jtptB);
  tB->SetBranchAddress("jteta",&jtetaB);
  tB->SetBranchAddress("refpt",&refptB);
  tB->SetBranchAddress("weight",&weightB);
  if(ppPbPb)tB->SetBranchAddress("bin",&binB);
  tB->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBB);

  float jtptC, refptC, jtetaC, weightC, refparton_flavorForBC, binC;

  tC->SetBranchAddress("jtpt",&jtptC);
  tC->SetBranchAddress("jteta",&jtetaC);
  tC->SetBranchAddress("refpt",&refptC);
  tC->SetBranchAddress("weight",&weightC);
  if(ppPbPb)tC->SetBranchAddress("bin",&binC);
  tC->SetBranchAddress("refparton_flavorForB",&refparton_flavorForBC);

  TProfile  *hL = new TProfile("hL","hL",250,50,300,0,10);
  TProfile  *hB = new TProfile("hB","hB",250,50,300,0,10);
  TProfile  *hC = new TProfile("hC","hC",250,50,300,0,10);
  hL->Sumw2(),hB->Sumw2(),hC->Sumw2();


  for(int i=0;i<tL->GetEntries();i++){
    tL->GetEntry(i);
    if(!ppPbPb) binL=39;

    if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi)
      hL->Fill(refptL,jtptL/refptL,weightL); 


    if(!ppPbPb){
      if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi && abs(refparton_flavorForBL)==5)
	hB->Fill(refptL,jtptL/refptL,weightL);
      
      if(fabs(jtetaL)<2 && binL>=cbinlo && binL<cbinhi && abs(refparton_flavorForBL)==4)
	hC->Fill(refptL,jtptL/refptL,weightL);      
    }
  }

  if(ppPbPb){
    for(int i=0;i<tB->GetEntries();i++){
      tB->GetEntry(i);
      if(fabs(jtetaB)<2 && binB>=cbinlo && binB<cbinhi && abs(refparton_flavorForBB)==5)
	hB->Fill(refptB,jtptB/refptB,weightB);
    }
    for(int i=0;i<tC->GetEntries();i++){
      tC->GetEntry(i);
      if(fabs(jtetaC)<2 && binC>=cbinlo && binC<cbinhi && abs(refparton_flavorForBC)==4)
	hC->Fill(refptC,jtptC/refptC,weightC);
    }
  }

  
 
  hL->SetMinimum(0.);
  
  hL->SetLineColor(kBlue);
  hB->SetLineColor(kRed);
  hC->SetLineColor(kGreen);

  hL->SetMarkerColor(kBlue);
  hB->SetMarkerColor(kRed);
  hC->SetMarkerColor(kGreen);
  
  //hL->SetMarkerStyle(4);
  //hB->SetMarkerStyle(4);
  //hC->SetMarkerStyle(4);
  
  hL->SetXTitle("genJet p_{T} (GeV/c)");
  hL->SetYTitle("<reco p_{T} / gen p_{T} >");

  hL->GetXaxis()->SetRangeUser(50.,199.999);
  hL->GetYaxis()->SetRangeUser(0.5,1.05);
  
  TCanvas *c1=new TCanvas("c1","c1",800,600);
  c1->SetGridx(1);
  c1->SetGridy(1);

  hL->Draw("e1");
  hB->Draw("e1,same");
  hC->Draw("e1,same");

  TLegend *leg=new TLegend(0.4,0.15,0.9,0.45);
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  if(ppPbPb&&cbinlo==0&&cbinhi==40)leg->SetHeader("Pythia+Hydjet, 0-100%");
  leg->AddEntry(hL,"Inclusive jets","pl");
  leg->AddEntry(hC,"c-jets","pl");
  leg->AddEntry(hB,"b-jets","pl");
  leg->Draw();

  TCanvas *c2=new TCanvas("c2","c2",1);
  /*
  TH1F *hL2 = (TH1F*)hL->Clone("hL2");
  TH1F *hB2 = (TH1F*)hB->Clone("hB2");
  hL2->Add(hB2,-1);
  hL2->Draw();
  */

  TH1F  *hcorr = new TH1F("hcorr","hcorr",250,50,300);
  hcorr->Sumw2();

  for(int i=0;i<hL->GetNbinsX();i++){
    cout<<" b resp "<<hB->GetBinContent(i+1)<<endl;
    cout<<" l resp "<<hL->GetBinContent(i+1)<<endl;
    cout<<" l offset "<<1.-hL->GetBinContent(i+1)<<endl;
    cout<<" corrected b resp "<<hB->GetBinContent(i+1)+1.-hL->GetBinContent(i+1)<<endl;
    float jesOffset = 1.-hL->GetBinContent(i+1);

    hcorr->SetBinContent(i+1,hB->GetBinContent(i+1)+jesOffset);

    hcorr->SetBinError(i+1,sqrt(hB->GetBinError(i+1)*hB->GetBinError(i+1)+hL->GetBinError(i+1)*hL->GetBinError(i+1)));


  }

  hcorr->SetMinimum(0.5);
  hcorr->SetMaximum(1.1);
      
  hcorr->SetLineColor(kRed);
  hcorr->SetMarkerColor(kRed);
  hcorr->SetMarkerStyle(4);
  hcorr->Draw();

  TF1 *fCorr = new TF1("fCorr","[0]+[1]*log(x)+[2]*log(x)*log(x)",50,300);
  fCorr->SetLineWidth(1);
  fCorr->SetLineColor(kBlue);
  hcorr->Fit(fCorr);

  TFile *fout;
  if(ppPbPb) fout =new TFile(Form("bJEShistos/bJetScale_PbPb_Cent_fineBin_%d_%d.root",cbinlo,cbinhi),"recreate");
  else fout =new TFile("bJEShistos/bJetScale_PP_fineBin.root","recreate");
  hcorr->Write();
  fCorr->Write();
  fout->Close();

}
Пример #4
0
void alicePlots(){
    
    TFile* alice = new TFile("~/Downloads/HEPData-ins1288320-v1-root.root");
    alice->cd("Table 16");
    TGraph* aliceData = Graph1D_y1;
    TH1F* hist = Hist1D_y1;
    TH1F* stat = Hist1D_y1_e1;
    TH1F* syst = Hist1D_y1_e2;
    TGraphAsymmErrors* graph2 = (TGraphAsymmErrors*)aliceData->Clone("graph2");

    Int_t numPts = aliceData->GetN();
    Double_t x, y;
    for(int i = 0; i<numPts; i++){
        aliceData->GetPoint(i, x, y);
        aliceData->SetPoint(i, x, (y - 0.89581));
        graph2->SetPoint(i, x, (y- 0.89581));
        hist->SetBinContent(i+1, hist->GetBinContent(i+1) - 0.89581);
        hist->SetBinError(i+1, stat->GetBinContent(i+1));
        graph2->SetPointEXhigh(i, 0.1);
        graph2->SetPointEXlow(i, 0.1);
    }

    graph2->SetLineColor(kBlue-10);
    graph2->SetLineWidth(2);
    graph2->SetMarkerColor(kBlue-10);
    graph2->SetFillColor(kBlue-10);
    hist->SetLineColor(kBlue-2);
    hist->SetLineWidth(2);

    aliceData->SetTitle("");
    aliceData->GetYaxis()->SetTitle("Mass - Vacuum Mass (GeV/c^{2})");
    aliceData->GetYaxis()->SetTitleSize(0.06);
    aliceData->GetYaxis()->SetLabelSize(0.04);
    aliceData->GetYaxis()->SetTitleOffset(1.65);
    aliceData->GetYaxis()->SetTitleFont(42);
    aliceData->GetYaxis()->SetLabelFont(42);
    aliceData->GetXaxis()->SetTitle("p_{T} (GeV/c)");
    aliceData->GetXaxis()->SetTitleSize(0.06);
    aliceData->GetXaxis()->SetLabelSize(0.05);
    aliceData->GetXaxis()->SetTitleFont(42);
    aliceData->GetXaxis()->SetLabelFont(42);
    aliceData->SetMarkerStyle(29);
    aliceData->SetMarkerSize(2.5);
    aliceData->SetMarkerColor(kBlue-2);
    aliceData->SetLineColor(kBlue-2);

    aliceData->GetYaxis()->SetRangeUser(-0.02, 0.015);
    aliceData->GetXaxis()->SetRangeUser(0, 5);

    TFile* phsd = new TFile("~/utaustin/resonancefits/finalplotting/20170721_KKbarAdded2_fixedwidth42_recon_pf100_scaled_error05.root");
    TH1D* mass = phsd->Get("kstar0mass");
    mass->SetName("mass");
    mass->SetMarkerStyle(26);
    mass->SetMarkerSize(2.5);
    mass->SetMarkerColor(2);
    mass->SetLineColor(2);

    TF1* line = new TF1("line", "[0]", 0.0, 5.0);
    line->SetParameter(0, 0.0);
    line->SetLineColor(1);
    line->SetLineStyle(7);
    line->SetLineWidth(3);

    for(int j = 0; j<mass->GetNbinsX(); j++){
        mass->SetBinContent(j+1, (mass->GetBinContent(j+1) - 0.892));
    }


    TFile* phsd2 = new TFile("~/utaustin/resonancefits/finalplotting/20170616_KKbarAdded2_fixedwidth_recon_pf100_scaled_error05.root");
    TH1D* mass2 = phsd2->Get("kstar0mass");
    mass2->SetName("mass2");
    mass2->SetMarkerStyle(22);
    mass2->SetMarkerSize(2.5);
    mass2->SetMarkerColor(2);
    mass2->SetLineColor(2);
    for(int j = 0; j<mass2->GetNbinsX(); j++){
        mass2->SetBinContent(j+1, (mass2->GetBinContent(j+1) - 0.892));
    }



    TExec *exec1 = new TExec("exec1", "gStyle->SetErrorX(0.1)");
    TExec *exec2 = new TExec("exec2", "gStyle->SetErrorX(0.5)");
    
    TCanvas *c = new TCanvas ("c", "c", 50, 50, 650, 600);
    c->cd()->SetMargin(0.1997, 0.0369, 0.1396, 0.0681);
    aliceData->Draw("APX");
    //exec1->Draw();
    graph2->Draw("SAME P2");
    //exec2->Draw();
    hist->Draw("SAME E1");
    line->Draw("SAME");
    mass2->Draw("SAME P E1");
    mass->Draw("SAME P E1");
    aliceData->Draw("SAME PX");
    

    TLegend* legend = new TLegend(0.5836, 0.1815, 0.9489, 0.3438);
    legend->SetMargin(0.2);
    legend->SetTextSizePixels(20);
    legend->AddEntry(aliceData, "ALICE data, 0-20%", "p");
    legend->AddEntry(mass2, "Fit IV to PHSD: w in-med", "p");
    legend->AddEntry(mass, "Fit IV to PHSD: w/o in-med", "p");
    legend->Draw("SAME"); 
  
    TPaveText* text = new TPaveText(0.2554, 0.7243, 0.6006, 0.9162, "NDC");
    text->AddText("(K*^{0} + #bar{K}*^{0})");
    text->AddText("Pb-Pb #sqrt{s_{NN}} = 2.76 TeV");
    text->GetLine(0)->SetTextSizePixels(36);
    text->GetLine(1)->SetTextSizePixels(24);
    text->SetTextFont(42);
    text->SetBorderSize(0);
    text->SetFillStyle(0);
    text->Draw();
}
void ppEffJpsi()   
{
  double minRap = 0.0;
  double maxRap = 2.4;
  double minPt = 6.5;
  double maxPt = 30.0;

  // if you want to measure low pT, you can set up minRap = 1.6 and minPt = 3.0, maxPt = 6.5;

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

  //==============================================Define Acc Eff Stuff here===========================================
  // Pt bin sizes
  // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

  TFile *outfile;
  char tmp_output[512];
  sprintf(tmp_output,"ppPrJpsi_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ_tnpWgt.root", minPt, maxPt, minRap, maxRap);
  outfile =new TFile(tmp_output, "Recreate");

  for(int iSpec = 0; iSpec < 2; iSpec++){

    const int nPtBins = 7;
    const int nRapBins = 6; // 6
    const int ndPhiBins = 4;
    double pt_bound[nPtBins+1] = {6.5, 7.5, 8.5, 9.5, 11.0, 13.0, 16.0, 30.0};
    double xpt_bound[nPtBins] = {0.0};
    //double rap_bound[nRapBins+1] = {0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4};
    double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
    double xrap_bound[nRapBins] = {0.0};
    double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/8, TMath::Pi()/4, 3*TMath::Pi()/8, TMath::Pi()/2};
    double xdphi_bound[ndPhiBins] = {0.0};

    const char *cSp[2] = {"Pts","Raps"};
    char OutTextFile[100];
    sprintf(OutTextFile,"ppPromp_eff_%s_pT_%0.1f_%0.1f_y_%0.1f_%0.1f_HighQ.tex", cSp[iSpec], minPt, maxPt, minRap, maxRap);
    ofstream dataFile(OutTextFile);
    //ofstream dataFile(Form(OutTextFile));

    cout<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;
    dataFile<< "%%%% Getting Efficiency starts : %s !!!!! %%%%%" << endl;

    // x, y, z - axis 
    dataFile<<""<<endl;
    dataFile<<"xaxis of pT"<<endl;
    for(int i = 0; i < nPtBins; i++){
      xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
      cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
    }
    dataFile<<""<<endl;
    dataFile<<"xaxis of rap"<<endl;
    for(int i = 0; i < nRapBins; i++){
      xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
      cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
    }
    dataFile<<""<<endl;
    dataFile<<"xaxis of dphi"<<endl;
    for(int i = 0; i < ndPhiBins; i++){
      xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
      cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
    }

    int nBins_tmp;
    if(iSpec == 0) { nBins_tmp = nPtBins; }
    if(iSpec == 1) { nBins_tmp = nRapBins; }
    const int nBins = nBins_tmp;

    TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
    TH1F *hGenDiMuon[nBins];
    TH1F *hRecoDiMuon[nBins];
    double genNo[nBins];
    double genErr[nBins];
    double recoNo[nBins];
    double recoErr[nBins];
    double eff[nBins];
    double effErr[nBins];
    for(int i = 0; i < nBins; i++){
      hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
      hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
      hGenDiMuon[i]->Sumw2();
      hRecoDiMuon[i]->Sumw2();
    }

    char fileName[10][512];

    // loop for pT
    cout<<"==================Prompt PrJpsi================================================"<<endl;

    sprintf(fileName[0],"/Users/dhmoon/Documents/Analysis/HiMC/EffStudy/gRpAngRootFiles_538_pp/HiDiMuonAna_538_pp_PromptJpsi_20140528_Trg21.root");


    TFile *infile;
    TTree *tree;
    TTree *gentree;
    TTree *evttree;

    infile=new TFile(fileName[0],"R");
    tree=(TTree*)infile->Get("SingleMuonTree");
    gentree=(TTree*)infile->Get("SingleGenMuonTree");
    evttree=(TTree*)infile->Get("EventTree");
    //Event variables
    int eventNb,runNb,lumiBlock;
    int hbit1;
    //double vertexZ;
    //double GenvertexZ;
    //Jpsi Variables
    Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
    Double_t JpsiVprob;
    Double_t JpsiPhi;
    Double_t JpsiEta;
    //2.) muon variables RECO                                                                       
    double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt, muPosP, muPosPhi;
    double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt, muNegP, muNegPhi;
    //(1).Positive Muon                                     
    double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
    int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated;
    bool muPos_matches,muPos_tracker;
    int muPos_Trigger10, muPos_Trigger2, muPos_Trigger21, muPos_Trigger22;
    //(2).Negative Muon                                     
    double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
    int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated;
    bool muNeg_matches,muNeg_tracker;
    int muNeg_Trigger10, muNeg_Trigger2, muNeg_Trigger21, muNeg_Trigger22;

    //Gen Level variables
    //Gen PrJpsi Variables
    double GenJpsiMass, GenJpsiPt, GenJpsiRap;
    double GenJpsiPx, GenJpsiPy, GenJpsiPz;
    double GenJpsiPhi;
    double GenJpsiEta;
    //2.) Gen muon variables 
    double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
    double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;
    double zVtx;

    //Event variables
    tree->SetBranchAddress("eventNb",&eventNb);
    tree->SetBranchAddress("runNb",&runNb);
    tree->SetBranchAddress("lumiBlock",&lumiBlock);
    tree->SetBranchAddress("hbit1",&hbit1);
    tree->SetBranchAddress("zVtx",&zVtx);
    //tree->SetBranchAddress("vertexZ",&vertexZ);

    //Jpsi Variables
    tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
    tree->SetBranchAddress("JpsiMass",&JpsiMass);
    tree->SetBranchAddress("JpsiPt",&JpsiPt);
    tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
    tree->SetBranchAddress("JpsiEta",&JpsiEta);
    tree->SetBranchAddress("JpsiRap",&JpsiRap);
    tree->SetBranchAddress("JpsiVprob",&JpsiVprob);

    //muon variable
    tree->SetBranchAddress("muPosPx",&muPosPx);
    tree->SetBranchAddress("muPosPy",&muPosPy);
    tree->SetBranchAddress("muPosPz",&muPosPz);
    tree->SetBranchAddress("muPosEta",&muPosEta);
    tree->SetBranchAddress("muPosPhi",&muPosPhi);
    tree->SetBranchAddress("muNegPx", &muNegPx);
    tree->SetBranchAddress("muNegPy", &muNegPy);
    tree->SetBranchAddress("muNegPz", &muNegPz);
    tree->SetBranchAddress("muNegEta", &muNegEta);
    tree->SetBranchAddress("muNegPhi", &muNegPhi);


    //1). Positive Muon
    tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
    tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
    tree->SetBranchAddress("muPos_dz", &muPos_dz);
    tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
    tree->SetBranchAddress("muPos_found", &muPos_found);
    tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
    tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
    tree->SetBranchAddress("muPos_matches", &muPos_matches);
    tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
    tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
    tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
    tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
    tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
    tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);

    //2). Negative Muon                                                                            
    tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
    tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
    tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
    tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
    tree->SetBranchAddress("muNeg_found", &muNeg_found);
    tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
    tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
    tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
    tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
    tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
    tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
    tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
    tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
    tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
    //====================================Gen Variables=========================================================
    //Gen Jpsi Variables
    gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
    gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
    gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
    gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
    gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
    gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
    gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
    gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
    //muon variable
    gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
    gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
    gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
    gentree->SetBranchAddress("GenmuPosEta",   &GenmuPosEta);
    gentree->SetBranchAddress("GenmuPosPhi",   &GenmuPosPhi);
    gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
    gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
    gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
    gentree->SetBranchAddress("GenmuNegEta",   &GenmuNegEta);
    gentree->SetBranchAddress("GenmuNegPhi",   &GenmuNegPhi);
    //gentree->SetBranchAddress("GenvertexZ",&GenvertexZ);

    //====================================================== Gen tree loop ================================================
    int NAccep=0;
    int nGenEntries=gentree->GetEntries();
    cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[0]<<"  "<<   nGenEntries<< " ==============="<<endl;

    for(int i=0; i< nGenEntries; i++)  {        
      //cout<<"i : "<<i<<endl;
      if(!(gentree->GetEntry(i))) continue;
      //cout<<" gentree ("<<i<<")"<<endl;
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nGenEntries<<endl;
        //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
      }

      bool GenPosIn=0, GenNegIn=0;
      GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
      GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

      if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
      if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

      int AccJpsi = 0;
      //if(GenJpsiPt < 6.5) continue;
      if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && GenPosIn == 1 && GenNegIn == 1)
          && GenJpsiMass > 2.0 && GenJpsiMass < 4.0
          ) {AccJpsi = 1;}

      if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

      //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
      //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = GenJpsiPt;
      if(iSpec == 1) vars = fabs(GenJpsiRap);
      for(int j = 0; j < nBins; j++){
        if(iSpec == 0){
          bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && fabs(GenJpsiRap) >= minRap && TMath::Abs(GenJpsiRap) <= maxRap && TMath::Abs(GenJpsiRap) >= minRap) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
        if(iSpec == 1){
          bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
          if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt) {
            hGenDiMuon[j]->Fill(GenJpsiMass);
          }
        }
      }
    }//gen loop end

    //cout<<" accepted no "<< NAccep<<endl;

    //=============== Rec Tree Loop ==============================================================================

    int nRecEntries=tree->GetEntries();
    cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[0]<<"  "<<nRecEntries<< "====="<<endl;
    for(int i=0; i<nRecEntries; i++)  {     
      tree->GetEntry(i);
      //Only printing 
      if(i%1000000==0){
        cout<<" processing record "<<i<<"/"<<nRecEntries<<endl;
        //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
        //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
      }
      bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
      muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
      muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
      muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
      muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

      double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
      if(JpsiPt > 6.5 && fabs(JpsiRap) < 1.6) {
        tnpWgt1 = 0.9967*TMath::Erf((muPosPt-1.371)/2.034)/TMath::Erf((muPosPt-1.488)/2.191);
        tnpWgt2 = 0.9967*TMath::Erf((muNegPt-1.371)/2.034)/TMath::Erf((muNegPt-1.488)/2.191);
      }else if(JpsiPt > 3.0 && 1.6 < fabs(JpsiRap) && fabs(JpsiRap) < 2.4) {
        tnpWgt1 = 1.016*TMath::Erf((muPosPt-1.155)/8.28)/TMath::Erf((muPosPt-1.381)/8.147);
        tnpWgt2 = 1.016*TMath::Erf((muNegPt-1.155)/8.28)/TMath::Erf((muNegPt-1.381)/8.147);
      }

      double RecWeight = 1.0;
      RecWeight = tnpWgt1*tnpWgt2;
      

      if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
      if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

      int AccJpsi = 0;
      //if(JpsiPt < 6.5) continue;
      if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && TMath::Abs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)
          && (JpsiMass >= 2.95 && JpsiMass < 3.25)
          ) {AccJpsi = 1;}

      bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
      bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

      if(muPos_found > 10 
          && muPos_pixeLayers > 0 
          && muPos_nchi2In < 4.0 
          && TMath::Abs(muPos_dxy) < 3 
          && TMath::Abs(muPos_dz) < 15 
          && muPos_nchi2Gl < 20 
          && muPos_arbitrated==1 
          && muPos_tracker==1){PosPass=1;}     

      if(muNeg_found > 10 
          && muNeg_pixeLayers > 0 
          && muNeg_nchi2In < 4.0 
          && TMath::Abs(muNeg_dxy) < 3 
          && TMath::Abs(muNeg_dz) < 15 
          && muNeg_nchi2Gl < 20 
          && muNeg_arbitrated==1 
          && muNeg_tracker==1){NegPass=1;}


      // Trigger10 : HLT_PAL2DoubleMu3_v1, Trigger 2 : HLT_PAL1DoubleMu0_HighQ_v1, Trigger 1 : HLT_PAL1DoubleMu0_v1
      // muPos_matches : HLT_PAL1DoubleMuOpen_v1
      //if((muPos_Trigger21==1 && muNeg_Trigger21==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if(hbit1 == 1 && (muPos_Trigger2==1 && muNeg_Trigger2==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_matches==1 && muNeg_matches==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}
      //if((muPos_Trigger10==1 && muNeg_Trigger10==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      // without trigger matched
      // if((PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1)&& mu_Global && mu_Tracker){AllCut=1;}

      //Eff loop for reco
      double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
      if(iSpec == 0) vars = JpsiPt;
      if(iSpec == 1) vars = fabs(JpsiRap);
      if((JpsiCharge == 0) && (JpsiVprob > 0.01)) {     
        for(int j = 0; j < nBins; j++){
          if(iSpec == 0){
            bin1 = pt_bound[j]; bin2 = pt_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && TMath::Abs(JpsiRap) <= maxRap && TMath::Abs(JpsiRap) >= minRap) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
          if(iSpec == 1){ 
            bin1 = rap_bound[j]; bin2 = rap_bound[j+1];
            if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt) {
              hRecoDiMuon[j]->Fill(JpsiMass,RecWeight);
            }
          }
        }
      }
    } //rec tree loop ends

    //======================  File loop Starts ============================

    ///////////////////////////////////////////////////////////////////
    cout<< " adding "<<endl;
    char gtmp[512], gtmp1[512];
    char rtmp[512], rtmp1[512];

    for(int i = 0; i < nBins; i++){
      if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
      if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f.png",pt_bound[i],pt_bound[i+1]);
      if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f.png",rap_bound[i],rap_bound[i+1]);
      hGenDiMuon[i]->SetName(gtmp);
      hRecoDiMuon[i]->SetName(rtmp);
    }

    cout<<"Starts to calculate efficiency"<<endl;
    dataFile<<""<<endl;
    //=====================Loop for eff========================================================================================//
    //define stuff here for error on weighted samples
    for(int i = 0; i < nBins; i++){
      int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
      int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95

      int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
      int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

      genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]); 
      recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);
      //calculate Eff         
      if(genNo[i] == 0 || recoNo[i] == 0) {
        eff[i] = 0;
        effErr[i] = 0;
      }else{
        eff[i] = recoNo[i]/genNo[i]; 

        effErr[i] = recoNo[i]/genNo[i]*TMath::Sqrt(genErr[i]*genErr[i]/(genNo[i]*genNo[i]) + recoErr[i]*recoErr[i]/(recoNo[i]*recoNo[i]));

        //error without weight
        dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        dataFile<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
        cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< recoNo[i]  <<", Gen Jpsi : "<< genNo[i] <<endl;
        cout<<" Eff ["<<i<<"] - "<< eff[i] <<" Error "<< effErr[i] <<endl;
      }
    }
    TH1F *hEff = new TH1F();
    int nEffBins;
    if(iSpec == 0) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
    if(iSpec == 1) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}

    dataFile<<"Efficiency"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<eff[i]<<endl;
    }

    dataFile<<""<<endl;
    dataFile<<"Errors"<<endl;
    for(int i = 0; i < nEffBins; i++){
      hEff->SetBinContent(i+1,eff[i]);
      hEff->SetBinError(i+1,effErr[i]);
      cout<<"Trying to measure eff vs "<<cSp[iSpec]<<endl;
      cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      dataFile<<effErr[i]<<endl;
    }


    outfile->cd();
    hEff->Draw();
    char tmp_histo[512];
    sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
    hEff->SetName(tmp_histo);
    hEff->Write();
    dataFile<<""<<endl;
    dataFile.close();
  }
  outfile->Write();
}
Пример #6
0
//void electron_master(const char* file_list="checkP10ic/electrons.list",const char* output="checkP10ic/electroncalib.root", const char* dbDate="2009-04-10 00:11:00", const char* geantfile="geant_func.root", const char* gfname="checkP10ic/mip.gains", const char* ngname="checkP10ic/electron.gains", const char* rgname="matrel.gains",const char* ffname="checkP10ic/electron.fits"){
void electron_master(const char* file_list="checkP11id/electrons.list",const char* output="checkP11id/electroncalib2.root", const char* dbDate="2009-04-10 00:11:00", const char* gfname="checkP11id/mip.gains", const char* ngname="checkP11id/electron2.gains",const char* ffname="checkP11id/electron2.fits"){
  //**********************************************//
  //Load Libraries                                //
  //**********************************************//
  gROOT->Macro("LoadLogger.C");
  gROOT->Macro("loadMuDst.C");
  gSystem->Load("StTpcDb");
  gSystem->Load("StDaqLib");
  gSystem->Load("StDetectorDbMaker");
  gSystem->Load("St_db_Maker");
  gSystem->Load("StDbUtilities");
  gSystem->Load("StEmcRawMaker");
  gSystem->Load("StMcEvent");
  gSystem->Load("StMcEventMaker");//***
  gSystem->Load("StEmcSimulatorMaker");//***
  gSystem->Load("StEmcADCtoEMaker");
  gSystem->Load("StEpcMaker");
  gSystem->Load("StDbBroker");
  gSystem->Load("StEEmcUtil");
  gSystem->Load("StAssociationMaker");
  gSystem->Load("StEmcTriggerMaker");
  gSystem->Load("StTriggerUtilities");
  gSystem->Load("StEmcOfflineCalibrationMaker");

  cout<<"input filelist: "<<file_list<<endl;
  cout<<"output:          "<<output<<endl;
  cout<<"db Date:        "<<dbDate<<endl;


  //**********************************************//
  //Initialize Stuff                              //
  //**********************************************//

  CalibrationHelperFunctions *helper = new CalibrationHelperFunctions();
	
  StBemcTablesWriter *bemctables = new StBemcTablesWriter();
  bemctables->loadTables(dbDate,"sim");
  StEmcDecoder* decoder = bemctables->getDecoder();


  //chain all input files together
  char file[300];
  TChain* tree = new TChain("skimTree");
  ifstream filelist(file_list);
  while(1){
    filelist >> file;
    if(!filelist.good()) break;
    cout<<file<<endl;
    tree->Add(file);
  }

  const int ntowers = 4800;
  const int nrings = 40;
  const int ncrates = 30;
  float gains[ntowers];
  int status[ntowers];
  float peaks[ntowers];
  float peakerr[ntowers];
  float gainerr[ntowers];

  ifstream gainfile(gfname);
  while(1){
    int id,stat;
    float peak,err,gain,eta,theta;
    gainfile >> id >> peak >> err >> stat;
    if(!gainfile.good())break;
    eta = helper->getEta(id);
    theta = helper->getTheta(id);
    gain = 0.264*(1+0.056*eta*eta)/(sin(theta)*peak);
    peaks[id-1] = peak;
    gains[id-1] = gain;
    if(status[id-1] != 1 || stat != 1) status[id-1] = stat;
    peakerr[id-1] = err;
    //cout<<id<<" "<<gain;
  }


  TFile* geant_file = new TFile("geant_fits.root","READ");
  TF1* geant_fits[20];
  for(int i = 0; i < 20; i++){
    TString fname = "fit_";
    fname += i;
    geant_fits[i] = (TF1*)geant_file->Get(fname);
  }


  TFile outfile(output,"RECREATE");

  TH1 *crate_histo[ncrates];
  TF1 *crate_fit[ncrates];
  TH1 *electron_histo[ntowers];
  TF1 *fit[ntowers];
  TH1 *prs_histo[ntowers];
  TH1 *ring_histo[nrings];
  TH1 *ring2_histo[nrings/2];
  TF1 *ring2fit[nrings/2];

  TH1 *etacrate_histo[ncrates*20];
  TH1 *etacrate_histo_p[ncrates*20];
  TH1 *etacrate_histo_n[ncrates*20];

  TH1 *bghisto[21];
  TH2F* drvsep = new TH2F("drvsep","drvsep",60,0,3.0,100,0.0,0.03);

  TF1 *ringfit[nrings];
  TH2F* ring_pve[nrings];
  TH2F* jan_pve[6];
  float eta;
  int etaindex;
  TH1F* ringprec = new TH1F("ringprec","",40,-1.0,1.0);
  TH1F* ringprec2 = new TH1F("ringprec2","",40,-1.0,1.0);
  ringprec->SetYTitle("E/p");
  ringprec->SetXTitle("#eta");
  ringprec2->SetYTitle("E/p");
  ringprec2->SetXTitle("#eta");
  TH1F* ring2prec = new TH1F("ring2prec","",nrings/2,-1.0,1.0);
  TH1F* ring2prec2 = new TH1F("ring2prec2","",nrings/2,-1.0,1.0);
  ring2prec->SetYTitle("E/p");
  ring2prec->SetXTitle("#eta");
  ring2prec2->SetYTitle("E/p");
  ring2prec2->SetXTitle("#eta");
  double ew[nrings];

  TH2F* trgcheck = new TH2F("trgcheck","trgcheck",2,-0.5,1.5,3,-0.5,2.5);

  TH1F* crateprec = new TH1F("crateprec","",30,0.5,30.5);
  crateprec->SetXTitle("Crate");
  crateprec->SetYTitle("E/p");

  TH2F *energyleak = new TH2F("energyleak","",20,0.0,0.03,20,0.0,1.0);
  TH2F *findbg = new TH2F("findbg","",20,0.0,0.03,30,0.0,5.0);
  TH1F *energymean = new TH1F("energymean","",20,0.0,0.03);
  TH1F *leakmean = new TH1F("leakmean","",20,0.0,0.03);
  energyleak->SetXTitle("#DeltaR");
  energyleak->SetYTitle("leaked energy / total energy");
  findbg->SetXTitle("#DeltaR");
  findbg->SetYTitle("Total energy / track momentum");
  TH2F *tevsp = new TH2F("tevsp","",50,0.0,20.0,50,0.0,30.0);
  TH1F *pmean = new TH1F("pmean","",20,0.0,15.0);
  tevsp->SetXTitle("track momentum (GeV)");
  tevsp->SetYTitle("Total Energy (GeV)");
  TH2F *tevspcent = new TH2F("tevspcent","",20,0.0,15.0,20,0.0,15.0);
  tevspcent->SetXTitle("track momentum (GeV)");
  tevspcent->SetYTitle("Energy in central tower (GeV)");
  TH1F *cmean = new TH1F("cmain","",20,0.0,15.0);
  TH2F *sistertracks = new TH2F("sistertracks","",20,0.0,8.0,20,0.0,8.0);
  sistertracks->SetXTitle("Track momentum (GeV)");
  sistertracks->SetYTitle("Neighbor momentum (GeV)");
  TH2F* dEdxvsp = new TH2F("dEdxvsp","",100,0.15,1.3,100,-5.7,-5.);
  dEdxvsp->SetXTitle("Log(p)");
  dEdxvsp->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_east = new TH2F("dEdxvsp_east","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_east->SetXTitle("Log(p)");
  dEdxvsp_east->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_west = new TH2F("dEdxvsp_west","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_west->SetXTitle("Log(p)");
  dEdxvsp_west->SetYTitle("Log(dE/dx)");
  TH2F* energyleak2 = new TH2F("energyleak2","",20,0.0,0.03,20,0.0,1.0);
  TH1F* energymean2 = new TH1F("energymean2","",20,0.0,0.03);
  TH1F* towermult = new TH1F("towermult","",9,0.0,9.0);
  energyleak2->SetXTitle("#DeltaR");
  energyleak2->SetYTitle("leaked energy/total energy");
  towermult->SetXTitle("Neighbors with energy");
  TH2F* multvsp = new TH2F("multvsp","",20,0.0,20.0,9,0.0,9.0);
  multvsp->SetXTitle("Track momentum (GeV)");
  multvsp->SetYTitle("Neighbors with energy");
  TH1F* multmean = new TH1F("multmean","",20,0.0,20.0);
  TH2F* tep3 = new TH2F("tep3","2 < p < 3",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep5 = new TH2F("tep5","3 < p < 5",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep10 = new TH2F("tep10","5 < p < 10",20,0.0,0.03,20,0.0,4.0);
  tep3->SetXTitle("DeltaR");
  tep3->SetYTitle("Total energy / track momentum");
  tep5->SetXTitle("DeltaR");
  tep5->SetYTitle("Total energy / track momentum");
  tep10->SetXTitle("DeltaR");
  tep10->SetYTitle("Total energy / track momentum");
  TH1F* tep3mean = new TH1F("tep3mean","",20,0,0.03);
  TH1F* tep5mean = new TH1F("tep5mean","",20,0,0.03);
  TH1F* tep10mean = new TH1F("tep10mean","",20,0,0.03);
  TH1F* multen = new TH1F("multen","",40,0.0,1.0);
  multen->SetXTitle("Energy in neighbor towers (GeV)");
  TH1F* east_histo = new TH1F("east_histo","Electron E/p in East",40,0.0,2.0);
  TH1F* west_histo = new TH1F("west_histo","Electron E/p in West",40,0.0,2.0);
  TH1F* all_histo = new TH1F("all_histo","Electron E/p",40,0.0,2.0);
  TH1F* notrg = new TH1F("notrg","Electron E/p",40,0.0,2.0);
  TH2F* pvsep = new TH2F("pvsep","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep->SetYTitle("p (Gev)");
  pvsep->SetXTitle("E/p");
  TH2F* pvsep0 = new TH2F("pvsep0","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep0->SetYTitle("p (Gev)");
  pvsep0->SetXTitle("E/p");
  TH2F* evsep = new TH2F("evsep","Electron E vs E/p",120,0,3.0,20,0,20.0);
  evsep->SetYTitle("E (GeV)");
  evsep->SetXTitle("E/p");

  TH1F* bsmde = new TH1F("bsmde","BSMDE ADC TOT",1500,0,1500);
  TH1F* bsmdp = new TH1F("bsmdp","BSMDP ADC TOT",1500,0,1500);

  TH1F* bsmde_central = new TH1F("bsmde_central","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_mid = new TH1F("bsmde_mid","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_outer = new TH1F("bsmde_outer","BSMDE ADC TOT",100,0,1500);

  TH2F* bsmdep = new TH2F("bsmdep","BSMDE v BSMDP",100,0,1500,100,0,1500);

  TH2F* bsmdevp = new TH2F("bsmdevp","BSMDE v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdpvp = new TH2F("bsmdpvp","BSMDP v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdevep = new TH2F("bsmdevep","BSMDE v E/p",100,0.0,2.0,100,0,1500);
  TH2F* bsmdpvep = new TH2F("bsmdpvep","BSMDP v E/p",100,0.0,2.0,100,0,1500);

  TH2F* bsmdeve = new TH2F("bsmdeve","BSMDE v E",100,1.0,30.0,100,0,1500);
  TH2F* bsmdpve = new TH2F("bsmdpve","BSMDP v E",100,1.0,30.0,100,0,1500);

  TH1F* httrig = new TH1F("httrig","HT Trigger",5,-0.5,4.5);

  TH1F* pplus = new TH1F("pplus","e+ p",100,0,20);
  TH1F* pminus = new TH1F("pminus","e- p",100,0,20);

  TH1F* posep = new TH1F("posep","e+ E/p",60,0,3.0);
  TH1F* negep = new TH1F("negep","e- E/p",60,0,3.0);


   //create the tower histograms
  char name1[100];

  for(int i = 0; i < ncrates; i++){
    for(int j = 0; j < 20; j++){
      TString ecname,ecnamep,ecnamen;
      ecname += "etacrate_";
      int cr = i+1;
      int et = j;
      ecname += cr;
      ecname += "_";
      ecname += et;
      ecnamep += ecname;
      ecnamen += ecname;
      ecnamep.ReplaceAll("te_","te_p_");
      ecnamen.ReplaceAll("te_","te_n_");
      etacrate_histo[i*20+j] = new TH1F(ecname.Data(),ecname.Data(),60,0.0,3.0);
      etacrate_histo_p[i*20+j] = new TH1F(ecnamep.Data(),ecnamep.Data(),60,0.0,3.0);
      etacrate_histo_n[i*20+j] = new TH1F(ecnamen.Data(),ecnamen.Data(),60,0.0,3.0);

    }
  }

  for(int i=0; i<ntowers; i++){
    char nameeh[100];
    sprintf(nameeh,"electron_histo_%i",i+1);
    electron_histo[i] = new TH1D(nameeh,"",60,0.,3.0);
    electron_histo[i]->SetXTitle("E/p");
    //sprintf(name1,"prs_histo_%i",i+1);
    //prs_histo[i] = new TH1D(name1,"",60,0.,500.);
    //prs_histo[i]->SetXTitle("ADC");
  }

  for(int i = 0; i < 21; i++){
    TString namebg;
    namebg += "bg_";
    namebg += i+25;
    bghisto[i] = new TH1F(namebg.Data(),namebg.Data(),60,0,3.0);
  }

  for(int i = 0; i < ncrates; i++){
    char name[100];
    char title[100];
    sprintf(name,"crate_%i",i+1);
    sprintf(title,"E/p for Crate %i",i+1);
    crate_histo[i] = new TH1F(name,title,60,0.,3.0);
    crate_histo[i]->SetXTitle("E/p");
  }

  for(int i = 0; i < nrings/2; i++){
    char name[100];
    sprintf(name,"ring2_histo_%i",i);
    ring2_histo[i] = new TH1F(name,"",60,0.,3.0);
    ring2_histo[i]->SetXTitle("E/p");
  }

  char name2[100];
  for(int i=0; i<nrings;i++)
    {
      sprintf(name2,"ring_histo_%i",i);
      //ring_histo[i] = new TH1D(name2,"",30,0.,140.0);
      //ring_histo[i]->SetXTitle("ADC / GeV Sin(#theta)");
      ring_histo[i] = new TH1D(name2,"",60,0.,3.0);
      ring_histo[i]->SetXTitle("E/p");
      char namerpve[100];
      sprintf(namerpve,"ring_pve_%i",i);
      ring_pve[i] = new TH2F(namerpve,"",20,0,20.0,20,0,20.0);
      ring_pve[i]->SetXTitle("E (GeV)");
      ring_pve[i]->SetYTitle("p (GeV)");
    }

  for(int i = 0; i < 6; i++){
    char jname[100];
    sprintf(jname,"jan_pve_%i",i);
    jan_pve[i] = new TH2F(jname,"",120,0,3.0,20,0,20.0);
    jan_pve[i]->SetXTitle("E/p");
    jan_pve[i]->SetYTitle("p (GeV)");
  }
  //global graphics functions
  gStyle->SetOptStat("oue");
  gStyle->SetOptFit(111);
  gStyle->SetCanvasColor(10);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetOptTitle(0);
  gStyle->SetPalette(1);
  gStyle->SetStatColor(0);

  StEmcOfflineCalibrationTrack* track = new StEmcOfflineCalibrationTrack();
  StEmcOfflineCalibrationCluster* cluster = new StEmcOfflineCalibrationCluster();
  tree->SetBranchAddress("clusters",&cluster);

  //**********************************************//
  //Loop Over Tracks, Fill Histograms             //
  //**********************************************//

  int nentries = tree->GetEntries();
  cout<<nentries<<endl;
  int ngoodhit = 0;
  int nplt10 = 0;
  int nnosis = 0;
  int nfinal = 0;
  int nbsmdgood = 0;
  int nnottrig = 0;
  int nfidu = 0;
  int nenterexit = 0;
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;
    if(j % 500000 == 0) cout<<"reading "<<j<<" of "<<nentries<<endl;

    httrig->Fill((float)track->htTrig);

    if(track->charge > 0)pplus->Fill(track->p);
    if(track->charge < 0)pminus->Fill(track->p);

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;

    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);

    double geant_scale = geant_fits[geantetaindex]->Eval(dR);
    scaled_adc /= geant_scale;
    //double geant_scale = geant_fit->Eval(dR);
    //scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;

    //now rescale dR for last ring to make cuts work
    if(geantetaindex == 19)dR *= 0.025/0.017;

    //double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1];
    double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;
    ngoodhit++;
    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] <= 2400)dEdxvsp_west->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] > 2400)dEdxvsp_east->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    trgcheck->Fill(track->nonhtTrig,track->htTrig);

    if(track->tower_id[0] != track->tower_id_exit)continue;
    nenterexit++;

    if(status[index-1]!=1)continue;

    pvsep0->Fill(scaled_adc*tgain,track->p);
    if(track->p > 10)continue;	
    nplt10++;		

    //if(track->p < 1.5)continue;
    //if(track->p < 3.0)continue;
    if(track->htTrig == 2 && track->nonhtTrig == 0)continue;
    nnottrig++;
    //change the fiducial cut to a square with diagonal = 0.06 in deta, dphi space
    float squarefid = 0.02;//0.03/TMath::Sqrt(2.0);
    //if(TMath::Abs(track->deta) > squarefid || TMath::Abs(track->dphi) > squarefid)continue;

    //calculate geant scaled, pedestal subtracted adc
    //if(dR > 0.0125)continue;
    int numsis = tracks->GetEntries();
    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }

    if(track->dEdx > 3.5e-6 && track->dEdx <5.0e-6 && numsis ==0 &&maxId == 0)drvsep->Fill(scaled_adc*tgain,dR);
    if(dR > 0.02)continue;
    nfidu++;
    //if(track->p > 6.0)continue;				
    //if(track->p > 15)continue;
    //cout<<track->dEdx<<endl;


    //if(track->dEdx*1000000 > 4.5 || track->dEdx*1000000 < 3.5)continue;

    //cout<<track->htTrig<<endl;

    for(int i = 0; i < 21; i++){
      if(numsis > 0)break;
      if(maxId != 0)break;
      if(track->dEdx*1e7 > 25 + i && track->dEdx*1e7 < 26+i)bghisto[i]->Fill(scaled_adc*tgain);
    }

    //if(track->dEdx < 3.5e-6 || track->dEdx > 5.0e-6)continue;
    if(track->dEdx < 3.5e-6 || track->dEdx > 4.5e-6)continue;
    //if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;
    nbsmdgood++;
    //if(bsmdeadctot < 500) continue;

    //if(bsmdeadctot < 84.*track->p)continue;
    //if(bsmdeadctot > 200.*track->p + 1500)continue;

    //if(bsmdpadctot < 800)continue;

    if(numsis > 0)continue;

    nnosis++;
    if(maxId != 0) continue;


    nfinal++;
    if(track->htTrig!=2)notrg->Fill(scaled_adc*tgain);

    //if(!track->nonhtTrig)continue;
    //if(track->nHits < 25)continue;
    //if(status[index-1]==1)ring_histo[etaindex]->Fill(scaled_adc*gains[index-1]);

    //scaled_adc = totalbtow/track->p;
    //tgain = 1.0;

    float phi = helper->getPhi(index);
    int crate,sequence;
    decoder->GetCrateFromTowerId(index,crate,sequence);
    etacrate_histo[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge > 0)etacrate_histo_p[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge < 0)etacrate_histo_n[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);

    electron_histo[index-1]->Fill(scaled_adc*tgain);
    ring_histo[etaindex]->Fill(scaled_adc*tgain);
    if(etaindex == 0 || etaindex == 39){
      //cout<<etaindex<<" "<<tgain<<" "<<track->p<<" "<<scaled_adc*tgain*track->p<<" "<<scaled_adc*tgain<<endl;
    }
    //cout<<index<<" "<<gains[index-1]<<" "<<scaled_adc*track->p<<" "<<track->p<<" "<<status[index-1]<<endl;
    ring_pve[etaindex]->Fill(scaled_adc*tgain*track->p,track->p);

    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    float abseta = TMath::Abs(eta);
    if(abseta > 0.95){
      jan_pve[5]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.9){
      jan_pve[4]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.6){
      jan_pve[3]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.3){
      jan_pve[2]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.05){
      jan_pve[1]->Fill(scaled_adc*tgain,track->p);
    }else{
      jan_pve[0]->Fill(scaled_adc*tgain,track->p);
    }

    all_histo->Fill(scaled_adc*tgain);
    pvsep->Fill(scaled_adc*tgain,track->p);
    evsep->Fill(scaled_adc*tgain,track->p*scaled_adc*tgain);
    tevsp->Fill(track->p,scaled_adc*tgain*track->p);

    if(track->charge > 0)posep->Fill(scaled_adc*tgain);
    if(track->charge < 0)negep->Fill(scaled_adc*tgain);

    //if(scaled_adc*tgain < 0.7 || scaled_adc*tgain > 5.0)continue;
    bsmde->Fill(bsmdeadctot);
    bsmdp->Fill(bsmdpadctot);
    bsmdep->Fill(bsmdeadctot,bsmdpadctot);

    if(abseta > 0.6){
      bsmde_outer->Fill(bsmdeadctot);
    }else if(abseta > 0.3){
      bsmde_mid->Fill(bsmdeadctot);
    }else{
      bsmde_central->Fill(bsmdeadctot);
    }

    bsmdevp->Fill(track->p,bsmdeadctot);
    bsmdpvp->Fill(track->p,bsmdpadctot);
    bsmdevep->Fill(scaled_adc*tgain,bsmdeadctot);
    bsmdpvep->Fill(scaled_adc*tgain,bsmdpadctot);

    bsmdeve->Fill(scaled_adc*tgain*track->p,bsmdeadctot);
    bsmdpve->Fill(scaled_adc*tgain*track->p,bsmdpadctot);

    if(dR > 0.015)continue;
    if(track->tower_id[0] <= 2400){
      west_histo->Fill(scaled_adc*tgain);
    }
    if(track->tower_id[0] > 2400){
      east_histo->Fill(scaled_adc*tgain);
    }

  }
  cout<<"processed electron tree"<<endl;
  cout<<"ngoodhit: "<<ngoodhit<<endl;
  cout<<"nenterexit: "<<nenterexit<<endl;
  cout<<"n not trig: "<<nnottrig<<endl;
  cout<<"n p < 10: "<<nplt10<<endl;
  cout<<"n in fidu: "<<nfidu<<endl;
  cout<<"nbsmdhit: "<<nbsmdgood<<endl;
  cout<<"n no sis: "<<nnosis<<endl;
  cout<<"n final: "<<nfinal<<endl;

  //double ew[21];
  for(int h=0;h<21;h++){
    TH1D* projection = energyleak->ProjectionY("projection",h,h);
    float mean = projection->GetMean();
    energymean->SetBinContent(h,mean);
    TH1D* projection1 = findbg->ProjectionY("projection1",h,h);
    float mean1 = projection1->GetMean();
    leakmean->SetBinContent(h,mean1);
    TH1D* projection2 = tevsp->ProjectionY("projection2",h,h);
    float mean2 = projection2->GetMean();
    pmean->SetBinContent(h,mean2);
    //ew[h] = projection2->GetRMS();
    TH1D* projection3 = tevspcent->ProjectionY("projection3",h,h);
    float mean3 = projection3->GetMean();
    cmean->SetBinContent(h,mean3);
    TH1D* projection4 = energyleak2->ProjectionY("projection4",h,h);
    float mean4 = projection4->GetMean();
    energymean2->SetBinContent(h,mean4);
    TH1D* projection5 = multvsp->ProjectionY("projection5",h,h);
    float mean5 = projection5->GetMean();
    multmean->SetBinContent(h,mean5);
    TH1D* projection6 = tep3->ProjectionY("projection6",h,h);
    float mean6 = projection6->GetMean();
    tep3mean->SetBinContent(h,mean6);
    TH1D* projection7 = tep3->ProjectionY("projection7",h,h);
    float mean7 = projection7->GetMean();
    tep5mean->SetBinContent(h,mean7);
    TH1D* projection8 = tep3->ProjectionY("projection8",h,h);
    float mean8 = projection8->GetMean();
    tep10mean->SetBinContent(h,mean8);
  }

  TF1* fitleak = new TF1("fitleak","[0]",0,0.03);
  fitleak->SetLineWidth(0.1);
  leakmean->Fit(fitleak,"rq");


  //**********************************************//
  //Fit Tower Histograms                          //
  //**********************************************//
  /*
  for(int i=0; i<ntowers; i++){
	  
    if(i%600 == 0) cout<<"fitting tower "<<i+1<<" of "<<ntowers<<endl;
		
    sprintf(name,"fit_%i",i+1);
		
		//this fit is for the electron tree
    fit[i] = new TF1(name,fit_function,0.,140.,6);
    fit[i]->SetParameter(1,65.);
    fit[i]->SetParameter(2,10.);
    fit[i]->SetParameter(3,10.); //relative height of peak to bg
    fit[i]->SetParameter(4,10.);
    fit[i]->SetParameter(5,3.);
    fit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
		
    fit[i]->SetLineColor(kGreen);
    fit[i]->SetLineWidth(0.6);
		
    electron_histo[i]->Fit(fit[i],"rq");
  }
  */
  //**********************************************//
  //Fit Ring Histograms                           //
  //**********************************************//

  for(int i=0; i<nrings; i++){
	  
    //cout<<"fitting ring "<<i+1<<" of "<<nrings<<endl;
		
    sprintf(name,"ring_fit_%i",i);
    /*
    ringfit[i] = new TF1(name,fit_function,0.,140.,6);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParameter(5,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
    */		
    //TF1* ffff = new TF1("ffff","expo(0) + gaus(2)",0.4,1.7);

    ring_histo[i]->Sumw2();
    //ring_histo[i]->Rebin(3);

    ringfit[i] = new TF1(name,"pol1(0) + gaus(2)");
    ringfit[i]->SetParLimits(0,0,10.0*ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParLimits(1,-10000,0);
    ringfit[i]->SetParLimits(2,0,10.0*ring_histo[i]->GetMaximum());
    ringfit[i]->SetParLimits(3,0,10);
    ringfit[i]->SetParameter(0,ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParameter(1,-ring_histo[i]->GetBinContent(1)/6.0);
    ringfit[i]->SetParameter(2,ring_histo[i]->GetMaximum());
    ringfit[i]->SetParameter(3,0.95);
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    /*
    ringfit[i] = new TF1(name,fit_function2,0.1,2.5,8);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.25);
    ringfit[i]->SetParameter(5,0.15);
    ringfit[i]->SetParameter(7,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma","Bg2 constant","Bg2 decay");
    	
    */
    ringfit[i]->SetLineColor(kBlue);
    ringfit[i]->SetLineWidth(0.6);
    
    ring_histo[i]->Fit(ringfit[i],"rql","",0.2,1.7);
		
    ringprec->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec->SetBinError(i+1,ringfit[i]->GetParameter(4));
    ringprec2->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec2->SetBinError(i+1,ringfit[i]->GetParError(3));
    //ew[i] = 4066/(60*(fit[i]->GetParameter(2))*(fit[i]->GetParameter(2)));

    float mean = ringfit[i]->GetParameter(3);
    float merr = ringfit[i]->GetParError(3);
    cout<<"ring "<<i<<" "<<mean<<" "<<merr/mean<<" "<<ring_histo[i]->GetEntries()<<endl;
  }

  for(int i = 0; i < nrings/2; i++){
    ring2_histo[i]->Add(ring_histo[2*i]);
    ring2_histo[i]->Add(ring_histo[2*i+1]);
    sprintf(name,"ring2_fit_%i",i);
    ring2fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);

    ring2_histo[i]->Rebin(3);

    ring2fit[i]->SetParLimits(0,0,10.0*ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParLimits(1,-10000,0);
    ring2fit[i]->SetParLimits(2,0,10.0*ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParLimits(3,0,10);
    ring2fit[i]->SetParLimits(4,0.17,0.175);
    ring2fit[i]->SetParameter(0,ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParameter(1,-ring2_histo[i]->GetBinContent(1)/6.0);
    ring2fit[i]->SetParameter(2,ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParameter(3,0.95);
    ring2fit[i]->SetParameter(4,0.11245);
    ring2fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");

    ring2_histo[i]->Fit(ring2fit[i],"rql","",0.3,1.7);

    ring2prec->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec->SetBinError(i+1,ring2fit[i]->GetParameter(4));
    ring2prec2->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec2->SetBinError(i+1,ring2fit[i]->GetParError(3));

    cout<<"ring2 "<<i<<" "<<ring2fit[i]->GetParameter(3)<<" "<<ring2fit[i]->GetParError(3)<<endl;
  }

  for(int i = 0; i < ntowers; i++){
    char name[100];
    sprintf(name,"electron_fit_%i",i+1);
    /*
    fit[i] = new TF1(name,"pol1(0)+gaus(2)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,-10000,0);
    fit[i]->SetParLimits(2,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(3,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,-electron_histo[i]->GetBinContent(1)/6.0);
    fit[i]->SetParameter(2,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(3,0.95);
    fit[i]->SetParameter(4,0.15);
    fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    */
    fit[i] = new TF1(name,"pol0(0)+gaus(1)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(2,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(2,0.95);
    fit[i]->SetParameter(3,0.15);
    fit[i]->SetParNames("constant1","constant2","Mean","Sigma");

    electron_histo[i]->Fit(fit[i],"rql","",0.3,1.7);
  }

  ofstream fitfile(ffname);

  TF1* etacrate_fit[ncrates*20];
  for(int ii = 0; ii < ncrates; ii++){
    for(int j = 0; j < 20; j++){
      TString ecname;
      ecname += "fit";
      int cr = ii+1;
      int et = j;
      int i = ii*20 + j;
      //ecname += cr;
      //ecname += "_";
      //ecname += et;
      etacrate_fit[i] = new TF1(ecname.Data(),"pol1(0) + gaus(2)",0.25,1.6);
      //etacrate_fit[i]->SetParLimits(0,0,10.0*etacrate_histo[i]->GetBinContent(1));
      etacrate_histo[i]->Rebin();
      etacrate_fit[i]->SetParLimits(1,-10000,0);
      etacrate_fit[i]->SetParLimits(2,0,10.0*etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParLimits(3,0,10);
      etacrate_fit[i]->SetParameter(0,etacrate_histo[i]->GetBinContent(2));
      etacrate_fit[i]->SetParameter(1,-etacrate_histo[i]->GetBinContent(2)/3.0);
      etacrate_fit[i]->SetParameter(2,etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParameter(3,0.96134);
      etacrate_fit[i]->SetParameter(4,0.141123);
      etacrate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
      
      etacrate_histo[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_p[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_n[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      fitfile << i << " " << etacrate_histo[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_p[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_n[i]->GetFunction("fit")->GetParameter(3) << endl;

    }
  }

  ofstream newgain(ngname);
  

  float gains2[ntowers];
  float gerr2[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    int crate,sequence;
    decoder->GetCrateFromTowerId(i+1,crate,sequence);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);
    TString ecname;
    ecname += "fit";
    //int cr = ii+1;
    //int et = j;
    //int i = ii*20 + j;
    //ecname += crate;
    //ecname += "_";
    //ecname += geantetaindex;
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    int etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    //float adjust = ring2fit[(int)etaindex/2]->GetParameter(3);
    //cout<<etaindex<<" "<<(int)etaindex/2<<" "<<adjust<<endl;
    //float adjust = fit[i]->GetParameter(3);
    float ng = 0;
    float ne = 0;
    if(status[i] == 1){
      //float og = bemctables->calib(1,i+1)*gains[i];
      float og = gains[i];
      //float aerr = ring2fit[(int)etaindex/2]->GetParError(3);
      float adjust = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParameter(3);
      float aerr = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParError(3);
      if(geantetaindex == 19){
	adjust = ringfit[etaindex]->GetParameter(3);
	aerr = ringfit[etaindex]->GetParError(3);
      }
      ng = og/adjust;
      float gerr = peakerr[i]*gains[i]/peaks[i];
      ne = sqrt(pow(og*aerr/(adjust*adjust),2) + pow(gerr/adjust,2));
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains2[i] = ng;
    gerr2[i] = ne;


  }

  newgain.close();

    ///////////////////////////////////////
   //Using new gains regenerate by crate//
  ///////////////////////////////////////


  /*
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;
    double geant_scale = geant_fit->Eval(dR);
    scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;
    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);

    double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1]*gains2[index-1];
    //double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;

    if(track->tower_id[0] != track->tower_id_exit)continue;

    if(track->htTrig == 2)continue;
    if(track->p > 6)continue;	

    if(dR > 0.025)continue;

    if(track->dEdx < 3.4e-6)continue;
    if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;

    int numsis = tracks->GetEntries();
    if(numsis > 0)continue;

    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }
    if(maxId != 0) continue;

    eta = helper->getEta(index);
    float phi = helper->getPhi(index);
    int crate = lookup_crate(eta,phi);
    if(status[index-1]==1)crate_histo[crate-1]->Fill(scaled_adc*tgain);
  }

  for(int i = 0; i < ncrates; i++){
    sprintf(name,"crate_fit_%i",i);
    crate_histo[i]->Sumw2();	
    crate_histo[i]->Rebin(4);	

    crate_fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);
    crate_fit[i]->SetParLimits(0,0,10.0*crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParLimits(1,-10000,0);
    crate_fit[i]->SetParLimits(2,0,10.0*crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParLimits(3,0,10);
    crate_fit[i]->SetParameter(0,crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParameter(1,-crate_histo[i]->GetBinContent(1)/6.0);
    crate_fit[i]->SetParameter(2,-crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParameter(3,0.929);
    crate_fit[i]->SetParameter(4,0.156);
    crate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    crate_fit[i]->SetLineColor(kBlue);
    crate_fit[i]->SetLineWidth(0.6);


    crate_histo[i]->Fit(crate_fit[i],"rql","",0.3,1.8);
    float mean = crate_histo[i]->GetFunction(name)->GetParameter(3);
    float merr = crate_histo[i]->GetFunction(name)->GetParError(3);
    crateprec->SetBinContent(i+1,mean);
    crateprec->SetBinError(i+1,merr);
    cout<<"crate "<<i+1<<" "<<mean<<" "<<merr/mean<<endl;
  }
  
  ofstream newgain(ngname);

  float gains3[ntowers];
  float gerr3[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    float phi = helper->getPhi(i+1);
    int crate = lookup_crate(eta,phi);
    float adjust = crate_fit[crate-1]->GetParameter(3);
    float og = bemctables->calib(1,i)*gains[i]*gains2[i];
    float ng = og;
    float aerr = crate_fit[crate-1]->GetParError(3);
    float ne = sqrt(pow(gains[i]*gerr2[i],2) + pow(gains2[i]*gainerr[i],2));
    if(fabs(adjust-1)/aerr > 1.5){
      ne = sqrt(pow(ne/(adjust),2)+pow(og*aerr/(adjust*adjust),2));
      ng /= adjust;
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains3[i] = ng;
    gerr3[i] = ne;
  }

  newgain.close();
  */
  outfile.Write();
  outfile.Close();

}
Пример #7
0
void oDependence()
{
  //set plot options
  gStyle->SetOptFit(1); 
  gStyle->SetOptStat(1);  
  TCanvas  * c1 = new TCanvas("canPRF","Pad response function",700,900);
  TPad * pad1 = new TPad("pad1THR","",0.05,0.55,0.45,0.95,21);
  pad1->Draw();
  TPad * pad2 = new TPad("pad2PRF","",0.55,0.55,0.95,0.95,21);
  pad2->Draw(); 
  TPad * pad3 = new TPad("pad3PRF","",0.55,0.05,0.95,0.45,21);
  pad3->Draw(); 
 
  pad1->cd();
  pad1->SetGridx();
  pad1->SetGridy();
  pad2->SetGridx();
  pad2->SetGridy();
  pad3->SetGridx();
  pad3->SetGridy();

  //make histogram of threshold dependence
  TH1F * hotd =new TH1F("Occupancy dependence on threshold",
			"Ocupancy at first pad row as function of threshold",
                        25,0.,25.);

  hotd->SetBinContent(5,0.625);
  hotd->SetBinError(5,0.02);
  hotd->SetBinContent(10,0.559);
  hotd->SetBinError(10,0.02); 
  hotd->SetBinContent(20,0.478);
  hotd->SetBinError(20,0.02);
  hotd->SetXTitle("Threshold   [channels]");
  hotd->SetYTitle("occupancy");
  hotd->Fit("pol1","+");  
  hotd->Draw("error");
  //make histogram of PRF  dependence
  TH1F * hoprfd =new TH1F("Occupancy dependence on PRF width",
			"Occupancy at first pad row as function of generic PRF sigma for  2.05x0.35 cm pad size ",
                        65, 0.,6.5);
  hoprfd->SetBinContent(10,0.492);
  hoprfd->SetBinError(10,0.02);

  hoprfd->SetBinContent(20,0.524);
  hoprfd->SetBinError(20,0.02); 

  hoprfd->SetBinContent(30,0.559);
  hoprfd->SetBinError(30,0.02);
  hoprfd->SetXTitle("Sigma of PRF   [mm]");
  hoprfd->SetYTitle("occupancy");
  pad2->cd();
  hoprfd->Fit("pol1","+");  
  hoprfd->Draw("error");
  pad2->Draw();
  //pad 3 histogram  
  pad3->cd();
   TH1F * hoprfd88 =new TH1F("Occupancy dependence on PRF width 08x08",
			"Occupancy at first pad row as function of generic PRF sigma for  0.8x0.8 cm pad size ",
                        65, 0.,6.5);

  hoprfd88->SetBinContent(20,0.322);
  hoprfd88->SetBinError(20,0.02);

  hoprfd88->SetBinContent(30,0.344);
  hoprfd88->SetBinError(30,0.02); 

  hoprfd88->SetBinContent(40,0.369);
  hoprfd88->SetBinError(40,0.02);
 
  hoprfd88->SetBinContent(60,0.416);
  hoprfd88->SetBinError(60,0.02);
  hoprfd88->SetXTitle("Sigma of PRF   [mm]");
  hoprfd88->SetYTitle("occupancy");
  hoprfd88->Fit("pol1","+");  
  hoprfd88->Draw("error");
  c1->cd();
  TPaveText * comment = new TPaveText(0.05,0.15,0.45,0.35,"NDC");
  comment->SetTextAlign(12);
  comment->SetFillColor(42);  
  comment->ReadFile("commentdep.txt");  
  comment->Draw();

}
Пример #8
0
//================================================
void DeltaZVsPos(const Int_t save = 0)
{
  THnSparseF *hn = (THnSparseF*)f->Get(Form("mhTrkDzDy_%s",trigName[kTrigType]));
  TList *list = new TList;

  // dz vs BL
  TH2F *hTrkDzVsBL = (TH2F*)hn->Projection(1,3);
  c = draw2D(hTrkDzVsBL,Form("%s: #Deltaz of matched track-hit pairs",trigName[kTrigType]));
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_BL_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_BL_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  list->Clear();
  TString legName[30];
  TH1F *hTrkDzInBL[30];
  Int_t counter = 0;
  for(Int_t i=0; i<30; i++)
    {
      hTrkDzInBL[i] = (TH1F*)hTrkDzVsBL->ProjectionY(Form("hDeltaZ_BL%d",i+1),i+1,i+1);
      if(hTrkDzInBL[i]->GetEntries()>0)
	{
	  legName[counter] = Form("Module %d",i+1);
	  hTrkDzInBL[i]->SetLineColor(color[counter]);
	  list->Add(hTrkDzInBL[i]);
	  counter ++;
	}
    }
  c = drawHistos(list,"TrkDzInBL",Form("%s: #Deltaz of matched track-hit pairs in backleg;#Deltaz (cm)",trigName[kTrigType]),kTRUE,-100,100,kTRUE,0,1.2*hTrkDzInBL[1]->GetMaximum(),kFALSE,kTRUE,legName,kTRUE,"",0.15,0.25,0.2,0.88,kFALSE,0.04,0.04,kFALSE,1,kTRUE,kFALSE);
  TLine *line = GetLine(0,0,0,1.1*hTrkDzInBL[1]->GetMaximum(),1);
  line->Draw();
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_BL_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_BL_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  // dz vs Mod
  TH2F *hTrkDzVsMod = (TH2F*)hn->Projection(1,4);
  c = draw2D(hTrkDzVsMod,Form("%s: #Deltaz of matched track-hit pairs",trigName[kTrigType]));
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_Mod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_vs_Mod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  TH1F *hMthMod = (TH1F*)hTrkDzVsMod->ProjectionX("hMthMod");
  hMthMod->Sumw2();
  hMthMod->Scale(1./hMthMod->Integral());
  TH2F *hMtdHitMap = (TH2F*)f->Get(Form("mhMtdHitMap_%s",trigName[kTrigType]));
  TH1F *htmp = (TH1F*)hMtdHitMap->ProjectionY("hHitMod_finebin");
  htmp->Rebin(12);
  TH1F *hMtdHitMod = new TH1F(Form("hMtdHitMod_%s",trigName[kTrigType]),"# of MTD hits per module;module",5,1,6);
  for(int i=0; i<hMtdHitMod->GetNbinsX(); i++)
    {
      hMtdHitMod->SetBinContent(i+1,htmp->GetBinContent(i+1));
      hMtdHitMod->SetBinError(i+1,htmp->GetBinError(i+1));
    }
  hMtdHitMod->Scale(1./hMtdHitMod->Integral());
  list->Clear();
  list->Add(hMthMod);
  list->Add(hMtdHitMod);
  TString legName3[2] = {"Matched good hits","All good hits"};
  c = drawHistos(list,"MtdHitMod",Form("%s: MTD hits per module;module;probability",trigName[kTrigType]),kFALSE,0,5,kTRUE,0,0.5,kFALSE,kTRUE,legName3,kTRUE,"",0.15,0.25,0.6,0.88,kTRUE);
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sCompMtdHitMod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sCompMtdHitMod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }

  list->Clear();
  TString legName2[5];
  TH1F *hTrkDzInMod[5];
  for(Int_t i=0; i<5; i++)
    {
      hTrkDzInMod[i] = (TH1F*)hTrkDzVsMod->ProjectionY(Form("hDeltaZ_Mod%d",i+1),i+1,i+1);
      legName2[i] = Form("Module %d",i+1);
      list->Add(hTrkDzInMod[i]);
    }
  c = drawHistos(list,"TrkDzInMod",Form("%s: #Deltaz of matched track-hit pairs in module;#Deltaz (cm)",trigName[kTrigType]),kTRUE,-100,100,kTRUE,0,1.2*hTrkDzInMod[3]->GetMaximum(),kFALSE,kTRUE,legName2,kTRUE,"",0.15,0.25,0.6,0.88,kTRUE);
  TLine *line = GetLine(0,0,0,hTrkDzInMod[3]->GetMaximum()*1.05,1);
  line->Draw();
  if(save) 
    {
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_Mod_%s.pdf",run_type,run_cfg_name.Data(),trigName[kTrigType]));
      c->SaveAs(Form("~/Work/STAR/analysis/Plots/%s/ana_Match/%sDeltaZ_in_Mod_%s.png",run_type,run_cfg_name.Data(),trigName[kTrigType]));
    }
}
Пример #9
0
TObjArray* get_mass_v_vars(RooDataSet* ds){
  //mass variable
  RooRealVar m( "Z_M", "Z_M", 60., 120. );
  //other variables needed to make dataset
  int nvars = 4;
  string vars[] = { "mup_eta", "mum_eta", "mup_phi", "mum_phi"};
  double los[]  = { 2.0, 2.0, -TMath::Pi(), -TMath::Pi() };
  double his[]  = { 4.5, 4.5, TMath::Pi(), TMath::Pi()   };
  int binss[]   = { 10, 10, 10, 10 };

  TObjArray* hists = new TObjArray();

  //fit_mass(ds, "", "");

  for (int i = 0 ; i < nvars ; ++i){
    string var = vars[i] ;
    double lo  = los[i]  ;
    double hi  = his[i]  ;
    int bins   = binss[i];
    vector<RooDataSet*> datasets   ;
    for (int i = 0 ; i < bins ; ++i) {
      ostringstream cut;
      double binlo = lo + i*((hi - lo)/bins);
      double binhi = lo + (i+1)*((hi-lo)/bins);
      cut  <<var<<">"<<binlo<<" && "<<var<<"<"<<binhi;
      //add dataset with specific cuts
      datasets.push_back((RooDataSet*)ds->reduce(cut.str().c_str()));
      
    }
    //make mass histogram
    TH1F* hist   = new TH1F(("mass_v_"+var+"_truth").c_str()   , ("mass_v_"+var+"_truth").c_str()   , bins, lo, hi);
    //calculate latex version of variable if possible
    string latexvar;
    if (var.find("eta") != std::string::npos) latexvar = "#eta";
    else if (var.find("phi") != std::string::npos ) latexvar = "#phi";
    else latexvar = var;
    for (int i = 0 ; i < bins ; ++i) {
      ostringstream s1;
      s1<<var<<"_truth_"<<i;
      double binlo = lo + i*((hi - lo)/bins);
      double binhi = lo + (i+1)*((hi-lo)/bins);
      //cut to be presented on plot
      ostringstream label;
      label<<binlo<<" < "<<latexvar<<" < "<<binhi;
      std::pair<double, double> result = fit_mass(datasets.at(i), s1.str(), label.str());
      hist->SetBinContent(i+1, result.first);
      hist->SetBinError(i+1, result.second);
    }
    
    TCanvas* canv = new TCanvas( "canv", "canv", 800.0, 600.0 );
    hist->SetXTitle(latexvar.c_str());
    hist->SetYTitle("Fitted Z0 Mass");
    hist->Draw("e1");
    canv->SaveAs(("mass_v_"+var+"_truth.pdf").c_str());

    hists->Add(hist);
  }

  return hists;

}
Пример #10
0
void unfold_2D(TString RR){

        bool CLOSURE_TEST = false;

        TString POSTFIX_corr = "";
        if (FEWZ_CORRECTED) POSTFIX_corr = "_corr";

        gROOT->ProcessLine(".L ../tools/plottools.C");
        gROOT->ProcessLine(".L ../tools/histotools.C");

        //SET UP ROO
        gSystem->Load("RooUnfold-1.1.1/libRooUnfold.so");

        //_inFile = new TFile("resMatrixProd.root");
        TString resRR = "";
        if (RR == "POWHEG") {
           CLOSURE_TEST = true;
           resRR = "_POWHEG";
        }
        _inFile = new TFile("../Inputs/unfold/resMatrixProd"+resRR+"_41.root");
        //
        //STEP0: GET HISTOGRAMS FROM THE PREVIOUS FILE
        //
        _inTrue = (TH1F*)_inFile->Get("htrue2"+POSTFIX_corr);
        _inMeasMC= (TH1F*)_inFile->Get("hmeas2"+POSTFIX_corr);
        if (USE_OVERFLOWS) {
          _inTrue24 = (TH1F*)_inFile->Get("htrue2_24"+POSTFIX_corr);
          _inMeasMC24= (TH1F*)_inFile->Get("hmeas2_24"+POSTFIX_corr);
          //_inTrue12 = (TH1F*)_inFile->Get("htrue2_12"+POSTFIX_corr);
          //_inMeasMC12= (TH1F*)_inFile->Get("hmeas2_12"+POSTFIX_corr);
        }
        if (USE_OVERFLOWS) _inEvMat = (TH2F*)_inFile->Get("hden2_156"+POSTFIX_corr);
        else _inEvMat = (TH2F*)_inFile->Get("hden2"+POSTFIX_corr); 
      
        TFile* _inData = new TFile("../Inputs/rawYield/DYspectrum_Rap.root");
        _inData->cd();
        if (USE_OVERFLOWS) sigNorm = (TH1F*)gDirectory->Get("hsig_fewz_r");
        else sigNorm = (TH1F*)gDirectory->Get("hsig_fewz");

        if (USE_OVERFLOWS) { 
          _inTrue = rebinWithOU1_2D(_inTrue,_inTrue24);
          _inMeasMC = rebinWithOU1_2D(_inMeasMC,_inMeasMC24);
        }  

        //SCALING PERFORMED ON A FINAL OU HISTO
        _inTrue->Scale(sigNorm->Integral()/_inTrue->Integral()); //73,96));
        _inMeasMC->Scale(sigNorm->Integral()/_inMeasMC->Integral());
        _inEvMat->Scale(sigNorm->Integral()/_inEvMat->Integral());

        normalizeToPeak(_inTrue,sigNorm);
        normalizeToPeak(_inMeasMC,sigNorm);
        normalizeToPeak2D(_inEvMat,sigNorm);

        _inMigMat = getMigMatrix(_inTrue,_inEvMat); //(TH2F*)_inFile->Get("migMatrix");
        //cout << "_inMigMat " << _inMigMat->GetBinContent(40,40) << " " << _inMigMat->GetBinContent(41,41) << endl;

        _inMeas = (TH1F*)_inMeasMC->Clone("inMeas");
        _inMeasData = (TH1F*)_inMeasMC->Clone("inMeas");

        _inResMat = (TH2F*)_inMigMat->Clone("resMatrix");

        _inMeas->Reset();

        //STEP1: subtract the bacgrkounds
        if (!CLOSURE_TEST) {
          //fill the raw yields to appropriate arrays 
	  std::vector<double> input_data;
	  std::vector<double> input_err;
          if (USE_OVERFLOWS) { 
             for (int i = 0; i < 156; i++) {
                 input_data.push_back(0.);
                 input_err.push_back(0.);
             }
          } else {
             for (int i = 0; i < 132; i++) {
                 input_data.push_back(0.);
                 input_err.push_back(0.);
             }
          }

          TFile* f = new TFile("../Inputs/rawYield/DYspectrum_Rap.root");
          f->cd(); 
          //main 132 bin histos
          TH1F* data, *qcd, *ttbar, *DYtautau, *ttbar_mc, *Wlepton, *diboson;
          TH1F* hdata, *hqcd, *httbar, *hDYtautau, *httbar_mc, *hWlepton, *hdiboson;
          //underflow
          TH1F* udata, *uqcd, *uttbar, *uDYtautau, *uttbar_mc, *uWlepton, *udiboson;
          //overflow
          //TH1F* odata, *oqcd, *ottbar, *oDYtautau, *ottbar_mc, *oWlepton, *odiboson;
          if (USE_OVERFLOWS && !DO_ROO) {
             data = (TH1F*)gDirectory->Get("hdata");
             udata = (TH1F*)hdata24->Clone();
             //odata = (TH1F*)hdata12->Clone();  
             hdata = rebinWithOU1_2D(data,udata);//,odata);
          } else {
             hdata = (TH1F*)gDirectory->Get("hdata");
          } 
          if (DATA_DRIVEN_BKG)  {
           qcd = (TH1F*)gDirectory->Get("hqcd");
           ttbar = (TH1F*)gDirectory->Get("httbar_mc");
           //case of OU 
           if (USE_OVERFLOWS && !DO_ROO) {
             uqcd = (TH1F*)hqcd24->Clone();
             uttbar = (TH1F*)httbar24->Clone();
             //oqcd = (TH1F*)hqcd12->Clone();
             //ottbar = (TH1F*)httbar12->Clone();
             hqcd = rebinWithOU1_2D(qcd,uqcd);//,oqcd);
             httbar = rebinWithOU1_2D(ttbar,uttbar);//,ottbar);
           } else {
             hqcd = (TH1F*)gDirectory->Get("hqcd");
             httbar = (TH1F*)gDirectory->Get("httbar_mc");
           }
          } else {
           DYtautau = (TH1F*)gDirectory->Get("hDYtautau");
           ttbar_mc = (TH1F*)gDirectory->Get("httbar_mc");
           Wlepton = (TH1F*)gDirectory->Get("hWlepton");
           diboson = (TH1F*)gDirectory->Get("hdiboson");
           //case of OU 
           if (USE_OVERFLOWS && !DO_ROO) {
             uDYtautau = (TH1F*)DYtautau24->Clone();
             uttbar_mc = (TH1F*)ttbar_mc24->Clone();
             uWlepton = (TH1F*)Wlepton24->Clone();
             udiboson = (TH1F*)diboson24->Clone();
             //oDYtautau =(TH1F*)DYtautau12->Clone();
             //ottbar_mc =(TH1F*)ttbar_mc12->Clone();
             //oWlepton =(TH1F*)Wlepton12->Clone();
             //odiboson =(TH1F*)diboson12->Clone();
             hDYtautau = rebinWithOU1_2D(DYtautau,DYtautau24);//,DYtautau12);
             httbar_mc= rebinWithOU1_2D(ttbar_mc,ttbar_mc24);//,ttbar_mc12);
             hWlepton= rebinWithOU1_2D(Wlepton,Wlepton24);//,Wlepton12);
             hdiboson=rebinWithOU1_2D(diboson,diboson24);//,diboson12);
           } else {
             hDYtautau = (TH1F*)gDirectory->Get("hDYtautau");
             httbar_mc = (TH1F*)gDirectory->Get("httbar_mc");
             hWlepton = (TH1F*)gDirectory->Get("hWlepton");
             hdiboson = (TH1F*)gDirectory->Get("hdiboson");
           }
          }

          if (USE_OVERFLOWS) nmass_bins = 7;
          for(int i = 0; i < nmass_bins; i++ ) {
            int nRapbins = 24;
            if(i == 5 && !USE_OVERFLOWS) nRapbins = 12;
            if(i == 6 && USE_OVERFLOWS) nRapbins = 12;
            for( int j = 0; j < nRapbins; j++ ) {
                //take data and subtract backgrounds
                double background = 0;
                double error = 0;
                //FIXME this assumes the data-driven error is proper in the file acessed
                if (DATA_DRIVEN_BKG) { 
                   background = (hqcd->GetBinContent(i*24+j+1)+httbar->GetBinContent(i*24+j+1));
                   error = sqrt(pow(hdata->GetBinError(i*24+j+1),2)+ pow(hqcd->GetBinError(i*24+j+1),2)+pow(httbar->GetBinError(i*24+j+1),2)); 
                } else { 
                   background = (hqcd->GetBinContent(i*24+j+1)+httbar_mc->GetBinContent(i*24+j+1)+hDYtautau->GetBinContent(i*24+j+1)+hWlepton->GetBinContent(i*24+j+1)+hdiboson->GetBinContent(i*24+j+1));
                   error = sqrt(pow(hdata->GetBinError(i*24+j+1),2)+ pow(hqcd->GetBinError(i*24+j+1),2)+pow(httbar_mc->GetBinError(i*24+j+1),2)+pow(hDYtautau->GetBinError(i*24+j+1),2)+pow(hWlepton->GetBinError(i*24+j+1),2)+pow(hdiboson->GetBinError(i*24+j+1),2));
                }
                input_data.at(i*24+j) = hdata->GetBinContent(i*24+j+1) - background;
                input_err.at(i*24+j) = error;
            }
          }

  	  int numbins = _inMeasData->GetNbinsX();
	  for( int ibin = 0; ibin < numbins; ibin++ ) {
	    //cout << "input(" << ibin << ") = " << input_data.at(ibin) << " " << input_err.at(ibin) << endl;
	    _inMeasData->SetBinContent(ibin+1, input_data.at(ibin));
	    _inMeasData->SetBinError(ibin+1, input_err.at(ibin));
	  }
	  _inMeasData->SetBinContent(0, 0);
	  _inMeasData->SetBinError(0, 0);
        } ////not closure test

        //
        //SET UP CANVAS TO DRAW
        //
        can = new TCanvas("can","can",800,600);
        gStyle->SetPalette(1);
        //can->SetLogy();
        //can->SetLogx();

        //
        //STEP2: SET UP THE UNFOLDER CLASS
        //   
        _unfolder = new Unfolder("badger");
        _unfolder->setTrue(_inTrue);
        if (!CLOSURE_TEST) {
          _inMeas->Add(_inMeasData);
          _unfolder->setMeas(_inMeas);
        } else {
          _unfolder->setMeas(_inMeasMC);
        }
        _unfolder->setMigrationMatrix(_inResMat);
        _unfolder->unfold();
        _unfolder->getUnfolded()->SetLineColor(kRed);//Draw();  
        _unfolder->getTrue()->Draw("hist");
        //_unfolder->getMeas()->Draw("hist");

        //_inMeas->Print("all");        

        //
        //STEP3: DO UNFOLDING
        //
        TH1F* crap;
        if (!DO_ROO) {
          crap = (TH1F*)_unfolder->getUnfolded();//->Clone("hunfolded");//Draw();       
          _htrue = (TH1F*)_unfolder->getTrue();

          //crap->Print("all"); 
        } else {
          if (!DO_BAYES) {
             RooUnfoldResponse response(_inMeasMC,_inTrue,_inEvMat); //_h2_tmp); //_inResMat);
          } else {
             RooUnfoldResponse response(_inMeasMC,_inTrue,_inResMat);
          }
          //if (USE_OVERFLOWS) response.UseOverflow();
          if (CLOSURE_TEST) {
             if (DO_BAYES) {
                RooUnfoldBayes unfoldBayes(&response, _inMeasMC, 1);
             } else {
                RooUnfoldSvd unfoldSVD(&response, _inMeasMC, 2);
             }
          } else  {
             if (DO_BAYES) {
                RooUnfoldBayes unfoldBayes(&response, _inMeasData, 1);
             } else {
                RooUnfoldSvd unfoldSVD(&response, _inMeasData, 2);
             }
          }
          if (DO_BAYES) {
              crap = (TH1F*) unfoldBayes.Hreco();
          } else {
              crap = (TH1F*) unfoldSVD.Hreco(); //analog of getUnfolded() in unfolder class
          }
        }

	for( int i = 0; i < nmass_bins; i++ ) {
          int nRapbins;
          if( i == nmass_bins-1 ) nRapbins = 12;
          else nRapbins = 24;
          for( int j = 0; j < nRapbins; j++ ) {
            double val = crap->GetBinContent(i*24+j+1);
            double err = sqrt(pow(crap->GetBinError(i*24+j+1),2));
	    crap->SetBinContent(24*i+j+1, val);
	    crap->SetBinError(24*i+j+1, err);
	  }
	}

        crap->SetMarkerStyle(20);
        crap->SetMarkerColor(kRed);
        crap->Draw("same");
        can->SaveAs("2D.png");

        TLegend* leg = MakeLegend();
        leg->AddEntry(_unfolder->getTrue(),"True","l");
        if (CLOSURE_TEST) {
          leg->AddEntry(crap,"Unfolded MC","lp");
        } else {
          leg->AddEntry(crap,"Unfolded","lp");
        }

        //
        //STEP4: ALL DONE SAVING OUTPUT
        //
        TH2F* invrseResMat = (TH2F*)_unfolder->matrixToHist(_unfolder->getMigMatInverse(),_inResMat);

	_outFile = new TFile("./rootfiles/unfoldData_HLT_Double_2D.root","recreate");
        _outFile->cd();
        invrseResMat->Write("inverse_Response");
        _inMeas->Write("hmeas");
        _inTrue->Write("htrue");
        crap->Write("hunfolded");
        _outFile->Write();


	return;		
	_unfolder->getMigMat()->Print();
	_unfolder->getMigMatInverse()->Print();

		
	_inTrue->Print("all");	
	

}
Пример #11
0
//void Plot(string observable = string ("NjetsNBjets_0_1.70"), string outname = string("TCHEL")){
void Plot2_main(string observable, string outname){
  
  /*
    gStyle->SetPadRightMargin(0.13);
    gStyle->SetPadLeftMargin(0.13);
    gStyle->SetPadBottomMargin(0.13);
  */
  
  
  float SF_trigger_error = 0.015;
  float SF_Lepton_error  = 0.010;
  float SF_MET_error     = 0.016;
  float SF_bag1_error     = 0.01;
  float SF_bag2_error     = 0.02;
 
  
  float systeError_VV     = 0.33;
  float systeError_stop   = 0.31;
  float systeError_ttbar  = 0.04;
  
  double frac_ee   = 0;
  double frac_mumu = 0;
  double frac_emu  = 0;
  
  
  float lumi_error=0.022;
  
  
  // For the canvas:
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0); // must be kWhite but I dunno how to do that in PyROOT
  gStyle->SetCanvasDefH(600); //Height of canvas
  gStyle->SetCanvasDefW(600); //Width of canvas
  gStyle->SetCanvasDefX(0);   //POsition on screen
  gStyle->SetCanvasDefY(0);
  
  
  // For the Pad:
  gStyle->SetPadBorderMode(0);
  // ROOT . gStyle . SetPadBorderSize(Width_t size = 1);
  gStyle->SetPadColor(0); // kWhite
  gStyle->SetPadGridX(0); //false
  gStyle->SetPadGridY(0); //false
  gStyle->SetGridColor(0);
  gStyle->SetGridStyle(3);
  gStyle->SetGridWidth(1);
  
  // For the frame:
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameBorderSize(1);
  gStyle->SetFrameFillColor(0);
  gStyle->SetFrameFillStyle(0);
  gStyle->SetFrameLineColor(1);
  gStyle->SetFrameLineStyle(1);
  gStyle->SetFrameLineWidth(1);
  
  // For the histo:
  // ROOT . gStyle . SetHistFillColor(1);
  // ROOT . gStyle . SetHistFillStyle(0);
  gStyle->SetHistLineColor(1);
  gStyle->SetHistLineStyle(0);
  gStyle->SetHistLineWidth(1);
  // ROOT . gStyle . SetLegoInnerR(Float_t rad = 0.5);
  // ROOT . gStyle . SetNumberContours(Int_t number = 20);
  
  gStyle->SetEndErrorSize(2);
  //ROOT . gStyle . SetErrorMarker(20);   /// I COMMENTED THIS OUT
  //ROOT . gStyle . SetErrorX(0.);
  
  //ROOT . gStyle . SetMarkerStyle(20);
  
  
  //For the fit/function:
  gStyle->SetOptFit(1011);
  gStyle->SetFitFormat("5.4g");
  gStyle->SetFuncColor(2);
  gStyle->SetFuncStyle(1);
  gStyle->SetFuncWidth(1);
  
  //For the date:
  gStyle->SetOptDate(0);
  // ROOT . gStyle . SetDateX(Float_t x = 0.01);
  // ROOT . gStyle . SetDateY(Float_t y = 0.01);
  
  // For the statistics box:
  gStyle->SetOptFile(0);
  gStyle->SetOptStat(0); // To display the mean and RMS:   SetOptStat("mr");
  gStyle->SetStatColor(0); // kWhite
  gStyle->SetStatFont(42);
  //ROOT . gStyle . SetStatFontSize(0.025);
  gStyle->SetStatFontSize(0.04);
  gStyle->SetStatTextColor(1);
  gStyle->SetStatFormat("6.4g");
  gStyle->SetStatBorderSize(1);
  gStyle->SetStatH(0.1);
  gStyle->SetStatW(0.15);
  // ROOT . gStyle . SetStatStyle(Style_t style = 1001);
  // ROOT . gStyle . SetStatX(Float_t x = 0);
  // ROOT . gStyle . SetStatY(Float_t y = 0);
  
  // Margins:
  gStyle->SetPadTopMargin(0.07);
  gStyle->SetPadBottomMargin(0.13);
  gStyle->SetPadLeftMargin(0.16);
  //ROOT . gStyle . SetPadRightMargin(0.12);
  gStyle->SetPadRightMargin(0.03);
  
  // For the Global title:
  
  gStyle->SetOptTitle(0);
  gStyle->SetTitleFont(42);
  gStyle->SetTitleColor(1);
  gStyle->SetTitleTextColor(1);
  gStyle->SetTitleFillColor(10);
  gStyle->SetTitleFontSize(0.05);
  // ROOT . gStyle . SetTitleH(0); // Set the height of the title box
  // ROOT . gStyle . SetTitleW(0); // Set the width of the title box
  // ROOT . gStyle . SetTitleX(0); // Set the position of the title box
  // ROOT . gStyle . SetTitleY(0.985); // Set the position of the title box
  // ROOT . gStyle . SetTitleStyle(Style_t style = 1001);
  // ROOT . gStyle . SetTitleBorderSize(2);
  
  // For the axis titles:
  
  gStyle->SetTitleColor(1, "XYZ");
  gStyle->SetTitleFont(42, "XYZ");
  gStyle->SetTitleSize(0.06, "XYZ");
  // ROOT . gStyle . SetTitleXSize(Float_t size = 0.02); // Another way to set the size?
  // ROOT . gStyle . SetTitleYSize(Float_t size = 0.02);
  gStyle->SetTitleXOffset(0.9);
  gStyle->SetTitleYOffset(1.25);
  // ROOT . gStyle . SetTitleOffset(1.1, "Y"); // Another way to set the Offset
  
  // For the axis labels:
  
  gStyle->SetLabelColor(1, "XYZ");
  gStyle->SetLabelFont(42, "XYZ");
  gStyle->SetLabelOffset(0.007, "XYZ");
  gStyle->SetLabelSize(0.05, "XYZ");
  
  // For the axis:
  
  gStyle->SetAxisColor(1, "XYZ");
  gStyle->SetStripDecimals(1); // kTRUE
  gStyle->SetTickLength(0.03, "XYZ");
  gStyle->SetNdivisions(510, "XYZ");
  gStyle->SetPadTickX(1);  // To get tick marks on the opposite side of the frame
  gStyle->SetPadTickY(1);
  
  // Change for log plots:
  gStyle->SetOptLogx(0);
  gStyle->SetOptLogy(0);
  gStyle->SetOptLogz(0);
  
  // Postscript options:
  gStyle->SetPaperSize(20.,20.);
  // ROOT . gStyle . SetLineScalePS(Float_t scale = 3);
  // ROOT . gStyle . SetLineStyleString(Int_t i, const char* text);
  // ROOT . gStyle . SetHeaderPS(const char* header);
  // ROOT . gStyle . SetTitlePS(const char* pstitle);
  
  // ROOT . gStyle . SetBarOffset(Float_t baroff = 0.5);
  // ROOT . gStyle . SetBarWidth(Float_t barwidth = 0.5);
  // ROOT . gStyle . SetPaintTextFormat(const char* format = "g");
  // ROOT . gStyle . SetPalette(Int_t ncolors = 0, Int_t* colors = 0);
  // ROOT . gStyle . SetTimeOffset(Double_t toffset);
  // ROOT . gStyle . SetHistMinimumZero(kTRUE);
  






  //TFile * file = new TFile("templates_proof_with_Wjets.root","OPEN");
  TFile * file = new TFile("outfile_Template.root","OPEN");
  cout<<"toto"<<endl;
  vector<pair<string,int> > process;
  process.push_back(pair<string,int>(string("TTbarSig"),kRed+1));
  process.push_back(pair<string,int>(string("TTbarBkg"),kRed-7));
  process.push_back(pair<string,int>(string("Wjets"),kGreen-3));
  process.push_back(pair<string,int>(string("VV"),13));
  process.push_back(pair<string,int>(string("StW"),kMagenta));
  process.push_back(pair<string,int>(string("Zjets"),kAzure-2));
  process.push_back(pair<string,int>(string("Data"),1));
  
  cout<<"toto"<<endl;
  vector<string> channels;
  channels.push_back(string("ee"));
  channels.push_back(string("emu"));
  channels.push_back(string("mumu"));
  
  cout<<"toto"<<endl;
  
  //string observable ("NjetsNBjets_0_1.70");
  
  cout<<"toto"<<endl;
  /*
    TH2F* histoEmpty = new TH2F("emtpy","",10,0,10,0,500);
    histoEmpty->GetXaxis()->SetTitle("(N_{jets},N_{b-tagged jets})");
    histoEmpty->GetYaxis()->SetTitle("Events");
    histoEmpty->Draw("");
  */
  
  
  TCanvas *c1 = new TCanvas("c1","c1", 1000, 800);
  c1->SetBottomMargin(0.3);
  c1->cd();
  
  
  
  
  TH1D* histo1D_ttSig = new TH1D("histo_ttSig","",11, 0, 11);
  TH1D* histo1D_ttBkg = new TH1D("histo_ttBkg","",11, 0, 11);
  TH1D* histo1D_VV    = new TH1D("histo_VV",   "",11, 0, 11);
  TH1D* histo1D_tW    = new TH1D("histo_tW",   "",11, 0, 11);
  TH1D* histo1D_DY    = new TH1D("histo_DY",   "",11, 0, 11);
  TH1D* histo1D_Data  = new TH1D("histo_Data", "",11, 0, 11);
  
  
  
 
   
  
  //******************************
  //get histograms
  //******************************
  
  
  string name = "ee_NjetsNBjets_6_0.244_TTbarSig";
  TH2D* histo2D_ee_ttSig = (TH2D*) file->Get(name.c_str()); 
  name = "ee_NjetsNBjets_6_0.244_TTbarBkg"; 
  TH2D* histo2D_ee_ttBkg = (TH2D*) file->Get(name.c_str()); 
  name = "ee_NjetsNBjets_6_0.244_VV"; 
  TH2D* histo2D_ee_VV = (TH2D*) file->Get(name.c_str()); 
  name = "ee_NjetsNBjets_6_0.244_StW"; 
  TH2D* histo2D_ee_tW = (TH2D*) file->Get(name.c_str()); 
  name = "ee_NjetsNBjets_6_0.244_Zjets"; 
  TH2D* histo2D_ee_Zjets = (TH2D*) file->Get(name.c_str()); 
  name = "ee_NjetsNBjets_6_0.244_Data"; 
  TH2D* histo2D_ee_Data = (TH2D*) file->Get(name.c_str()); 
  
  
  name = "mumu_NjetsNBjets_6_0.244_TTbarSig";
  TH2D* histo2D_mumu_ttSig = (TH2D*) file->Get(name.c_str()); 
  name = "mumu_NjetsNBjets_6_0.244_TTbarBkg"; 
  TH2D* histo2D_mumu_ttBkg = (TH2D*) file->Get(name.c_str()); 
  name = "mumu_NjetsNBjets_6_0.244_VV"; 
  TH2D* histo2D_mumu_VV = (TH2D*) file->Get(name.c_str()); 
  name = "mumu_NjetsNBjets_6_0.244_StW"; 
  TH2D* histo2D_mumu_tW = (TH2D*) file->Get(name.c_str()); 
  name = "mumu_NjetsNBjets_6_0.244_Zjets"; 
  TH2D* histo2D_mumu_Zjets = (TH2D*) file->Get(name.c_str()); 
  name = "mumu_NjetsNBjets_6_0.244_Data"; 
  TH2D* histo2D_mumu_Data = (TH2D*) file->Get(name.c_str()); 
  
  
  name = "emu_NjetsNBjets_6_0.244_TTbarSig";
  TH2D* histo2D_emu_ttSig = (TH2D*) file->Get(name.c_str()); 
  name = "emu_NjetsNBjets_6_0.244_TTbarBkg"; 
  TH2D* histo2D_emu_ttBkg = (TH2D*) file->Get(name.c_str()); 
  name = "emu_NjetsNBjets_6_0.244_VV"; 
  TH2D* histo2D_emu_VV = (TH2D*) file->Get(name.c_str()); 
  name = "emu_NjetsNBjets_6_0.244_StW"; 
  TH2D* histo2D_emu_tW = (TH2D*) file->Get(name.c_str()); 
  name = "emu_NjetsNBjets_6_0.244_Zjets"; 
  TH2D* histo2D_emu_Zjets = (TH2D*) file->Get(name.c_str()); 
  name = "emu_NjetsNBjets_6_0.244_Data"; 
  TH2D* histo2D_emu_Data = (TH2D*) file->Get(name.c_str()); 
 
 
  
  
  histo2D_ee_Zjets->Scale(220./histo2D_ee_Zjets->Integral());
  histo2D_emu_Zjets->Scale(136./histo2D_emu_Zjets->Integral());
  histo2D_mumu_Zjets->Scale(217./histo2D_mumu_Zjets->Integral());


  histo2D_ee_ttBkg->Scale(9./histo2D_ee_ttBkg->Integral());
  histo2D_emu_ttBkg->Scale(86./histo2D_emu_ttBkg->Integral());
  histo2D_mumu_ttBkg->Scale(15./histo2D_mumu_ttBkg->Integral());
 
 
  histo2D_ee_ttSig->Scale(1.44);
  histo2D_ee_VV->Scale(1.044);
  histo2D_ee_tW->Scale(1.044);
 
  histo2D_emu_ttSig->Scale(1.044);
  histo2D_emu_VV->Scale(1.044);
  histo2D_emu_tW->Scale(1.044);
 
  histo2D_mumu_ttSig->Scale(1.044);
  histo2D_mumu_VV->Scale(1.044);
  histo2D_mumu_tW->Scale(1.044);
  
  
  frac_ee  += histo2D_ee_Zjets->Integral();
  frac_mumu+= histo2D_emu_Zjets->Integral(); 
  frac_emu += histo2D_mumu_Zjets->Integral();
  
  
  frac_ee   = frac_ee/(  frac_ee+frac_mumu+frac_emu);
  frac_mumu = frac_mumu/(frac_ee+frac_mumu+frac_emu);
  frac_emu  = frac_emu/( frac_ee+frac_mumu+frac_emu);
  
  
  
  
  histo2D_ee_ttSig->Add( histo2D_ee_ttSig, histo2D_mumu_ttSig, 1, 1);
  histo2D_ee_ttSig->Add( histo2D_ee_ttSig, histo2D_emu_ttSig, 1, 1);
  
  histo2D_ee_ttBkg->Add( histo2D_ee_ttBkg, histo2D_mumu_ttBkg, 1, 1);
  histo2D_ee_ttBkg->Add( histo2D_ee_ttBkg, histo2D_emu_ttBkg  , 1, 1);
  
  histo2D_ee_Zjets->Add( histo2D_ee_Zjets, histo2D_mumu_Zjets, 1, 1);
  histo2D_ee_Zjets->Add( histo2D_ee_Zjets, histo2D_emu_Zjets  , 1, 1);
  
  histo2D_ee_VV->Add( histo2D_ee_VV, histo2D_mumu_VV, 1, 1);
  histo2D_ee_VV->Add( histo2D_ee_VV, histo2D_emu_VV  , 1, 1);
  
  histo2D_ee_tW->Add( histo2D_ee_tW, histo2D_mumu_tW, 1, 1);
  histo2D_ee_tW->Add( histo2D_ee_tW, histo2D_emu_tW  , 1, 1);
  
  histo2D_ee_Data->Add( histo2D_ee_Data, histo2D_mumu_Data, 1, 1);
  histo2D_ee_Data->Add( histo2D_ee_Data, histo2D_emu_Data  , 1, 1);
  
  
  
  
  
  //******************************
  //create 1D histograms
  //******************************
  
  
  TH1D* histo1D = new TH1D("histo","",11,0,11);
  histo1D->GetXaxis()->SetBinLabel(1,string("(2,0)").c_str());
  histo1D->GetXaxis()->SetBinLabel(2,string("(2,1)").c_str());
  histo1D->GetXaxis()->SetBinLabel(3,string("(2,2)").c_str());
  histo1D->GetXaxis()->SetBinLabel(4,string("(3,0)").c_str());
  histo1D->GetXaxis()->SetBinLabel(5,string("(3,1)").c_str());
  histo1D->GetXaxis()->SetBinLabel(6,string("(3,2)").c_str());
  histo1D->GetXaxis()->SetBinLabel(7,string("(3,3)").c_str());
  histo1D->GetXaxis()->SetBinLabel(8,string("(#geq4,0)").c_str());
  histo1D->GetXaxis()->SetBinLabel(9,string("(#geq4,1)").c_str());
  histo1D->GetXaxis()->SetBinLabel(10,string("(#geq4,2)").c_str());
  histo1D->GetXaxis()->SetBinLabel(11,string("(#geq4,#geq3)").c_str());
  //histo1D->SetLineColor(0);
  histo1D->GetXaxis()->SetTitle("(N_{jets},N_{btagjets})");
  histo1D->GetYaxis()->SetTitle("Number of Events");
  histo1D->GetYaxis()->SetRangeUser(0.,2500.);
    
  histo1D_Data->GetXaxis()->SetBinLabel(1,string("(2,0)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(2,string("(2,1)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(3,string("(2,2)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(4,string("(3,0)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(5,string("(3,1)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(6,string("(3,2)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(7,string("(3,3)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(8,string("(#geq4,0)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(9,string("(#geq4,1)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(10,string("(#geq4,2)").c_str());
  histo1D_Data->GetXaxis()->SetBinLabel(11,string("(#geq4,#geq3)").c_str());
  //histo1D->SetLineColor(0);
  histo1D_Data->GetXaxis()->SetTitle("(N_{jets},N_{btagjets})");
  histo1D_Data->GetYaxis()->SetTitle("Number of Events");
  histo1D_Data->GetYaxis()->SetRangeUser(0.,2500.);
    
    
    
  for(int ibin = 3; ibin <6; ibin++){
	int max = 4;
	if(ibin>3) max = 5;
	for(int jbin = 1; jbin<max;jbin++){
	  double bin1D = (ibin-3)*3+jbin;
	  histo1D_ttSig->SetBinContent(bin1D, histo2D_ee_ttSig->GetBinContent(ibin,jbin));
	  histo1D_ttBkg->SetBinContent(   bin1D, histo2D_ee_ttBkg->GetBinContent(ibin,jbin)   );
	  histo1D_VV->SetBinContent(      bin1D, histo2D_ee_VV->GetBinContent(ibin,jbin)      );
	  histo1D_tW->SetBinContent(      bin1D, histo2D_ee_tW->GetBinContent(ibin,jbin)      );
	  histo1D_DY->SetBinContent(      bin1D, histo2D_ee_Zjets->GetBinContent(ibin,jbin)   );
	  histo1D_Data->SetBinContent(    bin1D, histo2D_ee_Data->GetBinContent(ibin,jbin)    );
	}
   }
  
  
  //******************************
  //add histograms
  //******************************
  
  /*
  histo1D_ee_TTbarSig->Add(histo1D_ee_TTbarSig, histo1D_mumu_TTbarSig, 1, 1);
  histo1D_ee_TTbarSig->Add(histo1D_ee_TTbarSig, histo1D_emu_TTbarSig, 1, 1);
  
  histo1D_ee_ttBk->Add(histo1D_ee_ttBkg, histo1D_mumu_ttBkg, 1, 1);
  histo1D_ee_ttBk->Add(histo1D_ee_ttBkg, histo1D_emu_ttBkg, 1, 1);
  
  histo1D_ee_VV->Add(histo1D_ee_VV, histo1D_mumu_VV, 1, 1);
  histo1D_ee_VV->Add(histo1D_ee_VV, histo1D_emu_VV, 1, 1);
  
  histo1D_ee_tW->Add(histo1D_ee_tW, histo1D_mumu_tW, 1, 1);
  histo1D_ee_tW->Add(histo1D_ee_tW, histo1D_emu_tW, 1, 1);
  
  histo1D_ee_DY->Add(histo1D_ee_DY, histo1D_mumu_DY, 1, 1);
  histo1D_ee_DY->Add(histo1D_ee_DY, histo1D_emu_DY, 1, 1);
  
  histo1D_ee_Data->Add(histo1D_ee_Data, histo1D_mumu_Data, 1, 1);
  histo1D_ee_Data->Add(histo1D_ee_Data, histo1D_emu_Data, 1, 1);
  */
  
  TH1D* histo1D_mc = (TH1D*) histo1D_ttSig->Clone();
  histo1D_mc->Add(histo1D_mc, histo1D_ttBkg ,1, 1);
  histo1D_mc->Add(histo1D_mc, histo1D_VV ,1, 1);
  histo1D_mc->Add(histo1D_mc, histo1D_tW ,1, 1);
  histo1D_mc->Add(histo1D_mc, histo1D_DY ,1, 1);
  
  TH1F * lumiband = (TH1F*) histo1D_mc->Clone();
  
  for (int ilum=0; ilum<lumiband->GetNbinsX(); ilum++) {    
	  
	  
	  
	  
	  
	  double error_all = 
       pow( histo1D_ttSig->GetBinContent(ilum+1)*lumi_error, 2)+
       //*************************
       //uncertinty on trigger eff
       pow(histo1D_ttSig->GetBinContent(ilum+1)*SF_trigger_error, 2)+
       //*************************
       //uncertinty on lepton sel
       pow(histo1D_ttSig->GetBinContent(ilum+1)*SF_Lepton_error, 2)+
       //*************************
       //uncertinty on met sel
       pow( histo1D_ttSig->GetBinContent(ilum+1)*SF_MET_error, 2);
     
       error_all += pow(histo1D_ttSig->GetBinContent(ilum+1)*systeError_ttbar, 2);   
       if(ilum > 2) error_all += pow(histo1D_ttSig->GetBinContent(ilum+1)*0.01, 2);    
       if(ilum > 6) error_all += pow(histo1D_ttSig->GetBinContent(ilum+1)*0.02, 2);   
       error_all += pow(histo1D_VV->GetBinContent(ilum+1)*systeError_VV, 2);
       error_all += pow(histo1D_tW->GetBinContent(ilum+1)*systeError_stop, 2);
     
        
       //*************************
       //uncertinty on met sel
       if(ilum < 5) pow( histo1D_ttSig->GetBinContent(ilum+1)*0.02, 2);
       if(ilum >= 5 && ilum < 8) pow( histo1D_ttSig->GetBinContent(ilum+1)*0.03, 2);
       if(ilum >= 8)             pow( histo1D_ttSig->GetBinContent(ilum+1)*0.04, 2);
	  
	
	    
	    //frac_ee   = frac_ee/  (frac_ee+frac_mumu+frac_emu);
	    //frac_mumu = frac_mumu/(frac_ee+frac_mumu+frac_emu);
	    //frac_emu  = frac_emu/ (frac_ee+frac_mumu+frac_emu);
	    
	    //cout << "frac_ee   " << frac_ee << endl;
	    //cout << "frac_mumu " << frac_mumu << endl;
	    //cout << "frac_emu  " << frac_emu << endl;
	    
	   error_all += pow(histo1D_DY->GetBinContent(ilum+1)*((0.40/1.9281)*frac_ee + (0.37/1.82219)*frac_mumu+  (0.30/1.38872)*frac_emu), 2);
	   
     lumiband->SetBinError(ilum+1,sqrt(error_all));
     
     //modifications
     histo1D_mc->SetBinError(ilum+1,sqrt(error_all));
  }
  
  
  TGraphErrors *thegraph = new TGraphErrors(lumiband);
  thegraph->SetFillStyle(3005);
  thegraph->SetFillColor(1);
  
  histo1D_ttSig->SetFillStyle(1001);
  histo1D_ttBkg->SetFillStyle(1001);
  histo1D_DY->SetFillStyle(1001);
  histo1D_VV->SetFillStyle(1001);
  histo1D_tW->SetFillStyle(1001);
    
  histo1D_ttSig->SetFillColor(kRed+1);
  histo1D_ttBkg->SetFillColor(kRed-7);
  histo1D_DY->SetFillColor(kAzure-2);
  histo1D_VV->SetFillColor(13);
  histo1D_tW->SetFillColor(kMagenta);
  
  
  histo1D_ttSig->GetYaxis()->CenterTitle();
  histo1D_ttSig->GetYaxis()->SetTitle("");
  histo1D_ttSig->GetXaxis()->SetLabelSize(0);
  histo1D_ttSig->GetXaxis()->SetTitleSize(0);
  
  histo1D_ttBkg->GetYaxis()->CenterTitle();
  histo1D_ttBkg->GetYaxis()->SetTitle("");
  histo1D_ttBkg->GetXaxis()->SetLabelSize(0);
  histo1D_ttBkg->GetXaxis()->SetTitleSize(0);
  
  histo1D_VV->GetYaxis()->CenterTitle();
  histo1D_VV->GetYaxis()->SetTitle("");
  histo1D_VV->GetXaxis()->SetLabelSize(0);
  histo1D_VV->GetXaxis()->SetTitleSize(0);
  
  histo1D_tW->GetYaxis()->CenterTitle();
  histo1D_tW->GetYaxis()->SetTitle("");
  histo1D_tW->GetXaxis()->SetLabelSize(0);
  histo1D_tW->GetXaxis()->SetTitleSize(0);
  
  histo1D_DY->GetYaxis()->CenterTitle();
  histo1D_DY->GetYaxis()->SetTitle("");
  histo1D_DY->GetXaxis()->SetLabelSize(0);
  histo1D_DY->GetXaxis()->SetTitleSize(0);
  
  
  THStack* hs= new THStack();
  hs->Add(histo1D_ttSig);
  hs->Add(histo1D_ttBkg);
  //hs->Add(histo_Wjets);
  hs->Add(histo1D_VV);
  hs->Add(histo1D_tW);
  hs->Add(histo1D_DY);
  
  for (int ibin=0; ibin<lumiband->GetNbinsX(); ibin++) {    
    //hs->GetXaxis()->SetBinLabel(ibin+1, "");
  }
  
  //hs->GetXaxis()->SetLabelSize(0.);
      
  histo1D_Data->GetXaxis()->SetTitle("");
  histo1D_Data->GetYaxis()->SetTitle("");
  histo1D_Data->GetYaxis()->CenterTitle();
  histo1D_Data->GetYaxis()->SetTitle("");
  histo1D_Data->GetXaxis()->SetLabelSize(0);
  histo1D_Data->GetXaxis()->SetTitleSize(0);
  histo1D_Data->SetMarkerStyle(20);
  
  
  histo1D->SetMaximum(2000);
  histo1D->SetMinimum(0);
  
  hs->SetMaximum(2000);
  
  
  TH1D* histo_ratio = (TH1D*) histo1D_Data->Clone();
  
  
  histo1D_Data->GetYaxis()->CenterTitle();
  histo1D_Data->GetYaxis()->SetTitle("");
  histo1D_Data->GetXaxis()->SetLabelSize(0);
  histo1D_Data->GetXaxis()->SetTitleSize(0);
  
  
  
  /*histo1D_mc- >GetYaxis()->CenterTitle();
  histo1D_mc->GetYaxis()->SetTitle("");
  histo1D_mc->GetXaxis()->SetLabelSize(0);
  histo1D_mc->GetXaxis()->SetTitleSize(0);
  */
  histo1D->GetYaxis()->CenterTitle();
  histo1D->GetYaxis()->SetTitle("");
  histo1D->GetXaxis()->SetLabelSize(0);
  histo1D->GetXaxis()->SetTitleSize(0);
  
  
  histo_ratio->GetYaxis()->SetLabelSize(0.1);histo_ratio->GetYaxis()->SetLabelSize(0.1);
  
  histo1D->Draw();
  hs->Draw();
  
  for (int ibin=0; ibin<lumiband->GetNbinsX(); ibin++) {    
    hs->GetXaxis()->SetBinLabel(ibin+1, "");
  }
  
  hs->GetXaxis()->SetLabelSize(0.0);
  hs->GetYaxis()->SetLabelSize(0.04);
  
  
  histo_ratio->GetYaxis()->SetLabelSize(0.1);
  histo1D->Draw("epsame");
  histo1D_Data->SetMarkerSize(1.2);
  histo1D_Data->Draw("epsame");
  //histo1D_Data->Draw("");
  
  thegraph->Draw("e2same");
  histo1D->Draw("same");
  
  
  TLatex *latex = new TLatex();
  latex->SetNDC();
  latex->SetTextSize(0.04);
  latex->SetTextAlign(31); 
  latex->DrawLatex(0.45, 0.95, " ");
  
  
  
  TLatex *latex2 = new TLatex();
  latex2->SetNDC();
  latex2->SetTextSize(0.04);
  latex2->SetTextAlign(31); 
  latex2->DrawLatex(0.87, 0.95, "CMS 2.3 fb^{-1} at #sqrt{s} = 7 TeV");
  
  TString  info_data = "ee, #mu#mu, e#mu channels";
 
  TLatex* text2 = new TLatex(0.45,0.98, info_data);
  text2->SetNDC();
  text2->SetTextAlign(13);
  text2->SetX(0.18);
  text2->SetY(0.92);
  //text2->SetLineWidth(2);
  text2->SetTextFont(42);
  text2->SetTextSize(0.0610687);
  //    text2->SetTextSizePixels(24);// dflt=28
  text2->Draw();

  
  
  
  TLegend* qw = new TLegend(.80,.60,.95,.90);
  
  
  qw->SetShadowColor(0);
  qw->SetFillColor(0);
  qw->SetLineColor(0);
  
  
  //  qw->SetHeader("CMS Preliminary, 881.8 pb^{-1}");
  //  qw->AddEntry(histo_Data,         info_data,                "p");
  qw->AddEntry(histo1D_Data,         "Data" ,                "ep");
  qw->AddEntry(histo1D_DY,        "DY "                  ,"f");
  qw->AddEntry(histo1D_tW,  "tW "                  ,"f");
  qw->AddEntry(histo1D_VV,           "VV "                  ,"f");
  //qw->AddEntry(histo_Wjets,        "W  "                  ,"f");
  //qw->AddEntry(histo_TTbarBkg,     "t#bar{t} other  "     ,"f");
  qw->AddEntry(histo1D_ttBkg,     "non-prompt lepton  "     ,"f");
  qw->AddEntry(histo1D_ttSig,     "t#bar{t} signal "     ,"f");
  qw->SetFillColor(0);
  qw->SetTextFont(42);
  qw->Draw();

  
  
  
  
  
  TPad *canvas_2 = new TPad("canvas_2", "canvas_2", 0.0, 0.0, 1.0, 1.0);
    canvas_2->SetTopMargin(0.7);
    canvas_2->SetFillColor(0);
    canvas_2->SetFillStyle(0);
    canvas_2->SetGridy(1);
    canvas_2->Draw();
    canvas_2->cd(0);
    //gPad->SetBottomMargin(0.375);
    //gPad->SetGridy();
    
    //cout << " 721 histo_ratio->GetTitle()  " << histo_ratio->GetXaxis()->GetTitle() << endl;;
    
    //TH1D* histo_ratio = (TH1D*) histo1D_Data->Clone();
    histo_ratio->SetTitle("");
   
    histo_ratio->SetMarkerStyle(20);
    histo_ratio->SetMarkerSize(1.2);
    histo_ratio->SetMaximum( 1.5 );
    histo_ratio->SetMinimum(0.5);
    histo_ratio->GetYaxis()->SetTitle("");
    histo_ratio->GetXaxis()->SetLabelSize(0.04);
    histo_ratio->GetYaxis()->SetLabelSize(0.03);
    histo_ratio->GetYaxis()->SetNdivisions(6);
    
    histo_ratio->GetYaxis()->SetTitleSize(0.03);
    histo_ratio->SetMarkerSize(1.2);
    //histo_ratio->GetYaxis()->SetNdivisions(5);
    //ratio.Draw("e")
    
    histo_ratio->Divide(histo1D_mc);
    
    
    histo_ratio->SetMinimum(0.5);
    histo_ratio->SetMaximum(1.5);
    histo_ratio->Draw("E1X0");
    

    c1->cd();
   
  

}
Пример #12
0
void AnalysisBase::findCutoutRegion(TH2F* h){

  cout << "===============================================================" << endl;
  cout << "findCutoutRegion(): Looking for cutout region in D type sensor " << endl;
  cout << "===============================================================" << endl;


  int ilx = h->GetXaxis()->FindBin(xMin) + 1;
  int ihx = h->GetXaxis()->FindBin(xMax) - 1;
  int ily = 1;//h->GetYaxis()->GetBinFindBin(yMin) - 10;
  int ihy = h->GetYaxis()->FindBin(yMax) + 10;
  if(ily < 0) ily = 0;
  if(ihy > h->GetYaxis()->GetNbins()) ihy = h->GetYaxis()->GetNbins();  
  int nb = h->GetXaxis()->GetNbins(); 

  double xlow = h->GetXaxis()->GetBinLowEdge(1);
  double xhi = h->GetXaxis()->GetBinLowEdge(nb)+h->GetXaxis()->GetBinWidth(1);

  TH1F *hpr = new TH1F("hpr","Y vs X, edge",nb,xlow,xhi);

  TH1D *hpy;
  int ipeak = 0;
  for(int i=ilx; i<ihx-1; i++){
    hpy = h->ProjectionY("hpy",i,i);
    double maxcon  = 0.0;
    double maxbin  = 0.0;
    for(int j=ily;j<ihy;j++){
      maxcon = maxcon + hpy->GetBinContent(j);
      if(hpy->GetBinContent(j) > maxbin) {
        maxbin = hpy->GetBinContent(j) ;
        ipeak = j;
      }
    }
    // Find the lower "edge"
    for(int j=ipeak; j>=ily; j--){
      double r0 = (hpy->GetBinContent(j-1)+hpy->GetBinContent(j-2))/2.0;
      double r1 = hpy->GetBinContent(j);
      double r2 = (hpy->GetBinContent(j+3)+hpy->GetBinContent(j+4))/2.0;
      if(r1<=2 && r0<=1.5 && r2>5*r1 && r2>8){
        hpr->SetBinContent(i,hpy->GetBinCenter(j)+2*hpy->GetBinWidth(j));
        hpr->SetBinError(i,hpy->GetBinWidth(1)/2.0);
        //cout << "found: " << i << " " << hpy->GetEntries() << " " << hpy->GetBinCenter(j) << " " 
        //     << hpy->GetBinContent(j) << " " << r0 << " " << r1 << " " << r2 << " " << endl;
        break;
      }
    }
    
  }

  TF1* poly2 = new TF1("poly2","[0]+[1]*x+[2]*x*x",xMin,xMax);
  poly2->SetParameters(-1.5,-0.17,-0.15);
  hpr->Fit(poly2,"R0");
  hpr->SetLineColor(kRed);

  holeQuadPar[0] = poly2->GetParameter(0);
  holeQuadPar[1] = poly2->GetParameter(1);
  holeQuadPar[2] = poly2->GetParameter(2);

  //return;
  

  delete poly2;
  delete hpr;
  delete hpy;
  
  return;
}
Пример #13
0
void RAA_dataDrivenUnfoldingErrorCheck_new(int radius = 3, bool isATLASCut = true)
{

  TStopwatch timer; 
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  bool printDebug = true;
  bool dofakeremove = false;
  bool do10GeVBins = true;

  char * scale = (char*)"NeqScale";
  // 944Scale
  // NeqScale
  // NeqScalePerCent
  
  int unfoldingCut = 20;
  char * outLocation = (char*) "July20/";
  if(isATLASCut) outLocation = (char*)"July20/ATLASCut/";
  
  // get the data and mc histograms from the output of the read macro. 
  
  TDatime date;//this is just here to get them to run optimized. 

  // Pawan's files:
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_muMaxOverSumcandMaxLT0p975_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_MC_subid0_spectra_JetID_CutA_trkMaxOverpfptGT0p02_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_noPrescl_MC_subid0_spectra_JetID_CutA_finebins_%s_R0p%d.root", etaWidth, radius));
  //TFile * fPbPb_in = TFile::Open(Form("Pawan_TTree_PbPb_Data_noPrescl_MC_subid0_spectra_JetID_CutA_7GeVTrackCut_finebinscut_%s_R0p%d.root", etaWidth, radius));
  // get the files to perform MC closure from the fixed ntuples
  TFile * fPbPb_in, *fMinBias, *fPbPb_MC_in, * fTrig;
  
  if(isATLASCut) fPbPb_in    = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_histograms_FromForest_trkMax7OrNeMax8GeVCut_akPu%d_20_eta_20.root",radius),"r");
  if(!isATLASCut) fPbPb_in    = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_histograms_FromForest_akPu%d_20_eta_20.root",radius),"r");
  if(isATLASCut) fMinBias    = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MB_Data_histograms_FromForest_trkMax7OrNeMax8GeVCut_fix_pt15GeVCut_akPu%d_20_eta_20.root",radius));
  if(!isATLASCut) fMinBias    = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MB_Data_histograms_FromForest_fix_pt15GeVCut_akPu%d_20_eta_20.root",radius));
  //TFile * fPbPb_MC_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_pthat50andabove_akPu%d_20_eta_20.root",radius));
  if(isATLASCut) fPbPb_MC_in = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_trkMax7OrNeMax8GeVCut_akPu%d_20_eta_20.root",radius),"r");
  if(!isATLASCut) fPbPb_MC_in = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_MC_histograms_FromForest_akPu%d_20_eta_20.root",radius),"r");
  TFile * fPP_in      = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_Data_histograms_FromForest_ak%d_20_eta_20.root",radius),"r");
  TFile * fPP_MC_in   = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_MC_histograms_FromForest_ak%d_20_eta_20.root",radius),"r");
  if(isATLASCut) fTrig       = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_nofkSub_trkMax7OrNeMax8GeVCut_new_MC_turnonCurves_R%d_20_eta_20_20150715.root",radius),"r");
  if(!isATLASCut) fTrig       = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/PbPb_Data_nofkSub_new_MC_turnonCurves_R%d_20_eta_20_20150715.root",radius),"r");
  TFile * fTrig_pp = new TFile(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/Jun29/pp_MC_turnonCurves_R%d_20_eta_20_20150702.root", radius),"r");
  // TFile * fPPMCTrig = new TFile(Form("PP_Data_MC_turnonCurves_R%d_20_eta_20_20150618.root",radius),"r");

  TH1F * hMC_turnon[nbins_cent+1], * hData_turnon[nbins_cent+1];
  cout<<"after input file declaration"<<endl;
  
  
  // histogram declarations with the following initial appendage: d - Data, m - MC, u- Unfolded
  // for the MC closure test, ive kept separate 

  TH1F *dPbPb_TrgComb[nbins_cent+1], *dPbPb_TrgCombInput[nbins_cent+1], *dPbPb_Comb[nbins_cent+1], *dPbPb_Trg80[nbins_cent+1], *dPbPb_Trg65[nbins_cent+1], *dPbPb_Trg55[nbins_cent+1], *dPbPb_1[nbins_cent+1], *dPbPb_2[nbins_cent+1], *dPbPb_3[nbins_cent+1], *dPbPb_80[nbins_cent+1], *dPbPb_65[nbins_cent+1], *dPbPb_55[nbins_cent+1];
  
  TH1F *mPbPb_GenInput[nbins_cent+1], *mPbPb_RecoInput[nbins_cent+1];
  TH1F *mPbPb_Gen[nbins_cent+1], *mPbPb_Reco[nbins_cent+1];
  TH2F *mPbPb_Matrix[nbins_cent+1], * mPbPb_MatrixInput[nbins_cent+1], *mPbPb_Response[nbins_cent+1], *mPbPb_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_data[nbins_cent+1];
  TH2F *mPbPb_mcclosure_Matrix[nbins_cent+1],*mPbPb_mcclosure_Response[nbins_cent+1], *mPbPb_mcclosure_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_gen[nbins_cent+1];
  const int Iterations = 20; //for unfolding systematics. 
  const int BayesIter = 4;
  TH1F *uPbPb_Bayes[nbins_cent+1], *uPbPb_BinByBin[nbins_cent+1], *uPbPb_SVD[nbins_cent+1]; 
  TH1F *uPbPb_BayesianIter[nbins_cent+1][Iterations];
  TH1F *dPbPb_MinBias[nbins_cent];
  TH1F *hMinBias[nbins_cent];
  
  TH1F *dPP_1, *dPP_2, *dPP_3, *dPP_Comb, * dPP_CombInput;
  TH1F *mPP_Gen, *mPP_Reco, *mPP_GenInput, *mPP_RecoInput;
  TH2F *mPP_Matrix, *mPP_MatrixInput, *mPP_Response,*mPP_ResponseNorm;
  TH1F *mPP_mcclosure_data;
  TH2F *mPP_mcclosure_Matrix, *mPP_mcclosure_Response,*mPP_mcclosure_ResponseNorm;
  TH1F *mPP_mcclosure_Gen;
  TH1F *uPP_Bayes, *uPP_BinByBin, *uPP_SVD;
  TH1F *uPP_BayesianIter[Iterations];

  TH1F * hData_FaketoSub_fullbin[nbins_cent+1];
  
  // would be better to read in the histograms and rebin them. come to think of it, it would be better to have them already rebinned (and properly scaled - to the level of differential cross section in what ever barns (inverse micro barns) but keep it consistent) from the read macro. 

  if(radius == 2) unfoldingCut = unfoldingCut_R2;
  if(radius == 3) unfoldingCut = unfoldingCut_R3;
  if(radius == 4) unfoldingCut = unfoldingCut_R4;
  
  // TH1F * htest = new TH1F("htest","",nbins, ptbins_long);
  // Int_t unfoldingCutBin = htest->FindBin(unfoldingCut);
  
  //Float_t cutarray[6]={50,50,40,35,35,35};
  float cutarray[nbins_cent] = {0.0,0.0,0.0,0.0,0.0,0.0};
  
  if(radius == 2){
    cutarray[0] = 50;
    cutarray[1] = 40;
    cutarray[2] = 40;
    cutarray[3] = 40;
    cutarray[4] = 30;
    cutarray[5] = 30;
  }
  if(radius == 3){
    cutarray[0] = 55;
    cutarray[1] = 50;
    cutarray[2] = 50;
    cutarray[3] = 40;
    cutarray[4] = 35;
    cutarray[5] = 40;
  }
    
  if(radius == 4){
    cutarray[0] = 70;
    cutarray[1] = 60;
    cutarray[2] = 60;
    cutarray[3] = 45;
    cutarray[4] = 40;
    cutarray[5] = 30;
  }
    
  TH1F * hDataBeforeSub[nbins_cent], * hDataAfterSub[nbins_cent];
  
  // get PbPb data
  for(int i = 0;i<nbins_cent;++i){
    if(printDebug) cout<<"cent_"<<i<<endl;

    hData_turnon[i] = (TH1F*)fTrig->Get(Form("hHist_Data_Turnon_cent%d",i));
    
    hData_turnon[i] = (TH1F*)hData_turnon[i]->Rebin(nbins_short, Form("hData_turnon_cent%d",i), boundaries_short);
    //hData_turnon[i] = (TH1F*)hData_turnon[i]->Rebin(10);

    divideBinWidth(hData_turnon[i]);

     //  hMinBias[i]     = (TH1F*)fMinBias->Get(Form("hpbpb_noTrg_R%d_%s_cent%d",radius,etaWidth,i)); //MinBias Histo
    hMinBias[i]     = (TH1F*)fMinBias->Get(Form("hpbpb_HLTMBwoLJSbJ_R%d_%s_cent%d",radius,etaWidth,i)); //MinBias Histo
    hMinBias[i]->Print("base");

    dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLTComb_%s_R%d_%s_cent%d",scale, radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_%s_cent%d",radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_%s_cent%d",radius,etaWidth,i));
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_%s_cent%d",radius,etaWidth,i));
    // dPbPb_TrgComb[i]->Scale(1./(1+0.898+0.494)/1e16);
    // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    dPbPb_TrgComb[i]->Print("base");

    hDataBeforeSub[i] = (TH1F*)dPbPb_TrgComb[i]->Clone(Form("hData_Before_Sub_cent%d",i));
    
    //dPbPb_TrgComb[i] = (TH1F*)fPbPb_DataCorr_in->Get(Form("Data_TrigEffCorrected_FakeSub_cent%d",i));
    //dPbPb_TrgComb[i]->Print("base");
    
    // dPbPb_JEC_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JEC_HLTComb_R%d_%s_cent%d",radius,etaWidth,i));
    // // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    // dPbPb_JEC_TrgComb[i]->Print("base");
    // dPbPb_Smear_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_Smear_HLTComb_R%d_%s_cent%d",radius,etaWidth,i));
    // // //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    // dPbPb_Smear_TrgComb[i]->Print("base");
    // dPbPb_Trg80[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg80[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg80[i]->Print("base");
    // dPbPb_Trg65[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg65[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg65[i]->Print("base");
    // dPbPb_Trg55[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_%s_cent%d",radius,etaWidth,i));
    // //dPbPb_Trg55[i]->Scale(4*145.156*1e6);
    // dPbPb_Trg55[i]->Print("base");

    // if(dotrigcor){
      
    //   doTrigCorr(dPbPb_TrgComb[i], hData_turnon[i]);
    //   doTrigCorr(dPbPb_JEC_TrgComb[i], hData_turnon[i]);
    //   doTrigCorr(dPbPb_Smear_TrgComb[i], hData_turnon[i]);

    // }
    
    //Lets do the subtraction here _Sevil 

      // Float_t bincon=cutarray[i]; 
      // Int_t bincut= hMinBias[i]->FindBin(bincon); 
      
      // for(int k = bincut;k<=hMinBias[i]->GetNbinsX();k++) { 
      // 	hMinBias[i]->SetBinContent(k,0); 
      // 	hMinBias[i]->SetBinError(k,0);
      // } 

      // for(int k = 1;k<=15;k++) { 
      // 	hMinBias[i]->SetBinContent(k,0); 
      // 	hMinBias[i]->SetBinError(k,0);
      // }
      
      Float_t   bin_no = dPbPb_TrgComb[i]->FindBin(15);
      Float_t bin_end=dPbPb_TrgComb[i]->FindBin(25);
      
      Float_t   bin_nomb = hMinBias[i]->FindBin(15);
      Float_t bin_endmb=hMinBias[i]->FindBin(25);
      
      float scalerangeweight=dPbPb_TrgComb[i]->Integral(bin_no,bin_end)/hMinBias[i]->Integral(bin_nomb,bin_endmb);

      // for(int j = 0; j<hMinBias[i]->GetNbinsX(); ++j)
      // 	hMinBias[i]->SetBinError(j+1, (Float_t)hMinBias[i]->GetBinError(j+1)/scalerangeweight);
      
      hMinBias[i]->Scale(scalerangeweight);
      if(dofakeremove) dPbPb_TrgComb[i]->Add(hMinBias[i], -1);

      hDataAfterSub[i] = (TH1F*)dPbPb_TrgComb[i]->Clone(Form("hData_After_Sub_cent%d",i));
      
      // dPbPb_JEC_TrgComb[i]->Add(hMinBias[i], -1);
      // dPbPb_Smear_TrgComb[i]->Add(hMinBias[i], -1);

      // for(int j = 1; j<dPbPb_TrgComb[i]->GetNbinsX(); ++j){

      // 	if(dPbPb_TrgComb[i]->GetBinContent(j) <= 0 ||dPbPb_JEC_TrgComb[i]->GetBinContent(j) <= 0||dPbPb_Smear_TrgComb[i]->GetBinContent(j) <= 0){
      // 	  dPbPb_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_JEC_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_Smear_TrgComb[i]->SetBinContent(j, 0);
      // 	  dPbPb_TrgComb[i]->SetBinError(j, 0);
      // 	  dPbPb_JEC_TrgComb[i]->SetBinError(j, 0);
      // 	  dPbPb_Smear_TrgComb[i]->SetBinError(j, 0);
      // 	}
      // }
      
    

    // // lets truncate the histograms here:
    // cout<<" going to truncate Data histogram here cent "<<i<<endl;
    // dPbPb_TrgCombInput[i]->Print("base");

    // dPbPb_TrgComb[i] = new TH1F(Form("PbPb_data_minbiasSub_cent%d",i),"",365, 30, 395);
    // Truncate1D(dPbPb_TrgCombInput[i], dPbPb_TrgComb[i]);    
    
    // // dPbPb_TrgComb[i] = (TH1F*)Truncate1D(dPbPb_TrgComb[i], 340, unfoldingCutBin, 395);
    // // dPbPb_TrgComb[i]->Print("base");
    
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins, Form("PbPb_data_minbiasSub_cent%d",i), ptbins_long);
    dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(10);
    dPbPb_TrgComb[i]->SetName(Form("PbPb_data_minbiasSub_cent%d",i));
    divideBinWidth(dPbPb_TrgComb[i]);
    
    hMinBias[i] = (TH1F*)hMinBias[i]->Rebin(10);
    hDataAfterSub[i] = (TH1F*)hDataAfterSub[i]->Rebin(10);
    hDataBeforeSub[i] = (TH1F*)hDataBeforeSub[i]->Rebin(10);

    divideBinWidth(hMinBias[i]);
    divideBinWidth(hDataAfterSub[i]);
    divideBinWidth(hDataBeforeSub[i]);
    
    dPbPb_TrgComb[i]->Scale(1./(166 * 1e9));
    
    // dPbPb_TrgComb[i]->Print("base");
    
  }

  if(printDebug)cout<<"loaded the data histograms PbPb"<<endl;
  // get PbPb MC
  for(int i = 0;i<nbins_cent;i++){
    
    // mPbPb_GenInput[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_JetComb_gen_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_GenInput[i]->Print("base");
    // mPbPb_RecoInput[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_JetComb_reco_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_RecoInput[i]->Print("base");
    // mPbPb_MatrixInput[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    // mPbPb_MatrixInput[i]->Print("base");

    mPbPb_Gen[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_JetComb_gen_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Gen[i]->Rebin(nbins, Form("mPbPb_Gen_cent%d",i), ptbins_long);
    mPbPb_Gen[i]->Rebin(10);
    divideBinWidth(mPbPb_Gen[i]);
    mPbPb_Gen[i]->Print("base");
    mPbPb_Reco[i] = (TH1F*)fPbPb_MC_in->Get(Form("hpbpb_JetComb_reco_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Reco[i]->Rebin(nbins, Form("mPbPb_Reco_cent%d",i), ptbins_long);
    mPbPb_Reco[i]->Rebin(10);
    divideBinWidth(mPbPb_Reco[i]);
    mPbPb_Reco[i]->Print("base");
    mPbPb_Matrix[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    //mPbPb_Matrix[i] = (TH2F*)fPbPb_MC_in->Get(Form("hpbpb_anaBin_matrix_HLT_R%d_%s_cent%d",radius,etaWidth,i));
    mPbPb_Matrix[i]->Rebin2D(10, 10);
    mPbPb_Matrix[i]->Print("base");
    
    // if(etaWidth == "10_eta_10"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    // if(etaWidth == "10_eta_18"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(40);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    // if(etaWidth == "20_eta_20"){
    //   if(i == 0 && radius==2) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==2) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 3 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==2) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==2) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==3) unfoldingCutBin = htest->FindBin(70);
    //   if(i == 1 && radius==3) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==3) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==3) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==3) unfoldingCutBin = htest->FindBin(30);

    //   if(i == 0 && radius==4) unfoldingCutBin = htest->FindBin(80);
    //   if(i == 1 && radius==4) unfoldingCutBin = htest->FindBin(60);
    //   if(i == 2 && radius==4) unfoldingCutBin = htest->FindBin(50);
    //   if(i == 3 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 4 && radius==4) unfoldingCutBin = htest->FindBin(30);
    //   if(i == 5 && radius==4) unfoldingCutBin = htest->FindBin(30);
    // }

    int bincut = mPbPb_Gen[i]->FindBin(50);
    for(int k = 1;k<=bincut;k++){

    //   mPbPb_Gen[i]->SetBinContent(k,0);
    //   mPbPb_Reco[i]->SetBinContent(k,0);
    //   mPbPb_Gen[i]->SetBinError(k,0);
    //   mPbPb_Reco[i]->SetBinError(k,0);
    //   // set bin content matrix l,k works 
      for(int l = 1;l<=mPbPb_Gen[i]->GetNbinsX();l++){
	mPbPb_Matrix[i]->SetBinContent(l,k,0);
	mPbPb_Matrix[i]->SetBinError(l,k,0);
      }
      
    }

    SetUnfoldBins1D(dPbPb_TrgComb[i], 50, 350);
    
    // cout<<"going to truncate the MC histograms here."<<endl;
    
    // // mPbPb_Reco[i]->Print("base");
    // // mPbPb_Reco[i] = (TH1F*)Truncate1D_anaBin(mPbPb_Reco[i], nbins, ptbins_long);
    // // mPbPb_Reco[i]->Print("base");

    // mPbPb_GenInput[i]->Print("base");
    // mPbPb_Gen[i] = new TH1F(Form("mPbPb_Gen_spectra_cent%d",i),"",nbins, ptbins_long);
    // Truncate1D(mPbPb_GenInput[i], mPbPb_Gen[i]);
    // mPbPb_Gen[i]->Print("base");
    
    // mPbPb_RecoInput[i]->Print("base");
    // mPbPb_Reco[i] = new TH1F(Form("mPbPb_REco_spectra_cent%d",i),"",nbins, ptbins_long);
    // Truncate1D(mPbPb_RecoInput[i], mPbPb_Reco[i]);
    // mPbPb_Reco[i]->Print("base");
    
    // mPbPb_MatrixInput[i]->Print("base");
    // mPbPb_Matrix[i] = new TH2F(Form("mPbPb_Response_Matrix_cent%d",i),"",nbins_truncated, ptbins_long_truncated, nbins_truncated, ptbins_long_truncated);
    // Truncate2D(mPbPb_MatrixInput[i], mPbPb_Matrix[i]);
    // mPbPb_Matrix[i]->Print("base");
 
  }
  
  if(printDebug) cout<<"loaded the data and mc PbPb histograms from the files"<<endl;

  // get PP data
  if(printDebug) cout<<"Getting PP data and MC"<<endl;

  //fPP_in->ls();

  // dPP_1 = (TH1F*)fPP_in->Get(Form("hpp_HLT80_R%d_%s",radius,etaWidth)); 
  // dPP_1->Print("base");
  // dPP_2 = (TH1F*)fPP_in->Get(Form("hpp_HLT60_R%d_%s",radius,etaWidth));
  // dPP_2->Print("base");
  // dPP_3 = (TH1F*)fPP_in->Get(Form("hpp_HLT40_R%d_%s",radius,etaWidth));
  // dPP_3->Print("base");
  dPP_Comb = (TH1F*)fPP_in->Get(Form("hpp_HLTComb_R%d_%s",radius,etaWidth));
  //dPP_Comb = (TH1F*)dPP_1->Clone(Form("hpp_TrgComb_R%d_n20_eta_p20",radius,etaWidth));   
  //dPP_CombInput->Print("base");
  dPP_Comb->Scale(1./(5.3 * 1e9));
  
  // dPP_Comb = new TH1F("PP_MeasuredSpectra","",365, 30, 395);
  // Truncate1D(dPP_CombInput, dPP_Comb);

  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins, "PP_MeasuredSpectra", ptbins_long);
  dPP_Comb = (TH1F*)dPP_Comb->Rebin(10);
  dPP_Comb->SetName("PP_MeasuredSpectra");
  divideBinWidth(dPP_Comb);
  dPP_Comb->Print("base");
  
  // get PP MC
  // mPP_GenInput = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_gen_R%d_%s",radius,etaWidth));
  // mPP_GenInput->Print("base");
  // mPP_Gen = new TH1F("mPP_Gen_spectra","",nbins, ptbins_long);
  // Truncate1D(mPP_GenInput, mPP_Gen);
  // mPP_Gen->Print("base");
  
  // mPP_RecoInput = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_reco_R%d_%s",radius,etaWidth));
  // mPP_RecoInput->Print("base");
  // mPP_Reco = new TH1F("mPP_Reco_spectra","",nbins, ptbins_long);
  // Truncate1D(mPP_RecoInput, mPP_Reco);
  // mPP_Reco->Print("base");
  
  // mPP_MatrixInput = (TH2F*)fPP_MC_in->Get(Form("hpp_anaBin_matrix_HLT_R%d_%s",radius,etaWidth));
  // mPP_MatrixInput->Print("base");
  // mPP_Matrix = new TH2F("mPP_response_Matrix","",nbins_truncated, ptbins_long_truncated, nbins_truncated, ptbins_long_truncated);
  // Truncate2D(mPP_MatrixInput, mPP_Matrix);
  // mPP_Matrix->Print("base");

  // get PP MC
  // change from fPP_MC_in to fPP_in to run finebinscut
  //mPP_Gen = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_gen_R%d_20_eta_20",radius));
  mPP_Gen = (TH1F*)fPP_MC_in->Get(Form("hpp_JetComb_gen_R%d_20_eta_20",radius));
  //mPP_Gen->Rebin(nbins, "mPP_Gen", ptbins_long);
  mPP_Gen->Rebin(10);
  divideBinWidth(mPP_Gen);
  mPP_Gen->Print("base");

  //mPP_Reco = (TH1F*)fPP_MC_in->Get(Form("hpp_anaBin_JetComb_reco_R%d_20_eta_20",radius));
  mPP_Reco = (TH1F*)fPP_MC_in->Get(Form("hpp_JetComb_reco_R%d_20_eta_20",radius));
  //mPP_Gen->Rebin(nbins, "mPP_Gen", ptbins_long);
  mPP_Reco->Rebin(10);
  divideBinWidth(mPP_Reco);
  mPP_Reco->Print("base");

  //mPP_Matrix = (TH2F*)fPP_MC_in->Get(Form("hpp_anaBin_matrix_HLT_R%d_20_eta_20",radius));
  mPP_Matrix = (TH2F*)fPP_MC_in->Get(Form("hpp_matrix_HLT_R%d_20_eta_20",radius));
  mPP_Matrix->Rebin2D(10, 10);
  mPP_Matrix->Print("base");

  if(printDebug) cout<<"Filling the PbPb response Matrix"<<endl;

  // response matrix and unfolding for PbPb 
  // going to try it the way kurt has its. 

  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"centrality bin iteration = "<<i<<endl;
    TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
    f->SetParameters(1e10,-8.8,40);
    // TH1F *hGenSpectraCorr = (TH1F*)mPbPb_Matrix[i]->ProjectionX()->Clone(Form("hGenSpectraCorr_cent%d",i));
    // hGenSpectraCorr->Fit("f"," ");
    // hGenSpectraCorr->Fit("f","","");
    // hGenSpectraCorr->Fit("f","LL");
    // TH1F *fHist = functionHist(f,hGenSpectraCorr,Form("fHist_cent%d",i));// function that you get from the fitting 
    // hGenSpectraCorr->Divide(fHist);
    for (int y=1;y<=mPbPb_Matrix[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {
	if (mPbPb_Matrix[i]->GetBinContent(x,y)<=1*mPbPb_Matrix[i]->GetBinError(x,y)) {
	  //in the above line mine had 0*getbinerror while Kurt's had 1*. 
	  mPbPb_Matrix[i]->SetBinContent(x,y,0);
	  mPbPb_Matrix[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Matrix[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {	   
	double ratio = 1;
	// if (hGenSpectraCorr->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorr->GetBinContent(x);
	mPbPb_Matrix[i]->SetBinContent(x,y,mPbPb_Matrix[i]->GetBinContent(x,y)*ratio);
	mPbPb_Matrix[i]->SetBinError(x,y,mPbPb_Matrix[i]->GetBinError(x,y)*ratio);
      }
    }
    //mPbPb_Matrix[i]->Smooth(0);
    // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  
    
    mPbPb_Response[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_Response_cent%d",i));
    TH1F *hProj = (TH1F*)mPbPb_Response[i]->ProjectionY()->Clone(Form("hProj_cent%d",i));

    for (int y=1;y<=mPbPb_Response[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {
	if (mPbPb_Response[i]->GetBinContent(x,y)<=1*mPbPb_Response[i]->GetBinError(x,y)) {
	  // in the above if loop, kurt has 1*error and my old had 0*error
	  mPbPb_Response[i]->SetBinContent(x,y,0);
	  mPbPb_Response[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Response[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = 1;
	//if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
	// else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
	ratio = 1./sum;
	if (hProj->GetBinContent(y)==0) ratio = 1e-100/sum;
	else ratio = hProj->GetBinContent(y)/sum;
	mPbPb_Response[i]->SetBinContent(x,y,mPbPb_Response[i]->GetBinContent(x,y)*ratio);
	mPbPb_Response[i]->SetBinError(x,y,mPbPb_Response[i]->GetBinError(x,y)*ratio);
      }
    }
    
    mPbPb_ResponseNorm[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_ResponseNorm_cent%d",i));
    for (int x=1;x<=mPbPb_ResponseNorm[i]->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {
	if (mPbPb_ResponseNorm[i]->GetBinContent(x,y)<=1*mPbPb_ResponseNorm[i]->GetBinError(x,y)) {
	  mPbPb_ResponseNorm[i]->SetBinContent(x,y,0);
	  mPbPb_ResponseNorm[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_ResponseNorm[i]->GetBinContent(x,y);
      }
      
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	mPbPb_ResponseNorm[i]->SetBinContent(x,y,mPbPb_ResponseNorm[i]->GetBinContent(x,y)*ratio);
	mPbPb_ResponseNorm[i]->SetBinError(x,y,mPbPb_ResponseNorm[i]->GetBinError(x,y)*ratio);
      }
      
    }
    
    
  }

  
  if(printDebug) cout<<"Filling PP response Matrix"<<endl;

  // response matrix for pp.  
  // Kurt doesnt have this whole hGenSpectraCorr thing in his macro. need to check why the difference exists between out codes
  
  TF1 *fpp = new TF1("fpp","[0]*pow(x+[2],[1])");
  fpp->SetParameters(1e10,-8.8,40);
  // if(printDebug) cout<<"before getting the gen spectra corr matrix"<<endl;
  // TH1F *hGenSpectraCorrPP = (TH1F*)mPP_Matrix->ProjectionX()->Clone("hGenSpectraCorrPP");
  // if(printDebug) cout<<"after gettign the gen spectra corr matrix"<<endl;
  // hGenSpectraCorrPP->Fit("f"," ");
  // hGenSpectraCorrPP->Fit("f","","");
  // hGenSpectraCorrPP->Fit("f","LL");
  // TH1F *fHistPP = functionHist(fpp,hGenSpectraCorrPP,"fHistPP");// that the function that you get from the fitting 
  // hGenSpectraCorrPP->Divide(fHistPP);
  
  for (int y=1;y<=mPP_Matrix->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {
      if (mPP_Matrix->GetBinContent(x,y)<=1*mPP_Matrix->GetBinError(x,y)) {
	mPP_Matrix->SetBinContent(x,y,0);
	mPP_Matrix->SetBinError(x,y,0);
      }
      sum+=mPP_Matrix->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {	   
      double ratio = 1;
      // if (hGenSpectraCorrPP->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorrPP->GetBinContent(x);
      mPP_Matrix->SetBinContent(x,y,mPP_Matrix->GetBinContent(x,y)*ratio);
      mPP_Matrix->SetBinError(x,y,mPP_Matrix->GetBinError(x,y)*ratio);
    }
  }
  // mPbPb_Matrix[i]->Smooth(0);
  
  // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  

  if(printDebug) cout<<"getting the response matrix"<<endl;

  mPP_Response = (TH2F*)mPP_Matrix->Clone("mPP_Response");
  TH1F *hProjPP = (TH1F*)mPP_Response->ProjectionY()->Clone("hProjPP");
  
  
  for (int y=1;y<=mPP_Response->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {
      if (mPP_Response->GetBinContent(x,y)<=1*mPP_Response->GetBinError(x,y)) {
	// in the above if statement, kurt has 1*error and my old has 0*error
	mPP_Response->SetBinContent(x,y,0);
	mPP_Response->SetBinError(x,y,0);
      }
      sum+=mPP_Response->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {  	
      if (sum==0) continue;
      double ratio = 1;
      //if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
      // else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
      ratio = 1./sum;
      if (hProjPP->GetBinContent(y)==0) ratio = 1e-100/sum;
      else ratio = hProjPP->GetBinContent(y)/sum;
      mPP_Response->SetBinContent(x,y,mPP_Response->GetBinContent(x,y)*ratio);
      mPP_Response->SetBinError(x,y,mPP_Response->GetBinError(x,y)*ratio);
    }
  }
  if(printDebug) cout<<"getting the normalized response matrix"<<endl;
  mPP_ResponseNorm = (TH2F*)mPP_Matrix->Clone("mPP_ResponseNorm");
  for (int x=1;x<=mPP_ResponseNorm->GetNbinsX();x++) {
    double sum=0;
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {
      if (mPP_ResponseNorm->GetBinContent(x,y)<=1*mPP_ResponseNorm->GetBinError(x,y)) {
	mPP_ResponseNorm->SetBinContent(x,y,0);
	mPP_ResponseNorm->SetBinError(x,y,0);
      }
      sum+=mPP_ResponseNorm->GetBinContent(x,y);
    }
    
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {  	
      if (sum==0) continue;
      double ratio = 1./sum;
      mPP_ResponseNorm->SetBinContent(x,y,mPP_ResponseNorm->GetBinContent(x,y)*ratio);
      mPP_ResponseNorm->SetBinError(x,y,mPP_ResponseNorm->GetBinError(x,y)*ratio);
    }
    
    
  }
  
  // scale the spectra to the respective units

  // for(int i = 0;i<nbins_cent;++i){
  //   dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins,Form("PbPb_measured_spectra_combined_cent%d",i),ptbins_long);
  //   divideBinWidth(dPbPb_TrgComb[i]);
  // }

  // dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins,"pp_measured_spectra_combined",ptbins_long);
  // divideBinWidth(dPP_Comb);
  // dPP_Comb->Scale(1./ dPP_Comb->GetBinContent(nbins));
  
  // Now that we have all the response matrix for the 6 centralities in PbPb and one pp spectra lets start doing the steps:
  // we have 39 pt bins, so we need 1000 gaussian functions for each pt bin.
  
  Int_t unfoldingTrials = 1000;
  Double_t meanMeasPbPb[nbins][nbins_cent], sigmaMeasPbPb[nbins][nbins_cent];
  Double_t meanMeasPP[nbins], sigmaMeasPP[nbins];
  Double_t meanUnfoldPbPb[nbins][nbins_cent][unfoldingTrials], sigmaUnfoldPbPb[nbins][nbins_cent][unfoldingTrials];
  Double_t meanUnfoldPP[nbins][unfoldingTrials], sigmaUnfoldPP[nbins][unfoldingTrials]; 
  
  TRandom3 *random = new TRandom3(0);

  TH1F * hPbPb_beforeUnfold_Gaussian_pt150[nbins_cent];
  TH1F * hPP_beforeUnfold_Gaussian_pt150; 
  hPP_beforeUnfold_Gaussian_pt150 = new TH1F("hPP_beforeUnfold_Gaussian_pt150","",1000, 0.1 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)) , 1.9 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)));
  
  for(int i = 0; i<nbins_cent; ++i)
    hPbPb_beforeUnfold_Gaussian_pt150[i] = new TH1F(Form("hPbPb_beforeUnfold_Gaussian_pt150_cent%d",i),"Before Unfolding pt bin at 150 value spectra",1000, 0.1 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)), 1.9 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)));
  

  for(int u = 0;u<unfoldingTrials;++u){
    cout<<"unfolding trial no = "<<u+1<<endl;
  
    for(int j = 0;j<nbins;++j){
      for(int i = 0;i<nbins_cent;++i){
      
	meanMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinContent(j+1);
	sigmaMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinError(j+1);

      }// centrality loop

      meanMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      sigmaMeasPP[j] = dPP_Comb->GetBinError(j+1);
      
    }// nbins loop

    // now proceed to unfolding for each trial.

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

      TH1F * hPreUnfoldingSpectra = new TH1F("hPreUnfoldingSpectra","",nbins,0, 1000);
      TH1F * hAfterUnfoldingSpectra;

      for(int j = 0;j<nbins;++j){
	
	hPreUnfoldingSpectra->SetBinContent(j+1, random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	hPreUnfoldingSpectra->SetBinError(j+1, sigmaMeasPbPb[j][i]/sqrt(unfoldingTrials));
	if(j+1 == dPbPb_TrgComb[i]->FindBin(150)) hPbPb_beforeUnfold_Gaussian_pt150[i]->Fill(random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	
      }// nbins loop

      TH1F* hMCGen          = (TH1F*)mPbPb_Response[i]->ProjectionX();
      removeZero(hMCGen);
      bayesianUnfold myUnfoldingMulti(mPbPb_Matrix[i], hMCGen, 0);
      myUnfoldingMulti.unfold(hPreUnfoldingSpectra, BayesIter);

      hAfterUnfoldingSpectra = (TH1F*) myUnfoldingMulti.hPrior->Clone("hAfterUnfoldingSpectra");

      for(int j = 0;j<nbins;++j){

	meanUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinContent(j+1);
	sigmaUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinError(j+1);

      }// nbins loop
      
      delete hPreUnfoldingSpectra;
      delete hAfterUnfoldingSpectra;
      delete hMCGen; 
      
    }// centrality loop

    cout<<"pp "<<endl;

    // now do it for the pp:
    TH1F * hPreUnfoldingSpectraPP = new TH1F("hPreUnfoldingSpectraPP","",nbins,0, 1000);
    TH1F * hAfterUnfoldingSpectraPP;
    
    for(int j = 0;j<nbins;++j){
	
      hPreUnfoldingSpectraPP->SetBinContent(j+1, random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      hPreUnfoldingSpectraPP->SetBinError(j+1, sigmaMeasPP[j]/sqrt(unfoldingTrials));
      if(j+1 == dPP_Comb->FindBin(150)) hPP_beforeUnfold_Gaussian_pt150->Fill(random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      
    }// nbins loop
    TH1F* hMCGenPP          = (TH1F*)mPP_Response->ProjectionX();
    removeZero(hMCGenPP);
    bayesianUnfold myUnfoldingMultiPP(mPP_Matrix, hMCGenPP, 0);
    myUnfoldingMultiPP.unfold(hPreUnfoldingSpectraPP, BayesIter);

    hAfterUnfoldingSpectraPP = (TH1F*) myUnfoldingMultiPP.hPrior->Clone("hAfterUnfoldingSpectraPP");

    for(int j = 0;j<nbins;++j){

      meanUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinContent(j+1);
      sigmaUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinError(j+1);

    }// nbins loop

    delete hPreUnfoldingSpectraPP;
    delete hAfterUnfoldingSpectraPP;
    delete hMCGenPP; 
    
  }// unfolding trials loop


  // Now that we have all the necesary values we need, lets proceed to fill a histogram with the mean values for each ptbin and get the corrected values.
  TH1F * hAfterUnfoldingptBinDistribution[nbins];
  TH1F * hCorrUnfoldingPbPb[nbins_cent];

  // we need to store one gaussian histogram in the root file which we can plot 
  TH1F * hPbPb_Gaussian_pt150[nbins_cent];
  TH1F * hPP_Gaussian_pt150;


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

    hCorrUnfoldingPbPb[i] = new TH1F(Form("PbPb_BayesianUnfolded_cent%d",i),"Spectra after correction", nbins,0, 1000);
    hPbPb_Gaussian_pt150[i] = new TH1F(Form("PbPb_Gaussian_pt150_cent%d",i),"gaussian distribution of values at pt bin at 150",1000, 0.1 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)), 1.9 * dPbPb_TrgComb[i]->GetBinContent(dPbPb_TrgComb[i]->FindBin(150)));

    for(int j = 0;j<nbins;++j){
      
      hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	0, 1);
      for(int u = 0;u<unfoldingTrials;++u){

	hAfterUnfoldingptBinDistribution[j]->Fill(meanUnfoldPbPb[j][i][u]);
	if(j+1 == dPbPb_TrgComb[i]->FindBin(150)) hPbPb_Gaussian_pt150[i]->Fill(meanUnfoldPbPb[j][i][u]);

      }// unfolding trials loop

      hCorrUnfoldingPbPb[i]->SetBinContent(j+1, hAfterUnfoldingptBinDistribution[j]->GetMean());
      hCorrUnfoldingPbPb[i]->SetBinError(j+1, hAfterUnfoldingptBinDistribution[j]->GetRMS());

      delete hAfterUnfoldingptBinDistribution[j];
      
    }// nbins loop

  }// centrality loop

  // similar for the pp:
  TH1F * hAfterUnfoldingptBinDistributionPP[nbins];
  TH1F * hCorrUnfoldingPP;
  
  hCorrUnfoldingPP = new TH1F("PP_BayesianUnfolded","Spectra after unfolding error correction",nbins,0, 1000);
  hPP_Gaussian_pt150 = new TH1F("PP_Gaussian_pt100","gaussian distribution of values at pt bin at 150",1000, 0.1 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)) , 1.9 * dPP_Comb->GetBinContent(dPP_Comb->FindBin(150)));
  
  for(int j = 0;j<nbins;++j){
    
    hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",100, 0, 1);
    for(int u = 0;u<unfoldingTrials;++u){
      
      hAfterUnfoldingptBinDistributionPP[j]->Fill(meanUnfoldPP[j][u]);
      if(j+1 == dPP_Comb->FindBin(150)) hPP_Gaussian_pt150->Fill(meanUnfoldPP[j][u]);
      
    }// unfolding trials loop
    
    hCorrUnfoldingPP->SetBinContent(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetMean());
    hCorrUnfoldingPP->SetBinError(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetRMS());
    
    delete hAfterUnfoldingptBinDistributionPP[j];
    
  }// nbins loop
    
  TFile f(Form("July20/HiForest_%disATLASCut_%ddo10GeVBins_data_driven_correction_ak%d.root" , isATLASCut, do10GeVBins, radius),"RECREATE");
  f.cd();

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

    //hCorrUnfoldingPbPb[i] = (TH1F*)hCorrUnfoldingPbPb[i]->Rebin(nbins_coarse, Form("PbPb_BayesianUnfolded_cent%d",i), ptbins_long_coarse);
    //divideBinWidth(hCorrUnfoldingPbPb[i]);
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_coarse, Form("PbPb_measured_cent%d",i), ptbins_long_coarse);
    //divideBinWidth(dPbPb_TrgComb[i]);

    hMinBias[i]->Write();
    hDataBeforeSub[i]->Write();
    hDataAfterSub[i]->Write();
    
    hCorrUnfoldingPbPb[i]->Scale(166 * 1e9);
    hCorrUnfoldingPbPb[i]->Write();
    hCorrUnfoldingPbPb[i]->Print("base");

    dPbPb_TrgComb[i]->Scale(166 * 1e9);
    dPbPb_TrgComb[i]->SetName(Form("PbPb_data_minbiasSub_cent%d",i));
    //dPbPb_TrgComb[i]->Scale(145.156 * 1e9);
    dPbPb_TrgComb[i]->Write();
    dPbPb_TrgComb[i]->Print("base");

    hPbPb_beforeUnfold_Gaussian_pt150[i]->Write();
    hPbPb_beforeUnfold_Gaussian_pt150[i]->Print("base");
    
    hPbPb_Gaussian_pt150[i]->Write();
    hPbPb_Gaussian_pt150[i]->Print("base");

    mPbPb_Matrix[i]->Write();
    
  }

  //hCorrUnfoldingPP = (TH1F*)hCorrUnfoldingPP->Rebin(nbins_coarse, "PP_BayesianUnfolded", ptbins_long_coarse);
  //divideBinWidth(hCorrUnfoldingPP);
  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_coarse, "PP_measured", ptbins_long_coarse);  
  //divideBinWidth(dPP_Comb);
  
  hCorrUnfoldingPP->Scale(5.3 * 1e9);
  hCorrUnfoldingPP->Write();
  hCorrUnfoldingPP->Print("base");

  dPP_Comb->Scale(5.3 * 1e9);
  dPP_Comb->Write();
  dPP_Comb->Print("base");

  hPP_beforeUnfold_Gaussian_pt150->Write();
  hPP_beforeUnfold_Gaussian_pt150->Print("base");
  
  hPP_Gaussian_pt150->Write();
  hPP_Gaussian_pt150->Print("base");
  mPP_Matrix->Write();

  f.Write();
  f.Close();

  // make the data driven Error correction histograms and plots here:
  
  TH1F * hError_Meas[nbins_cent+1], * hError_Fixed[nbins_cent+1];
  for(int i = 0; i<nbins_cent+1; ++i){
    cout<<"centrality "<<i<<endl;
    if(i < nbins_cent){
      hError_Meas[i]  = new TH1F(Form("hError_Meas_cent%d",i),"",nbins, 0, 1000);
      hError_Fixed[i] = new TH1F(Form("hError_Fixed_cent%d",i),"",nbins, 0, 1000);
    }
    if(i == nbins_cent){
      hError_Meas[i]  = new TH1F(Form("hError_PP_Meas_cent%d",i),"",nbins, 0, 1000);
      hError_Fixed[i] = new TH1F(Form("hError_PP_Fixed_cent%d",i),"",nbins, 0, 1000);
    }

    for(int j = 1; j<=nbins; ++j){
      //cout<<"ptbins "<<j<<endl;
      if(i < nbins_cent){
	if(dPbPb_TrgComb[i]->GetBinContent(j)!=0) hError_Meas[i]->SetBinContent(j, (float)dPbPb_TrgComb[i]->GetBinError(j)/dPbPb_TrgComb[i]->GetBinContent(j));
        //hError_Meas[i]->SetBinContent(j, (float)dPbPb_TrgComb[i]->GetBinError(j));
	if(hCorrUnfoldingPbPb[i]->GetBinContent(j)!=0)hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPbPb[i]->GetBinError(j)/hCorrUnfoldingPbPb[i]->GetBinContent(j));
	cout<<j<<" "<<hError_Fixed[i]->GetBinContent(j)<<endl;
	//hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPbPb[i]->GetBinError(j));
      }
      if(i == nbins_cent){
	hError_Meas[i]->SetBinContent(j, (float)dPP_Comb->GetBinError(j)/dPP_Comb->GetBinContent(j));
	//hError_Meas[i]->SetBinContent(j, (float)dPP_Comb->GetBinError(j));
	hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPP->GetBinError(j)/hCorrUnfoldingPP->GetBinContent(j));
	//hError_Fixed[i]->SetBinContent(j, (float)hCorrUnfoldingPP->GetBinError(j));
      }
    }
    
    hError_Meas[i]->SetAxisRange(50, 299, "X");
    //hError_Meas[i]->Print("base");
    //hError_Fixed[i]->Print("base");
    //hError_Meas[i]->SetAxisRange(1e-12, 1, "Y");
  }
  //cout<<" passed the loop"<<endl;

  TCanvas * cSpectra = new TCanvas("cSpectra","",1200,1000);
  makeMultiPanelCanvas(cSpectra,3,2,0.0,0.0,0.2,0.15,0.07);  
  for(int i = 0; i<nbins_cent; ++i){
    //cout<<i<<endl;
    cSpectra->cd(nbins_cent-i);
    cSpectra->cd(nbins_cent-i)->SetLogy();
    dPbPb_TrgComb[i]->SetMarkerStyle(24);
    dPbPb_TrgComb[i]->SetMarkerColor(kBlack);
    makeHistTitle(dPbPb_TrgComb[i]," ","jet pT","dN/dpT");
    dPbPb_TrgComb[i]->SetAxisRange(50, 299, "X");
    dPbPb_TrgComb[i]->Draw("p");

    hCorrUnfoldingPbPb[i]->SetMarkerStyle(33);
    hCorrUnfoldingPbPb[i]->SetMarkerColor(kRed);
    hCorrUnfoldingPbPb[i]->Draw("psame");

  }
  TLegend * Spec = myLegend(0.55,0.55,0.75,0.75);
  cSpectra->cd(1);
  putCMSPrel();
  Spec->AddEntry(dPbPb_TrgComb[0],"Measured","pl");
  Spec->AddEntry(hCorrUnfoldingPbPb[0],"Data Driven Correction","pl");
  Spec->SetTextSize(0.04);
  Spec->Draw();
  
  cSpectra->SaveAs(Form("%sUnfoldingSpectra_fromDataDrivenMacro_PbPb_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");

  
  TCanvas * cErrorFix = new TCanvas("cErrorFix","",1200,1000);
  makeMultiPanelCanvas(cErrorFix,3,2,0.0,0.0,0.2,0.15,0.07);  
  for(int i = 0; i<nbins_cent; ++i){
    //cout<<i<<endl;
    cErrorFix->cd(nbins_cent-i);
    cErrorFix->cd(nbins_cent-i)->SetLogy();
    makeHistTitle(hError_Meas[i]," ","jet pT","Error/Content");
    hError_Meas[i]->SetMarkerStyle(24);
    hError_Meas[i]->SetMarkerColor(kBlack);
    hError_Meas[i]->Draw("p");

    hError_Fixed[i]->SetMarkerStyle(33);
    hError_Fixed[i]->SetMarkerColor(kRed);
    hError_Fixed[i]->Draw("psame");

  }
  TLegend * err = myLegend(0.55,0.55,0.75,0.75);
  cErrorFix->cd(1);
  putCMSPrel();
  err->AddEntry(hError_Meas[0],"Measured","pl");
  err->AddEntry(hError_Fixed[0],"Data Driven Correction","pl");
  err->SetTextSize(0.04);
  err->Draw();
  
  cErrorFix->SaveAs(Form("%sUnfoldingErrorFix_fromDataDrivenMacro_PbPb_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");

  TCanvas * cErrorFixPP = new TCanvas("cErrorFixPP","",800,600);
  cErrorFixPP->SetLogy();
  hError_Meas[nbins_cent]->SetMarkerStyle(24);
  hError_Meas[nbins_cent]->SetMarkerColor(kBlack);
  hError_Meas[nbins_cent]->Draw("p");
  
  hError_Fixed[nbins_cent]->SetMarkerStyle(33);
  hError_Fixed[nbins_cent]->SetMarkerColor(kRed);
  hError_Fixed[nbins_cent]->Draw("psame");
  TLegend * errPP = myLegend(0.55,0.55,0.75,0.75);
  putCMSPrel();
  errPP->AddEntry(hError_Meas[nbins_cent],"Measured","pl");
  errPP->AddEntry(hError_Fixed[nbins_cent],"Data Driven Correction","pl");
  errPP->SetTextSize(0.04);
  errPP->Draw();
  
  cErrorFixPP->SaveAs(Form("%sUnfoldingErrorFix_fromDataDrivenMacro_PP_%s_R%d_%d_hiForest_%dGeVCut.pdf",outLocation,etaWidth,radius,date.GetDate(),unfoldingCut),"RECREATE");
  
  timer.Stop();
  if(printDebug) cout<<"CPU time (mins) = "<<(Float_t)timer.CpuTime()/60<<endl;
  if(printDebug) cout<<"Real tile (mins) = "<<(Float_t)timer.RealTime()/60<<endl;


}
Пример #14
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    //int MinPhi = 41;
    //int MaxPhi = 53;
    int MinPhi = 1;
    int MaxPhi = 71;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  //TF1 *fped = new TF1("fped","gaus",0, 80);
	  TF1 *fped = new TF1("fped","gaus",0, 20);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  cout<<"depth "<<iDepth<<" ieta "<<iEta<<" iphi "<<iPhi
	      <<" pploc "<<pploc<<" ppwidth "<<ppwidth<<endl;
	  //hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + 3*ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  //constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<fped->GetParameter(1)<<" "<<fped->GetParError(1)<<" "<<fped->GetParameter(2)<<" "<<fped->GetParError(2)<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;

	  //constants_file<<fit->GetParameter(3)<<" "<<fit->GetParError(3)<<endl;

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
Пример #15
0
// --------------------------------- //
void ClosureTest()
{
   setTDRStyle();
   gROOT->ForceStyle();

   // input files
   // TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_v2.root", "READ");

   /* TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v2.root", "READ");
      TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_v2.root", "READ");*/

   /*TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v4.root", "READ");
     TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_nominal_v4.root", "READ");*/

   //TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final.root", "READ");

   TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_NotSmeared_v4.root", "READ");
     TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_Smeared_v4.root", "READ");

   TString suffix = "_PythiaSmearedVsPythia_v4";
   // TString suffix = "_HerwigVsPythia";
   // TString suffix = "_PythiaVsHerwig_v4";

 
   // define helper histos
   TH1F *tmp_mcsmeared = new TH1F();
   TH1F *tmp_mc = new TH1F();
   TH1F *tmp_gensmeared = new TH1F();
   TH1F *tmp_gen = new TH1F();
   tmp_mcsmeared->Sumw2();
   tmp_mc->Sumw2();
   tmp_gensmeared->Sumw2();
   tmp_gen->Sumw2();
 
   std::vector<float> alpha;
   alpha.push_back(0.1); 
   alpha.push_back(0.125); 
   alpha.push_back(0.15); 
   alpha.push_back(0.175); 
   alpha.push_back(0.20); 
   alpha.push_back(0.225);
   alpha.push_back(0.25); 
      
   float pt_bins[14] = {62, 107, 175, 205, 242, 270, 310, 335, 379, 410, 467, 600, 1000, 2000};
   // float eta_bins[6] = {0, 0.5, 1.1, 1.7, 2.3, 5.0};
   float eta_bins[8] = {0, 0.5, 1.1, 1.7, 2.3, 2.8, 3.2, 5.0};
   TH1F *extrapolated_mcsmeared = new TH1F("extrapolated_mcsmeared", "extrapolated_mcsmeared", 13, pt_bins);
   TH1F *extrapolated_mc = new TH1F("extrapolated_mc", "extrapolated_mc", 13, pt_bins);
   TH1F *extrapolated_gen = new TH1F("extrapolated_gen", "extrapolated_gen", 13, pt_bins);
   TH1F *extrapolated_mcsmeared_with_pli = new TH1F("extrapolated_mcsmeared_with_pli", "extrapolated_mcsmeared", 13, pt_bins);
   TH1F *extrapolated_mc_with_pli = new TH1F("extrapolated_mc_with_pli", "extrapolated_mc", 13, pt_bins);

   TH1F* RatioVsEta = new TH1F("RatioVsEta", "", 7, eta_bins);
   TH1F* RatioVsEta_with_pli = new TH1F("RatioVsEta_with_pli", "", 7, eta_bins);
   extrapolated_mcsmeared->Sumw2();
   extrapolated_mc->Sumw2();
   extrapolated_gen->Sumw2();
   extrapolated_mcsmeared_with_pli->Sumw2();
   extrapolated_mc_with_pli->Sumw2();
 
   RatioVsEta->Sumw2();
   RatioVsEta_with_pli->Sumw2();

   // how much should be truncated?
   double yq_IQW[2],xq_IQW[2];
   xq_IQW[0] = 0.0;
   xq_IQW[1] = 0.985;
   
   //// get asymmetry histos
   for(int ieta=0; ieta < 5; ++ieta){
      //  cout << "eta Bin: " << ieta << endl;

      extrapolated_mcsmeared->Reset();
      extrapolated_mc->Reset();
      extrapolated_gen->Reset();
      extrapolated_mcsmeared_with_pli->Reset();
      extrapolated_mc_with_pli->Reset();
    
      for(int ipt=0; ipt < 13; ++ipt){     
         //  cout << "pt Bin: " << ipt << endl;
         std::vector<double> x,x_e,MCy,MCy_e,Datay,Datay_e,Geny,Geny_e;

         for(int ialpha=0; ialpha < 7; ++ialpha){
         //for(int ialpha=0; ialpha < 3; ++ialpha){
            //  cout << "alpha Bin: " << ialpha << endl;
            TString hname = Form("Pt%i_eta%i_alpha%i", ipt, ieta, ialpha);
            TString hname_gen = Form("GenAsymm_Pt%i_eta%i_alpha%i", ipt, ieta, ialpha);

            //  cout << "hname: " << hname << endl;

            mc_file->cd();
            tmp_mc = 0;
            tmp_gen = 0;
            tmp_mc = (TH1F*) gDirectory->FindObjectAny(hname);
            tmp_gen = (TH1F*) gDirectory->FindObjectAny(hname_gen);

            mc_smeared_file->cd();
            tmp_mcsmeared = 0;
            tmp_gensmeared = 0;
            tmp_mcsmeared = (TH1F*) gDirectory->FindObjectAny(hname);
            tmp_gensmeared = (TH1F*) gDirectory->FindObjectAny(hname_gen);
                               
            x.push_back(alpha.at(ialpha));
            x_e.push_back(0.);

            double mc_width = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW);
            double mc_width_err = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mc->GetEffectiveEntries()));
            double data_width = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW);
            double data_width_err = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mcsmeared->GetEffectiveEntries()));
            double gen_width = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW);
            double gen_width_err = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_gen->GetEffectiveEntries()));

            MCy.push_back( mc_width );
            MCy_e.push_back( mc_width_err );
            Datay.push_back( data_width );
            Datay_e.push_back( data_width_err );
            Geny.push_back( gen_width );
            Geny_e.push_back( gen_width_err );

            tmp_mc->Scale(tmp_mcsmeared->Integral()/tmp_mc->Integral());
            tmp_gen->Scale(tmp_gensmeared->Integral()/tmp_gen->Integral());

            // draw asymmetry histos
            TCanvas *c5 = new TCanvas("c5", "", 600, 600);
            c5->SetLogy();
            //  tmp_mc->GetYaxis()->SetRangeUser(0.1, 100.*tmp_mc->GetMaximum());
            // tmp_mc->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})");
            tmp_mc->GetXaxis()->SetTitle("|A|");
            tmp_mc->GetYaxis()->SetTitle("Events");
            tmp_mc->SetLineColor(30);
            //  tmp_mc->SetFillColor(30);
            tmp_mc->Rebin(10);
            tmp_mc->Draw("hist");
            //   gauss_mc->Draw("same");
            tmp_mcsmeared->Rebin(10);
            tmp_mcsmeared->SetMarkerStyle(20);
            tmp_mcsmeared->Draw("histsame");
          
            TPaveText *label = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01);
            label->AddText("Anti-k_{T} (R=0.5) PFCHS Jets");
            label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq  p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
            label->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) );
            label->Draw("same");
            
            TLegend* leg1 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2);
            leg1->AddEntry(tmp_mcsmeared,"Herwig","L");
            leg1->AddEntry(tmp_mc,"Pythia","L");
            leg1->Draw();

            if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps(");
            else if(ieta == 4 && ipt == 12 && ialpha == 6) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps)");
            else c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps"); 

            // draw gen-asymmetry histos
            TCanvas *c5b = new TCanvas("c5b", "", 600, 600);
            c5b->SetLogy();
            //  tmp_gen->GetYaxis()->SetRangeUser(0.1, 100.*tmp_gen->GetMaximum());
            // tmp_gen->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})");
            tmp_gen->GetXaxis()->SetTitle("|A_{gen}|");
            tmp_gen->GetYaxis()->SetTitle("Events");
            tmp_gen->SetLineColor(30);
            //  tmp_gen->SetFillColor(30);
            tmp_gen->Rebin(10);
            tmp_gen->Draw("hist");
            //   gauss_gen->Draw("same");
            tmp_gensmeared->Rebin(10);
            tmp_gensmeared->SetMarkerStyle(20);
            tmp_gensmeared->Draw("histsame");
          
            TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01);
            label2->AddText("Anti-k_{T} (R=0.5) PFCHS Jets");
            label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq  p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
            label2->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) );
            label2->Draw("same");
            
            TLegend* leg2 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2);
            leg2->AddEntry(tmp_gensmeared,"Herwig","L");
            leg2->AddEntry(tmp_gen,"Pythia","L");
            leg2->Draw();

            if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps(");
            else if(ieta == 4 && ipt == 12 && ialpha == 6) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps)");
            else c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps"); 
         }

         // Covariance matrices needed for fitting 
         TMatrixD y_cov_mc;
         TMatrixD y_cov_data;
         TMatrixD y_cov_gen;
         y_cov_mc.ResizeTo(alpha.size(), alpha.size());
         y_cov_data.ResizeTo(alpha.size(), alpha.size());
         y_cov_gen.ResizeTo(alpha.size(), alpha.size());

         // fill covariance matrix for data and mc
         for(int ialpha=0; ialpha < alpha.size(); ++ialpha){
            for (Int_t jalpha =0; jalpha < alpha.size(); jalpha++){
               if( ialpha <= jalpha ) {
                  double n1_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2));
                  double n2_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2));
          
                  double n1_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2));
                  double n2_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2));

                  double n1_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2));
                  double n2_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2));

                  y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(ialpha),2) * pow((n1_mc/n2_mc),2)*
                     (MCy.at(ialpha)/MCy.at(jalpha));
                  y_cov_data(ialpha, jalpha) = pow(Datay_e.at(ialpha),2) * pow((n1_data/n2_data),2)*
                     (Datay.at(ialpha)/Datay.at(jalpha));  
                  y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(ialpha),2) * pow((n1_gen/n2_gen),2)*
                     (Geny.at(ialpha)/Geny.at(jalpha));  
               }
               else {
                  double n1_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2));
                  double n2_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2));

                  double n1_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2));
                  double n2_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2));

                  double n1_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2));
                  double n2_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2));

                  y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(jalpha),2) * pow((n1_mc/n2_mc),2)*
                     (MCy.at(jalpha)/MCy.at(ialpha));
                  y_cov_data(ialpha, jalpha) = pow(Datay_e.at(jalpha),2) * pow((n1_data/n2_data),2)*
                     (Datay.at(jalpha)/Datay.at(ialpha));
                  y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(jalpha),2) * pow((n1_gen/n2_gen),2)*
                     (Geny.at(jalpha)/Geny.at(ialpha));
               }
            }
         }        
  
         //create TGraphErrors from previously defined vectors
         TGraphErrors *extrapol_MC = new TGraphErrors(alpha.size(),&x[0],&MCy[0],&x_e[0],&MCy_e[0]);
         TGraphErrors *extrapol_Data = new TGraphErrors(alpha.size(),&x[0],&Datay[0],&x_e[0],&Datay_e[0]);
         TGraphErrors *extrapol_Gen = new TGraphErrors(alpha.size(),&x[0],&Geny[0],&x_e[0],&Geny_e[0]);
 
         // fit linear extrapolation function
         TF1 *lin_extrapol_mc = new TF1("lin_extrapol_mc","[0]+[1]*x",0,alpha.back()+0.05); 
         TF1 *lin_extrapol_data = new TF1("lin_extrapol_data","[0]+[1]*x",0,alpha.back()+0.05);
         TF1 *lin_extrapol_gen = new TF1("lin_extrapol_gen","[0]+[1]*x",0,alpha.back()+0.05);
                  
         //fit extrapolation function to the TGraphErrors for data and MC  
         // extrapol_MC->Fit("lin_extrapol_mc","Q","same",0,alpha.back()+0.05);
         //  extrapol_Data->Fit("lin_extrapol_data","Q","same",0,alpha.back()+0.05);
                 
         // fit mc
         data.reset();
         data.x_val = x;
         data.y_val = MCy;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_mc;
         data.CheckPoints();
         
         // choose start values for MC fit
         double slope = (MCy.at(MCy.size()-1) - MCy.at(MCy.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         double d_slope = slope;
         double offset = MCy.at(MCy.size()-1) - (slope*x.at(x.size()-1));
         double d_offset = offset;
             
         std::cout << "MC start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "MC fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 

         lin_extrapol_mc->SetParameter(0, offset);
         lin_extrapol_mc->SetParError(0, d_offset);
         lin_extrapol_mc->SetParameter(1, slope);
         lin_extrapol_mc->SetParError(1, d_slope);
         extrapol_MC->GetListOfFunctions()->Add(lin_extrapol_mc);
         
         data.reset();
         
         // fit data
         data.x_val = x;
         data.y_val = Datay;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_data;
         data.CheckPoints();
         
         // choose start values for data fit
         slope = (Datay.at(Datay.size()-1) - Datay.at(Datay.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         d_slope = slope;
         offset = Datay.at(Datay.size()-1) - (slope*x.at(x.size()-1));
         d_offset = offset;
            
         std::cout << "Data start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "Data fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         
         lin_extrapol_data->SetParameter(0, offset);
         lin_extrapol_data->SetParError(0, d_offset);
         lin_extrapol_data->SetParameter(1, slope);
         lin_extrapol_data->SetParError(1, d_slope);
         extrapol_Data->GetListOfFunctions()->Add(lin_extrapol_data);
         
         data.reset();

         // fit gen
         data.x_val = x;
         data.y_val = Geny;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_gen;
         data.CheckPoints();
         
         // choose start values for gen fit
         slope = (Geny.at(Geny.size()-1) - Geny.at(Geny.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         d_slope = slope;
         offset = Geny.at(Geny.size()-1) - (slope*x.at(x.size()-1));
         d_offset = offset;
            
         std::cout << "Gen start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "Gen fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         
         lin_extrapol_gen->SetParameter(0, offset);
         lin_extrapol_gen->SetParError(0, d_offset);
         lin_extrapol_gen->SetParameter(1, slope);
         lin_extrapol_gen->SetParError(1, d_slope);
         extrapol_Gen->GetListOfFunctions()->Add(lin_extrapol_gen);
         
         data.reset();

         // draw extrapolations data + mc
         TCanvas *c = new TCanvas("c","",600,600);
         std::pair <float,float> minMaxPair = determineMinMax(extrapol_Data);
         c->DrawFrame(0,minMaxPair.first*0.5-0.05,alpha.back()+0.05,minMaxPair.second*1.47,(";Threshold #alpha_{max};#sigma_{A}"));
         extrapol_MC->SetMarkerStyle(20);
         extrapol_MC->SetMarkerColor(kRed+1);
         extrapol_MC->SetLineColor(kRed+1);
         extrapol_MC->Draw("P");
         extrapol_Data->SetMarkerStyle(20);
         extrapol_Data->SetMarkerColor(kBlack);
         extrapol_Data->SetLineColor(kBlack);
         extrapol_Data->Draw("Psame");
         TF1* MCTemp = new TF1();
         TF1* DataTemp = new TF1();
         extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineColor(kRed+1);
         extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineStyle(2);
         extrapol_Data->GetFunction("lin_extrapol_data")->SetLineColor(kBlack);
         extrapol_Data->GetFunction("lin_extrapol_data")->SetLineStyle(2);
         MCTemp=(TF1*) extrapol_MC->GetFunction("lin_extrapol_mc")->Clone();
         DataTemp=(TF1*) extrapol_Data->GetFunction("lin_extrapol_data")->Clone();
         MCTemp->SetRange(0.1,1);
         MCTemp->SetLineStyle(1);
         MCTemp->Draw("same");
         DataTemp->SetRange(0.1,1);
         DataTemp->SetLineStyle(1);
         DataTemp->Draw("same");
       
         TPaveText *label = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.5);
         label->AddText("Anti-k_{T} (R=0.5) PFchs Jets");
         label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
         label->Draw("same");
  
         TLegend* leg1 = util::LabelFactory::createLegendWithOffset(2,0.6);
         leg1->AddEntry(extrapol_Data,"Extrapolation (MC smeared)","LP");
         leg1->AddEntry(extrapol_MC,"Extrapolation (MC)","LP");

         leg1->Draw();
         cmsPrel(-1, false , 8);

         TString name;
         name = Form("ClosureTest/Extrapol_Eta%i_pt%i" + suffix + ".eps", ieta, ipt);
         c->Print(name);

         TCanvas *cb = new TCanvas("c","",600,600);
         std::pair <float,float> minMaxPair2 = determineMinMax(extrapol_Data);
         cb->DrawFrame(0,minMaxPair2.first*0.5-0.05,alpha.back()+0.05,minMaxPair2.second*1.47,(";Threshold #alpha_{max, gen};#sigma_{A, gen}"));
         extrapol_Gen->SetMarkerStyle(20);
         extrapol_Gen->SetMarkerColor(kBlue+1);
         extrapol_Gen->SetLineColor(kBlue+1);
         extrapol_Gen->Draw("P");
         TF1* GenTemp = new TF1();
         extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineColor(kBlue+1);
         extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineStyle(2);
         GenTemp=(TF1*) extrapol_Gen->GetFunction("lin_extrapol_gen")->Clone();
         GenTemp->SetRange(0.1,1);
         GenTemp->SetLineStyle(1);
         GenTemp->Draw("same");

         TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.05);
         label2->AddText("Anti-k_{T} (R=0.5) PFchs Jets");
         label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
         label2->Draw("same");
  
         TLegend* leg2 = util::LabelFactory::createLegendWithOffset(2,0.15);
         leg2->AddEntry(extrapol_Gen,"Extrapolation (PLI)","LP");

         leg2->Draw();
         cmsPrel(-1, false , 8);

         TString name2;
         name2 = Form("ClosureTest/Extrapol_Eta%i_pt%i_gen" + suffix + ".eps", ieta, ipt);
         cb->Print(name2);

         float par_data = lin_extrapol_data->GetParameter(0);
         float par_data_err = lin_extrapol_data->GetParError(0);
         float par_mc = lin_extrapol_mc->GetParameter(0);
         float par_mc_err = lin_extrapol_mc->GetParError(0);
         float par_gen = lin_extrapol_gen->GetParameter(0);
         float par_gen_err = lin_extrapol_gen->GetParError(0);
       
         cout << "ieta : " << ieta << "  ipt : " << ipt << endl;
         cout << "Parameter data: " << par_data << endl;
         cout << "Parameter error data: " << par_data_err << endl;
         cout << "Parameter mc: " << par_mc << endl;
         cout << "Parameter error mc: " << par_mc_err << endl;
         cout << "Parameter gen: " << par_gen << endl;
         cout << "Parameter error gen: " << par_gen_err << endl;

         extrapolated_mcsmeared->SetBinContent(ipt+1, par_data);
         extrapolated_mcsmeared->SetBinError(ipt+1, par_data_err);
         extrapolated_mc->SetBinContent(ipt+1, par_mc);
         extrapolated_mc->SetBinError(ipt+1, par_mc_err);   
         extrapolated_gen->SetBinContent(ipt+1, par_gen);
         extrapolated_gen->SetBinError(ipt+1, par_gen_err);    

         float par_data_pli_corr = 0;
         float par_data_pli_corr_err = 0;
         float par_mc_pli_corr = 0;
         float par_mc_pli_corr_err = 0;

         if(par_gen > 0 && par_data > 0 && par_mc > 0 && par_data > par_gen && par_mc > par_gen) {
            par_data_pli_corr = TMath::Sqrt(pow(par_data,2) - pow(par_gen,2));
            par_data_pli_corr_err = TMath::Sqrt( pow(par_data,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_data_err,2) +  pow(par_gen,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_gen_err,2));
            par_mc_pli_corr = TMath::Sqrt(pow(par_mc,2) - pow(par_gen,2));
            par_mc_pli_corr_err = TMath::Sqrt( pow(par_mc,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_mc_err,2) +  pow(par_gen,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_gen_err,2));
         }
            
         extrapolated_mcsmeared_with_pli->SetBinContent(ipt+1, par_data_pli_corr);
         extrapolated_mcsmeared_with_pli->SetBinError(ipt+1, par_data_pli_corr_err);
         extrapolated_mc_with_pli->SetBinContent(ipt+1, par_mc_pli_corr);
         extrapolated_mc_with_pli->SetBinError(ipt+1, par_mc_pli_corr_err);

         cout << "Parameter data after pli: " << par_data_pli_corr << endl;
         cout << "Parameter error data after pli: " << par_data_pli_corr_err << endl;
         cout << "Parameter mc after pli: " << par_mc_pli_corr << endl;
         cout << "Parameter error mc after pli: " << par_mc_pli_corr_err << endl;
      }

      // --------------------------------------- //
      // calc data/mc ratio and fit with constant
      TH1F* ratio = new TH1F(*extrapolated_mc);
      TH1F* ratio_with_pli = new TH1F(*extrapolated_mc);
      ratio->Divide(extrapolated_mcsmeared, extrapolated_mc, 1, 1);
      ratio_with_pli->Divide(extrapolated_mcsmeared_with_pli, extrapolated_mc_with_pli, 1, 1);
    
      TF1 *fit_const = new TF1("fit_const", "[0]", ratio->GetXaxis()->GetXmin(), ratio->GetXaxis()->GetXmax());
      fit_const->SetParameters(0, 1.1);
      fit_const->SetParName(0, "const");
      ratio->Fit("fit_const", "", "same");
      ratio->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]");
      ratio->GetYaxis()->SetRangeUser(0.7, 1.4);
      ratio->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)");

      RatioVsEta->SetBinContent(ieta+1, ratio->GetFunction("fit_const")->GetParameter(0));
      RatioVsEta->SetBinError(ieta+1, ratio->GetFunction("fit_const")->GetParError(0));

      TCanvas *c3 = new TCanvas("c3","",600,600);
      c3->SetLogx();
      ratio->Draw();
      TString name3;
      name3 = Form("ClosureTest/ExtrapolRatio_Eta%i" + suffix + ".eps", ieta);
      c3->Print(name3);

      ratio_with_pli->Fit("fit_const", "", "same");
      ratio_with_pli->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]");
      ratio_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4);
      ratio_with_pli->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)");
    
      TCanvas *c3b = new TCanvas("c3","",600,600);
      c3b->SetLogx();
      ratio_with_pli->Draw();
      TString name4;
      name4 = Form("ClosureTest/ExtrapolRatio_Eta%i_with_pli" + suffix + ".eps", ieta);
      c3b->Print(name4);

      RatioVsEta_with_pli->SetBinContent(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParameter(0));
      RatioVsEta_with_pli->SetBinError(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParError(0));

   }

   // draw data/mc scaling factors vs. eta
   TCanvas *c4 = new TCanvas();
   RatioVsEta->GetYaxis()->SetRangeUser(0.7, 1.3);
   RatioVsEta->GetXaxis()->SetTitle("|#eta|");
   RatioVsEta->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)");
   RatioVsEta->Draw();
   c4->Print("ClosureTest/ScalingFactorsVsEta" + suffix + ".eps");

   cout << "//----------------------------------------------//" << endl;
   cout << "Scaling factors without PLI: " << endl;
   cout << "Ratio eta1: " << RatioVsEta->GetBinContent(1) << " +- " << RatioVsEta->GetBinError(1) << endl;
   cout << "Ratio eta2: " << RatioVsEta->GetBinContent(2) << " +- " << RatioVsEta->GetBinError(2) << endl;
   cout << "Ratio eta3: " << RatioVsEta->GetBinContent(3) << " +- " << RatioVsEta->GetBinError(3) << endl;
   cout << "Ratio eta4: " << RatioVsEta->GetBinContent(4) << " +- " << RatioVsEta->GetBinError(4) << endl;
   cout << "Ratio eta5: " << RatioVsEta->GetBinContent(5) << " +- " << RatioVsEta->GetBinError(5) << endl;
   cout << "Ratio eta6: " << RatioVsEta->GetBinContent(6) << " +- " << RatioVsEta->GetBinError(6) << endl;
   cout << "Ratio eta7: " << RatioVsEta->GetBinContent(7) << " +- " << RatioVsEta->GetBinError(7) << endl;
   cout << "//----------------------------------------------//" << endl;

   TCanvas *c4b = new TCanvas();
   RatioVsEta_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4);
   RatioVsEta_with_pli->GetXaxis()->SetTitle("|#eta|");
   RatioVsEta_with_pli->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)");
   RatioVsEta_with_pli->Draw();
   c4b->Print("ClosureTest/ScalingFactorsVsEta_with_pli" + suffix + ".eps");

   cout << "//----------------------------------------------//" << endl;
   cout << "Scaling factors with PLI: " << endl;
   cout << "Ratio eta1: " << RatioVsEta_with_pli->GetBinContent(1) << " +- " << RatioVsEta_with_pli->GetBinError(1) << endl;
   cout << "Ratio eta2: " << RatioVsEta_with_pli->GetBinContent(2) << " +- " << RatioVsEta_with_pli->GetBinError(2) << endl;
   cout << "Ratio eta3: " << RatioVsEta_with_pli->GetBinContent(3) << " +- " << RatioVsEta_with_pli->GetBinError(3) << endl;
   cout << "Ratio eta4: " << RatioVsEta_with_pli->GetBinContent(4) << " +- " << RatioVsEta_with_pli->GetBinError(4) << endl;
   cout << "Ratio eta5: " << RatioVsEta_with_pli->GetBinContent(5) << " +- " << RatioVsEta_with_pli->GetBinError(5) << endl;
   cout << "Ratio eta6: " << RatioVsEta_with_pli->GetBinContent(6) << " +- " << RatioVsEta_with_pli->GetBinError(6) << endl;
   cout << "Ratio eta7: " << RatioVsEta_with_pli->GetBinContent(7) << " +- " << RatioVsEta_with_pli->GetBinError(7) << endl;
   cout << "//----------------------------------------------//" << endl;

}
Пример #16
0
void drawDifference(TH1* iH0,TH1 *iH1,TH1* iH2, TGraphErrors* iH3, int chnl,TGraphErrors* iH4,TGraphAsymmErrors* iH5,TH1* StatErrBand,TGraphErrors* iH6){
  std::string lName = std::string(iH0->GetName());
  TH1F *lHDiff  = new TH1F((lName+"Diff").c_str(),(lName+"Diff").c_str(),nBins-1,WptLogBins);// lHDiff->Sumw2();
  TH1F *lXHDiff1 = new TH1F((lName+"XDiff1").c_str(),(lName+"XDiff1").c_str(),iH0->GetNbinsX(),iH0->GetXaxis()->GetXmin(),iH0->GetXaxis()->GetXmax());
  int i1 = 0;
  lXHDiff1->SetLineWidth(2); lXHDiff1->SetLineColor(kBlack); //lXHDiff1->SetLineStyle(2);
  
  StatErrBand->SetMarkerStyle(kFullCircle); StatErrBand->SetMarkerColor(kBlack);StatErrBand->SetMarkerSize(0.6);
  StatErrBand->SetLineWidth(2); StatErrBand->SetLineColor(kBlack);

  //lHDiff->GetYaxis()->SetRangeUser(0.2,1.8);
  lHDiff->GetYaxis()->SetRangeUser(0.6,1.5);
  if (chnl == 2)
    lHDiff->GetYaxis()->SetRangeUser(0.4,1.4);
  if (chnl == 3)
    lHDiff->GetYaxis()->SetRangeUser(0.3,1.3);
  lHDiff->GetYaxis()->SetTitleOffset(0.4);
  lHDiff->GetYaxis()->SetTitleSize(0.12);
  lHDiff->GetYaxis()->SetLabelSize(0.12);
  lHDiff->GetYaxis()->CenterTitle();
  lHDiff->GetXaxis()->SetTitleOffset(1.);
  lHDiff->GetXaxis()->SetTitleSize(0.12);
  lHDiff->GetXaxis()->SetLabelSize(0);
  if(chnl==3)
    lHDiff->GetXaxis()->SetLabelSize(0.12);
  lHDiff->GetYaxis()->SetNdivisions(405);
  if (chnl == 3)
    lHDiff->GetXaxis()->SetTitle(" W p_{T} ");
  lHDiff->GetYaxis()->SetTitle("Theory/Data");
  //lHDiff->GetYaxis()->SetTitle("Data/ResBos");
  gStyle->SetOptStat(0);
  
  for(int i0 = 0; i0 < lHDiff->GetNbinsX()+1; i0++) {
    double lXCenter = lHDiff->GetBinCenter(i0);
    double lXVal     = iH0   ->GetBinContent(i0);
    lXHDiff1->SetBinContent(i0, 1.0);
    while(iH1->GetBinCenter(i1) < lXCenter) {i1++;}
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinContent(i0,lXVal/(iH1->GetBinContent(i0)));
    //if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError(i0,iH0->GetBinError(i0)/(iH1->GetBinContent(i0)));
    if(iH1->GetBinContent(i0) > 0) lHDiff->SetBinError(i0,0.00001);
  }
  
  TGraphErrors* ErrBand = new TGraphErrors(iH2);
  ErrBand->SetFillColor(kBlack);
  ErrBand->SetFillStyle(3354);
  ErrBand->SetLineWidth(1);
  
  if (chnl == 1)
  {
    lHDiff->SetMarkerStyle(kOpenCircle);
    lHDiff->SetMarkerColor(kBlue);
    lHDiff->SetLineColor(kBlue);
  }
  if (chnl == 2)
  {
    lHDiff->SetMarkerStyle(kOpenTriangleUp);
    lHDiff->SetMarkerColor(kRed);
    lHDiff->SetLineColor(kRed);
  }
  if (chnl == 3)
  {
    lHDiff->SetMarkerStyle(kOpenSquare);
    lHDiff->SetMarkerColor(kGreen+3);
    lHDiff->SetLineColor(kGreen+3);
  }
  
  lHDiff->SetMarkerSize(0.8);
  
  //lHDiff->SetLineColor(kBlack); lHDiff->SetMarkerColor(kBlack);
  
  lHDiff->SetTitle("");
  lHDiff->Draw("E");
  if (chnl == 1)
    iH5->Draw("2same");
  if (chnl == 2 || chnl == 3)
    iH4->Draw("2same");
  if (chnl == 2 || chnl == 3)
    iH3->Draw("2same");
  if (chnl == 3)
    iH6->Draw("2");
  lXHDiff1->Draw("histsame");
  ErrBand->Draw("2same");
  lHDiff->Draw("Esame");
  StatErrBand->Draw("E1same");
}
Пример #17
0
void drawFigure4a(TString var="Njets") 
{
  gInterpreter->ExecuteMacro("GoodStyle.C");
  gROOT->LoadMacro("tdrstyle.C");                                                                                                                           
  setTDRStyle();    

  TString variable = "p_{T,max}^{#font[12]{l}}";
  std::ostringstream filename, madname;
  filename<<"rootfiles/all_unfolding_"<<var<<".root";
  TFile* file = new TFile(filename.str().c_str(), "read");
  madname<<"hGenXs"<<var<<"_1";
  std::cout<<madname.str().c_str()<<std::endl;
  TH1F* xsValue          = (TH1F*)(file->Get("hComb_diff")->Clone("xsValue"));
  TH1F* xsValue_Madgraph = (TH1F*)(file->Get(madname.str().c_str())->Clone("xsValue_Madgraph"));
  TH1F* xsValue_MCnlo    = (TH1F*)(file->Get("mcfm_tot")->Clone("xsValue_MCnlo"));

  // Set the data errors- I don't need this because I already have complete error in my plot
  //----------------------------------------------------------------------------
  
  // Data cosmetics
  //----------------------------------------------------------------------------
  xsValue->SetLineWidth(1);
  xsValue->SetMarkerSize(_msize);
  xsValue->SetMarkerStyle(kFullCircle);
  xsValue->SetMarkerColor(kBlack);
  xsValue->SetLineColor(kBlack);
  xsValue->SetFillStyle(1001);
  xsValue->SetFillColor(kWhite);
  // Madgraph cosmetics
  //----------------------------------------------------------------------------
  xsValue_Madgraph->SetFillColor(kOrange);
  //xsValue_Madgraph->SetFillColor(kWhite);
  xsValue_Madgraph->SetFillStyle(1001);
  xsValue_Madgraph->SetLineColor(kOrange+7);
  xsValue_Madgraph->SetLineWidth(1);
  xsValue_Madgraph->SetMarkerColor(kOrange+7);
  xsValue_Madgraph->SetMarkerSize(_msize);
  xsValue_Madgraph->SetMarkerStyle(21);


  // MCNLO cosmetics
  //----------------------------------------------------------------------------
  xsValue_MCnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  xsValue_MCnlo->SetFillStyle(1001);
  xsValue_MCnlo->SetLineColor(kAzure);
  xsValue_MCnlo->SetLineWidth(1);
  xsValue_MCnlo->SetMarkerColor(kAzure);
  xsValue_MCnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  xsValue_MCnlo->SetMarkerStyle(24);

  //  TCanvas * c1=new TCanvas("c1", "c1");
  
//xsValue_MCnlo->Draw("pey0");
   

  // Set the canvas and pads
  //----------------------------------------------------------------------------
  TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 600);
  //  TCanvas* canvas = new TCanvas("wwxs", "wwxs"); 

  //defalut
  //TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 850);
  //  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.55, 1, 1.000);
  //TPad* pad2 = new TPad("pad2", "pad2", 0, 0.39, 1, 0.552);
  //TPad* pad3 = new TPad("pad3", "pad3", 0, 0.23, 1, 0.392);

  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.49, 1, 1.000);
  TPad* pad2 = new TPad("pad2", "pad2", 0, 0.33, 1, 0.492);
  TPad* pad3 = new TPad("pad3", "pad3", 0, 0, 1, 0.332);
  
  pad1->SetTopMargin(0.09);
  pad2->SetTopMargin(0);
  pad3->SetTopMargin(0);

  pad1->SetBottomMargin(0);
  pad2->SetBottomMargin(0);
  //  pad3->SetBottomMargin(0.15);
  pad3->SetBottomMargin(0.45);

  pad1->SetLeftMargin(0.16);
  pad2->SetLeftMargin(0.16);
  pad3->SetLeftMargin(0.16);

  pad1->SetRightMargin(0.06);
  pad2->SetRightMargin(0.06);
  pad3->SetRightMargin(0.06);



  // pad1
  //----------------------------------------------------------------------------
  pad1->Draw();
  pad1->cd();
  pad1->SetLogy();


  // Draw
  //----------------------------------------------------------------------------
  AxisFonts(xsValue->GetXaxis(), variable + " (GeV)");
  if (var=="Zpt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{Z}");
  if (var=="LeadingJetPt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{LeadingJet}");
  
  //TH1F* hpowError = (TH1F*)xsValue_Powheg->Clone();
  //  TH1F* hmadError = (TH1F*)xsValue_Madgraph->Clone();
  //TH1F* hmcError  = (TH1F*)xsValue_MCnlo->Clone();

  xsValue         ->Draw("pe");
  xsValue_Madgraph->Draw("p,same");
  xsValue_MCnlo   ->Draw("p,same");

  xsValue->SetMinimum(1.1e-4);

 
  // Legend
  //----------------------------------------------------------------------------
  DrawLegend(0.718, 0.80, xsValue,   " Data",     "lp");
  DrawLegend(0.718, 0.74, xsValue_Madgraph, " Madgraph", "flp");  
  DrawLegend(0.718, 0.68, xsValue_MCnlo,  " MCFM",   "flp");


  // Draw text 
  //----------------------------------------------------------------------------
  DrawLatex(_cmsTextFont,   0.173, 0.935, 0.065, 11, "CMS");
  DrawLatex(_extraTextFont, 0.268, 0.935, 0.035, 11, "Preliminary");
  DrawLatex(_lumiTextFont,  0.940, 0.935, 0.050, 31, "19.6 fb^{-1} (8 TeV)");


  // Prepare the ratios
  //----------------------------------------------------------------------------
  TH1F* ratio_mad    = xsValue_Madgraph->Clone("ratio");
  TH1F* ratio_mcnlo  = xsValue_Madgraph->Clone("ratio");
  //  TH1F* ratio_mcnlo  = xsValue_MCnlo->Clone("ratio");
  TH1F* hratio_mad   = xsValue_Madgraph->Clone("ratio");
  TH1F* hratio_mcnlo = xsValue_MCnlo->Clone("ratio");
  TH1F* ratioErr     = xsValue->Clone("ratio");


  ratioErr->SetFillColor  (kGray+2);
  ratioErr->SetFillStyle  (   3004);
  ratioErr->SetLineColor  (kGray+2);
  ratioErr->SetMarkerColor(kGray+2);
  ratioErr->SetMarkerSize (      0);


  // Set the bin content
  //----------------------------------------------------------------------------
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {
   
    Double_t madValue = xsValue_Madgraph->GetBinContent(ibin);
    //Double_t madError = xsValue_Madgraph->GetBinError  (ibin);
   
    Double_t mcnloValue = xsValue_MCnlo->GetBinContent(ibin);
    //Double_t mcnloError = xsValue_MCnlo->GetBinError  (ibin);
   
    Double_t dataValue = xsValue->GetBinContent(ibin);
    
    Double_t dataError = xsValue->GetBinError(ibin);
   
    Double_t ratioValue_mad = (madValue > 0) ? madValue / dataValue : 0.0;
    //Double_t ratioError_mad = (madValue > 0) ? madError / dataValue : 0.0;
    Double_t ratioError_mad = madValue/pow(dataValue,2)*dataError;
    Double_t ratioValue_mcnlo = (mcnloValue > 0) ? mcnloValue / dataValue : 0.0;
    // Double_t ratioError_mcnlo = (mcnloValue > 0) ? mcnloError / dataValue : 0.0;
    Double_t ratioError_mcnlo = mcnloValue/pow(dataValue,2)*dataError;
   
    Double_t uncertaintyError = (dataValue > 0) ? dataError / dataValue : 0.0;
   
    ratio_mad ->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinError  (ibin, ratioError_mad);
   
    ratio_mcnlo ->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
   
    ratioErr->SetBinContent(ibin, 1.0);
    ratioErr->SetBinError  (ibin, uncertaintyError);  //??? ovo nije bas jasno sto je
  }


  //  AxisFontsRatio(ratioErr->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratioErr->GetXaxis(), "x", variable + " (GeV)");
  AxisFontsRatio(ratio_mad->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratio_mad->GetXaxis(), "x", variable + " (GeV)");

  AxisFontsRatio(ratio_mcnlo->GetYaxis(), "y", "Theory / Data");

  if (var=="Zpt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{Z} (GeV)");
  if (var=="LeadingJetPt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{LeadingJet} (GeV)");
  ratio_mcnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  ratio_mcnlo->SetFillStyle(1001);
  ratio_mcnlo->SetLineColor(kAzure);
  ratio_mcnlo->SetLineWidth(1);
  ratio_mcnlo->SetMarkerColor(kAzure);
  ratio_mcnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  ratio_mcnlo->SetMarkerStyle(24);

  // Draw pad2
  //----------------------------------------------------------------------------
  canvas->cd();
  pad2->Draw();
  pad2->cd();
  
  //ratioErr  ->Draw("e2");
  
  ratio_mad ->Draw("pz");
  hratio_mad->Draw("e2,same");
  ratio_mad ->Draw("p, same");
  ratio_mad->GetYaxis()->SetRangeUser(0.1, 2.3);  

  pad2->Modified();
  
  DrawLatex(43, 0.2, 0.79, 15.0, 11, "Madgraph+Pythia normalized to #sigma_{NLO}");
  

  // Draw pad3
  //----------------------------------------------------------------------------
  canvas->cd();
  pad3->Draw();
  pad3->cd();
  std::cout<<"Default option: "<<ratio_mcnlo->GetOption()<<std::endl;
  
  //ratioErr    ->Draw("e2");
  ratio_mcnlo->Draw("pz");
  hratio_mcnlo->Draw("e2,same");

  ratio_mcnlo ->Draw("pz, same");
  ratio_mcnlo->GetYaxis()->SetRangeUser(0.1, 2.3);  
  //ratio_mcnlo->GetYaxis()->SetRangeUser(0.0, 0.5);  
  
  pad3->Modified();

  DrawLatex(43, 0.2, 0.89, 15.0, 11, "MCFM");
  
    

  // Save
  //----------------------------------------------------------------------------
  pad1->cd(); pad1->GetFrame()->DrawClone();
  pad2->cd(); pad2->GetFrame()->DrawClone();
  pad3->cd(); pad3->GetFrame()->DrawClone();

  canvas->cd();

  std::ostringstream saveName, saveName2;
  saveName  << "pdf/unfolded_"<<var<<".pdf";
  saveName2 << "png/unfolded_"<<var<<".png";
  canvas->SaveAs(saveName.str().c_str());
  canvas->SaveAs(saveName2.str().c_str());
}
Пример #18
0
void MakeVtxEffPlots(TString foldname="",Bool_t savefile=kFALSE){
  
  //Make efficiency plots for SPD vertex, TRK Vertex and TPC Vertex
  // Author: 
  // L. Milano, [email protected]
  
  TFile *infil=new TFile(Form("%sAnalysisResults.root",foldname.Data()),"read");
  TDirectory *dirFile=(TDirectory*)infil->Get("Vertex_Performance");
  TList *cOutput = (TList*)dirFile->Get("cOutputVtxESD");
    
  TH1F *fhTriggeredTrklets=(TH1F*)cOutput->FindObject("fhTriggeredTrklets");
  TH1F *fhSPDZTrklets=(TH1F*)cOutput->FindObject("fhSPDZTrklets");
  TH1F *fhSPD3DTrklets=(TH1F*)cOutput->FindObject("fhSPD3DTrklets");
  TH1F *fhTRKTrklets=(TH1F*)cOutput->FindObject("fhTRKTrklets");
  TH1F *fhTRKcTrklets=(TH1F*)cOutput->FindObject("fhTRKcTrklets");
  TH1F *fhTRKncTrklets=(TH1F*)cOutput->FindObject("fhTRKncTrklets");
  TH1F *fhTPCTrklets=(TH1F*)cOutput->FindObject("fhTPCTrklets");
  TH1F *fhTPCcTrklets=(TH1F*)cOutput->FindObject("fhTPCcTrklets");
  TH1F *fhTPCncTrklets=(TH1F*)cOutput->FindObject("fhTPCncTrklets");
  TH1F *fhSPDZZreco=(TH1F*)cOutput->FindObject("fhSPDZZreco");
  TH1F *fhSPD3DZreco=(TH1F*)cOutput->FindObject("fhSPD3DZreco");
  
  TGraphAsymmErrors *fhSPDZEffTrklets=new TGraphAsymmErrors(fhSPDZTrklets,fhTriggeredTrklets,"w");
  fhSPDZEffTrklets->SetName("fhSPDZEffTrklets");
  fhSPDZEffTrklets->SetDrawOption("AP");
  TGraphAsymmErrors *fhSPD3DEffTrklets=new TGraphAsymmErrors(fhSPD3DTrklets,fhTriggeredTrklets,"w");
  fhSPD3DEffTrklets->SetName("fhSPD3DEffTrklets");
  TH1F * fhSPDOverallTrklets=(TH1F*)fhSPDZTrklets->Clone("fhSPDOverallTrklets");
  fhSPDOverallTrklets->Add(fhSPD3DTrklets);
  TGraphAsymmErrors *fhSPDOverallEffTrklets=new TGraphAsymmErrors(fhSPDOverallTrklets,fhTriggeredTrklets,"w");
  fhSPDOverallEffTrklets->SetName("fhSPDOverallEffTrklets");
  TGraphAsymmErrors *fhTRKEffTrklets=new TGraphAsymmErrors(fhTRKTrklets,fhTriggeredTrklets,"w");
  fhTRKEffTrklets->SetName("fhTRKEffTrklets");
  TGraphAsymmErrors *fhTRKcEffTrklets=new TGraphAsymmErrors(fhTRKcTrklets,fhTriggeredTrklets,"w");
  fhTRKcEffTrklets->SetName("fhTRKcEffTrklets");
  TGraphAsymmErrors *fhTRKncEffTrklets=new TGraphAsymmErrors(fhTRKncTrklets,fhTriggeredTrklets,"w");
  fhTRKncEffTrklets->SetName("fhTRKncEffTrklets");
  TGraphAsymmErrors *fhTPCEffTrklets=new TGraphAsymmErrors(fhTPCTrklets,fhTriggeredTrklets,"w");
  fhTPCEffTrklets->SetName("fhTPCEffTrklets");
  TGraphAsymmErrors *fhTPCcEffTrklets=new TGraphAsymmErrors(fhTPCcTrklets,fhTriggeredTrklets,"w");
  fhTPCcEffTrklets->SetName("fhTPCcEffTrklets");
  TGraphAsymmErrors *fhTPCncEffTrklets=new TGraphAsymmErrors(fhTPCncTrklets,fhTriggeredTrklets,"w");
  fhTPCncEffTrklets->SetName("fhTPCncEffTrklets");
  TH1F * fhSPDOverallZreco=(TH1F*)fhSPDZZreco->Clone("fhSPDOverallZreco");
  fhSPDOverallZreco->Add(fhSPD3DZreco);
  TGraphAsymmErrors *fhSPDEffZreco=new TGraphAsymmErrors(fhSPD3DZreco,fhSPDOverallZreco,"w");
  fhSPDEffZreco->SetName("fhSPDEffZreco");

  TH1F *fhEff = new TH1F("hEff","hEff",9,0.5,9.5);
  Int_t count=1;
  if(fhSPDZTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhSPDZTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhSPDZTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"SPDZ");
  
  count++;
  if(fhSPD3DTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhSPD3DTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhSPD3DTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"SPD3D");
  
  count++;
  if(fhSPDOverallTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhSPDOverallTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhSPDOverallTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"SPD Overall");
  
  count++;
  if(fhTRKTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTRKTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTRKTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TRK");
  
  count++;
  if(fhTRKcTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTRKcTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTRKcTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TRKc");
  
  count++;
  if(fhTRKncTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTRKncTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTRKncTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TRKnc");
  
  count++;
  if(fhTPCTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTPCTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTPCTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TPC");
  
  count++;
  if(fhTPCcTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTPCcTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTPCcTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TPCc");
  
  count++;
  if(fhTPCncTrklets->GetEntries()!=0 && fhTriggeredTrklets->GetEntries()!=0){
    fhEff->Fill(count,fhTPCncTrklets->GetEntries()/fhTriggeredTrklets->GetEntries());
    fhEff->SetBinError(count,fhEff->GetBinContent(count)*TMath::Sqrt(1/fhTPCncTrklets->GetEntries()+1/fhTriggeredTrklets->GetEntries()));
  }
  fhEff->GetXaxis()->SetBinLabel(count,"TPCnc");
  
  TCanvas *canvSPDTrklets=new TCanvas("canvSPDTrklets","SPD Eff vs tracklet multiplicy");
  canvSPDTrklets->SetBottomMargin(0.14);
  canvSPDTrklets->SetTopMargin(0.08);
  canvSPDTrklets->SetLeftMargin(0.14);
  canvSPDTrklets->SetRightMargin(0.08);
  fhSPDZEffTrklets->SetMinimum(0);
  fhSPDZEffTrklets->SetMaximum(1.2);
  fhSPDZEffTrklets->GetXaxis()->SetTitle("tracklet multiplicity");
  fhSPDZEffTrklets->GetXaxis()->SetTitleSize(0.05);
  fhSPDZEffTrklets->GetYaxis()->SetTitle("efficiency");
  fhSPDZEffTrklets->GetYaxis()->SetTitleSize(0.05);
  setDrawAtt(22,4,2,4,2,fhSPDZEffTrklets);
  setDrawAtt(23,2,2,2,2,fhSPD3DEffTrklets);
  setDrawAtt(24,1,2,1,2,fhSPDOverallEffTrklets);
  fhSPDZEffTrklets->SetTitle("SPDZ efficiency");
  fhSPDZEffTrklets->Draw("ALP");
  fhSPD3DEffTrklets->Draw("PLSAME");
  fhSPDOverallEffTrklets->Draw("PLSAME"); 
  TLegend *legSPD=new TLegend(0.6,0.2,0.9,0.4);
  legSPD->AddEntry(fhSPD3DEffTrklets,"SPD3D","P");
  legSPD->AddEntry(fhSPDZEffTrklets,"SPDZ","P");
  legSPD->AddEntry(fhSPDOverallEffTrklets,"SPDZ + SPD3D","P");
  legSPD->Draw();
  
  TCanvas *canvTRKTrklets=new TCanvas("canvTRKTrklets","TRK Eff vs tracklet multiplicy");
  canvTRKTrklets->SetBottomMargin(0.14);
  canvTRKTrklets->SetTopMargin(0.08);
  canvTRKTrklets->SetLeftMargin(0.14);
  canvTRKTrklets->SetRightMargin(0.08);
  fhTRKEffTrklets->SetMinimum(0);
  fhTRKEffTrklets->SetMaximum(1.2);
  fhTRKEffTrklets->GetXaxis()->SetTitle("tracklet multiplicity");
  fhTRKEffTrklets->GetXaxis()->SetTitleSize(0.05);
  fhTRKEffTrklets->GetYaxis()->SetTitle("efficiency");
  fhTRKEffTrklets->GetYaxis()->SetTitleSize(0.05);
  setDrawAtt(22,4,2,4,2,fhTRKEffTrklets);
  setDrawAtt(23,2,2,2,2,fhTRKcEffTrklets);
  setDrawAtt(24,1,2,1,2,fhTRKncEffTrklets);
  fhTRKEffTrklets->SetTitle("TRK efficiency");
  fhTRKEffTrklets->Draw("ALP");
  fhTRKcEffTrklets->Draw("PLSAME");
  fhTRKncEffTrklets->Draw("PLSAME"); 
  TLegend *legTRK=new TLegend(0.6,0.2,0.9,0.4);
  legTRK->AddEntry(fhTRKEffTrklets,"TRK","P");  
  legTRK->AddEntry(fhTRKcEffTrklets,"TRKc","P");
  legTRK->AddEntry(fhTRKncEffTrklets,"TRKnc","P");
  legTRK->Draw();
  
  TCanvas *canvTPCTrklets=new TCanvas("canvTPCTrklets","TPC Eff vs tracklet multiplicy");
  canvTPCTrklets->SetBottomMargin(0.14);
  canvTPCTrklets->SetTopMargin(0.08);
  canvTPCTrklets->SetLeftMargin(0.14);
  canvTPCTrklets->SetRightMargin(0.08);
  fhTPCEffTrklets->SetMinimum(0);
  fhTPCEffTrklets->SetMaximum(1.2);
  fhTPCEffTrklets->GetXaxis()->SetTitle("tracklet multiplicity");
  fhTPCEffTrklets->GetXaxis()->SetTitleSize(0.05);
  fhTPCEffTrklets->GetYaxis()->SetTitle("efficiency");
  fhTPCEffTrklets->GetYaxis()->SetTitleSize(0.05);
  setDrawAtt(22,4,2,4,2,fhTPCEffTrklets);
  setDrawAtt(23,2,2,2,2,fhTPCcEffTrklets);
  setDrawAtt(24,1,2,1,2,fhTPCncEffTrklets);
  fhTPCEffTrklets->SetTitle("TPC efficiency");
  fhTPCEffTrklets->Draw("ALP");
  fhTPCcEffTrklets->Draw("PLSAME");
  fhTPCncEffTrklets->Draw("PLSAME"); 
  TLegend *legTPC=new TLegend(0.6,0.2,0.9,0.4);
  legTPC->AddEntry(fhTPCEffTrklets,"TPC","P");  
  legTPC->AddEntry(fhTPCcEffTrklets,"TPCc","P");
  legTPC->AddEntry(fhTPCncEffTrklets,"TPCnc","P");
  legTPC->Draw();
  
  TCanvas *canvZ=new TCanvas("canvZ","3D/reco vs Z");
  canvZ->SetBottomMargin(0.14);
  canvZ->SetTopMargin(0.08);
  canvZ->SetLeftMargin(0.14);
  canvZ->SetRightMargin(0.08);
  fhSPDEffZreco->SetMinimum(0);
  fhSPDEffZreco->SetMaximum(1.2);
  fhSPDEffZreco->GetXaxis()->SetTitle("Z - <Z> [cm]");
  fhSPDEffZreco->GetXaxis()->SetTitleSize(0.05);
  fhSPDEffZreco->GetYaxis()->SetTitle("3D rec / (3D+Z rec)");
  fhSPDEffZreco->GetYaxis()->SetTitleSize(0.05);
  setDrawAtt(22,4,2,4,2,fhSPDEffZreco);
  fhSPDEffZreco->SetTitle("SPD3D/(SPD3D+Z) vs Zreco");
  fhSPDEffZreco->Draw("AP");
  TLegend *legZ=new TLegend(0.6,0.2,0.9,0.4);
  legZ->AddEntry(fhSPDEffZreco,"SPD3D/(SPD3D+Z) vs Zreco","P");
  legZ->Draw();
  
  TCanvas *canvOverall=new TCanvas("canvOverall","Eff integrated over multiplicy");
  canvOverall->SetBottomMargin(0.14);
  canvOverall->SetTopMargin(0.08);
  canvOverall->SetLeftMargin(0.14);
  canvOverall->SetRightMargin(0.08);
  fhEff->SetMinimum(0);
  fhEff->SetMaximum(1.2);
  fhEff->GetXaxis()->SetTitleSize(0.05);
  fhEff->GetYaxis()->SetTitle("efficiency");
  fhEff->GetYaxis()->SetTitleSize(0.05);
  fhEff->SetTitle("integrated over multiplicity");
  fhEff->Draw("");

  if(savefile){
  TFile* fileEff = new TFile("VtxEff.root","recreate");
  fhSPDZEffTrklets->Write();
  fhSPD3DEffTrklets->Write();
  fhSPDOverallEffTrklets->Write();
  fhTRKEffTrklets->Write();
  fhTRKcEffTrklets->Write();
  fhTRKncEffTrklets->Write();
  fhSPDEffZreco->Write();
  fhEff->Write();
  fileEff->Close();
  delete fileEff;
  }
  
  
}
Пример #19
0
void tpcanalall(Int_t isec =1, Int_t lstep = 1,Float_t tmin=400)
{
   AliTPCParam * tpcparam = gtpc->GetParam();
 //make window for displaying results
  TCanvas  * c_occu = new TCanvas("coccu","Occupancy dependence",700,900);
  c_occu->Update();
  TPad * pad1 = new TPad("occupancy","occupancy",0.05,0.25,0.95,0.95,21);
  pad1->Draw();
  //add comments to the histograms 
  TPaveText * comment = new TPaveText(0.05,0.03,0.95,0.2,"NDC");
  comment->SetTextAlign(12);
  comment->SetFillColor(42);
  comment->ReadFile("comment.txt");
  comment->Draw();
  //prepare histogram 
  Int_t irow = tpcparam->GetNRow(isec);
  Float_t xmin = tpcparam->GetPadRowRadii(isec,1);
  Float_t xmax = tpcparam->GetPadRowRadii(isec,irow);  
  pad1->cd();
  char s[220];
  char sh[220];
  sprintf(s,"occu_sector%d",isec);
  sprintf(sh,"Occupancy in sector %d as function of pad raw",isec);  
  TH1F * occudep = new TH1F(s,sh,300,xmin,xmax);
  Float_t   res[20];
  Float_t   x;
  for (Int_t i=2;i<irow;i+=lstep)
    { 
      tpcanal(isec,i,10,&res[0],kFALSE,tmin);
      x = tpcparam->GetPadRowRadii(isec,i) ;
      Int_t index = (300*(x-xmin))/(xmax-xmin);
      cout<<i<<"  "<<index<<"   "<<x<<"   "<<res[0]<<"   "<<res[1]<<"\n";  
      occudep->SetBinContent(index,res[0]);
      occudep->SetBinError(index,res[1]);      
    }
  //plot occupancy histogram
  
  pad1->SetGridx();
  pad1->SetGridy();
  gStyle->SetOptFit(0);       
  occudep->Draw("error");
  occudep->SetXTitle("pad row center position [cm]");
  occudep->SetYTitle("occupancy"); 
 
  //fit occupancy dependence
  //linear fit
  TF1 * g1 = new TF1("pol1_r","pol1");  
  occudep->Fit("pol1_r","+Q"); 
  Double_t par[3];
  Float_t error[3]; 
  Float_t chi;
  g1->GetParameters(&par[0]);
  error[0]=g1->GetParError(0);
  error[1]=g1->GetParError(1);   
  Float_t  chi = g1->GetChisquare();
  sprintf(s,"Linear fit     ocupancy = (%2.3f - %2.3f) +(%2.1f+- %2.1f).r   chi2 = %2.2f",
	  par[0],error[0],1000*par[1],1000*error[1],chi);
  comment->AddText(s);
 //(1-exp([0]1/(r*2+[1]**2)  fit
   TF1 * g1 = new TF1("polm1",occur,1,00,1);  
    occudep->Fit("polm1","+Q"); 
    Double_t par[3];
    Float_t error[3]; 
    g1->GetParameters(&par[0]);
    error[0]=g1->GetParError(0);
    //    error[1]=g1->GetParError(1);
    chi = g1->GetChisquare();
    sprintf(s,"(1-exp(P1/(x^2) fit   P1=(%2.3f+- %2.3f)    chi2=%2.2f ",
  	  par[0],error[0],chi);
    comment->AddText(s);
  c_occu->Update();
    
}
int main(int argc, char * argv[]){

        cout<<"****************************** FILES OPENING ***************************************"<<endl;

        string INPUT(argv[1]);
        string OUTPUT(argv[2]);

        FileSaver finalHistos;
        FileSaver Plots;

        finalHistos.setName(INPUT.c_str());
        Plots.setName(OUTPUT.c_str());


        bool checkfile = finalHistos.CheckFile();


        cout<<"****************************** BINS ***************************************"<<endl;

        SetBins();

	PRB.Print();

        cout<<"**TOF**"<<endl;
        ToFDB.Print();

        cout<<"**NaF**"<<endl;
        NaFDB.Print();

        cout<<"**Agl**"<<endl;
        AglDB.Print();

        ToFDB.UseBetaEdges();
        NaFDB.UseBetaEdges();
        AglDB.UseBetaEdges();

        PRB.UseREdges();


        cout<<endl;

        cout<<"****************************** PLOTTING FITS ***************************************"<<endl;

	TemplateFIT * ToFfits= new TemplateFIT(finalHistos,"TOFfits",ToFDB);
	TemplateFIT * NaFfits= new TemplateFIT(finalHistos,"NaFfits",NaFDB);
	TemplateFIT * Aglfits= new TemplateFIT(finalHistos,"Aglfits",AglDB);

	DrawFits(ToFfits,finalHistos,Plots);
	DrawFits(NaFfits,finalHistos,Plots);
	DrawFits(Aglfits,finalHistos,Plots);



	cout<<"****************************** RESULTS ***************************************"<<endl;

	TCanvas * c4 = new TCanvas("Deuteron Counts");
	c4->SetCanvasSize(2000,1500);

	std::string pathresTOF   = (ToFfits->GetName() + "/Fit Results/");
	std::string pathresNaF   = (NaFfits->GetName() + "/Fit Results/");
	std::string pathresAgl   = (Aglfits->GetName() + "/Fit Results/");
		
	TH1F * DCountsTOF = (TH1F*) finalHistos.Get((pathresTOF+"Deuteron Counts").c_str());
	TH1F * DCountsNaF = (TH1F*) finalHistos.Get((pathresNaF+"Deuteron Counts").c_str());
	TH1F * DCountsAgl = (TH1F*) finalHistos.Get((pathresAgl+"Deuteron Counts").c_str());
	TH1F * PCountsTOF = (TH1F*) finalHistos.Get((pathresTOF+"Proton Counts").c_str());
	TH1F * PCountsNaF = (TH1F*) finalHistos.Get((pathresNaF+"Proton Counts").c_str());
	TH1F * PCountsAgl = (TH1F*) finalHistos.Get((pathresAgl+"Proton Counts").c_str());
	
	TH1F * DCountsPrimTOF = (TH1F*) finalHistos.Get((pathresTOF+"Primary Deuteron Counts").c_str());
	TH1F * DCountsPrimNaF = (TH1F*) finalHistos.Get((pathresNaF+"Primary Deuteron Counts").c_str());
	TH1F * DCountsPrimAgl = (TH1F*) finalHistos.Get((pathresAgl+"Primary Deuteron Counts").c_str());
	
	PlotTH1FintoGraph(gPad,ToFDB, DCountsTOF,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Deuteron Counts (TOF)",8);
	PlotTH1FintoGraph(gPad,NaFDB, DCountsNaF,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Deuteron Counts (NaF)",22);
	PlotTH1FintoGraph(gPad,AglDB, DCountsAgl,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Deuteron Counts (Agl)",29);

	PlotTH1FintoGraph(gPad,ToFDB, DCountsPrimTOF,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Primary Counts (TOF)",4);
	PlotTH1FintoGraph(gPad,NaFDB, DCountsPrimNaF,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Primary Counts (NaF)",26);
	PlotTH1FintoGraph(gPad,AglDB, DCountsPrimAgl,"Kinetic Energy [GeV/nucl.]", "Counts",4,true,"Psame",0.1,10,10,7e4,"Primary Counts (Agl)",30);


	Plots.Add(c4);
	Plots.writeObjsInFolder("Results");


	TCanvas * c5 = new TCanvas("D/P Raw Counts ratio");
        c5->SetCanvasSize(2000,1500);
	
	TH1F * RatioTOF = (TH1F*)DCountsTOF->Clone();
	RatioTOF->Divide(PCountsTOF);
	TH1F * RatioNaF = (TH1F*)DCountsNaF->Clone();
	RatioNaF->Divide(PCountsNaF);
	TH1F * RatioAgl = (TH1F*)DCountsAgl->Clone();
	RatioAgl->Divide(PCountsAgl);

	PlotTH1FintoGraph(gPad,ToFDB, RatioTOF,"Kinetic Energy [GeV/nucl.]", "Counts ratio",2,true,"Psame",0.1,10,1e-3,1e-1,"d/P Counts ratio (TOF)",8);
	PlotTH1FintoGraph(gPad,NaFDB, RatioNaF,"Kinetic Energy [GeV/nucl.]", "Counts ratio",2,true,"Psame",0.1,10,1e-3,1e-1,"d/P Counts ratio (NaF)",22);
	PlotTH1FintoGraph(gPad,AglDB, RatioAgl,"Kinetic Energy [GeV/nucl.]", "Counts ratio",2,true,"Psame",0.1,10,1e-3,1e-1,"d/P Counts ratio (Agl)",29);


	Plots.Add(c5);
	Plots.writeObjsInFolder("Results");

	
	TCanvas * c6 = new TCanvas("Uncertainty Break-down");
        c6->SetCanvasSize(5000,1000);
	c6->Divide(3,1);

	TH1F * StatErrTOF = (TH1F*) finalHistos.Get((pathresTOF+"StatError").c_str());
        TH1F * SystErrTOF = (TH1F*) finalHistos.Get((pathresTOF+"SystError").c_str());
	TH1F * HeCoErrTOF = (TH1F*) finalHistos.Get((pathresTOF+"HeContTOF_Eff").c_str());
	TH1F * StatErrNaF = (TH1F*) finalHistos.Get((pathresNaF+"StatError").c_str());
        TH1F * SystErrNaF = (TH1F*) finalHistos.Get((pathresNaF+"SystError").c_str());
	TH1F * HeCoErrNaF = (TH1F*) finalHistos.Get((pathresNaF+"HeContNaF_Eff").c_str());
	TH1F * StatErrAgl = (TH1F*) finalHistos.Get((pathresAgl+"StatError").c_str());
        TH1F * SystErrAgl = (TH1F*) finalHistos.Get((pathresAgl+"SystError").c_str());
	TH1F * HeCoErrAgl = (TH1F*) finalHistos.Get((pathresAgl+"HeContAgl_Eff").c_str());
	
	TH1F * TotErrTOF  = (TH1F *)StatErrTOF->Clone();
	TH1F * TotErrNaF  = (TH1F *)StatErrNaF->Clone();
	TH1F * TotErrAgl  = (TH1F *)StatErrAgl->Clone();
	
	for(int bin=0;bin<DCountsTOF->GetNbinsX();bin++) {
		if(DCountsTOF->GetBinContent(bin+1)>0){
			TotErrTOF->SetBinContent(bin+1,DCountsTOF->GetBinError(bin+1)/DCountsTOF->GetBinContent(bin+1));
			TotErrTOF->SetBinError(bin+1,0);
		}
		if(DCountsNaF->GetBinContent(bin+1)>0){	
			TotErrNaF->SetBinContent(bin+1,DCountsNaF->GetBinError(bin+1)/DCountsNaF->GetBinContent(bin+1));
			TotErrNaF->SetBinError(bin+1,0);
		}
		if(DCountsAgl->GetBinContent(bin+1)>0){	
			TotErrAgl->SetBinContent(bin+1,DCountsAgl->GetBinError(bin+1)/DCountsAgl->GetBinContent(bin+1));
			TotErrAgl->SetBinError(bin+1,0);
		}	

	}	


	c6->cd(1);
	PlotDistribution(gPad,TotErrTOF ,"TOF Range Bin","Relative error",2,"same",1e-4,1.1,10,"T. Fit Total Error");
	PlotDistribution(gPad,SystErrTOF,"TOF Range Bin","Relative error",4,"same",1e-4,1.1,4,"T. Fit Systematic Error");
	PlotDistribution(gPad,StatErrTOF,"TOF Range Bin","Relative error",1,"same",1e-4,1.1,4,"T. Fit Statistical Error");
	PlotDistribution(gPad,HeCoErrTOF,"TOF Range Bin","Relative error",3,"same",1e-4,1.1,4,"Helium Fragm. Error");
	c6->cd(2);
	PlotDistribution(gPad,TotErrNaF ,"NaF Range Bin","Relative error",2,"same",1e-4,1.1,10,"T. Fit Total Error");
	PlotDistribution(gPad,SystErrNaF,"NaF Range Bin","Relative error",4,"same",1e-4,1.1,4,"T. Fit Systematic Error");
	PlotDistribution(gPad,StatErrNaF,"NaF Range Bin","Relative error",1,"same",1e-4,1.1,4,"T. Fit Statistical Error");
	PlotDistribution(gPad,HeCoErrNaF,"NaF Range Bin","Relative error",3,"same",1e-4,1.1,4,"Helium Fragm. Error");
	c6->cd(3);
	PlotDistribution(gPad,TotErrAgl ,"Agl Range Bin","Relative error",2,"same",1e-4,1.1,10,"T. Fit Total Error");
	PlotDistribution(gPad,SystErrAgl,"Agl Range Bin","Relative error",4,"same",1e-4,1.1,4,"T. Fit Systematic Error");
	PlotDistribution(gPad,StatErrAgl,"Agl Range Bin","Relative error",1,"same",1e-4,1.1,4,"T. Fit Statistical Error");
	PlotDistribution(gPad,HeCoErrAgl,"Agl Range Bin","Relative error",3,"same",1e-4,1.1,4,"Helium Fragm. Error");

	Plots.Add(c6);
	Plots.writeObjsInFolder("Results");


	
	
	TCanvas * c7 = new TCanvas("Chi Square");
        c7->SetCanvasSize(5000,1000);
	c7->Divide(3,1);

	TH1F * BestChiSquareTOF         = (TH1F*) finalHistos.Get((pathresTOF+"Best ChiSquare").c_str());
        TH1F * OriginalChiSquareTOF     = (TH1F*) finalHistos.Get((pathresTOF+"Original ChiSquare").c_str());
        TH1F * BestChiSquareNaF         = (TH1F*) finalHistos.Get((pathresNaF+"Best ChiSquare").c_str());
        TH1F * OriginalChiSquareNaF     = (TH1F*) finalHistos.Get((pathresNaF+"Original ChiSquare").c_str());
        TH1F * BestChiSquareAgl         = (TH1F*) finalHistos.Get((pathresAgl+"Best ChiSquare").c_str());
        TH1F * OriginalChiSquareAgl     = (TH1F*) finalHistos.Get((pathresAgl+"Original ChiSquare").c_str());

	c7->cd(1);
	PlotDistribution(gPad,BestChiSquareTOF ,"TOF Range Bin","#chi^2 of T. Fit",2,"Psame",1e-1,30,3,"Best #chi^{2} mod. Template");
	PlotDistribution(gPad,OriginalChiSquareTOF,"TOF Range Bin","#chi^2 of T. Fit",4,"Psame",1e-1,30,3,"Original MC Templates");
	
	c7->cd(2);
	PlotDistribution(gPad,BestChiSquareNaF ,"NaF Range Bin","#chi^2 of T. Fit",2,"Psame",1e-1,35,3,"Best #chi^{2} mod. Template");
	PlotDistribution(gPad,OriginalChiSquareNaF,"NaF Range Bin","#chi^2 of T. Fit",4,"Psame",1e-1,35,3,"Original MC Templates");

	c7->cd(3);
	PlotDistribution(gPad,BestChiSquareAgl ,"Agl Range Bin","#chi^2 of T. Fit",2,"Psame",1e-1,35,3,"Best #chi^{2} mod. Template");
	PlotDistribution(gPad,OriginalChiSquareAgl,"Agl Range Bin","#chi^2 of T. Fit",4,"Psame",1e-1,35,3,"Original MC Templates");
	
	Plots.Add(c7);
	Plots.writeObjsInFolder("Results");



	
	DrawParameters(finalHistos,Plots,pathresTOF,ToFDB,"Parameters TOF","[ps]",0.45,0.9,-100,100,-40,180);
	DrawParameters(finalHistos,Plots,pathresNaF,NaFDB,"Parameters NaF","[rad/10^{4}]",0.7,0.98,-1000,1000,-1000,2000);
	DrawParameters(finalHistos,Plots,pathresAgl,AglDB,"Parameters Agl","[rad/10^{4}]",0.95,1.005,-230,230,-150,400);



	return 0;
}
Пример #21
0
void FitAndGiveCorr(string inputfile="histo_file_HToTauTau_13TeV_Fall13dr_PU40bx25.root", TString histoName = "hTau_NeIsoVSpuCorrIso" ){
	gROOT->ProcessLine(".L ./tdrstyle.C");
	setTDRStyle();
	gStyle->SetOptStat(00000000);

	TFile* f = new TFile(inputfile.c_str());	
	TH2F*  h2  = (TH2F*)f->Get(histoName);
		
	//////////////////////////////////////////////////////////////////canvas scatter rho vs iso neutral///////////////////////////////////////////////////////////////////////////////////////////////////	
	TCanvas* canvas2 = new TCanvas("canvas2", "canvas2", 700, 700);
	h2->GetYaxis()->SetTitle("Iso^{Neutral} [GeV]");
	h2->GetXaxis()->SetTitle("PuIso [GeV]");
	h2->Draw("COLZ");
	cout<<"XY correlation factor "<<h2->GetCorrelationFactor()<<endl;
	canvas2->SaveAs( "DirPlotsPU/"+histoName+".png" );
	const int NBins = h2->GetNbinsX();
	cout<<" NBins "<<NBins<<endl;
	TH1D *ProjY; 
	ProjY = (TH1D) malloc(NBins * sizeof(TH1D));
	
	TH1F *hMean = new TH1F("hMean","hMean",NBins,0,NBins);
	TH1F *hRMS = new TH1F("hRMS","hRMS",NBins,0,NBins);
	
	double meanRMS =0;
	double den =0;
	double num =0;

	double weight[500];
	
	for(int i=0;i<NBins;++i){
		TString id =  "ProjY";
		id  ++;
		ProjY[i]= h2->ProjectionY("ProjY", i, i+1); 

		if( ProjY[i].GetEntries() > 100) {
			

		hMean->SetBinContent(i,ProjY[i].GetMean());
		hMean->SetBinError(i,ProjY[i].GetMeanError() );
	    hRMS->SetBinContent(i, ProjY[i].GetRMS());
		hRMS->SetBinError(i,ProjY[i].GetRMSError());

			//cout<<i<<" Mean "<<ProjY[i].GetMean()<<" ± "<<ProjY[i].GetMeanError()<<endl;
			//cout<<"	RMS= "<< ProjY[i].GetRMS()<<" ± "<<ProjY[i].GetRMSError()<< endl;	
			
			weight[i] = 1/ (ProjY[i].GetRMSError()*ProjY[i].GetRMSError())    ;
			//std::cout<<"weight="<<weight[i]<<endl;
			
			num +=  ((ProjY[i].GetRMS()) * weight[i] ) ;	
			den += weight[i];
			
			meanRMS +=  ProjY[i].GetRMS();
		}
		
	}
	
	cout<<" num  "<<meanRMS<<endl;
	cout<<" den  "<<den<<endl;
	double RMS = num/den ;
	
	TCanvas* canvas3 = new TCanvas("canvas3", "MEAN", 500, 500);
	canvas3->cd();
	hMean->SetMarkerColor(kBlue);
	//TF1  *fun1 = new TF1("fun1","(1-exp((-1/x)*[0]))",0,NBins) ; 
	TF1  *fun1 = new TF1("fun1"," [0]*x + [1]",0,NBins) ; 
	
	TF1  *fun1 = new TF1("fun1","[0]*(1-exp(x/[1]))",0,NBins) ; 
/*	fun1->SetParameter(0,2);
	fun1->SetParameter(1,1);
    fun1->SetParameter(2,-2);*/

	hMean->Fit("fun1","N0","E",0,NBins);
	cout<<" chi1 "<<fun1->GetChisquare()<<endl;
	hMean->Draw("pe");
	fun1->SetParameter(0,fun1->GetParameter(0));
	fun1->SetParameter(1,fun1->GetParameter(1));
	//fun1->SetParameter(2,fun1->GetParameter(2));
	
	fun1->SetLineColor(kBlue); 
	fun1->Draw("same");
	hMean->GetYaxis()->SetTitle("<Tau Neutral Isolation>");

	TCanvas* canvas4 = new TCanvas("canvas4", "RMS", 500, 500);
	canvas4->cd();
	hRMS->SetMarkerColor(kMagenta);
	hRMS->Draw("pe");
	hRMS->GetXaxis()->SetRangeUser(0,70);
	TF1  *fun2 = new TF1("fun2"," [0]*x + [1]",0,NBins) ; 
	hRMS->Fit("fun2","RN0","E",0,NBins);
	hRMS->Draw("pe");
	fun2->SetParameter(0,fun2->GetParameter(0));
	fun2->SetParameter(1,fun2->GetParameter(1));
	
	fun2->SetLineColor(kMagenta); 
	fun2->Draw("same");

	hRMS->GetYaxis()->SetTitle("RMS(P_{T}^{#gamma}) [GeV]");
	hRMS->GetXaxis()->SetTitle("N_{vtx}");
	
		
	std::cout<<"  Slope  "<<fun1->GetParameter(0)<<endl;
	std::cout<<"  Offset "<<fun1->GetParameter(1)<<endl;
	std::cout<<"  RMS    "<<RMS<<endl;

	canvas3->SaveAs("PlotNota/Mean20.pdf");
	canvas4->SaveAs("PlotNota/RMS20.pdf");
	
	
	
	TFile fout("fPU40.root","recreate"); 
	hMean->Write("MeanNeIso");
	hRMS->Write("RMS");
		
	fout.Close();
	
}
Пример #22
0
int compare(){
	
    gROOT->SetStyle("Plain");

    // For the canvas:
    gStyle->SetCanvasColor(0);

    // For the Pad:
    gStyle->SetPadColor(0);
    gStyle->SetPadTickX(1);
    gStyle->SetPadTickY(1);
    gStyle->SetPadBorderSize(2);

    // For the frame:
    gStyle->SetFrameBorderMode(0);


    // For the statistics box:
    gStyle->SetOptStat(0);

    // Margins:
    gStyle->SetPadBottomMargin(0.25);
    gStyle->SetPadTopMargin(0.15);
    gStyle->SetPadLeftMargin(0.15);
    gStyle->SetPadRightMargin(0.1);

    // For the Global title:
    gStyle->SetOptTitle(0);
    gStyle->SetTitleColor(1);
    gStyle->SetTitleFillColor(10);
    gStyle->SetTitleTextColor(1);
    gStyle->SetTitleFont(42);
    gStyle->SetTitleFontSize(0.05);
    gStyle->SetTitleBorderSize(0);

    // For the axis
    gStyle->SetNdivisions(510, "X");
    gStyle->SetNdivisions(510, "Y");
    gStyle->SetTickLength(0.03);

    // For the axis titles:
    gStyle->SetTitleOffset(1.4, "X");
    gStyle->SetTitleOffset(1.2, "Y");
    gStyle->SetTitleOffset(0.5, "Z");
    gStyle->SetTitleSize(0.061, "XYZ");
    gStyle->SetTitleFont(42, "XYZ");

    // For the axis labels:
    gStyle->SetLabelSize(0.04, "XYZ");
    gStyle->SetLabelOffset(0.01, "XYZ");
    gStyle->SetLabelFont(42, "XYZ");

    // For the legend
    gStyle->SetLegendBorderSize(0);

    gROOT->ForceStyle();

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

	TFile *f1 = new TFile("output_GetPrediction/prediction_histos_MyTest_data_METsoftSmeared_noAngSmear_N20_CR_v3.root", "READ", "", 0);
    TFile *f2 = new TFile("output_GetPrediction/bkg.root", "READ", "", 0);
	selection = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_selection");
	prediction = (TH1F*) f1->FindObjectAny("VBF_MET_presel_4JV_dPhiSide_prediction_px");
	background2 = (TH1F*) f2->FindObjectAny("met_check_inVR_rebin");
	TH1F* background = new TH1F(*prediction);
	background->Reset();
	for (int i = 1; i <= background->GetXaxis()->GetNbins(); ++i) {
		float x = background->GetXaxis()->GetBinCenter(i);
		int j = background2->GetXaxis()->FindBin(x);
		float value = background2->GetBinContent(j);
		float error = background2->GetBinError(j);
		background->SetBinContent(i,value);
		background->SetBinError(i,error);
	}
	
	//double MinX = selection->GetXaxis()->GetBinLowEdge(1);
    //double MaxX = selection->GetXaxis()->GetBinUpEdge(selection->GetXaxis()->GetNbins());
	double MinX = 150;
    double MaxX = 500;
    double BinWidth = selection->GetXaxis()->GetBinWidth(selection->GetXaxis()->GetNbins());
    double MaxY = prediction->GetBinContent(prediction->GetMaximumBin());
    double MaxYsel = selection->GetBinContent(selection->GetMaximumBin());
    if (MaxY < MaxYsel) MaxY = MaxYsel;
    double YRangeMax = 2.*pow(10., int(log10(MaxY))+2);
    double MinY = prediction->GetBinContent(prediction->GetMinimumBin());
    double MinYsel = selection->GetBinContent(selection->GetMinimumBin());
    if (MinY > MinYsel) MinY = MinYsel;
    if (MinY < 0.001) MinY = 0.001;
    double YRangeMin = 0.5*pow(10., int(log10(MinY))-2);
    TString titlePrediction;
    TString titleSelection;
    TString titleBackground;
    TString RatioTitle;
    TString LumiTitle;
    TString Title;
    TString xTitle;
    TString yTitle;

	LumiTitle = "ATLAS internal, L = 36.1 fb^{  -1}, #sqrt{s} = 13 TeV";

    Title = "3 jets, 1.8<#Delta#phi(jj)<2.7, MET>150 GeV, M(jj)>0.6 TeV, p_{T}^{3rd}<50 GeV";
    xTitle = "#slash{E}_{T} (GeV)";
    yTitle = "Events";

    titlePrediction = "Data-driven Pred.";
    titleSelection = "Data";
    titleBackground = "non-QCD background";

    RatioTitle = "(Pred-Data)/Data";

    static Int_t c_LightBrown = TColor::GetColor( "#D9D9CC" );
    static Int_t c_LightGray  = TColor::GetColor( "#DDDDDD" );

    selection->SetAxisRange(MinX, MaxX, "X");
    selection->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    selection->SetMarkerStyle(20);
    selection->SetMarkerSize(0.9);
    selection->SetMarkerColor(kBlack);
    selection->SetXTitle(xTitle);
    selection->SetYTitle(yTitle);

    prediction->SetAxisRange(MinX, MaxX, "X");
    prediction->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    prediction->SetFillColor(c_LightGray);
    prediction->SetTitle("");
    prediction->SetXTitle(xTitle);
    prediction->SetYTitle(yTitle);

    background->SetAxisRange(MinX, MaxX, "X");
    background->GetYaxis()->SetRangeUser(YRangeMin, YRangeMax);
    background->SetTitle("");
    background->SetLineColor(kRed);
    background->SetLineWidth(2);
    background->SetXTitle(xTitle);
    background->SetYTitle(yTitle);

    TCanvas *c = new TCanvas("ca", "Comparison and ratio of two histos", 700, 700);

    TPad *pad1 = new TPad("pad1a", "pad1a", 0, 0.35, 1, 1);
    pad1->SetLogy();
    pad1->SetBottomMargin(0);
    pad1->Draw();
    pad1->cd();

    prediction->DrawCopy("hist");
    selection->Draw("same");
    prediction->SetFillColor(kAzure-3);
    prediction->SetFillStyle(3354);
    prediction->DrawCopy("e2same");
    background->Scale(36.1/32.6);
    background->Draw("same");

    prediction->SetFillStyle(1001);
    //prediction->SetFillColor(c_LightBrown);
    prediction->SetFillColor(c_LightGray);

    //TLegend* leg1 = new TLegend(0.48, 0.63, 0.95, 0.83);
    TLegend* leg1 = new TLegend(0.44, 0.63, 0.91, 0.83);
    leg1->SetFillStyle(0);
    leg1->SetLineStyle(1);
    leg1->SetTextFont(42);
    //leg1->SetTextSize(0.04);
    leg1->SetTextSize(0.045);
    leg1->AddEntry(prediction, titlePrediction, "lf");
    leg1->AddEntry(selection, titleSelection, "lep");
    leg1->AddEntry(background, titleBackground, "l");
    leg1->Draw("same");

    TPaveText* pt = new TPaveText(0.11, 0.98, 0.95, 0.86, "NDC");
    pt->SetBorderSize(0);
    pt->SetFillStyle(0);
    pt->SetTextAlign(12);
    pt->SetTextSize(0.045);
    pt->AddText(Title);
    pt->AddText(LumiTitle);
    pt->Draw();

    c->cd();
    TPad *pad2 = new TPad("pad2a", "pad2a", 0, 0, 1, 0.35);
    pad2->SetTopMargin(0);
    pad2->Draw();
    pad2->cd();
    TH1F* r = new TH1F(*prediction);
    r->SetTitle("");
    r->SetLabelSize(0.08, "XYZ");
    r->SetLabelOffset(0.01, "XYZ");
    // r->SetTitleSize(0.09, "XYZ");
    r->SetTitleSize(0.125, "XYZ");
    r->SetTitleOffset(0.95, "X");
    r->SetTitleOffset(0.53, "Y");
    // r->SetTitleOffset(0.65, "Y");
    r->SetTickLength(0.05);
    r->SetYTitle(RatioTitle);
    r->SetStats(0);
    r->SetMarkerStyle(20);
    r->SetMarkerSize(0.9);
    r->SetMarkerColor(kBlack);
    r->Reset();
    r->Add(prediction, 1);
    r->Add(background, 1);
    r->Add(selection, -1);
    r->Divide(selection);
    r->SetMaximum(2.2);
    r->SetMinimum(-2.2);
    r->Draw("ep");
    TLine l;
    l.DrawLine(MinX, 0., MaxX+BinWidth, 0.);
    c->cd();
    
    c->SaveAs("compare.pdf");
	
	return 0;
}
//void pi0_mfitpeak(char *FileName, char *HistName, Int_t etapi0flag) 
void pi0_mfitpeak(TH1F *mh1, Int_t etapi0flag, float xmin, float xmax, int npol,float res[],int posFlag, const char *dirName, const char *histName, float text_x, float text_y, const char *texName) 
  
{
  TGaxis::SetMaxDigits(3);


  // TVirtualFitter::SetDefaultFitter("Minuit");
  


  // This script attempts to fit any pi0 peak so that the freaking fit function would converge
  // currently background is fitted to a pol4 function and the peak by a gaussian;
  // results are not very nice
  // usage  .x pi0_mfitpeak.C++ ("pi0calib.root","minv_spb")
  // or eg.  .x pi0_mfitpeak.C ("../pi0anal/pi0ana_punorm.root","minv_spb",0)

  gROOT->Reset();
  //  gStyle->SetOptFit();
  //  gStyle->SetOptFit(0);
  //  gStyle->SetOptStat(0);
  //  gStyle->SetOptTitle(0);
Bool_t NOTE=1;
  if(NOTE) gStyle->SetCanvasBorderMode(0);

  gStyle->SetPadTopMargin(0.08);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadRightMargin(0.08);

  mh1->GetXaxis()->SetRangeUser(xmin,xmax);
  
  Int_t highx=500;
  TCanvas *c2 = new TCanvas("c2","",200,10,highx,500);


    // cout<<FileName<<" "<<HistName<<endl;

  //     TFile f(FileName);
  //   TH1F *mh1 = (TH1F*) f.Get(HistName);
      mh1->SetMarkerStyle(20);
      mh1->SetMarkerSize(1.);
      mh1->SetStats(0); // 1/0 to set the stat box

   mh1->GetXaxis()->SetTitle("Invariant Mass of Photon Pairs (GeV/c^{2})");


   float binwidth = mh1->GetBinWidth(1);
   
   char *ytitle = new char[100];

   sprintf(ytitle,"Photon Pairs / %4.3f GeV/c^{2}",binwidth);
   

   mh1->GetYaxis()->SetTitle(ytitle);


   mh1->GetXaxis()->SetTitleSize(0.055);
   mh1->GetYaxis()->SetTitleSize(0.055);
   mh1->GetXaxis()->SetLabelSize(0.045);
   mh1->GetYaxis()->SetLabelSize(0.045);
   mh1->GetXaxis()->SetTitleOffset(0.90);
   mh1->GetXaxis()->CenterTitle();
   mh1->GetYaxis()->SetTitleOffset(1.32);
   

   // First work with the histogram and find the peak and fit ranges
   TAxis *xaxis = mh1->GetXaxis();
   Float_t binsiz= xaxis->GetBinCenter(3) - xaxis->GetBinCenter(2);
   Int_t nbins = xaxis->GetNbins(); 
   Float_t nevtperbin0[10000];
   Float_t errorbin0[10000];
   Float_t nevttot;
   Float_t maxbin=0; Int_t nmaxbin=0, nminbord=0, nmaxbord=nbins;
   
   for (Int_t nn=1; nn <= nbins; nn++)
     {
       nevtperbin0[nn] = mh1->GetBinContent(nn); 
       if(nevtperbin0[nn] > maxbin) { maxbin=nevtperbin0[nn]; nmaxbin=nn; }
       errorbin0[nn] = mh1->GetBinError(nn); 
       nevttot+=nevtperbin0[nn];
       if(nevtperbin0[nn] > 0 && nminbord == 0) nminbord=nn; 
       if(nevtperbin0[nn] == 0 && (nn > nminbord +10) && nmaxbord==0 && nminbord > 0) nmaxbord=nn; 
     }
   cout<<"Minbordl "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbordl "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
   nminbord+=0;
   nmaxbord-=0;
   Int_t nmin0=nminbord;
   while(nevtperbin0[nminbord] < nevtperbin0[nmaxbin]*0.025) nminbord++;
   while(nevtperbin0[nmaxbord] < nevtperbin0[nmaxbin]*0.025) nmaxbord--;
   // the above was just to get the info and low/high bins

   // Set the fit range ! This is for total fit !	 
   Float_t fitl=xmin;
     float fith=xmax;
   //     Float_t fitl=0.07, fith=0.2;// this works better for pileup
   //         Float_t fitl=0.08, fith=0.18;// this works even better for pileup
     //  if(etapi0flag == 1)
     // {
     //  fitl=0.35; fith=0.75;
     //}
     

     //   if(fitl < xaxis->GetBinCenter(nmin0)) fitl = xaxis->GetBinCenter(nmin0);
   //if(fith > xaxis->GetBinCenter(nmaxbord)) fith = xaxis->GetBinCenter(nmaxbord);
 
   


   cout<<" fit range "<<fitl<<" -- "<<fith<<endl;

   cout <<"Bin size "<<binsiz<<endl;
   cout<<"Total events "<<nevttot<<endl;
   cout<<"MaxBin "<<nmaxbin<<" with events: "<<nevtperbin0[nmaxbin]<<endl;
   cout<<"Minbord "<<nminbord<<" with events: "<<nevtperbin0[nminbord]<<endl;
   cout<<"Maxbord "<<nmaxbord<<" with events: "<<nevtperbin0[nmaxbord]<<endl;
      mh1->DrawCopy("sep");

      Float_t lowgauss=0.135-4.*0.010;
      Float_t highgauss=0.135+4.*0.010;
      if(etapi0flag == 1)
	{
	  lowgauss=0.55-5.*0.025;
              highgauss=0.55+5.*0.025;
	}
      Int_t nlowgauss=Int_t((lowgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      Int_t nhighgauss=Int_t((highgauss-xaxis->GetBinCenter(1))/Float_t(binsiz)+0.5);
      cout <<xaxis->GetBinCenter(nlowgauss)<<" "<<xaxis->GetBinCenter(nhighgauss)<<endl;
   // now make the "background" histogram and fit it with p4
      Float_t lowvalgauss=nevtperbin0[nlowgauss];
      Float_t increm=(nevtperbin0[nhighgauss]-nevtperbin0[nlowgauss])/Float_t(nhighgauss-nlowgauss);
      TH1F *hbkg = (TH1F*)mh1->Clone();
      hbkg->SetName("bkg_clone");
      for (Int_t nn=nlowgauss; nn<=nhighgauss; nn++)
	{
	  hbkg->SetBinContent(nn,Float_t(lowvalgauss+(nn-nlowgauss)*increm));
	  hbkg->SetBinError(nn,sqrt(lowvalgauss+(nn-nlowgauss)*increm));
	}
      hbkg->DrawCopy("samesep");
      //      break;
      // Now define the "gaussian" histogram
      TH1F *hgauss = (TH1F*)mh1->Clone();
      hgauss->SetName("gauss_clone");
      hgauss->Sumw2();
      hgauss->Add(mh1,hbkg,1,-1); // if errors are independent Add needs to be used !
       for (Int_t nn=1; nn <= nbins; nn++)
	 {
	   if(hgauss->GetBinContent(nn) < 0.) hgauss->SetBinContent(nn,0.001*nevtperbin0[nmaxbin]);
	   hgauss->SetBinError(nn,sqrt(hgauss->GetBinContent(nn)));
	 }

   // Declare function with wich to fit
       TF1 *g1 = new TF1("g1","gaus",lowgauss,highgauss);
   hgauss->Fit(g1,"R0");
   hgauss->DrawCopy("sep");
   g1->Draw("same");
   //  break;

   char *polff = new char[20];

   sprintf(polff,"pol%d",npol);
   
   TF1 *p4bkg; 
   if(etapi0flag != 1)
     p4bkg   = new TF1("pm2",polff, xaxis->GetBinCenter(nminbord),xaxis->GetBinCenter(nmaxbord));
   else
     p4bkg   = new TF1("pm2",polff, 0.35,0.75);
   
   

   hbkg->Fit(p4bkg,"R0");
   hbkg->DrawCopy("sep");
   p4bkg->SetLineStyle(kDashed);
   p4bkg->Draw("same");
   // break;
   
   
   Double_t par[20],parf[20],errparf[20];
   g1->GetParameters(&par[0]);
   p4bkg->GetParameters(&par[3]);

   char *totff = new char[20];
   
   sprintf(totff,"gaus(0)+pol%d(3)",npol);
   
   
   TF1 *total = new TF1("total",totff,fitl,fith);
   TF1 *p4bkgfin   = new TF1("pm2",polff,fitl,fith);
   total->SetParameters(par);

   if(etapi0flag==0){
     total->SetParLimits(1,0.10,0.15);
     total->SetParLimits(2,0.135*0.06,0.135*0.3);
     
   }else{
     total->SetParLimits(1,0.35,0.65);
   }
   
   
   //  total->FixParameter(1,1.21340e-01); 
   // total->FixParameter(2,2.69780e-02);
   
   
   

   

   mh1->Fit(total,"R0");
   
   cout<<" yield.. "<< total->GetParameter(0) <<"+/- " << total->GetParError(0)<<endl;
   

     total->GetParameters(parf);


     for( Int_t nn=0; nn < 3+npol+1; nn++) errparf[nn]=total->GetParError(nn);
     g1->SetParameters(&parf[0]);
     p4bkgfin->SetParameters(&parf[3]);
     cout <<" Piz Mass = "<<parf[1]*1000.<<" +- "<<errparf[1]*1000.<<
       " Sigma ="<<parf[2]*1000.<<" +- "<<errparf[2]*1000.<<endl;
      cout << " Sigma Rel. = "<< parf[2]/parf[1]<<" +- "
	   << errparf[2]/parf[1] <<endl;

    Float_t int_min=parf[1]-3.*parf[2];
    Float_t int_max=parf[1]+3.*parf[2];
    Float_t sig_peak=g1->Integral(int_min,int_max)/binsiz;
    Float_t bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-3. sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    Float_t SB=sig_peak/bkgd_peak; Float_t SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   

    int_min=parf[1]-2.*parf[2];
    int_max=parf[1]+2.*parf[2];
    sig_peak=g1->Integral(int_min,int_max)/binsiz;
    bkgd_peak=p4bkgfin->Integral(int_min,int_max)/binsiz;
    cout<<" In +-2.sigma window: Signal="<<sig_peak<<" Bkgd="<<bkgd_peak<<endl;
    SB=sig_peak/bkgd_peak; SBerr=SB*(sqrt(1./sig_peak+1./bkgd_peak));
    cout<<" Signal/Bkgd "<<SB<<" +- "<<SBerr<<endl;   
 			

    float S = sig_peak; 
    float B = bkgd_peak; 
    
    int_min=parf[1]-20.*parf[2];
    int_max=parf[1]+20.*parf[2];
    float S_all = g1->Integral(int_min,int_max)/binsiz;
    
    

    float test_sall =  parf[0] * parf[2] * sqrt(acos(-1)) / binsiz; 
    
    cout<<"signal all: "<< S_all << " "<< test_sall <<endl; 
    
    float Serr_all = errparf[0]/ parf[0] * S_all; 
    


    res[0] = S_all; 
    res[1] = Serr_all; 

    res[2] = parf[1]; 
    res[3] = errparf[1];
    
    res[4] = parf[2]; 
    res[5] = errparf[2];

    res[6] = SB; 
    res[7] = SBerr; 
    


    total->SetLineWidth(3);
    
   total->SetLineColor(kBlue);

   p4bkgfin->SetLineWidth(3);
   
   p4bkgfin->SetLineColor(kRed);
   mh1->DrawCopy("sep");

   //   total->SetRange(0.07,0.185);
   //    p4bkgfin->SetRange(0.07,0.185);
   total->Draw("same");
   p4bkgfin->SetLineStyle(kDashed);
   p4bkgfin->Draw("same");   

   TLatex l;
   
   //   l.SetTextSize(0.06);
   l.SetTextSize(0.05);
   
   
   l.SetTextColor(1);
   l.SetNDC();
   
  
   float sigma = parf[2]/ parf[1]*100; 
   float sigmaerr = errparf[2]/ parf[1]*100; 
   char *sigma_name = new char[50]; 
   if(sigmaerr>0.005)
     sprintf(sigma_name,"#sigma = %3.2f #pm %3.2f %% ",sigma,sigmaerr);
   else sprintf(sigma_name,"#sigma = %3.2f %% ",sigma);
   
   if(posFlag==1){
     l.DrawLatex(0.54,0.75,sigma_name);
   }else if( posFlag==2){
     l.DrawLatex(0.54,0.3,sigma_name);

   }
      
      //  sprintf(sigma_name,"S/B = %3.2f #pm %3.2f ",SB,SBerr);
      //
      sprintf(sigma_name,"S = %2.1f #pm %2.1f",S_all,Serr_all);
	      //
      
      // l.DrawLatex(0.5,0.5,sigma_name);
      
      sprintf(sigma_name,"M = %3.1f #pm %3.1f MeV",parf[1]*1000.,errparf[1]*1000);
      if(posFlag==1){
      l.DrawLatex(0.54,0.82,sigma_name);
      }else if( posFlag==2){
	l.DrawLatex(0.54,0.37,sigma_name);

      }
      ///l.DrawLatex(0.169,470.,"d)");


      c2->Modified();
   c2->Update();
   //   c2->SaveAs("nice_pi0.gif");

   
   
   if( text_x >0 && text_y >0){
    TLatex *   tex = new TLatex(text_x, text_y, texName);
    tex->SetNDC();
    tex->SetTextSize(0.06);
    tex->SetLineWidth(2);
    tex->Draw();
  }
  

   char *filename = new char[1000];

   
   sprintf(filename,"%s/%s.gif",dirName,histName);
   c2->Print(filename);
   sprintf(filename,"%s/%s.C",dirName,histName);
   c2->Print(filename);
   
   // .x pi0_mfitpeak.C ("pi0ana_508030.root","minv_spb",0)
   // .x pi0_mfitpeak.C ("pi0ana_npu.root","minv_bkg",0)  
   // .x pi0_mfitpeak.C ("pi0ana_punormv2.root","minv_spb",0)
}
Пример #24
0
plot()
{
// DATA
 TFile *f0 = new TFile("../output/QCD_Pt30-80_7TeV_SD_Jet50U_SSVT.root");
// Primary MC sample
 TFile *f1 = new TFile("../output/QCD_Pt30-80_SD_Jet50U_SSVT.root");
// MC with Track History
 TFile *f2 = new TFile("../output/QCD_Pt80-170_7TeV_SSVT.root");

// *****************************************************************************

 char* xtitle = "p_{T}(jet) (GeV)";
 int nbin = 20;
 float binw = 10., bini = 30.;

 float EtaMin = 0., EtaMax = 2.4;
//  float EtaMin = 0., EtaMax = 0.7;
//  float EtaMin = 0.7, EtaMax = 1.4;
//  float EtaMin = 1.4, EtaMax = 2.4;

//  string TaggerName = "jetProbabilityBJetTags";
//  string TaggerName = "trackCountingHighEffBJetTags";
//  string TaggerName = "trackCountingHighPurBJetTags";
 string TaggerName = "simpleSecondaryVertexBJetTags";

//  float wp = 1.90; // TCHEL
//  float wp = 3.99; // TCHEM
//  float wp = 2.17; // TCHPM
//  float wp = 4.31; // TCHPT
//  float wp = .230; // JPL
//  float wp = .495; // JPM
//  float wp = .700; // JPT
//  float wp = 2.02; // SSVM
 float wp = 3.40; // SSVT

// *****************************************************************************

 int stati=0;
 bool  fit=0;
 bool logy=1;

// *****************************************************************************

 TCanvas *c1 = new TCanvas("c1", "plots",200,10,700,730);
 c1->SetFillColor(10);
 c1->SetFillStyle(4000);
 c1->SetBorderSize(2);

// *****************************************************************************

// TPaveLabel *p01 = new TPaveLabel(0.05,0.93,0.95,0.97,
//                   "mistag in QCD 30-120 CMSSW 1.6.0 : IP2 > 4","br");
// //                   "mistag in QCD 30-120 CMSSW 1.6.0 : IP2 > 4, no pos. IP1 > 4","br");
// // p01->SetFillColor(7);
// p01->SetFillColor(0);
// p01->SetFillStyle(3017);
// p01->SetTextSize(0.8);
// p01->Draw();

pad1 = new TPad("pad1","This is pad1",0.04,0.50,0.96,0.93,21);
pad2 = new TPad("pad2","This is pad2",0.04,0.05,0.96,0.48,21);

pad1->SetFillColor(0);
pad1->SetBorderMode(0);
pad1->SetFrameFillColor(10);
pad1->Draw();
pad1->SetLogy(logy);
   pad1->SetTopMargin(0.05);
   pad1->SetBottomMargin(0.15);
   pad1->SetRightMargin(0.05);
   pad1->SetLeftMargin(0.15);

pad2->SetFillColor(0);
pad2->SetBorderMode(0);
pad2->SetFrameFillColor(10);
pad2->Draw();
pad2->SetLogy(0);
   pad2->SetTopMargin(0.05);
   pad2->SetBottomMargin(0.15);
   pad2->SetRightMargin(0.05);
   pad2->SetLeftMargin(0.15);

//$$ gStyle->SetOptDate(1);
gStyle->SetOptDate(0);
gStyle->SetStatColor(0);
gStyle->SetTitleColor(29);
gStyle->SetTitleW(0.2);
gStyle->SetTitleH(0.1);
gStyle->SetOptStat(stati);

if (fit) {
gStyle->SetOptFit(111);
gStyle->SetStatW(0.5);
gStyle->SetStatH(0.2);
} else {
gStyle->SetOptFit(0);
gStyle->SetStatW(0.4);
gStyle->SetStatH(0.3);
}

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Systematics

// Flavour fraction
 float Xbb = 0.5;
 float Xcc = 0.5;
 float Xgg = 0.2;

// IP Sign Flip
 float XipM = 0.011 * TMath::Sqrt(1.1);    // 10 pb-1
//  float XipM = 0.011 * TMath::Sqrt(0.2); // 100 pb-1
//  float XipM = 0.011 * TMath::Sqrt(0.11); // 1000 pb-1
 float XipT = 0.014 * TMath::Sqrt(1.1);    // 10 pb-1
//  float XipT = 0.014 * TMath::Sqrt(0.2); // 100 pb-1
//  float XipT = 0.014 * TMath::Sqrt(0.11); // 1000 pb-1
 float Xip = XipM;

// V0 fraction
 float Xv = 0.2;

// Bad tracks fraction
 float Xbad = 0.3;
 float SFbad = 2; // medium

 float BinMin[30], BinMax[30]; 
 float Leff[30], LeffMin[30], LeffMax[30], LeffErr[30];
 float Lsf[30], LsfMin[30], LsfMax[30], LsfErr[30];

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Initialise Histograms

       f1->cd();
 TH1F* g00 = (TH1F*)gROOT->FindObject("hAllFlav_JetPt");   // all
 TH1F* g01 = (TH1F*)gROOT->FindObject("hUDSFlav_JetPt");   // uds-jet
 TH1F* g02 = (TH1F*)gROOT->FindObject("hCFlav_JetPt");     // c-jet
 TH1F* g03 = (TH1F*)gROOT->FindObject("hBFlav_JetPt");     // b-jet
 TH1F* g04 = (TH1F*)gROOT->FindObject("hGluonFlav_JetPt"); // g-jet
 TH1F* g09 = (TH1F*)gROOT->FindObject("hLightFlav_JetPt"); // udsg-jet
//
 TH1F* g10 = (TH1F*)gROOT->FindObject("hAllFlav_NegTag_JetPt");   // all neg
 TH1F* g19 = (TH1F*)gROOT->FindObject("hLightFlav_NegTag_JetPt"); // udsg neg 
//
 TH1F* h00 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_JetPt");   // all with veto
 TH1F* h01 = (TH1F*)gROOT->FindObject("hUDSFlav_Veto_JetPt");   // uds-jet with veto 
 TH1F* h02 = (TH1F*)gROOT->FindObject("hCFlav_Veto_JetPt");     // c-jet with veto 
 TH1F* h03 = (TH1F*)gROOT->FindObject("hBFlav_Veto_JetPt");     // b-jet with veto
 TH1F* h04 = (TH1F*)gROOT->FindObject("hGluonFlav_Veto_JetPt"); // g-jet with veto
 TH1F* h09 = (TH1F*)gROOT->FindObject("hLightFlav_Veto_JetPt"); // udsg-jet with veto 
//
 TH1F* h10 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_NegTag_JetPt");   // all neg with veto
 TH1F* h11 = (TH1F*)gROOT->FindObject("hUDSFlav_Veto_NegTag_JetPt");   // uds neg with veto 
 TH1F* h12 = (TH1F*)gROOT->FindObject("hCFlav_Veto_NegTag_JetPt");     // c neg with veto
 TH1F* h13 = (TH1F*)gROOT->FindObject("hBFlav_Veto_NegTag_JetPt");     // b neg with veto
 TH1F* h14 = (TH1F*)gROOT->FindObject("hGluonFlav_Veto_NegTag_JetPt"); // g neg with veto
//
 TH1F* h20 = (TH1F*)gROOT->FindObject("hAllFlav_PosTag_JetPt");   // all pos
 TH1F* h21 = (TH1F*)gROOT->FindObject("hUDSFlav_PosTag_JetPt");   // uds pos 
 TH1F* h22 = (TH1F*)gROOT->FindObject("hCFlav_PosTag_JetPt");     // c pos 
 TH1F* h23 = (TH1F*)gROOT->FindObject("hBFlav_PosTag_JetPt");     // b pos
 TH1F* h24 = (TH1F*)gROOT->FindObject("hGluonFlav_PosTag_JetPt"); // g pos
 TH1F* h29 = (TH1F*)gROOT->FindObject("hLightFlav_PosTag_JetPt"); // udsg pos
//
       g00->Sumw2(); 
       g01->Sumw2(); 
       g02->Sumw2(); 
       g03->Sumw2(); 
       g04->Sumw2(); 
       g09->Sumw2(); 
       g10->Sumw2(); 
       g19->Sumw2(); 
       h00->Sumw2(); 
       h01->Sumw2(); 
       h02->Sumw2(); 
       h03->Sumw2(); 
       h04->Sumw2(); 
       h10->Sumw2(); 
       h11->Sumw2(); 
       h12->Sumw2(); 
       h13->Sumw2(); 
       h14->Sumw2(); 
       h20->Sumw2(); 
       h21->Sumw2(); 
       h22->Sumw2(); 
       h23->Sumw2(); 
       h24->Sumw2(); 
       h29->Sumw2(); 

       f2->cd();
 TH1F* i00 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_JetPt");   // all with veto
 TH1F* i10 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_NegTag_JetPt");   // all neg with veto
 TH1F* i09 = (TH1F*)gROOT->FindObject("hLightFlav_Veto_JetPt"); // udsg-jet with veto 
 TH1F* i29 = (TH1F*)gROOT->FindObject("hLightFlav_PosTag_JetPt"); // udsg pos
//
       i00->Sumw2(); 
       i10->Sumw2(); 
       i09->Sumw2(); 
       i29->Sumw2(); 

 TH1F* h100 = (TH1F*)gROOT->FindObject("hAllFlav_K0s_JetPt");
 TH1F* h109 = (TH1F*)gROOT->FindObject("hLightFlav_K0s_JetPt");
 TH1F* h110 = (TH1F*)gROOT->FindObject("hAllFlav_K0s_Veto_NegTag_JetPt");
 TH1F* h129 = (TH1F*)gROOT->FindObject("hLightFlav_K0s_PosTag_JetPt");
//
 TH1F* h200 = (TH1F*)gROOT->FindObject("hAllFlav_Fak_JetPt");
 TH1F* h209 = (TH1F*)gROOT->FindObject("hLightFlav_Fak_JetPt");
 TH1F* h210 = (TH1F*)gROOT->FindObject("hAllFlav_Fak_Veto_NegTag_JetPt");
 TH1F* h229 = (TH1F*)gROOT->FindObject("hLightFlav_Fak_PosTag_JetPt");
//
 TH1F* h300 = (TH1F*)gROOT->FindObject("hAllFlav_Gam_JetPt");
 TH1F* h309 = (TH1F*)gROOT->FindObject("hLightFlav_Gam_JetPt");
 TH1F* h310 = (TH1F*)gROOT->FindObject("hAllFlav_Gam_Veto_NegTag_JetPt");
 TH1F* h329 = (TH1F*)gROOT->FindObject("hLightFlav_Gam_PosTag_JetPt");
//
       h100->Sumw2(); 
       h109->Sumw2(); 
       h110->Sumw2(); 
       h129->Sumw2(); 
       h200->Sumw2(); 
       h209->Sumw2(); 
       h210->Sumw2(); 
       h229->Sumw2(); 
       h300->Sumw2(); 
       h309->Sumw2(); 
       h310->Sumw2(); 
       h329->Sumw2(); 

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Mistags and Negative Tags

 TH1F* h4= new TH1F("h4","",nbin,bini,bini+nbin*binw);  // light pos / light
       h4->Divide(h29,g09,1,1,"B"); 

 TH1F* h5= new TH1F("h5","",nbin,bini,bini+nbin*binw);  // all neg with veto / all with veto
       h5->Divide(h10,h00,1,1,"B");

 TH1F* Rlight= new TH1F("Rlight","",nbin,bini,bini+nbin*binw);  // (light pos/light) / (all neg/all)
       Rlight->Divide(h4,h5,1,1);

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Flavour fraction

 TH1F* k00= new TH1F("k00","",nbin,bini,bini+nbin*binw);  // g/uds ratio
 TH1F* k01= new TH1F("k01","",nbin,bini,bini+nbin*binw);  // uds-fraction
 TH1F* k02= new TH1F("k02","",nbin,bini,bini+nbin*binw);  // c-fraction
 TH1F* k03= new TH1F("k03","",nbin,bini,bini+nbin*binw);  // b-fraction
 TH1F* k04= new TH1F("k04","flavour fraction",nbin,bini,bini+nbin*binw);  // g-fraction
 TH1F* k11= new TH1F("k11","",nbin,bini,bini+nbin*binw);  // uds-fraction neg
 TH1F* k12= new TH1F("k12","flavour fraction",nbin,bini,bini+nbin*binw);  // c-fraction neg
 TH1F* k13= new TH1F("k13","",nbin,bini,bini+nbin*binw);  // b-fraction neg
 TH1F* k14= new TH1F("k14","",nbin,bini,bini+nbin*binw);  // g-fraction neg
 TH1F* k21= new TH1F("k21","",nbin,bini,bini+nbin*binw);  // uds-fraction pos
 TH1F* k24= new TH1F("k24","",nbin,bini,bini+nbin*binw);  // g-fraction pos

       k00->Divide(g04,g01,1,1);
       k01->Divide(g01,g00,1,1,"B");
       k11->Divide(h11,h10,1,1,"B");
       k21->Divide(h21,h29,1,1,"B");
       k02->Divide(g02,g00,1,1,"B");
       k12->Divide(h12,h10,1,1,"B");
       k03->Divide(g03,g00,1,1,"B");
       k13->Divide(h13,h10,1,1,"B");
       k04->Divide(g04,g00,1,1,"B");
       k14->Divide(h14,h10,1,1,"B");
       k24->Divide(h24,h29,1,1,"B");

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Systematics

// systematics due to flavour fraction

 TH1F* bb= new TH1F("bb","",nbin,bini,bini+nbin*binw);
       for (int i=1; i<nbin+1; i++) {
        float yneg = k13->GetBinContent(i);
	float y = k13->GetBinContent(i) - k03->GetBinContent(i);
	y = Xbb * TMath::Abs( y );
	float ey = Xbb * k13->GetBinError(i);
        bb->SetBinContent(i,y);
        bb->SetBinError(i,ey);
       }
 TH1F* cc= new TH1F("cc","",nbin,bini,bini+nbin*binw);
       for (int i=1; i<nbin+1; i++) {
        float yneg = k12->GetBinContent(i);
	float y = k12->GetBinContent(i) - k02->GetBinContent(i);
	y = Xcc * TMath::Abs( y );
	float ey = Xcc * k12->GetBinError(i);
        cc->SetBinContent(i,y);
        cc->SetBinError(i,ey);
       }

 TH1F* gg= new TH1F("gg","",nbin,bini,bini+nbin*binw);
       for (int i=1; i<nbin+1; i++) {
        float frac = k00->GetBinContent(i);
        float lneg = k11->GetBinContent(i);
        float lpos = k21->GetBinContent(i);
        float gneg = k14->GetBinContent(i);
        float gpos = k24->GetBinContent(i);
	float yl = frac * (lpos - lneg);
	float yg = gpos - gneg;
	y = Xgg * TMath::Abs( yg - yl );
        float elneg = k11->GetBinError(i);
        float elpos = k21->GetBinError(i);
        float egneg = k14->GetBinError(i);
        float egpos = k24->GetBinError(i);
	float eyneg = (egneg - frac*elneg) * (egneg - frac*elneg);
	float eypos = (egpos - frac*elpos) * (egpos - frac*elpos);
	float ey = Xgg * TMath::Sqrt( eyneg + eypos );
        gg->SetBinContent(i,y);
        gg->SetBinError(i,ey);
       }

// systematics due to sign flip

 TH1F* h1= new TH1F("h1","",nbin,bini,bini+nbin*binw); // all pos / all neg
       h1->Divide(h20,g10,1,1);
 TH1F* h2= new TH1F("h2","",nbin,bini,bini+nbin*binw); // light neg / light pos
       h2->Divide(g19,h29,1,1);
 TH1F* sf= new TH1F("sf","",nbin,bini,bini+nbin*binw); // sign flip
       sf->Add(h1,h2,Xip,-Xip);

// systematics due to V0

 TH1F* h71= new TH1F("h71","",nbin,bini,bini+nbin*binw); // K0 neg / all neg
       h71->Divide(h110,i10,1,1,"B");
 TH1F* h72= new TH1F("h72","",nbin,bini,bini+nbin*binw); // light K0 pos / light pos
       h72->Divide(h129,i29,1,1,"B");
 TH1F* h73= new TH1F("h73","",nbin,bini,bini+nbin*binw); // light K0 / light
       h73->Divide(h109,i09,1,1,"B");
 TH1F* h74= new TH1F("h74","",nbin,bini,bini+nbin*binw); // K0 / all
       h74->Divide(h100,i00,1,1,"B");

 TH1F* h81= new TH1F("h81","",nbin,bini,bini+nbin*binw); // Bad neg / all neg
       h81->Divide(h210,i10,SFbad,1,"B");
 TH1F* h82= new TH1F("h82","",nbin,bini,bini+nbin*binw); // light Bad pos / light pos
       h82->Divide(h229,i29,SFbad,1,"B");
 TH1F* h83= new TH1F("h83","",nbin,bini,bini+nbin*binw); // light Bad / light
       h83->Divide(h209,i09,SFbad,1,"B");
 TH1F* h84= new TH1F("h84","",nbin,bini,bini+nbin*binw); // Bad / all
       h84->Divide(h200,i00,SFbad,1,"B");

 TH1F* h91= new TH1F("h91","",nbin,bini,bini+nbin*binw); // gamma neg / all neg
       h91->Divide(h310,i10,1,1,"B");
 TH1F* h92= new TH1F("h92","",nbin,bini,bini+nbin*binw); // light gamma pos / light pos
       h92->Divide(h329,i29,1,1,"B");
 TH1F* h93= new TH1F("h93","",nbin,bini,bini+nbin*binw); // light gamma / light
       h93->Divide(h309,i09,1,1,"B");
 TH1F* h94= new TH1F("h94","",nbin,bini,bini+nbin*binw); // gamma / all
       h94->Divide(h300,i00,1,1,"B");

 TH1F* ka = new TH1F("ka","",nbin,bini,bini+nbin*binw);
 TH1F* bad = new TH1F("bad","",nbin,bini,bini+nbin*binw);
 TH1F* ga = new TH1F("ga","",nbin,bini,bini+nbin*binw);
 TH1F* v0 = new TH1F("v0","",nbin,bini,bini+nbin*binw);

       for (int i=1; i<nbin+1; i++) {
	float y    = h72->GetBinContent(i) - h71->GetBinContent(i);
	             - h73->GetBinContent(i) + h74->GetBinContent(i);
	y = Xv * TMath::Abs( y );
	float ey = h71->GetBinError(i)*h71->GetBinError(i) 
	           + h72->GetBinError(i)*h72->GetBinError(i);
	ey = Xv * TMath::Sqrt( ey );
        ka->SetBinContent(i,y);
        ka->SetBinError(i,ey);
       }
       for (int i=1; i<nbin+1; i++) {
	float y    = h82->GetBinContent(i) - h81->GetBinContent(i);
	             - h83->GetBinContent(i) + h84->GetBinContent(i);
	y = Xbad * TMath::Abs( y );
	float ey = h81->GetBinError(i)*h81->GetBinError(i) 
	           + h82->GetBinError(i)*h82->GetBinError(i);
	ey = Xbad * TMath::Sqrt( ey );
        bad->SetBinContent(i,y);
        bad->SetBinError(i,ey);
       }
       for (int i=1; i<nbin+1; i++) {
	float y    = h92->GetBinContent(i) - h91->GetBinContent(i);
	             - h93->GetBinContent(i) + h94->GetBinContent(i);
	y = Xv * TMath::Abs( y );
	float ey = h91->GetBinError(i)*h91->GetBinError(i) 
	           + h92->GetBinError(i)*h92->GetBinError(i);
	ey = Xv * TMath::Sqrt( ey );
        ga->SetBinContent(i,y);
        ga->SetBinError(i,ey);
       }
       for (int i=1; i<nbin+1; i++) {
	float y = ka->GetBinContent(i)*ka->GetBinContent(i) 
	          + ga->GetBinContent(i)*ga->GetBinContent(i);
	y = TMath::Sqrt( y );
	float ey = ka->GetBinError(i)*ka->GetBinError(i) 
	           + ga->GetBinError(i)*ga->GetBinError(i);
	ey = TMath::Sqrt( ey );
        v0->SetBinContent(i,y);
        v0->SetBinError(i,ey);
       }

 TH1F* tot= new TH1F("tot","",nbin,bini,bini+nbin*binw);
       for (int i=1; i<nbin+1; i++) {
        float ybb = bb->GetBinContent(i);
        float ycc = cc->GetBinContent(i);
        float ygg = gg->GetBinContent(i);
        float ysf = sf->GetBinContent(i);
        float yv0 = v0->GetBinContent(i);
        float ybad = bad->GetBinContent(i);
        float y = ybb + ycc;
	y = TMath::Sqrt( y*y + ygg*ygg + ysf*ysf + yv0*yv0 + ybad*ybad );
        float eybb = bb->GetBinError(i);
        float eycc = cc->GetBinError(i);
        float eygg = gg->GetBinError(i);
        float eysf = sf->GetBinError(i);
        float eyv0 = v0->GetBinError(i);
        float eybad = bad->GetBinError(i);
        float ey = eybb + eycc;
	ey = TMath::Sqrt( ey*ey + eygg*eygg + eysf*eysf + eyv0*eyv0 + eybad*eybad );
        tot->SetBinContent(i,y);
        tot->SetBinError(i,ey);
       }

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Mistag in Data = all neg data * Rlight

 TF1 *Fun = new TF1("Fun","[0]+[1]*x+[2]*x*x",bini,bini+nbin*binw);
//  TF1 *Fun = new TF1("Fun","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x",bini,bini+nbin*binw);
      Fun->SetLineColor(1);
      Fun->SetLineStyle(1);
 TF1 *Gun = new TF1("Gun","[0]+[1]*x+[2]*x*x",bini,bini+nbin*binw);
//  TF1 *Gun = new TF1("Gun","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x",bini,bini+nbin*binw);
      Gun->SetLineColor(1);
      Gun->SetLineStyle(2);
 TF1 *Hun = new TF1("Hun","[0]+[1]*x+[2]*x*x",bini,bini+nbin*binw);
//  TF1 *Hun = new TF1("Hun","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x",bini,bini+nbin*binw);
      Hun->SetLineColor(1);
      Hun->SetLineStyle(2);

       f0->cd();
 TH1F* H00 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_JetPt");   // all with veto
 TH1F* H10 = (TH1F*)gROOT->FindObject("hAllFlav_Veto_NegTag_JetPt");   // all neg with veto
       H00->Sumw2(); 
       H10->Sumw2(); 

 TH1F* H5= new TH1F("H5","",nbin,bini,bini+nbin*binw);  // all neg with veto / all with veto
       H5->Divide(H10,H00,1,1,"B");
 TH1F* Mistag= new TH1F("Mistag","",nbin,bini,bini+nbin*binw);  // mistag data
       Mistag->Multiply(H5,Rlight,1,1); 
 TH1F* MisMax= new TH1F("MisMax","",nbin,bini,bini+nbin*binw);  // mistag data up
 TH1F* MisMin= new TH1F("MisMin","",nbin,bini,bini+nbin*binw);  // mistag data down

// MC Truth in "Data"

 TH1F* G09 = (TH1F*)gROOT->FindObject("hLightFlav_JetPt"); // udsg-jet
 TH1F* H29 = (TH1F*)gROOT->FindObject("hLightFlav_PosTag_JetPt"); // udsg pos
       G09->Sumw2(); 
       H29->Sumw2(); 
 TH1F* H4= new TH1F("H4","",nbin,bini,bini+nbin*binw);  // light pos / light
       H4->Divide(H29,G09,1,1,"B"); 

     pad1->cd();
       Mistag->Draw("E"); 
       Mistag->SetLineColor(1);
       Mistag->SetMarkerStyle(20);
       Mistag->SetMarkerColor(1);
       Mistag->SetMarkerSize(1.);
       H4->Draw("Esame");
       H4->SetLineColor(6);
       H4->SetMarkerStyle(21);
       H4->SetMarkerColor(6);
       H4->SetMarkerSize(1.1);
       Mistag->GetXaxis()->SetLabelSize(0.06);
       Mistag->GetYaxis()->SetLabelSize(0.06);
       Mistag->GetXaxis()->SetTitleSize(0.06);
       Mistag->GetXaxis()->SetTitle(xtitle);
       Mistag->GetXaxis()->SetTitleColor(1);
//        Mistag->SetMinimum(0.04); Mistag->SetMaximum(0.4); // Loose
//        Mistag->SetMinimum(0.002); Mistag->SetMaximum(0.05); // Medium
       Mistag->SetMinimum(0.0001); Mistag->SetMaximum(0.02); // Tight
//        Mistag->SetMinimum(0.0001); Mistag->SetMaximum(1.00);
       Mistag->GetXaxis()->SetNdivisions(509);
       Mistag->GetYaxis()->SetNdivisions(509);
       Mistag->Draw("Esame"); 
       Mistag->Fit("Fun","rvee"); 
       H4->Draw("Esame"); 
       Mistag->Draw("Esame"); 
       Fun->Draw("same"); 

       for (int i=1; i<nbin+1; i++) {
	float y = Mistag->GetBinContent(i);
	float ey = Mistag->GetBinError(i);
	float syst = y * tot->GetBinContent(i);
        float stat = Fun->IntegralError(bini+(i-1)*binw,bini+i*binw) / binw;
        float eror = TMath::Sqrt( syst*syst + stat*stat);
	MisMax->SetBinContent(i,y + eror);
	MisMax->SetBinError(i,ey);
	MisMin->SetBinContent(i,y - eror);
	MisMin->SetBinError(i,ey);
	if ( y > 0. ) {
	  MisMax->SetBinError(i,ey * (1. + eror/y ));
	  MisMin->SetBinError(i,ey * (1. - eror/y ));
	}
//$$
    cout << i << " Mistag " << y << " syst " << syst << " stat " << stat << endl;
//$$
	BinMin[i] = bini+(i-1)*binw;
	BinMax[i] = bini+i*binw;
	Leff[i] = Fun->Integral(BinMin[i],BinMax[i]) / binw;;
       }

       MisMax->Fit("Gun","rvee0");
       Gun->Draw("same"); 
       for (int i=1; i<nbin+1; i++) {
	LeffMax[i] = Gun->Integral(BinMin[i],BinMax[i]) / binw;
       }

       MisMin->Fit("Hun","rvee0");
       Hun->Draw("same"); 
       for (int i=1; i<nbin+1; i++) {
	LeffMin[i] = Hun->Integral(BinMin[i],BinMax[i]) / binw;
	LeffErr[i] = (LeffMax[i] - LeffMin[i]) / 2.;
//$$
    cout << BinMin[i] << " " << BinMax[i] << " " 
         << " Light Eff " << int(Leff[i]*1e6)/1e6 << " +_ " << int(LeffErr[i]*1e6)/1e6 << endl;
//$$
       }

  TLegend* leg = new TLegend(0.20,0.73,0.50,0.93);
    leg->SetHeader("Mistag");
    leg->AddEntry(Mistag,"DATA","P");
    leg->AddEntry(H4,"MC truth","P");
    leg->Draw();

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Data/MC Scale Factor

 TF1 *FUn = new TF1("FUn","[0]",bini,bini+nbin*binw);
      FUn->SetLineColor(1);
      FUn->SetLineStyle(1);
 TF1 *GUn = new TF1("GUn","[0]+[1]*x+[2]*x*x",bini,bini+nbin*binw);
      GUn->SetLineColor(1);
      GUn->SetLineStyle(2);
 TF1 *HUn = new TF1("HUn","[0]+[1]*x+[2]*x*x",bini,bini+nbin*binw);
      HUn->SetLineColor(1);
      HUn->SetLineStyle(2);

 TH1F* SFlight= new TH1F("SFlight","",nbin,bini,bini+nbin*binw);  // Scale Factor
       SFlight->Divide(H5,h5,1,1); 
 TH1F* SFmax= new TH1F("SFmax","",nbin,bini,bini+nbin*binw);  // SF up
 TH1F* SFmin= new TH1F("SFmin","",nbin,bini,bini+nbin*binw);  // SF down

     pad2->cd();
       SFlight->Draw("E"); 
       SFlight->SetLineColor(1);
       SFlight->SetMarkerStyle(20);
       SFlight->SetMarkerColor(1);
       SFlight->SetMarkerSize(1.);
       SFlight->GetXaxis()->SetLabelSize(0.06);
       SFlight->GetYaxis()->SetLabelSize(0.06);
       SFlight->GetXaxis()->SetTitleSize(0.06);
       SFlight->GetXaxis()->SetTitle(xtitle);
       SFlight->GetXaxis()->SetTitleColor(1);
       SFlight->SetMinimum(0.); 
       SFlight->SetMaximum(2.);
       SFlight->GetXaxis()->SetNdivisions(509);
       SFlight->GetYaxis()->SetNdivisions(509);
       SFlight->Draw("Esame"); 
       SFlight->Fit("FUn","rvee"); 
       FUn->Draw("same"); 

       for (int i=1; i<nbin+1; i++) {
	float y = SFlight->GetBinContent(i);
	float ey = SFlight->GetBinError(i);
	float syst = y * tot->GetBinContent(i);
        float eror = TMath::Sqrt( syst*syst + ey*ey);
        float yfit = FUn->Integral(bini+(i-1)*binw,bini+i*binw) / binw;
	SFmax->SetBinContent(i,yfit + eror);
	SFmax->SetBinError(i,ey);
	SFmin->SetBinContent(i,yfit - eror);
	SFmin->SetBinError(i,ey);
//$$
//$$    cout << i << " SF " << y << " syst " << syst << " stat " << stat << endl;
//$$
	Lsf[i] = FUn->Integral(BinMin[i],BinMax[i]) / binw;
       }

       SFmax->Fit("GUn","rvee0");
       GUn->Draw("same"); 
       for (int i=1; i<nbin+1; i++) {
	LsfMax[i] = GUn->Integral(BinMin[i],BinMax[i]) / binw;
       }

       SFmin->Fit("HUn","rvee0");
       HUn->Draw("same"); 
       for (int i=1; i<nbin+1; i++) {
	LsfMin[i] = HUn->Integral(BinMin[i],BinMax[i]) / binw;
	LsfErr[i] = (LsfMax[i] - LsfMin[i]) / 2.;
//$$
    cout << BinMin[i] << " " << BinMax[i] << " " 
         << " Light SF " << int(Lsf[i]*1e6)/1e6 << " +_ " << int(LsfErr[i]*1e6)/1e6 << endl;
//$$
       }

  TLegend* leg = new TLegend(0.20,0.78,0.50,0.93);
    leg->SetHeader("Scale Factor");
    leg->AddEntry(SFlight,"Neg.Tag Data/MC","P");
    leg->Draw();
    
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// Write the ascii file

       string blabla_file = "Mistag.txt";

       ofstream out_txt(blabla_file.c_str(), ios::out);

       out_txt << TaggerName << endl; // < ---the tagger name
       out_txt << wp << endl; // <---- the WP cut on the discriminator
       out_txt << "PerformancePayloadFromTable" << endl;
       out_txt << 4 << endl; // <---- # of results, lighteff and lightefferr
       out_txt << 2 << endl; // <---- # of variables to bin (eta and pt)
       out_txt << "1005 1006 1013 1014" << endl; // <----- results are light eff +_ error, light SF +_ error
       out_txt << "5 2" << endl; // <----- binning is |eta| / pt
       for (int i=1; i<nbin+1; i++) { // <----- eta and Et ranges, light eff +_ error, light SF +_ error
        if (EtaMin == 0 && BinMin[i] < 100 && BinMax[i] < 100) {  
          out_txt << EtaMin    << "       " << EtaMax     << "      " 
                  << BinMin[i] << "      " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
        else if (EtaMin == 0 && BinMin[i] < 100) {  
          out_txt << EtaMin    << "       " << EtaMax     << "      " 
                  << BinMin[i] << "     " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
        else if (EtaMin == 0) {  
          out_txt << EtaMin    << "       " << EtaMax     << "     " 
                  << BinMin[i] << "     " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
        else if (BinMin[i] < 100 && BinMax[i] < 100) {  
          out_txt << EtaMin    << "     " << EtaMax     << "      " 
                  << BinMin[i] << "      " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
        else if (BinMin[i] < 100) {  
          out_txt << EtaMin    << "     " << EtaMax     << "      " 
                  << BinMin[i] << "     " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
        else {  
          out_txt << EtaMin    << "     " << EtaMax     << "     " 
                  << BinMin[i] << "     " << BinMax[i]  << "     " 
	          << int(Leff[i]*1e6)/1e6   << "     " << int(LeffErr[i]*1e6)/1e6 << "     " 
	          << int(Lsf[i]*1e6)/1e6    << "     " << int(LsfErr[i]*1e6)/1e6  << endl;
	}
       }

// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

  c1->Update();
}
void 
HTT_EE_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="ee_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category = "ee, 2 jet";          }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category_extra = "VBF";              }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV";}
 
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* ZTT     = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     ); InitHist(ZTT     , "", "", kOrange  -  4, 1001);
  TH1F* ZEE     = refill((TH1F*)input ->Get(TString::Format("%s/ZEE"     , directory)), "ZEE"     ); InitHist(ZEE     , "", "", kAzure   +  2, 1001);
  TH1F* TTJ     = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     ); InitHist(TTJ     , "", "", kBlue    -  8, 1001);
  TH1F* QCD     = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     ); InitHist(QCD     , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons= refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons"); InitHist(Dibosons, "", "", kGreen   -  4, 1001);
  TH1F* WJets   = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   ); InitHist(WJets   , "", "", kRed     +  2, 1001);
#ifdef MSSM
  TH1F* ggH     = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH     = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     ); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH     = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH     = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH      = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);
#else
  InitHist(data, "#bf{D}", "#bf{dN/dD}"     ); InitData(data);
#endif

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZEE);
  ref->Add(TTJ);
  ref->Add(QCD);
  ref->Add(Dibosons);
  ref->Add(WJets);

  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZEE->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD->Integral();
  unscaled[4] = Dibosons->Integral();
  unscaled[5] = WJets->Integral();
#ifdef MSSM
  unscaled[6] = ggH->Integral();
  unscaled[7] = bbH->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH->Integral();
  unscaled[7] = qqH->Integral();
  unscaled[8] = VH ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT, 1); 
    rescale(ZEE, 2); 
    rescale(TTJ, 3); 
    rescale(QCD, 4); 
    rescale(Dibosons, 5); 
    rescale(WJets,    6);
#ifdef MSSM 
    rescale(ggH, 7);
    rescale(bbH, 8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH, 7);
    rescale(qqH, 8);
    rescale(VH,  9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
  scales[1] = new TH1F("scales-ZEE"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZEE->Integral()/unscaled[1]-1.)      : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)    : 0.);
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[4]-1.)      : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[5]-1.)      : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[6]-1.)      : 0.);
#endif
#endif

  WJets->Add(Dibosons);
  QCD->Add(WJets);
  TTJ->Add(QCD);
  ZTT->Add(TTJ);
  ZEE->Add(ZTT);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(WJets);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(WJets);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZTT, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZTT, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)ZEE ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{e}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.55, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"           , "LP");
#else
  leg->AddEntry(data , "observed"                    , "LP");
#endif
  leg->AddEntry(ZEE  , "Z#rightarrowee"              , "F" );
  leg->AddEntry(ZTT  , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(TTJ  , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD  , "QCD"                         , "F" );
  leg->AddEntry(WJets, "electroweak"                 , "F" );
  //leg->AddEntry(Dibosons  , "Dibosons"             , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)ZEE ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, ZEE->GetBinContent(ibin+1)>0 ? ZEE ->GetBinError  (ibin+1)/ZEE->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
#ifdef MSSM
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat1->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) ZEE->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
#if defined MSSM
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kOrange  -  4, 1001);
  InitHist  (scales[1], "", "", kAzure   +  2, 1001);
  InitHist  (scales[2], "", "", kBlue    -  8, 1001);
  InitHist  (scales[3], "", "", kMagenta - 10, 1001);
  InitHist  (scales[4], "", "", kGreen   -  4, 1001);
  InitHist  (scales[5], "", "", kRed     +  2, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZEE}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"  );
  ZEE->Write("Zee"  );
  TTJ->Write("ttbar");
  QCD->Write("Fakes");
  Dibosons->Write("Dibosons");
  WJets->Write("EWK");
#ifdef MSSM
  ggH  ->Write("ggH");
  bbH  ->Write("bbH");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH");
  qqH  ->Write("qqH");
  VH   ->Write("VH" );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Пример #26
0
void 
Unfolded  (
     bool drawRatio = 1,
     int differential = 0,
     int nsel = 0,
     int ReBin = 1,
     TString XTitle = "p_{T,max}^{l} (GeV)",
     TString units = "", 
     TString plotName = "data/XSLeadingPt_AN.root", 
     TString outputName = "WW_LeadingPt_final",
     bool isLogY = false,
     double lumi = 19.5
 )
{  
 
 gInterpreter->ExecuteMacro("GoodStyle.C");
 
 std::cout << "reading " << plotName << std::endl ;
 TFile* file = new TFile(plotName, "read");
 
 //---- prepare the object that is making the plots
 //---- ---- ---- ---- ---- ---- ---- ---- ---- ----
 
 std::cout << "setting up the plot object " << std::endl ;

 
 TH1F* xsValue = (TH1F*) xsValue->Clone();
 TH1F* xsValue_Powheg =  (TH1F*) xsValue_Powheg->Clone();
 TH1F* xsValue_Madgraph = (TH1F*) xsValue_Madgraph->Clone();
 TH1F* xsValue_MCnlo = (TH1F*) xsValue_MCnlo->Clone();
 TH1F* systHisto = (TH1F*) systHisto->Clone();
 
 
 TCanvas* canvas ;
 TPad *pad1, *pad2, *pad3, *pad4;
 
 if (drawRatio) {
  canvas = new TCanvas("wwxs", "wwxs", 600, 850);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  canvas->SetHighLightColor(2);
  canvas->Range(0,0,1,1);
  canvas->SetFillColor(0);
  canvas->SetBorderMode(0);
  canvas->SetBorderSize(2);
  canvas->SetTickx(1);
  canvas->SetTicky(1);
  canvas->SetLeftMargin(0.16);
  canvas->SetRightMargin(0.02);
  canvas->SetTopMargin(0.05);
  canvas->SetBottomMargin(0.13);
  canvas->SetFrameFillStyle(0);
  canvas->SetFrameBorderMode(0);
  
  
  
  pad1 = new TPad("pad1", "pad1",0.01,0.55,0.99,0.99);
  pad1->Draw();
  pad1->cd();
  pad1->Range(-147.2973,-5.811723,960.8108,2.535539);
  pad1->SetFillColor(0);
  pad1->SetBorderMode(0);
  pad1->SetBorderSize(2);
  pad1->SetLogy();
  pad1->SetTickx(1);
  pad1->SetTicky(1);
  pad1->SetLeftMargin(0.16);
  pad1->SetBottomMargin(0);
  pad1->SetFrameFillStyle(0);
  pad1->SetFrameBorderMode(0);
  pad1->SetFrameFillStyle(0);
  pad1->SetFrameBorderMode(0);
   
 }
 else { 
  canvas = new TCanvas("wwxs", "wwxs", 550, 550);
 }
 
 if (drawRatio) pad1->cd();
 
 std::cout << " now plot " << std::endl;
 
 //Plot Data
 xsValue->SetLineWidth(1);
 xsValue->SetMarkerSize(1.0);
 
 int NBins = xsValue->GetNbinsX();
 
 for(int i=1; i <NBins; i++) {
  
  float err_stat = xsValue->GetBinError(i);
  float err_syst = systHisto->GetBinError(i);
  float err_total = sqrt(err_stat*err_stat + err_syst*err_syst);
  
  xsValue->SetBinError(i, err_total);
 }
 
 
 //-- Plot Powheg
 
 TH1F *hpowError  = (TH1F*) xsValue_Powheg->Clone();
 
 xsValue_Powheg->SetMarkerColor(kGreen+2);
 xsValue_Powheg->SetLineWidth(1);
 xsValue_Powheg->SetLineColor(kGreen+2);
 xsValue_Powheg->SetMarkerStyle(22);
 xsValue_Powheg->SetMarkerSize(1.2);
 
 
 hpowError->SetLineWidth(0);
 hpowError->SetMarkerSize (      0);  
 hpowError->SetFillColor  (kGreen-7);
 
 
 //-- Plot Madgraph
 
 TH1F *hmadError  = (TH1F*) xsValue_Madgraph->Clone();
 
 xsValue_Madgraph->SetMarkerColor(kMagenta);
 xsValue_Madgraph->SetLineWidth(1);
 xsValue_Madgraph->SetLineStyle(1);
 xsValue_Madgraph->SetMarkerStyle(21);
 xsValue_Madgraph->SetMarkerSize(1.0);
 
 hmadError->SetLineWidth(0);
 hmadError->SetMarkerSize (      0); 
 hmadError->SetFillColor  (kMagenta-10);
 
 
 //-- Plot MCNLO
 
 TH1F *hmcError  = (TH1F*) xsValue_MCnlo->Clone();
 
 xsValue_MCnlo->SetMarkerColor(kRed);
 xsValue_MCnlo->SetLineColor(kRed);
 xsValue_MCnlo->SetLineWidth(1);
 xsValue_MCnlo->SetLineStyle(1);
 xsValue_MCnlo->SetMarkerStyle(24);
 xsValue_MCnlo->SetMarkerSize(1.0);
 
 hmcError->SetLineWidth(0);
 hmcError->SetMarkerSize (      0); 
 hmcError->SetFillColor  (kOrange);
 
 
 
 
 //-- Plot Data
 
 xsValue->SetMarkerStyle(kFullCircle);
 
 if (differential == 0) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} d#sigma(WW#rightarrow#mu#nue#nu + < 1 jet)/dp_{T,max}^{l}");
 if (differential == 1) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} d#sigma(WW#rightarrow#mu#nue#nu + < 1 jet)/dp_{T}(ll)}");
 if (differential == 2) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} d#sigma(WW#rightarrow#mu#nue#nu + < 1 jet)/dm_{#font[12]{ll}}");
 if (differential == 3) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} d#sigma(WW#rightarrow#mu#nue#nu + < 1 jet)/d#Delta#phi_{ll}");

 
//  if (differential == 0) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dp_{T,max}^{l}}");
//  if (differential == 1) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dp_{T}(ll)}");
//  if (differential == 2) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{dm_{#font[12]{ll}}}");
//  if (differential == 3) AxisFonts (xsValue->GetYaxis(), "#frac{1}{#sigma} #frac{d#sigma}{d#Delta#phi_{ll}}");

 AxisFonts (xsValue->GetXaxis(), XTitle);
 
 
 
 xsValue->Draw("p");
 hmadError->Draw("e2,same"); 
 xsValue_Madgraph->Draw("pe1,same");
 hmcError->Draw("e2,same");
 xsValue_MCnlo->Draw("pe1,same");
 hpowError->Draw("e2,same");
 xsValue_Powheg->Draw("pe1,same");
 //systHisto->Draw("e2, same");
 xsValue->Draw("pe1,same");
 
 // Legend
 //----------------------------------------------------------------------------
 
 DrawLegend (0.65, 0.85, xsValue, "Data", "P");
 DrawLegend (0.65, 0.80, hpowError,   "", "F");
 DrawLegend (0.65, 0.80, xsValue_Madgraph,   "Madgraph", "PL");  
 DrawLegend (0.65, 0.75, hmadError,   "", "F");
 DrawLegend (0.65, 0.75, xsValue_MCnlo,   "MCNLO", "LP");
 DrawLegend (0.65, 0.70, hmcError,   "", "F");
 DrawLegend (0.65, 0.70, xsValue_Powheg,   "Powheg", "PL");
 
 canvas->GetFrame()->DrawClone();
 
 
 
 // Draw text 
 //----------------------------------------------------------------------------
 TLatex *   tex = new TLatex(0.17,0.96,"CMS             #sqrt{s} = 8 TeV             19.4 fb^{-1}");
 tex->SetNDC();
 tex->SetTextAlign(12);
 tex->SetTextFont(42);
 tex->SetTextSize(0.07);
 tex->SetLineWidth(2);
 tex->Draw();
 
//  TLatex * CMSLabel = new TLatex (0.18, 0.96, "#bf{CMS}");
//  CMSLabel->SetNDC ();
//  CMSLabel->SetTextAlign (10);
//  CMSLabel->SetTextFont (42);
//  CMSLabel->SetTextSize (_tsize);
//  CMSLabel->Draw ("same") ;
//  
//  
//  TLatex * _lumiLabel = new TLatex (0.95, 0.96, "19.4fb#lower[0.3]{^{-1}} (8 TeV)");
//  _lumiLabel->SetNDC ();
//  _lumiLabel->SetTextAlign (30);
//  _lumiLabel->SetTextFont (42);
//  _lumiLabel->SetTextSize (_tsize);
//  _lumiLabel->Draw ("same") ;
 
 
 // Draw also ratio
 //----------------------------------------------------------------------------
 if (drawRatio) {
  
  //---- prepare the distributions

  TH1F* ratio_pow       = xsValue_Powheg->Clone("ratio");
  TH1F* ratio_mad       = xsValue_Madgraph->Clone("ratio");
  TH1F* ratio_mcnlo     = xsValue_MCnlo->Clone("ratio");
  TH1F* hratio_pow      = xsValue_Powheg->Clone("ratio");
  TH1F* hratio_mad      = xsValue_Madgraph->Clone("ratio");
  TH1F* hratio_mcnlo    = xsValue_MCnlo->Clone("ratio");
  TH1F* ratioErr        = xsValue->Clone("ratio");
  
  
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {
   
   Double_t powValue = xsValue_Powheg->GetBinContent(ibin);
   Double_t powError = xsValue_Powheg->GetBinError  (ibin);
   
   Double_t madValue = xsValue_Madgraph->GetBinContent(ibin);
   Double_t madError = xsValue_Madgraph->GetBinError  (ibin);
   
   Double_t mcnloValue = xsValue_MCnlo->GetBinContent(ibin);
   Double_t mcnloError = xsValue_MCnlo->GetBinError  (ibin);
   
   Double_t dataValue = xsValue->GetBinContent(ibin);
   Double_t statError = xsValue->GetBinError  (ibin);
   Double_t systError = systHisto->GetBinError(ibin);
   
   Double_t dataError = systError;
   
   Double_t ratioValue_pow           = (powValue > 0) ? powValue/dataValue : 0.0;
   Double_t ratioError_pow           = (powValue > 0) ? powError / dataValue : 0.0;
   
   Double_t ratioValue_mad           = (madValue > 0) ? madValue/dataValue : 0.0;
   Double_t ratioError_mad           = (madValue > 0) ? madError/dataValue : 0.0;
   
   Double_t ratioValue_mcnlo         = (mcnloValue > 0) ? mcnloValue/dataValue : 0.0;
   Double_t ratioError_mcnlo         = (mcnloValue > 0) ? mcnloError/dataValue : 0.0;
   
   Double_t uncertaintyError         = (dataValue > 0) ? dataError/dataValue : 0.0;
   
   
   //dataError/dataValue 
   ratio_pow->SetBinContent(ibin, ratioValue_pow);
   hratio_pow->SetBinContent(ibin, ratioValue_pow);
   hratio_pow->SetBinError  (ibin, ratioError_pow);
   
   ratio_mad->SetBinContent(ibin, ratioValue_mad);
   hratio_mad->SetBinContent(ibin, ratioValue_mad);
   hratio_mad->SetBinError  (ibin, ratioError_mad);
   
   ratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
   hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
   hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
   
   ratioErr->SetBinContent(ibin, 1.0);
   ratioErr->SetBinError  (ibin, uncertaintyError);
  }
  
  ratioErr->SetTitle("");

  ratioErr->SetFillColor  (kGray+2);
  ratioErr->SetFillStyle  (   3004);
//   ratioErr->SetFillStyle  (   3345);
  ratioErr->SetLineColor  (kGray+2);
  ratioErr->SetMarkerColor(kGray+2);
  ratioErr->SetMarkerSize (      0);
  
  
  
  //---- now draw
  
  canvas->cd();
  pad2 = new TPad("pad2", "pad2",0.01,0.39,0.99,0.55);
  pad2->Draw();
  pad2->cd();
  pad2->Range(-147.2973,0.2,960.8108,1.8);
  pad2->SetFillColor(0);
  pad2->SetBorderMode(0);
  pad2->SetBorderSize(2);
  pad2->SetTickx(1);
  pad2->SetTicky(1);
  pad2->SetLeftMargin(0.16);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(0);
  pad2->SetFrameFillStyle(0);
  pad2->SetFrameBorderMode(0);
  pad2->SetFrameFillStyle(0);
  pad2->SetFrameBorderMode(0);
  
  
  ratioErr  ->Draw("e2");
  ratio_mad      ->SetLineColor(kMagenta);
  ratio_mad      ->SetMarkerSize(1.0);
  ratio_mad      ->SetLineWidth(1);
  ratio_mad      ->SetMarkerStyle(21);
  hratio_mad     ->SetLineWidth(0);
  hratio_mad     ->SetMarkerSize (      0);  
  hratio_mad     ->SetFillColor  (kMagenta-10);
  hratio_mad     ->SetFillStyle  (1001);
  hratio_mad     ->Draw("e2,same");
  ratio_mad      ->Draw("e1p,same");
  AxisFontsRatio (ratioErr->GetYaxis(), "y", "Theory/data");
  AxisFontsRatio (ratioErr->GetXaxis(), "x", XTitle);
  ratioErr->Draw("sameaxis");
  ratioErr->GetYaxis()->SetRangeUser(0.4, 1.6);  
  pad2->Modified();
  
  TLatex* tex_mad = new TLatex(0.2,0.1,"Madgraph+Pythia, normalized to #sigma_{NNLO}");
  tex_mad->SetNDC();
  tex_mad->SetTextAlign(12);
  tex_mad->SetTextFont(42);
  tex_mad->SetTextSize(0.1);
  tex_mad->SetLineWidth(2);
  tex_mad->Draw();
  
  
  
  canvas->cd();
  pad3 = new TPad("pad3", "pad3",0.01,0.23,0.99,0.39);
  pad3->Draw();
  pad3->cd();
  pad3->Range(-147.2973,0.2,960.8108,1.8);
  pad3->SetFillColor(0);
  pad3->SetBorderMode(0);
  pad3->SetBorderSize(2);
  pad3->SetTickx(1);
  pad3->SetTicky(1);
  pad3->SetLeftMargin(0.16);
  pad3->SetTopMargin(0);
  pad3->SetBottomMargin(0);
  pad3->SetFrameFillStyle(0);
  pad3->SetFrameBorderMode(0);
  pad3->SetFrameFillStyle(0);
  pad3->SetFrameBorderMode(0);
  
  ratioErr  ->Draw("e2");
  ratio_mcnlo     ->SetLineColor(kRed);
  ratio_mcnlo     ->SetMarkerSize(1.0);
  ratio_mcnlo      ->SetLineWidth(1);
  ratio_mcnlo     ->SetMarkerStyle(24);
  hratio_mcnlo    ->SetLineWidth(0);
  hratio_mcnlo    ->SetMarkerSize (      0);  
  hratio_mcnlo    ->SetFillColor  (kOrange);
  hratio_mcnlo     ->SetFillStyle  (1001);
  hratio_mcnlo    ->Draw("e2,same");
  ratio_mcnlo     ->Draw("ep,same");
//   AxisFontsRatio (ratioErr->GetYaxis(), "y", "Theory/data");
//   AxisFontsRatio (ratioErr->GetXaxis(), "x", XTitle);
  ratioErr->Draw("sameaxis");
  ratioErr->GetYaxis()->SetRangeUser(0.4, 1.6);  
  pad3->Modified();
  
  TLatex* tex_mcnlo = new TLatex(0.2,0.1,"MC@NLO+Herwig, normalized to #sigma_{NNLO}");
  tex_mcnlo->SetNDC();
  tex_mcnlo->SetTextAlign(12);
  tex_mcnlo->SetTextFont(42);
  tex_mcnlo->SetTextSize(0.1);
  tex_mcnlo->SetLineWidth(2);
  tex_mcnlo->Draw();
  
  
  
  
  canvas->cd();
  pad4 = new TPad("pad4", "pad4",0.01,0.01,0.99,0.23);
  pad4->Draw();
  pad4->cd();
  pad4->Range(-147.2973,-0.4857143,960.8108,1.8);
  pad4->SetFillColor(0);
  pad4->SetBorderMode(0);
  pad4->SetBorderSize(2);
  pad4->SetTickx(1);
  pad4->SetTicky(1);
  pad4->SetLeftMargin(0.16);
  pad4->SetTopMargin(0);
  pad4->SetBottomMargin(0.3);
  pad4->SetFrameFillStyle(0);
  pad4->SetFrameBorderMode(0);
  pad4->SetFrameFillStyle(0);
  pad4->SetFrameBorderMode(0);
  
  ratioErr  ->Draw("e2");
  ratio_pow      ->SetLineColor(kGreen+2);
  ratio_pow      ->SetMarkerSize(1.2);
  ratio_pow      ->SetLineWidth(1);
  ratio_pow      ->SetMarkerStyle(22);
  hratio_pow     ->SetLineWidth(0);
  hratio_pow     ->SetMarkerSize (      0);  
  hratio_pow     ->SetFillColor  (kGreen-7);
  hratio_pow     ->SetFillStyle  (1001);
  hratio_pow     ->Draw("e2,same");
  ratio_pow      ->Draw("e1p,same");
//   AxisFontsRatio (ratioErr->GetYaxis(), "y", "Theory/data", 1);
//   AxisFontsRatio (ratioErr->GetXaxis(), "x", XTitle);
  ratioErr->Draw("sameaxis");
  ratioErr->GetYaxis()->SetRangeUser(0.4, 1.6);  
  pad4->Modified();
  
  TLatex* tex_pow = new TLatex(0.2,0.39,"Powheg+Pythia, normalized to #sigma_{NNLO}");
  tex_pow->SetNDC();
  tex_pow->SetTextAlign(12);
  tex_pow->SetTextFont(42);
  tex_pow->SetTextSize(0.1);
  tex_pow->SetLineWidth(2);
  tex_pow->Draw();
  
  canvas->cd();
  
  
 }
 
 
}
Пример #27
0
void calccorr(int i=0, string t){
if(i==0) TString dire = "north";
if(i==1) TString dire = "south";

  float const PI = acos(-1.0);
const int nntrk = 10;
const int npt = 10;
TFile *f=TFile::Open("merged.root");
TH1F* kforebbcw[nntrk][npt];
TH1F* hforebbcw[nntrk][npt];
TH1F* kbackbbcw2[nntrk][npt];
TH1F* kforebbcw_In;
TH1F* hforebbcw_In;
TH1F* kbackbbcw2_In;
double ptbin[npt+1] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double ntrkbin[nntrk+1] = {0,1,2,3,4,5,6,7,8,9,10};
TString type = t.c_str();
if(type=="ptIn25_4"){
double selptbin[] = {2.5,4.0};
double selntrkbin[] = {0,1,2,3,10};
}
else if(type=="ptIn"){
double selptbin[] = {1.0,3.0};
double selntrkbin[] = {0,1,2,3,10};
}
else if(type=="ptcoarser"){
double selptbin[] = {0.2,1.0,2.0,3.0,5.0};
double selntrkbin[] = {0,1,2,3,10};
}
else if(type=="ptfiner"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selntrkbin[] = {0,1,2,3,10};
}
else if(type=="ntrkIn"){
double selptbin[] = {0.2,0.5,1.0,1.5,2.0,2.5,3.0,3.5,4.0,4.5,5.0};
double selntrkbin[] = {0,10};
}
else{exit(0);};

/*double ptmin = 1.0; double ptmax = 3.0;//has to be boundary
for(int ipt=0; ipt<npt; ipt++){
if(ptmin >= ptbin[ipt] && ptmin < ptbin[ipt+1]){int xptmin = ipt; continue;}
if(ptmax >= ptbin[ipt] && ptmax < ptbin[ipt+1]){int xptmax = ipt; continue;}
}*/
  ofstream fsout(Form("stat_%s_%s.txt",type.Data(),dire.Data()));
  ofstream fout(Form("c1_c2_%s_%s.dat",type.Data(),dire.Data()));
for(int intrk=0; intrk<nntrk; intrk++){
for(int ipt=0; ipt<npt; ipt++){
kforebbcw[intrk][ipt] = (TH1F*)f->Get(Form("kfore%sbbcw_%d_%d",dire.Data(),intrk,ipt));
hforebbcw[intrk][ipt] = (TH1F*)f->Get(Form("hfore%sbbcw_%d_%d",dire.Data(),intrk,ipt));
kbackbbcw2[intrk][ipt] = (TH1F*)f->Get(Form("kback%sbbcw2_%d_%d",dire.Data(),intrk,ipt));
}
}
int nntrk_a = sizeof(selntrkbin)/sizeof(double)-1;
int npt_a = sizeof(selptbin)/sizeof(double)-1;
for(int intrk_a=0;intrk_a<nntrk_a;intrk_a++){
for(int intrk_b=0; intrk_b<nntrk+1; intrk_b++)
if(selntrkbin[intrk_a] == ntrkbin[intrk_b]) break;
int xntrkmin = intrk_b;
for(int intrk_b=0; intrk_b<nntrk+1; intrk_b++)
if(selntrkbin[intrk_a+1] == ntrkbin[intrk_b]) break;
int xntrkmax = intrk_b;
if((xntrkmin == nntrk+1) || (xntrkmax == nntrk+1)) exit(0);
for(int ipt_a=0;ipt_a<npt_a;ipt_a++){
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a] == ptbin[ipt_b]) break;
int xptmin = ipt_b;
for(int ipt_b=0; ipt_b<npt+1; ipt_b++)
if(selptbin[ipt_a+1] == ptbin[ipt_b]) break;
int xptmax = ipt_b;
if((xptmin == npt+1) || (xptmax == npt+1)) exit(0);
cout<<xntrkmin<<"\t"<<xntrkmax<<"\t"<<endl;
cout<<xptmin<<"\t"<<xptmax<<"\t"<<endl;
kforebbcw_In = (TH1F*)kforebbcw[xntrkmin][xptmin]->Clone();
hforebbcw_In = (TH1F*)hforebbcw[xntrkmin][xptmin]->Clone();
kbackbbcw2_In = (TH1F*)kbackbbcw2[xntrkmin][xptmin]->Clone();
kforebbcw_In->Reset();
hforebbcw_In->Reset();
kbackbbcw2_In->Reset();
for(int intrk=xntrkmin; intrk<xntrkmax; intrk++){
for(int ipt=xptmin; ipt<xptmax; ipt++){
kforebbcw_In->Add(kforebbcw[intrk][ipt]);
hforebbcw_In->Add(hforebbcw[intrk][ipt]);
kbackbbcw2_In->Add(kbackbbcw2[intrk][ipt]);
}
}
kforebbcw_In->Rebin(2);
hforebbcw_In->Rebin(2);
kbackbbcw2_In->Rebin(2);


TH1F* hpp;
TH1F* hbackpp;
  hpp = (TH1F*)kforebbcw_In->Clone();
  hbackpp = (TH1F*)kbackbbcw2_In->Clone();
  float nbackpp = hbackpp->Integral()/2.0/PI;
  float nforepp = hpp->Integral()/2.0/PI;
  //float ntrig0 = ptforedis_0->Integral(11,30);
   for(int i=0; i<20; i++){
     float pp_cont = 1.0*hpp->GetBinContent(i+1);
     //float pp0_err = 1.0*hpp->GetBinError(i+1);
     float weight2 = sqrt(1.0*hforebbcw_In->GetBinContent(i+1));

     float backpp_cont = 1.0*hbackpp->GetBinContent(i+1);
    
     float con = pp_cont/backpp_cont*nbackpp/nforepp;
     float err = weight2/backpp_cont*nbackpp/nforepp;

     hpp->SetBinContent(i+1, con);
     hpp->SetBinError(i+1, err);

     if(i==0) fsout<<pp_cont<<" "<<weight2<<" "<<con<<" "<<err<<endl;
   }
  TF1 *fun0 = new TF1("fun0","[0]*(1+2*[1]*cos(x)+2*[2]*cos(2*x)+2*[3]*cos(3*x)+2*[4]*cos(4*x))", -0.5*PI, 1.5*PI);

  fun0->SetLineColor(1);
  hpp->Fit("fun0","NORQ");

  TF1 *fun1 = new TF1("fun1","[0]*(1+2*[1]*cos(x))",   -0.5*PI, 1.5*PI);
  TF1 *fun2 = new TF1("fun2","[0]*(1+2*[1]*cos(2*x))", -0.5*PI, 1.5*PI);
  TF1 *fun3 = new TF1("fun3","[0]*(1+2*[1]*cos(3*x))", -0.5*PI, 1.5*PI);
  TF1 *fun4 = new TF1("fun4","[0]*(1+2*[1]*cos(4*x))", -0.5*PI, 1.5*PI);

  fout<<fun0->GetParameter(1)<<" "<<fun0->GetParError(1)<<" "
      <<fun0->GetParameter(2)<<" "<<fun0->GetParError(2)<<" "
      <<fun0->GetParameter(3)<<" "<<fun0->GetParError(3)<<endl;
}
}
  fout.close();
  fsout.close();

/*  
  cout<<"*************** v2 ***********"<<endl;
  float v2_0 = funvn0->GetParameter(1)/(zym_pp0 + funvn0->GetParameter(0));
  float v2_1 = funvn1->GetParameter(1)/(zym_pp1 + funvn1->GetParameter(0));
  float v2_2 = funvn2->GetParameter(1)/(zym_pp2 + funvn2->GetParameter(0));
  float v2_3 = funvn3->GetParameter(1)/(zym_pp3 + funvn3->GetParameter(0));
  

  cout<<v2_0<<" "<<v2_1<<" "<<v2_2<<" "<<v2_3<<endl;
 
  
  cout<<funvn0->GetParameter(0)*funvn0->GetParameter(1)<<" "
      <<funvn1->GetParameter(0)*funvn1->GetParameter(1)<<" "
      <<funvn2->GetParameter(0)*funvn2->GetParameter(1)<<" "
      <<funvn3->GetParameter(0)*funvn3->GetParameter(1)<<endl;
  

  cout<<"*************** v2 ***********"<<endl;
  cout<<funvn0->GetParameter(2)<<" "<<funvn1->GetParameter(2)<<" "<<funvn2->GetParameter(2)<<" "<<funvn3->GetParameter(2)<<endl;

  cout<<"*************** v3 ***********"<<endl;
  cout<<funvn0->GetParameter(3)<<" "<<funvn1->GetParameter(3)<<" "<<funvn2->GetParameter(3)<<" "<<funvn3->GetParameter(3)<<endl;
*/
}
void pbpbEffJpsiSFSysSTA__idx_()   
{
  int Prompt =1; int PutWeight = 1;

  int JpsiCat_ = 1; // 1 : prompt, 2 : non-prompt

  double minRap = 0.0; double maxRap = 1.2;
  double minPt = 6.5; double maxPt = 30.0;
  for(int eCat_ = 1; eCat_ < 6; eCat_++){

    if(eCat_ == 1) {minRap = 0.0; maxRap = 1.2;}
    if(eCat_ == 2) {minRap = 1.2; maxRap = 1.6;}
    if(eCat_ == 3) {minRap = 1.6; maxRap = 2.4;}
    if(eCat_ == 4) {
      minRap = 1.6; maxRap = 2.4;
      minPt = 3.0; maxPt = 6.5;
    }
    if(eCat_ == 5){
      minRap = 0.0; maxRap = 2.4;
      minPt = 6.5; maxPt = 30.0;
    }

    bool bDefault = true; // true : default, false : sailor or cowboy

    char cCd[512];
    if(bDefault) sprintf(cCd, "default");

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

    //==============================================Define Acc Eff Stuff here===========================================
    // Pt bin sizes
    // 0-1.5, 1.5-3, 3-4.5, 4.5-6, 6-7.5...

    const char *cTrg[5] = {"Bit1", "L1DM0HighQ", "L2Mu3NHitQ", "L3Mu3", "L3DMOpen"};
    //int iTrg = 0;
    TFile *outfile;
    char tmp_output[512];
    if(eCat_ == 1) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y1.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 2) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y2.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 3) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y3.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 4) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_lowpt.root", minRap, maxRap, minPt, maxPt);
    if(eCat_ == 5) sprintf(tmp_output,"pbpbPrJpsi_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_HighQ_tnpWgt_2D_y4.root", minRap, maxRap, minPt, maxPt);
    outfile =new TFile(tmp_output, "Recreate");
    TH1F *hGenCent = new TH1F("hGenCent",";Centrality (%);Weighted Counts",40,0,40);
    TH1F *hRecCent = new TH1F("hRecCent",";Centrality (%);Weighted Counts",40,0,40);
    hGenCent->Sumw2();
    hRecCent->Sumw2();

    for(int iSpec = 0; iSpec < 1; iSpec++){

      const int nCentBins = 6; // Non-prompt (60-100)
      const int nPtBins = 7;
      const int nRapBins = 6;
      const int ndPhiBins = 8;
      //const int ndPhiBins = 4;
      const int ndPhi2Bins = 8;
      const int nPhiBins = 8;
      const int nFiles = 6;
      double ct_bound[nCentBins+1] = {0, 4, 8, 12, 16, 20, 40}; // NonPrompt (60-100)
      double ct_bound2[nCentBins+1] = {0.0};
      for(int ict = 0; ict < nCentBins+1; ict++){
        ct_bound2[ict] = ct_bound[ict]*2.5;
      }
      double xct_bound[nCentBins] = {0.0};
      //double pt_bound[nPtBins+1] = {0.0, 3.0, 6.5};
      // pT bins : 6.5-7.5, 7.5-8.5, 8.5-9.5, 9.5-10.5, 10.5-11.5, 11.5-12.5, 12.5-14.5, 14.5-16.5, 16.5-20.0, 20.0-30.0
      double pt_bound[nPtBins+1] = {6.5, 7.5, 8.5, 9.5, 11.0, 13.0, 16.0, 30.0};
      double xpt_bound[nPtBins] = {0.0};
      // rap bins : 0.0-0.3, 0.3-0.6, 0.6-0.9, 0.9-1.2, 1.2-1.5, 1.5-1.8, 1.8-2.1, 2.1-2.4
      double rap_bound[nRapBins+1] = {0.0, 0.4, 0.8, 1.2, 1.6, 2.0, 2.4};
      double xrap_bound[nRapBins] = {0.0};
      double dphi_bound[ndPhiBins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
      double xdphi_bound[ndPhiBins] = {0.0};
      double phi_bound[nPhiBins+1] = {-4*TMath::Pi()/4, -3*TMath::Pi()/4, -2*TMath::Pi()/4, -1*TMath::Pi()/4,0.0, TMath::Pi()/4, 2*TMath::Pi()/4, 3*TMath::Pi()/4, TMath::Pi()};
      double xphi_bound[nPhiBins] = {0.0};
      double dphi2_bound[ndPhi2Bins+1] = {0.0, TMath::Pi()/16, 2*TMath::Pi()/16, 3*TMath::Pi()/16, 4*TMath::Pi()/16, 5*TMath::Pi()/16, 6*TMath::Pi()/16, 7*TMath::Pi()/16, 8*TMath::Pi()/16};
      double xdphi2_bound[ndPhi2Bins] = {0.0};

      const char *cSp[6] = {"Cents","Pts","Raps","Phi","dPhi","gdPhi"};
      char OutTextFile[100];
      if(eCat_ == 1) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y1.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 2) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y2.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 3) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y3.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 4) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_lowpt.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      if(eCat_ == 5) sprintf(OutTextFile,"eff_%s_%s_%s_y_%0.1f_%0.1f_pT_%0.1f_%0.1f_2D_y4.tex", cSp[iSpec], cCd, cTrg[0], minRap, maxRap, minPt, maxPt);
      //sprintf(OutTextFile,"eff_HighPt_%s_%s_%s.tex", cSp[iSpec], cCd, cTrg[iCat]);
      ofstream dataFile(Form(OutTextFile));

      char tmp_start[512];
      sprintf(tmp_start,"%%%% Getting Efficiency starts, Category : %s !!!!! %%%%%", cCd);  
      cout<< tmp_start << endl;
      //dataFile<< tmp_start << endl;

      // x, y, z - axis 
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of Cent"<<endl;
      for(int i = 0; i < nCentBins; i++){
        if(i == (nCentBins-1)){
          xct_bound[i] = ct_bound[i-4] + (ct_bound[i-1]-ct_bound[i-4])/2;
          //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
          //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        }else{
          xct_bound[i] = ct_bound[i] + (ct_bound[i+1]-ct_bound[i])/2;
          //cout<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
          //dataFile<<"xct_bound["<<i<<"] : "<<xct_bound[i]<<endl;
        }
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of pT"<<endl;
      for(int i = 0; i < nPtBins; i++){
        xpt_bound[i] = pt_bound[i] + (pt_bound[i+1]-pt_bound[i])/2;
        //cout<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
        //dataFile<<"xpt_bound["<<i<<"] : "<<xpt_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of rap"<<endl;
      for(int i = 0; i < nRapBins; i++){
        xrap_bound[i] = rap_bound[i] + (rap_bound[i+1]-rap_bound[i])/2;
        //cout<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
        //dataFile<<"xrap_bound["<<i<<"] : "<<xrap_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of dphi"<<endl;
      for(int i = 0; i < ndPhiBins; i++){
        xdphi_bound[i] = dphi_bound[i] + (dphi_bound[i+1]-dphi_bound[i])/2;
        //cout<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
        //dataFile<<"xdphi_bound["<<i<<"] : "<<xdphi_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of phi"<<endl;
      for(int i = 0; i < nPhiBins; i++){
        xphi_bound[i] = phi_bound[i] + (phi_bound[i+1]-phi_bound[i])/2;
        //cout<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
        //dataFile<<"xphi_bound["<<i<<"] : "<<xphi_bound[i]<<endl;
      }
      //dataFile<<""<<endl;
      //dataFile<<"xaxis of dphi2"<<endl;
      for(int i = 0; i < ndPhi2Bins; i++){
        xdphi2_bound[i] = dphi2_bound[i] + (dphi2_bound[i+1]-dphi2_bound[i])/2;
        //cout<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
        //dataFile<<"xdphi2_bound["<<i<<"] : "<<xdphi2_bound[i]<<endl;
      }

      int nBins_tmp = 0;
      if(iSpec == 0) { nBins_tmp = nCentBins; }
      if(iSpec == 1) { nBins_tmp = nPtBins; }
      if(iSpec == 2) { nBins_tmp = nRapBins; }
      if(iSpec == 3) { nBins_tmp = nPhiBins; }
      if(iSpec == 4) { nBins_tmp = ndPhiBins; }
      if(iSpec == 5) { nBins_tmp = ndPhi2Bins; }
      const int nBins = nBins_tmp;

      TH1F *hTempMass = new TH1F("hTempMass","",100, 2.0, 4.0);
      TH1F *hGenDiMuonf[nFiles][nBins];
      TH1F *hRecoDiMuonf[nFiles][nBins];
      TH1F *hGenDiMuon[nBins];
      TH1F *hRecoDiMuon[nBins];
      double genNo[nBins];
      double genErr[nBins];
      double recoNo[nBins];
      double recoErr[nBins];
      double eff[nBins];
      double effErr[nBins];
      for(int fl = 0; fl < nFiles; fl++){
        for(int i = 0; i < nBins; i++){
          hGenDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
          hRecoDiMuonf[fl][i] = (TH1F*)hTempMass->Clone();
          hGenDiMuon[i] = (TH1F*)hTempMass->Clone();
          hRecoDiMuon[i] = (TH1F*)hTempMass->Clone();
          hGenDiMuonf[fl][i]->Sumw2();
          hRecoDiMuonf[fl][i]->Sumw2();
          hGenDiMuon[i]->Sumw2();
          hRecoDiMuon[i]->Sumw2();
        }
      }

      char fileName[10][512];
      //scales for different pT bins

      double scale[6]={5.83233e-06, 8.13987e-06, 3.64971e-06, 1.13816e-06, 3.50384e-07, 2.1568e-07};
      if(PutWeight==0){scale[0]=(1);scale[1]=(1);scale[2]=(1);scale[3]=(1);scale[4]=(1);scale[5]=(1);}

      // loop for pT
      cout<<"================================="<<endl;
      sprintf(fileName[0],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0003.root");
      sprintf(fileName[1],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0306.root");
      sprintf(fileName[2],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0609.root");
      sprintf(fileName[3],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_0912.root");
      sprintf(fileName[4],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_1215.root");
      sprintf(fileName[5],"/Users/dmoon/Dropbox/Analysis/HiMC/EffStudy/gRpAngRootFiles_Regit_NonPro/HiDiMuonAna_NonPrompt_RegIt_MC_20131006_Pt_1530.root");


      TFile *infile;
      TTree *tree;
      TTree *gentree;

      for(int ifile = 0; ifile < nFiles; ifile++){
        infile=new TFile(fileName[ifile],"R");
        tree=(TTree*)infile->Get("SingleMuonTree");
        gentree=(TTree*)infile->Get("SingleGenMuonTree");
        //Event variables
        int eventNb,runNb,lumiBlock, gbin, rbin;
        int hbit1;
        double zVtx;
        //Jpsi Variables
        Double_t JpsiMass,JpsiPt,JpsiRap, JpsiCharge;
        Double_t JpsiVprob;
        Double_t JpsiPhi;
        Double_t JpsiEta;
        Double_t JpsiPsi[38];
        Double_t JpsiGenPsi;
        //2.) muon variables RECO                                                                       
        double muPosPx, muPosPy, muPosPz,  muPosEta, muPosPt, muPosP, muPosPhi;
        double muNegPx, muNegPy, muNegPz,  muNegEta, muNegPt, muNegP, muNegPhi;
        //(1).Positive Muon                                     
        double muPos_nchi2In, muPos_dxy, muPos_dz, muPos_nchi2Gl;
        int muPos_found, muPos_pixeLayers, muPos_nValidMuHits,muPos_arbitrated,muPos_TMOneST,muPos_trkLayMeas;
        bool muPos_matches,muPos_tracker;
        int muPos_Trigger2, muPos_Trigger10;
        int muPos_Trigger4, muPos_Trigger12, muPos_Trigger13;
        int muPos_Trigger21, muPos_Trigger22;
        //(2).Negative Muon                                     
        double muNeg_nchi2In, muNeg_dxy, muNeg_dz, muNeg_nchi2Gl;
        int muNeg_found, muNeg_pixeLayers, muNeg_nValidMuHits,muNeg_arbitrated,muNeg_TMOneST,muNeg_trkLayMeas;
        bool muNeg_matches,muNeg_tracker;
        int muNeg_Trigger2, muNeg_Trigger10;
        int muNeg_Trigger4, muNeg_Trigger12, muNeg_Trigger13;
        int muNeg_Trigger21, muNeg_Trigger22;

        //Gen Level variables
        //Gen PrJpsi Variables
        double GenJpsiMass, GenJpsiPt, GenJpsiRap;
        double GenJpsiPx, GenJpsiPy, GenJpsiPz;
        double GenJpsiPhi;
        double GenJpsiEta;
        double GenJpsiPsi;
        //2.) Gen muon variables 
        double GenmuPosPx, GenmuPosPy, GenmuPosPz,  GenmuPosEta, GenmuPosPt, GenmuPosPhi;
        double GenmuNegPx, GenmuNegPy, GenmuNegPz,  GenmuNegEta, GenmuNegPt, GenmuNegPhi;

        //Event variables
        tree->SetBranchAddress("eventNb",&eventNb);
        tree->SetBranchAddress("runNb",&runNb);
        tree->SetBranchAddress("lumiBlock",&lumiBlock);
        tree->SetBranchAddress("hbit1",&hbit1);
        tree->SetBranchAddress("zVtx",&zVtx);

        //Jpsi Variables
        tree->SetBranchAddress("JpsiCharge",&JpsiCharge);
        tree->SetBranchAddress("JpsiMass",&JpsiMass);
        tree->SetBranchAddress("JpsiPt",&JpsiPt);
        tree->SetBranchAddress("JpsiPhi",&JpsiPhi);
        tree->SetBranchAddress("JpsiEta",&JpsiEta);
        tree->SetBranchAddress("JpsiPsi",&JpsiPsi);
        tree->SetBranchAddress("JpsiGenPsi",&JpsiGenPsi);
        tree->SetBranchAddress("JpsiRap",&JpsiRap);
        tree->SetBranchAddress("JpsiVprob",&JpsiVprob);
        tree->SetBranchAddress("rbin",&rbin);

        //muon variable
        tree->SetBranchAddress("muPosPx",&muPosPx);
        tree->SetBranchAddress("muPosPy",&muPosPy);
        tree->SetBranchAddress("muPosPz",&muPosPz);
        tree->SetBranchAddress("muPosEta",&muPosEta);
        tree->SetBranchAddress("muPosPhi",&muPosPhi);
        tree->SetBranchAddress("muNegPx", &muNegPx);
        tree->SetBranchAddress("muNegPy", &muNegPy);
        tree->SetBranchAddress("muNegPz", &muNegPz);
        tree->SetBranchAddress("muNegEta", &muNegEta);
        tree->SetBranchAddress("muNegPhi", &muNegPhi);


        //1). Positive Muon
        tree->SetBranchAddress("muPos_nchi2In", &muPos_nchi2In);
        tree->SetBranchAddress("muPos_dxy", &muPos_dxy);
        tree->SetBranchAddress("muPos_dz", &muPos_dz);
        tree->SetBranchAddress("muPos_nchi2Gl", &muPos_nchi2Gl);
        tree->SetBranchAddress("muPos_found", &muPos_found);
        tree->SetBranchAddress("muPos_pixeLayers", &muPos_pixeLayers);
        tree->SetBranchAddress("muPos_nValidMuHits", &muPos_nValidMuHits);
        tree->SetBranchAddress("muPos_matches", &muPos_matches);
        tree->SetBranchAddress("muPos_tracker", &muPos_tracker);
        tree->SetBranchAddress("muPos_arbitrated", &muPos_arbitrated);
        tree->SetBranchAddress("muPos_TMOneST", &muPos_TMOneST);
        tree->SetBranchAddress("muPos_trkLayMeas", &muPos_trkLayMeas);
        tree->SetBranchAddress("muPos_Trigger2", &muPos_Trigger2);
        tree->SetBranchAddress("muPos_Trigger21", &muPos_Trigger21);
        tree->SetBranchAddress("muPos_Trigger22", &muPos_Trigger22);
        tree->SetBranchAddress("muPos_Trigger4", &muPos_Trigger4);
        tree->SetBranchAddress("muPos_Trigger10", &muPos_Trigger10);
        tree->SetBranchAddress("muPos_Trigger12", &muPos_Trigger12);
        tree->SetBranchAddress("muPos_Trigger13", &muPos_Trigger13);

        //2). Negative Muon                                                                            
        tree->SetBranchAddress("muNeg_nchi2In", &muNeg_nchi2In);
        tree->SetBranchAddress("muNeg_dxy", &muNeg_dxy);
        tree->SetBranchAddress("muNeg_dz", &muNeg_dz);
        tree->SetBranchAddress("muNeg_nchi2Gl", &muNeg_nchi2Gl);
        tree->SetBranchAddress("muNeg_found", &muNeg_found);
        tree->SetBranchAddress("muNeg_pixeLayers", &muNeg_pixeLayers);
        tree->SetBranchAddress("muNeg_nValidMuHits", &muNeg_nValidMuHits);
        tree->SetBranchAddress("muNeg_matches", &muNeg_matches);
        tree->SetBranchAddress("muNeg_tracker", &muNeg_tracker);
        tree->SetBranchAddress("muNeg_arbitrated", &muNeg_arbitrated);
        tree->SetBranchAddress("muNeg_TMOneST", &muNeg_TMOneST);
        tree->SetBranchAddress("muNeg_trkLayMeas", &muNeg_trkLayMeas);
        tree->SetBranchAddress("muNeg_Trigger2", &muNeg_Trigger2);
        tree->SetBranchAddress("muNeg_Trigger21", &muNeg_Trigger21);
        tree->SetBranchAddress("muNeg_Trigger22", &muNeg_Trigger22);
        tree->SetBranchAddress("muNeg_Trigger4", &muNeg_Trigger4);
        tree->SetBranchAddress("muNeg_Trigger10", &muNeg_Trigger10);
        tree->SetBranchAddress("muNeg_Trigger12", &muNeg_Trigger12);
        tree->SetBranchAddress("muNeg_Trigger13", &muNeg_Trigger13);
        //====================================Gen Variables=========================================================
        //Gen Jpsi Variables
        gentree->SetBranchAddress("GenJpsiMass",   &GenJpsiMass);
        gentree->SetBranchAddress("GenJpsiPt",     &GenJpsiPt);
        gentree->SetBranchAddress("GenJpsiPhi",    &GenJpsiPhi);
        gentree->SetBranchAddress("GenJpsiPsi",    &GenJpsiPsi);
        gentree->SetBranchAddress("GenJpsiRap",    &GenJpsiRap);
        gentree->SetBranchAddress("GenJpsiEta",    &GenJpsiEta);
        gentree->SetBranchAddress("GenJpsiPx",     &GenJpsiPx);
        gentree->SetBranchAddress("GenJpsiPy",     &GenJpsiPy);
        gentree->SetBranchAddress("GenJpsiPz",     &GenJpsiPz);
        gentree->SetBranchAddress("gbin",          &gbin);
        //muon variable
        gentree->SetBranchAddress("GenmuPosPx",    &GenmuPosPx);
        gentree->SetBranchAddress("GenmuPosPy",    &GenmuPosPy);
        gentree->SetBranchAddress("GenmuPosPz",    &GenmuPosPz);
        gentree->SetBranchAddress("GenmuPosEta",   &GenmuPosEta);
        gentree->SetBranchAddress("GenmuPosPhi",   &GenmuPosPhi);
        gentree->SetBranchAddress("GenmuNegPx",    &GenmuNegPx);
        gentree->SetBranchAddress("GenmuNegPy",    &GenmuNegPy);
        gentree->SetBranchAddress("GenmuNegPz",    &GenmuNegPz);
        gentree->SetBranchAddress("GenmuNegEta",   &GenmuNegEta);
        gentree->SetBranchAddress("GenmuNegPhi",   &GenmuNegPhi);

        //====================================================== Gen tree loop ================================================
        int NAccep=0;
        int nGenEntries=gentree->GetEntries();
        cout<<" Total Entries in GenLevel Tree for pT range: "<<fileName[ifile]<<"  "<<   nGenEntries<< " ==============="<<endl;

        for(int iGen=0; iGen< nGenEntries; iGen++)  {        
          //cout<<"i : "<<i<<endl;
          if(!(gentree->GetEntry(iGen))) continue;
          //cout<<" gentree ("<<i<<")"<<endl;
          //Only printing 
          if(iGen%10000==0){
            //cout<<" processing record "<<iGen<<"/"<<nGenEntries<<endl;
            //cout<<" Mass "<< GenJpsiMass<< " pT "<< GenJpsiPt << " Y " <<GenJpsiRap<<endl;
          }

          bool GenPosIn=0, GenNegIn=0;
          GenmuPosPt= TMath::Sqrt(GenmuPosPx*GenmuPosPx + GenmuPosPy*GenmuPosPy); 
          GenmuNegPt= TMath::Sqrt(GenmuNegPx*GenmuNegPx + GenmuNegPy*GenmuNegPy); 

          if(IsAccept(GenmuPosPt, GenmuPosEta)) {GenPosIn=1;}
          if(IsAccept(GenmuNegPt, GenmuNegEta)) {GenNegIn=1;}

          double GenCenWeight =0, GenWeight =0;
          GenCenWeight=FindCenWeight(gbin);   
          GenWeight=GenCenWeight*scale[ifile];

          hGenCent->Fill(gbin,GenWeight);

          int AccJpsi = 0;
          //if(GenJpsiPt < 6.5) continue;
          if((GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) <= maxRap && 
                GenPosIn == 1 && GenNegIn == 1 && GenJpsiMass > 2.0 && GenJpsiMass < 4.0)) {AccJpsi = 1;}

          if((GenPosIn ==1 && GenNegIn==1)) NAccep++;

          if(PutWeight==0) GenWeight=1; 

          //adding pT of all pt bins to see diss is cont

          //cout<<"1. GenJpsiPt : "<<GenJpsiPt<<", GenJpsiEta : "<<GenJpsiEta<<", GenJpsiRap : "<<GenJpsiRap<<", |GenJpsiPsi| : "<<TMath::Abs(GenJpsiPsi)<<endl;
          //cout<<"1. GenPosIn : "<<GenPosIn<<", GenNegIn : "<<GenNegIn<<endl;
          double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
          if(iSpec == 0) vars = gbin;
          if(iSpec == 1) vars = GenJpsiPt;
          if(iSpec == 2) vars = fabs(GenJpsiRap);
          if(iSpec == 3) vars = GenJpsiPhi;
          if(iSpec == 4) vars = fabs(GenJpsiPsi);
          if(iSpec == 5) vars = fabs(GenJpsiPsi);
          for(int i = 0; i < nBins; i++){
            if(iSpec == 0){
              bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && GenJpsiPt >= minPt && GenJpsiPt <= maxPt && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 1){
              bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && fabs(GenJpsiRap) >= minRap && fabs(GenJpsiRap) < maxRap ) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 2){
              bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 3){
              bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 4){
              bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
            if(iSpec == 5){
              bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
              if( (AccJpsi==1) && (vars >= bin1 && vars < bin2) && gbin >= 0 && gbin <= 40 && GenJpsiPt >= minPt && GenJpsiPt < maxPt && fabs(GenJpsiRap) < maxRap) {
                hGenDiMuonf[ifile][i]->Fill(GenJpsiMass,GenWeight);
              }
            }
          }
        }//gen loop end

        //cout<<" accepted no "<< NAccep<<endl;

        //=============== Rec Tree Loop ==============================================================================

        int nRecEntries=tree->GetEntries();
        cout<<"Total Entries in reconstructed Tree for pT range "<<fileName[ifile]<<"  "<<nRecEntries<< "====="<<endl;
        for(int iRec=0; iRec<nRecEntries; iRec++)  {     
          tree->GetEntry(iRec);
          //Only printing 
          if(iRec%10000==0){
            //cout<<" processing record "<<iRec<<"/"<<nRecEntries<<endl;
            //cout<<" processing Run  " <<runNb <<" event "<<eventNb<<" lum block "<<lumiBlock<<endl;    
            //cout<<" Mass "<< JpsiMass<< " pT "<< JpsiPt << " Y " <<JpsiRap<<"  "<<JpsiVprob<<" charge "<<JpsiCharge<<" rbin "<<rbin<<endl; 
          }
          bool PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0;
          muPosPt= TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy); 
          muPosP = TMath::Sqrt(muPosPx*muPosPx + muPosPy*muPosPy+ muPosPz*muPosPz); 
          muNegPt= TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy); 
          muNegP = TMath::Sqrt(muNegPx*muNegPx + muNegPy*muNegPy +muNegPz*muNegPz); 

          double tnpWgt1 = 0.0, tnpWgt2 = 0.0;
          double staWgt1 = 0.0, staWgt2 = 0.0;

          double x = 0.0;
          if(fabs(muPosEta) < 0.9){
            x = muPosPt;
            tnpWgt1 = tnpSF1->Eval(x);
          }else if(fabs(muPosEta) < 1.6){
            x = muPosPt;
            tnpWgt1 = tnpSF2->Eval(x);
          }else if(fabs(muPosEta) < 2.1){
            x = muPosPt;
            tnpWgt1 = tnpSF3->Eval(x);
          }else{
            x = muPosPt;
            tnpWgt1 = tnpSF4->Eval(x);
          }

          if(fabs(muNegEta) < 0.9){
            x = muNegPt;
            tnpWgt2 = tnpSF1->Eval(x);
          }else if(fabs(muNegEta) < 1.6){
            x = muNegPt;
            tnpWgt2 = tnpSF2->Eval(x);
          }else if(fabs(muNegEta) < 2.1){
            x = muNegPt;
            tnpWgt2 = tnpSF3->Eval(x);
          }else{
            x = muNegPt;
            tnpWgt2 = tnpSF4->Eval(x);
          }

          double xta = 0.0;
          if(fabs(muPosEta) < 1.6){
            xta = muPosPt;
            staWgt1 = fun1->Eval(xta);
          }else{
            xta = muPosPt;
            staWgt1 = fun2->Eval(xta);
          }

          if(fabs(muNegEta) < 1.6){
            xta = muNegPt;
            staWgt2 = fun1->Eval(xta);
          }else{
            xta = muNegPt;
            staWgt2 = fun2->Eval(xta);
          }

          double RecCenWeight=0,RecWeight=0;
          RecCenWeight=FindCenWeight(rbin);   
          RecWeight=RecCenWeight*scale[ifile]*tnpWgt1*tnpWgt2*staWgt1*staWgt2;

          hRecCent->Fill(gbin,RecWeight);

          if(IsAccept(muPosPt, muPosEta)){PosIn=1;}
          if(IsAccept(muNegPt, muNegEta)){NegIn=1;}

          int AccJpsi = 0;
          if((JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap && PosIn == 1 && NegIn == 1)) {AccJpsi = 1;}

          /*
             cout<<"muPos_pixeLayers : "<<muPos_pixeLayers<<" muPos_nchi2In : "<<muPos_nchi2In
             <<" TMath::Abs(muPos_dxy) : "<<TMath::Abs(muPos_dxy)<<" TMath::Abs(muPos_dz) : "<<TMath::Abs(muPos_dz)
             <<" muPos_trkLayMeas : "<<muPos_trkLayMeas
             <<" muPos_arbitrated : "<<muPos_arbitrated<<" muPos_TMOneST : "<<muPos_TMOneST<<" muPos_tracker : "<<muPos_tracker<<endl;
             cout<<"muNeg_pixeLayers : "<<muNeg_pixeLayers<<" muNeg_nchi2In : "<<muNeg_nchi2In
             <<" TMath::Abs(muNeg_dxy) : "<<TMath::Abs(muNeg_dxy)<<" TMath::Abs(muNeg_dz) : "<<TMath::Abs(muNeg_dz)
             <<" muNeg_trkLayMeas : "<<muNeg_trkLayMeas
             <<" muNeg_arbitrated : "<<muNeg_arbitrated<<" muNeg_TMOneST : "<<muNeg_TMOneST<<" muNeg_tracker : "<<muNeg_tracker<<endl;
             */
          bool mu_Global = ((muPos_nchi2Gl >=0) && (muNeg_nchi2Gl >=0));
          bool mu_Tracker = ((muPos_tracker==1) && (muNeg_tracker==1));

          if(muPos_found > 10 &&
              muPos_pixeLayers > 0 &&
              muPos_nchi2In < 4.0 &&
              TMath::Abs(muPos_dxy) < 3 &&
              TMath::Abs(muPos_dz) < 15 && muPos_nchi2Gl < 20 &&
              muPos_arbitrated==1 &&
              muPos_tracker==1){
            PosPass=1;
          }

          if(muNeg_found > 10 &&
              muNeg_pixeLayers > 0 &&
              muNeg_nchi2In < 4.0 &&
              TMath::Abs(muNeg_dxy) < 3 &&
              TMath::Abs(muNeg_dz) < 15 &&
              muNeg_nchi2Gl < 20 &&
              muNeg_arbitrated==1 &&
              muNeg_tracker==1){
            NegPass=1;
          }

          if(hbit1 == 1 && (muPos_Trigger22==1 && muNeg_Trigger22==1) && (PosIn==1 && NegIn==1) && (PosPass==1 && NegPass==1) && mu_Global && mu_Tracker ){AllCut=1;}

          if(PutWeight==0)RecWeight=1;

          double JpsidPhi = JpsiGenPsi;

          //Eff loop for reco
          double vars = 0.0, bin1 = 0.0, bin2 = 0.0;
          if(iSpec == 0) vars = rbin;
          if(iSpec == 1) vars = JpsiPt;
          if(iSpec == 2) vars = fabs(JpsiRap);
          if(iSpec == 3) vars = JpsiPhi;
          if(iSpec == 4) vars = fabs(JpsidPhi);
          if(iSpec == 5) vars = fabs(JpsiGenPsi);
          if((JpsiCharge == 0) && (JpsiVprob > 0.01) && (JpsiMass >= 2.95 && JpsiMass < 3.25)) {     
            for(int i = 0; i < nBins; i++){
              if(iSpec == 0){
                bin1 = ct_bound[i]; bin2 = ct_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 1){
                bin1 = pt_bound[i]; bin2 = pt_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && fabs(JpsiRap) >= minRap && fabs(JpsiRap) <= maxRap ) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 2){ 
                bin1 = rap_bound[i]; bin2 = rap_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 3){ 
                bin1 = phi_bound[i]; bin2 = phi_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 4){ 
                bin1 = dphi_bound[i]; bin2 = dphi_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
              if(iSpec == 5){ 
                bin1 = dphi2_bound[i]; bin2 = dphi2_bound[i+1];
                if( AccJpsi == 1 && (AllCut == 1) && (vars >= bin1 && vars < bin2) && rbin >= 0 && rbin <= 40 && JpsiPt >= minPt && JpsiPt <= maxPt && fabs(JpsiRap) <=maxRap) {
                  hRecoDiMuonf[ifile][i]->Fill(JpsiMass,RecWeight);
                }
              }
            }
          }
        } //rec tree loop ends
      }  // file loop ends

      //======================  File loop Starts ============================

      ///////////////////////////////////////////////////////////////////
      cout<< " adding "<<endl;
      TCanvas *c1 = new TCanvas();
      char gtmp[512], gtmp1[512];
      char rtmp[512], rtmp1[512];

      for(int i = 0; i < nBins; i++){
        for(int ifile = 0; ifile < nFiles; ifile++){
          hGenDiMuon[i]->Add(hGenDiMuonf[ifile][i],1);
          hRecoDiMuon[i]->Add(hRecoDiMuonf[ifile][i],1);
        }
        if(iSpec == 0) sprintf(gtmp,"hGenDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
        if(iSpec == 1) sprintf(gtmp,"hGenDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
        if(iSpec == 2) sprintf(gtmp,"hGenDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
        if(iSpec == 0) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
        if(iSpec == 1) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
        if(iSpec == 2) sprintf(gtmp1,"plots/Gen/hGenDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
        if(iSpec == 0) sprintf(rtmp,"hRecDiMuon_Cent_%1.f_%1.f",ct_bound[i],ct_bound[i+1]);
        if(iSpec == 1) sprintf(rtmp,"hRecDiMuon_Pt_%0.1f_%0.1f",pt_bound[i],pt_bound[i+1]);
        if(iSpec == 2) sprintf(rtmp,"hRecDiMuon_Rap_%0.1f_%0.1f",rap_bound[i],rap_bound[i+1]);
        if(iSpec == 0) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Cent_%1.f_%1.f_%s.png",ct_bound[i],ct_bound[i+1],cCd);
        if(iSpec == 1) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Pt_%0.1f_%0.1f_%s.png",pt_bound[i],pt_bound[i+1],cCd);
        if(iSpec == 2) sprintf(rtmp1,"plots/Rec/hRecDiMuon_Rap_%0.1f_%0.1f_%s.png",rap_bound[i],rap_bound[i+1],cCd);
        hGenDiMuon[i]->SetName(gtmp);
        //hGenDiMuon[i]->Write();
        //hGenDiMuon[ipt][irap][idphi]->Draw();
        //c1->SaveAs(gtmp1);
        hRecoDiMuon[i]->SetName(rtmp);
        //hRecoDiMuon[i]->Write();
        //hRecoDiMuon[ipt][irap][idphi]->Draw();
        //c1->SaveAs(rtmp1);
      }

      TH1F *hReco = new TH1F();
      TH1F *hGen = new TH1F();
      hReco->Sumw2();
      hGen->Sumw2();
      int nRecoBins;
      int nGenBins;
      if(iSpec == 0) {hReco = new TH1F("hReco","hReco;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nRecoBins = nCentBins;}
      if(iSpec == 1) {hReco = new TH1F("hReco","hReco;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nRecoBins = nPtBins;}
      if(iSpec == 2) {hReco = new TH1F("hReco","hReco;y;Weighted Yields",nRapBins,rap_bound); nRecoBins = nRapBins;}
      if(iSpec == 3) {hReco = new TH1F("hReco","hReco;#phi;Weighted Yields",nPhiBins,phi_bound); nRecoBins = nPhiBins;}
      if(iSpec == 4) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nRecoBins = ndPhiBins;}
      if(iSpec == 5) {hReco = new TH1F("hReco","hReco;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nRecoBins = ndPhi2Bins;}

      if(iSpec == 0) {hGen = new TH1F("hGen","hGen;Centrality (%);Weighted Yields",nCentBins,ct_bound2); nGenBins = nCentBins;}
      if(iSpec == 1) {hGen = new TH1F("hGen","hGen;p_{T} GeV/c;Weighted Yields",nPtBins,pt_bound); nGenBins = nPtBins;}
      if(iSpec == 2) {hGen = new TH1F("hGen","hGen;y;Weighted Yields",nRapBins,rap_bound); nGenBins = nRapBins;}
      if(iSpec == 3) {hGen = new TH1F("hGen","hGen;#phi;Weighted Yields",nPhiBins,phi_bound); nGenBins = nPhiBins;}
      if(iSpec == 4) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhiBins,dphi_bound); nGenBins = ndPhiBins;}
      if(iSpec == 5) {hGen = new TH1F("hGen","hGen;d#phi;Weighted Yields",ndPhi2Bins,dphi2_bound); nGenBins = ndPhi2Bins;}

      cout<<"Starts to calculate efficiency"<<endl;
      //dataFile<<""<<endl;
      //=====================Loop for eff========================================================================================//
      //define stuff here for error on weighted samples
      for(int i = 0; i < nBins; i++){
        int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.0);//2.95
        int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(4.0);//2.95
        //int Gbinlow =hGenDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
        //int Gbinhi=hGenDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

        int Rbinlow =hRecoDiMuon[i]->GetXaxis()->FindBin(2.95);//2.95
        int Rbinhi=hRecoDiMuon[i]->GetXaxis()->FindBin(3.25);//2.95

        cout<<"Gbinlow : "<<Gbinlow<<", Gbinhi : "<<Gbinhi<<endl;
        cout<<"Rbinlow : "<<Rbinlow<<", Rbinhi : "<<Rbinhi<<endl;

        genNo[i] = hGenDiMuon[i]->IntegralAndError(Gbinlow, Gbinhi, genErr[i]);
        recoNo[i] = hRecoDiMuon[i]->IntegralAndError(Rbinlow, Rbinhi, recoErr[i]);

        //calculate Eff         
        if(genNo[i] == 0 || recoNo[i] == 0) {
          cout<<"No Gen or Reco, # of Gen : "<<genNo[i] <<", # of Reco : "<<recoNo[i]<<endl;
          eff[i] = 0;
          effErr[i] = 0;
        }else{
          eff[i] = recoNo[i]/genNo[i]; 

          double tmpGenNo = genNo[i];
          double tmpGenErr = genErr[i];
          double tmpRecNo = recoNo[i];
          double tmpRecErr = recoErr[i];
          double tmpEff = eff[i];
          double tmpEffErr = 0.0;

          hReco->SetBinContent(i+1,tmpRecNo);
          hReco->SetBinError(i+1,tmpRecErr);
          hGen->SetBinContent(i+1,tmpGenNo);
          hGen->SetBinError(i+1,tmpGenErr);

          //error    
          double tmp_err_s1_1 = (tmpEff * tmpEff)/(tmpGenNo * tmpGenNo);
          double tmp_err_s1_2 = (tmpRecErr * tmpRecErr);
          double tmp_err_cat_s1 = tmp_err_s1_1 * tmp_err_s1_2;


          double tmp_err_s2_1 = ( (1 - tmpEff)*(1 - tmpEff) ) / (tmpGenNo * tmpGenNo);
          double tmp_err_s2_2 = TMath::Abs(( tmpGenErr*tmpGenErr ) - ( tmpRecErr * tmpRecErr));
          double tmp_err_cat_s2 = tmp_err_s2_1 * tmp_err_s2_2;
          tmpEffErr = sqrt( tmp_err_cat_s1 + tmp_err_cat_s2 );

          effErr[i] = tmpEffErr;

          //error without weight
          //dataFile<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
          //dataFile<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
          cout<<" Bin ["<<i<<"] - "<< " Reco Jpsi : "<< tmpRecNo  <<", Gen Jpsi : "<< tmpGenNo <<endl;
          cout<<" Eff ["<<i<<"] - "<< tmpEff <<" Error "<< tmpEffErr <<endl;
        }
      }
      TH1F *hEff = new TH1F();
      hEff->Sumw2();
      int nEffBins = 0;
      if(iSpec == 0) {hEff = new TH1F("hEff","hEff;Centrality (%);Efficiency",nCentBins,ct_bound2); nEffBins = nCentBins;}
      if(iSpec == 1) {hEff = new TH1F("hEff","hEff;p_{T} GeV/c;Efficiency",nPtBins,pt_bound); nEffBins = nPtBins;}
      if(iSpec == 2) {hEff = new TH1F("hEff","hEff;y;Efficiency",nRapBins,rap_bound); nEffBins = nRapBins;}
      if(iSpec == 3) {hEff = new TH1F("hEff","hEff;#phi;Efficiency",nPhiBins,phi_bound); nEffBins = nPhiBins;}
      if(iSpec == 4) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhiBins,dphi_bound); nEffBins = ndPhiBins;}
      if(iSpec == 5) {hEff = new TH1F("hEff","hEff;d#phi;Efficiency",ndPhi2Bins,dphi2_bound); nEffBins = ndPhi2Bins;}

      for(int i = 0; i < nEffBins; i++){
        hEff->SetBinContent(i+1,eff[i]);
        hEff->SetBinError(i+1,effErr[i]);
        cout<<"Trying to measure Reconstruction eff vs "<<cSp[iSpec]<<endl;
        cout<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
        dataFile<<eff[i]<<endl;//", err : "<<effErr[i]<<endl;
        //dataFile<<"Eff : "<<eff[i]<<", err : "<<effErr[i]<<endl;
      }

      outfile->cd();
      hEff->Draw();
      char tmp_histo[512];
      sprintf(tmp_histo,"hEff_%s",cSp[iSpec]);
      char tmp_histo_reco[512];
      sprintf(tmp_histo_reco,"hReco_%s",cSp[iSpec]);
      char tmp_histo_gen[512];
      sprintf(tmp_histo_gen,"hGen_%s",cSp[iSpec]);
      hEff->SetName(tmp_histo);
      hEff->Write();
      hReco->SetName(tmp_histo_reco);
      hReco->Write();
      hGen->SetName(tmp_histo_gen);
      hGen->Write();
      //c1->SaveAs("eff_3D_default_etHFm.png");
      //outfile->Close();
      dataFile<<""<<endl;
      dataFile.close();
    }
    hGenCent->Write();
    hRecCent->Write();
    outfile->Write();
  }
}
Пример #29
0
//void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfile="ROOTfiles/NPFitPP.root", TString outputfile="outfMasshisto/mass")
void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfit="0", TString outputfile="outfMasshisto/mass")
{
  _nominalcut = nominalcut;
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptStat(0);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(0.8);

  collisionsystem = collsyst;
  infname = outputfile;
  varname=varname_;
  vartex=vartex_;
  isLarger=isLarger_;

  //TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, float NPpar[]);
  TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, TString npfit);
  //void getNPFnPar(TString npfname, float par[]);
  //float NPpar[2];
  //getNPFnPar(npfile, NPpar);
  //std::cout<<"NP parameter 0: "<<NPpar[0]<<std::endl;
  //std::cout<<"NP parameter 1: "<<NPpar[1]<<std::endl;
  
  Float_t varstep;
  if(varbins==1) varstep = 0.5;
  else varstep = (varmax-varmin)/(varbins-1);
  TH1F* hMCCut = new TH1F("hMCCut","",varbins,varmin,varmax+varstep);
  TH1F* hMCNoCut = new TH1F("hMCNoCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaCut = new TH1F("hDaCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaNoCut = new TH1F("hDaNoCut","",varbins,varmin,varmax+varstep);
  for(float i=0;i<varbins+1;i++)
    {
      Float_t yield,yieldErr;
      Float_t ivar = varmin+(i-1)*varstep;
      //TF1* fMC = fit(ivar,i,1, NPpar);
      TF1* fMC = fit(ivar,i,1, npfit);
      yield = fMC->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fMC->Integral(minhisto,maxhisto)/binwidthmass*fMC->GetParError(0)/fMC->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hMCNoCut->SetBinContent(j+1,yield);
              hMCNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hMCCut->SetBinContent(i,yield);
          hMCCut->SetBinError(i,yieldErr);
        }
      //TF1* fDa = fit(ivar,i,0, NPpar);
      TF1* fDa = fit(ivar,i,0, npfit);
      yield = fDa->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fDa->Integral(minhisto,maxhisto)/binwidthmass*fDa->GetParError(0)/fDa->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hDaNoCut->SetBinContent(j+1,yield);
              hDaNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hDaCut->SetBinContent(i,yield);
          hDaCut->SetBinError(i,yieldErr);
        }
    }

  TCanvas* cMCRatio = new TCanvas("cMCRatio","",600,600);
  TH1F* hMCRatio = (TH1F*)hMCCut->Clone("hMCRatio");
  hMCRatio->SetTitle(Form(";%s;hMCRatio",vartex.Data()));
  hMCRatio->Divide(hMCNoCut);
  hMCRatio->Draw();

  TCanvas* cDaRatio = new TCanvas("cDaRatio","",600,600);
  TH1F* hDaRatio = (TH1F*)hDaCut->Clone("hDaRatio");
  hDaRatio->SetTitle(Form(";%s;hDaRatio",vartex.Data()));
  hDaRatio->Divide(hDaNoCut);
  hDaRatio->Draw();

  TCanvas* chDoubleRatio = new TCanvas("chDoubleRatio","",600,600);
  TH1F* hDoubleRatio = (TH1F*)hDaRatio->Clone("hDoubleRatio");
  hDoubleRatio->SetTitle(Form(";%s;hDoubleRatio",vartex.Data()));
  hDoubleRatio->Divide(hMCRatio);
  hDoubleRatio->Draw();

  Float_t aDoubleRatio[varbins],aDoubleRatioErr[varbins],aX[varbins],aZero[varbins];
  Float_t AbsMax = max(fabs(hDoubleRatio->GetMaximum()-1), fabs(hDoubleRatio->GetMinimum()-1));
  for(int i=0;i<varbins;i++)
    {
      aDoubleRatio[i] = hDoubleRatio->GetBinContent(i+1);
      aDoubleRatioErr[i] = hDoubleRatio->GetBinError(i+1);
      aX[i] = varmin+i*varstep;
      aZero[i] = 0;
    }
  TGraphErrors* gDoubleRatio = new TGraphErrors(varbins,aX,aDoubleRatio,aZero,aDoubleRatioErr);
  TH2F* hemptyDoubleRatio = new TH2F("hemptyDoubleRatio","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.,2.);
  hemptyDoubleRatio->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyDoubleRatio->GetYaxis()->SetTitle("(Yield^{Data}_{Cuts}/Yield^{Data}_{NoCuts})/(Yield^{MC}_{Cuts}/Yield^{MC}_{NoCuts})");
  hemptyDoubleRatio->GetXaxis()->SetTitleOffset(1.);
  hemptyDoubleRatio->GetYaxis()->SetTitleOffset(1.4);
  hemptyDoubleRatio->GetXaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetYaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetXaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetYaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetYaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelSize(0.04);
  hemptyDoubleRatio->GetYaxis()->SetLabelSize(0.04);
  TLine* lDoubleRatio = new TLine(varmin-0.5*varstep, 1., varmax+0.5*varstep, 1.);
  lDoubleRatio->SetLineWidth(1);
  lDoubleRatio->SetLineStyle(7);
  lDoubleRatio->SetLineColor(1);
  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  TCanvas* cDoubleRatio = new TCanvas("cDoubleRatio","",600,600);
  hemptyDoubleRatio->Draw();
  gDoubleRatio->Draw("psame");
  lDoubleRatio->Draw();
  texCms->Draw();
  texCol->Draw();
  TLatex* texAbsMax = new TLatex(0.88,0.85, Form("max diff: %.3f",AbsMax));
  texAbsMax->SetNDC();
  texAbsMax->SetTextAlign(32);
  texAbsMax->SetTextSize(0.04);
  texAbsMax->SetTextFont(42);
  texAbsMax->Draw();
	
  cDoubleRatio->SaveAs(Form("plotRatios/%s_%s_DoubleRatio.pdf",collisionsystem.Data(),varname.Data()));

  TFile* outf = new TFile(Form("outfDoubleratio/f%s_%s_DoubleRatio.root",collisionsystem.Data(),varname.Data()),"recreate");
  outf->cd();
  hDoubleRatio->Write();
  outf->Close();
}
Пример #30
0
void 
//HHH_TT_X_notag(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
HHH_TT_X_notag(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category_extra= "2-jet 0 b-tag";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category_extra= "2-jet 1 b-tag";     }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category_extra = "2-jet 2 b-tag";              }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){
    if(std::string(directory).find("btag")!=std::string::npos){
      dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                18.3 fb^{-1} (8 TeV)";
    }
    else{
        dataset = "#scale[1.5]{CMS}  H#rightarrow hh#rightarrow#tau#tau bb                         19.7 fb^{-1} (8 TeV)";
    }
  }
#else
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MH_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"      , directory)), "ZLL" ); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK3 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK  , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggHTohhTo2Tau2B    = refill((TH1F*)input2->Get(TString::Format("%s/ggHTohhTo2Tau2B$MH" , directory)), "ggHTohhTo2Tau2B"); InitSignal(ggHTohhTo2Tau2B); ggHTohhTo2Tau2B->Scale($TANB*SIGNAL_SCALE);
 // if(std::string(directory)=="tauTau_2jet0tag") ggHTohhTo2Tau2B->Scale(4);
/*  TH1F* ggH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125",directory)),"ggH_SM125");InitSignal(ggH_SM125);ggH_SM125->Scale(SIGNAL_SCALE);
  TH1F* qqH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125",directory)),"qqH_SM125");InitSignal(qqH_SM125);qqH_SM125->Scale(SIGNAL_SCALE);
  TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125",directory)),"VH_SM125");InitSignal(VH_SM125);VH_SM125->Scale(SIGNAL_SCALE);
  TH1F* WHToBB_SM125 = refill((TH1F*)input->Get(TString::Format("%s/WHToBB_SM125",directory)),"WHToBB_SM125");InitSignal(WHToBB_SM125);WHToBB_SM125->Scale(SIGNAL_SCALE);
  TH1F* ZHToBB_SM125 = refill((TH1F*)input->Get(TString::Format("%s/ZHToBB_SM125",directory)),"ZHToBB_SM125");InitSignal(ZHToBB_SM125);ZHToBB_SM125->Scale(SIGNAL_SCALE);
*/
/*
  TH1F* ggAToZhToLLTauTau = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLTauTau$MH",directory)),"ggAToZhToLLTauTau"); InitSignal(ggAToZhToLLTauTau);
  TH1F* ggAToZhToLLBB = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLBB$MH",directory)),"ggAToZhToLLBB"); InitSignal(ggAToZhToLLBB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MH" , directory)), "bbH"); InitSignal(bbH);
*/
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data",true);
#endif
  InitHist(data, "#bf{m_{H} [GeV]}", "#bf{dN/dm_{H} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(EWK );
  ref->Add(ttbar);
  ref->Add(Ztt  );


  double unscaled[8];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggHTohhTo2Tau2B  ->Integral();
/*  unscaled[5] = ggH_SM125->Integral();
  unscaled[5]+= qqH_SM125->Integral();
  unscaled[5]+= VH_SM125->Integral();
*/
/*
  unscaled[5] = ggAToZhToLLTauTau->Integral();
  unscaled[6] = ggAToZhToLLBB->Integral();
  unscaled[7] = bbH  ->Integral();
*/
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK1  = refill(shape_histos(EWK1, datacard, "W"), "W");
    EWK2  = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK   = refill(shape_histos(EWK, datacard, "VV"), "VV");
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT"); 
    Ztt   = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT"); 
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MH"), "ggH$MH"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MH"), "bbH$MH"); 
#else
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH");
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH");
    VH  = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif
*/
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggHTohhTo2Tau2B  , 8); 
/*
    rescale(ggAToZhToLLTauTau,9);
    rescale(ggAToZhToLLBB,10);
    rescale(bbH  , 11);  
*/
#endif
  }

  TH1F* scales[8];
  scales[0] = new TH1F("scales-Fakes", "", 8, 0, 8);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 8, 0, 8);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 8, 0, 8);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 8, 0, 8);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggHTohhTo2Tau2B"  , "", 8, 0, 8);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggHTohhTo2Tau2B  ->Integral()/unscaled[4]-1.) : 0.);
/*  scales[5] = new TH1F("scales-sm","",8,0,8);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? ((ggH_SM125->Integral()+qqH_SM125->Integral()+VH_SM125->Integral())/unscaled[5]-1.) : 0.);
*/
/*
  scales[5] = new TH1F("scales-ggAToZhToLLTauTau"  , "", 8, 0, 8);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (ggAToZhToLLTauTau  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-ggAToZhToLLBB"  , "", 8, 0, 8);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggAToZhToLLBB  ->Integral()/unscaled[6]-1.) : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 8, 0, 8);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH  ->Integral()/unscaled[7]-1.) : 0.);
*/
#endif

//#ifdef MSSM
//  qqH_SM125->Add(ggH_SM125);
 // VH_SM125->Add(qqH_SM125);
 // Fakes->Add(VH_SM125);
//#endif
  Fakes->Add(ttbar);
  EWK1 ->Add(Fakes);
  EWK2 ->Add(Fakes );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
//  ttbar->Add(EWK  );
  Ztt  ->Add(EWK);

 /*ggH_SM125->Add(qqH_SM125);
 ggH_SM125->Add(VH_SM125);
 ggH_SM125->Add(ZHToBB_SM125);
 ggH_SM125->Add(WHToBB_SM125);
*/
  //if(log){
//#ifdef MSSM
 //   ggH->Add(bbH);
//#else
 //   qqH->Add(VH );
  //  ggH->Add(qqH);
//#endif
 // }
  //else{
//#ifdef MSSM    
 //   bbH->Add(Ztt);
  //  ggH->Add(bbH);
//#else
 //   VH ->Add(Ztt);
  //  qqH->Add(VH );
   // ggH->Add(qqH);
//#endif
 // }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); } else{ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggHTohhTo2Tau2B, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
//#ifdef MSSM
//    VH_SM125->Draw("histsame");
//#endif
    $DRAW_ERROR
    ggHTohhTo2Tau2B  ->Draw("histsame");
   /* ggH_SM125->SetLineColor(kRed);
    ggH_SM125->Draw("histsame");
*/
  }
  else{
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
#ifdef MSSM
    //VH_SM125->Draw("histsame");
#endif
    $DRAW_ERROR
    ggHTohhTo2Tau2B  ->Draw("histsame");
    /*ggH_SM125->SetLineColor(kRed);
    ggH_SM125->Draw("histsame");
*/
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (strcmp(category_extra2,"")!=0) chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (strcmp(category_extra2,"")!=0) chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();
/*
  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{H}=$MH GeV, tan#beta=$TANB");
  massA->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggHTohhTo2Tau2B  , TString::Format("%0.f #times H#rightarrowhh#rightarrow#tau#taubb", SIGNAL_SCALE) , "L" );
  //leg->AddEntry(ggH_SM125, TString::Format("%0.f #times SM H(125 GeV) #rightarrow #tau#tau/bb", SIGNAL_SCALE), "L");
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
/*#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
*/
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }

double chi2prob=0.;
double chi2ndof=0.;
double ksprob=0.;
double ksprobpe=0.;

if(!BLIND_DATA){
  chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  
}
  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if(edges.size()>1){
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  else if (edges[edges.size()-2]>0.2) { range = 0.5; }
  else if (edges[edges.size()-2]>0.5) { range = 1.0; }
  else if (edges[edges.size()-2]>1.0) { range = 1.5; }
  else if (edges[edges.size()-2]>1.5) { range = 2.0; }
}
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
if(!BLIND_DATA){
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
}
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
if(edges.size()>1){
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
}
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); } else{ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
  InitHist(scales[4],"","",kGreen+2,1001);
/*  InitHist(scales[5],"","",kGreen+2,1001);
  InitHist(scales[6],"","",kGreen+2,1001);
  InitHist(scales[7],"","",kGreen+2,1001);
*/

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggHTohhTo2tau2B}"  );
/*
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{ggAToZhToLLTauTau}");
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggAToZhToLLBB}");
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
*/
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
 /* scales[5]->Draw("same");
  scales[6]->Draw("same");
*/
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggHTohhTo2Tau2B  ->Write("ggHTohhTo2Tau2B"     );
/*
  ggAToZhToLLTauTau->Write("ggAToZhToLLTauTau");
  ggAToZhToLLBB->Write("ggAToZhToLLBB");
  bbH  ->Write("bbH"     );
*/
#endif
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}