Exemplo n.º 1
0
void getMCcorrectionfactors(TString func = "exp"){

  // some parameters
  bool sepLeg=true;
  bool grey=false;
  bool plotsepfit   =true;
  bool plotfiterrors=false;
  TString optD= plotsepfit ? "" : "0";
  double xmax=500;
  TString Txmax=getTStringFromDouble(xmax);

  // colors
  int color7=kRed-4;
  int color8=kBlue+2;
  int ljets7color=color7;//kRed;//kRed+1;
  int dilep7color=color7;//kOrange+7;
  int ljets8color=color8;//kBlue+2;//kBlue;
  int dilep8color=color8;//kGreen+2;//kAzure+6;
  int fit7color=color7;//kMagenta-4;
  int fit8color=color8;//kTeal+3;
  int colorband=kCyan-7;

  // ---
  //    canvas style 
  // ---
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  myStyle.SetErrorX(0.5);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  gStyle->SetEndErrorSize(10);
  gStyle->SetOptFit(0);

  // ---
  //    collect all curves
  // ---
  // 7 TeV
  int NbinsLjets7=7;
  TGraphAsymmErrors* SFljets = new TGraphAsymmErrors(NbinsLjets7);
  int NbinsDilep7=5;
  TGraphAsymmErrors* SFdilep = new TGraphAsymmErrors(NbinsDilep7);
  //int Nbins7=NbinsLjets7+NbinsDilep7;
  TGraphAsymmErrors* SF7 = new TGraphAsymmErrors(0);
  // 8 TeV
  int NbinsLjets8=8;
  TGraphAsymmErrors* SFljets8 = new TGraphAsymmErrors(NbinsLjets8);
  int NbinsDilep8=5;
  TGraphAsymmErrors* SFdilep8 = new TGraphAsymmErrors(NbinsDilep8);
  //int Nbins8=NbinsLjets8+NbinsDilep8;
  TGraphAsymmErrors* SF8 = new TGraphAsymmErrors(0);
  // combined
  //int Nbins=NbinsLjets7+NbinsDilep7+NbinsLjets8+NbinsDilep8;
  TGraphAsymmErrors* SF = new TGraphAsymmErrors(0);
  // ---
  //    top Pt data / MC ratio
  // ---
  // a) l+jets 7TeV data points
  //           bin x(BCC)    data  / Madgraph         // BCCNNLO // BCC MG
  SFljets->SetPoint( 0, 28   , 0.004536 / 0.003806 ); //28       // 26.2
  SFljets->SetPoint( 1, 85.6 , 0.006658 / 0.006574 ); //85.6     // 88.8
  SFljets->SetPoint( 2, 125  , 0.004740 / 0.004740 ); //125      // 126.2
  SFljets->SetPoint( 3, 173.6, 0.002501 / 0.002748 ); //173.6    // 173.8
  SFljets->SetPoint( 4, 227.5, 0.001042 / 0.001195 ); //227.5    // 228.8
  SFljets->SetPoint( 5, 287.3, 0.000378 / 0.000454 ); //287.3    // 288.8
  SFljets->SetPoint( 6, 355.8, 0.000120 / 0.000154 ); //355.8    // 356.2
  //                   x errors   rel.err(data) *( data  / Madgraph)
  SFljets->SetPointError( 0, 0., 0., (4.4 /100.)*(0.004536 / 0.003806), (4.4 /100.)*(0.004536 / 0.003806) );
  SFljets->SetPointError( 1, 0., 0., (5.5 /100.)*(0.006658 / 0.006574), (5.5 /100.)*(0.006658 / 0.006574) );
  SFljets->SetPointError( 2, 0., 0., (4.0 /100.)*(0.004740 / 0.004740), (4.0 /100.)*(0.004740 / 0.004740) );
  SFljets->SetPointError( 3, 0., 0., (5.8 /100.)*(0.002501 / 0.002748), (5.8 /100.)*(0.002501 / 0.002748) );
  SFljets->SetPointError( 4, 0., 0., (6.2 /100.)*(0.001042 / 0.001195), (6.2 /100.)*(0.001042 / 0.001195) );
  SFljets->SetPointError( 5, 0., 0., (9.0 /100.)*(0.000378 / 0.000454), (9.0 /100.)*(0.000378 / 0.000454) );
  SFljets->SetPointError( 6, 0., 0., (11.1/100.)*(0.000120 / 0.000154), (11.1/100.)*(0.000120 / 0.000154) );
  //style of ratio
  SFljets->SetLineWidth(3.);
  SFljets->SetMarkerSize(1.5);
  SFljets->SetMarkerStyle(26);
  SFljets->SetMarkerColor(ljets7color);
  SFljets->SetLineColor(ljets7color);

  // b) dilepton 7TeV data points
  //           bin x(BCC)    data  / Madgraph               // BCCNNLO // BCC MG
  SFdilep->SetPoint( 0, 33.7,  (0.00509572 / 0.00453114 )  );// 33.7    // 34 
  SFdilep->SetPoint( 1, 107 ,  (0.00626002 / 0.00600115 )  );// 106     // 107
  SFdilep->SetPoint( 2, 162 ,  (0.00296467 / 0.00321705 )  );// 162     // 163
  SFdilep->SetPoint( 3, 242 ,  (0.000701592/ 0.000931674)  );// 242     // 247
  SFdilep->SetPoint( 4, 343 ,  (0.00012036 / 0.000191065)  );// 343     // 350
  //                   x errors   rel.err(data) *( data  / Madgraph)
  SFdilep->SetPointError( 0, 0., 0., 0.0601381*(0.00509572 / 0.00453114 ), 0.0601381*(0.00509572 / 0.00453114 ) );
  SFdilep->SetPointError( 1, 0., 0., 0.0469906*(0.00626002 / 0.00600115 ), 0.0469906*(0.00626002 / 0.00600115 ) );
  SFdilep->SetPointError( 2, 0., 0., 0.0555114*(0.00296467 / 0.00321705 ), 0.0555114*(0.00296467 / 0.00321705 ) );
  SFdilep->SetPointError( 3, 0., 0., 0.071274* (0.000701592/ 0.000931674), 0.071274* (0.000701592/ 0.000931674) );
  SFdilep->SetPointError( 4, 0., 0., 0.0924826*(0.00012036 / 0.000191065), 0.0924826*(0.00012036 / 0.000191065) );
  //style of ratio
  SFdilep->SetLineWidth(3.);
  SFdilep->SetMarkerSize(1.5);
  SFdilep->SetMarkerStyle(22);
  SFdilep->SetMarkerColor(dilep7color);
  SFdilep->SetLineColor(dilep7color);

  // collect 8 TeV BCC x values for analysis binning
  std::vector<double> xBCCljets_;
  xBCCljets_.push_back( 28  );   //   0.0 ..  60.0
  xBCCljets_.push_back( 86  );   //  60.0 .. 100.0
  xBCCljets_.push_back(125  );   // 100.0 .. 150.0
  xBCCljets_.push_back(173  );   // 150.0 .. 200.0
  xBCCljets_.push_back(227.3);   // 200.0 .. 260.0
  xBCCljets_.push_back(288  );   // 260.0 .. 320.0
  xBCCljets_.push_back(356  );   // 320.0 .. 400.0
  xBCCljets_.push_back(444  );   // 400.0 .. 500.0
  std::vector<double> xBCCdilep_;
  xBCCdilep_.push_back( 29.7);  //   0.0 ..  65.0
  xBCCdilep_.push_back( 99.6);  //  65.0 .. 125.0
  xBCCdilep_.push_back(159.7);  // 125.0 .. 200.0
  xBCCdilep_.push_back(239.1);  // 200.0 .. 290.0
  xBCCdilep_.push_back(336.2);  // 290.0 .. 400.0

  // c) l+jets 8TeV data points
  for(int p=0; p<NbinsLjets8; ++p){
    // get line with all informations
    TString line= readLineFromFile(p+1, groupSpace+"CommonFiles/topPtInputForReweighting/diffXSecTopSemiLepPartontopPt.txt");
    // data value
    TString temp = getStringEntry(line, 3 , "&");
    temp.ReplaceAll(" ","");
    double data=atof(temp.Data());
    temp = getStringEntry(line, 2 , "&");
    temp.ReplaceAll(" ","");
    double MC  =atof(temp.Data());
    SFljets8->SetPoint( p,  xBCCljets_.at(p) , data/MC ); 
    temp = getStringEntry(line, 6 , "&");
    double unc=atof(temp.Data());
    SFljets8->SetPointError( p, 0., 0., (unc/100.)*(data/MC), (unc /100.)*(data/MC) );
  }
  whipEmptyBinsAway(SFljets8, 0);

  //style of ratio
  SFljets8->SetLineWidth(3.);
  SFljets8->SetMarkerSize(1.5);
  SFljets8->SetMarkerStyle(24);
  //SFljets8->SetLineStyle(2);
  SFljets8->SetMarkerColor(ljets8color);
  SFljets8->SetLineColor(ljets8color);

  // d) dilepton 8TeV data points
  // MC prediction point (as not in provided table)
  std::vector<double> MCdilep_;
  MCdilep_.push_back(0.00396076 ); 
  MCdilep_.push_back(0.00620269 ); 
  MCdilep_.push_back(0.00336987 ); 
  MCdilep_.push_back(0.00102834 ); 
  MCdilep_.push_back(0.000228163); 
  for(int p=0; p<NbinsDilep8; ++p){
    // get line with all informations
    TString line= readLineFromFile(p+4, groupSpace+"CommonFiles/topPtInputForReweighting/HypToppTLaTeX.txt");
    // data value
    TString temp = getStringEntry(line, 3 , "&");
    temp.ReplaceAll(" ","");
    double data=atof(temp.Data());
    //temp = getStringEntry(line, 2 , "&");
    //temp.ReplaceAll(" ","");
    double MC  =MCdilep_[p];
    SFdilep8->SetPoint( p,  xBCCdilep_.at(p) , data/MC ); 
    temp = getStringEntry(line, 6 , "&");
    double unc=atof(temp.Data());
    SFdilep8->SetPointError( p, 0., 0., (unc/100.)*(data/MC), (unc /100.)*(data/MC) );
  }

  //style of ratio
  SFdilep8->SetLineWidth(3.);
  SFdilep8->SetMarkerSize(1.5);
  SFdilep8->SetMarkerStyle(20);
  SFdilep8->SetMarkerColor(dilep8color);
  SFdilep8->SetLineColor(dilep8color);

  // e) combined 7 TeV data points
  addTAE(SFdilep , SF7);
  addTAE(SFljets , SF7);
  //style of ratio
  SF7->SetLineWidth(3.);
  SF7->SetMarkerSize(0.1);
  SF7->SetMarkerStyle(20);
  SF7->SetMarkerColor(kWhite);
  SF7->SetLineColor(kWhite);

  // f) combined 8 TeV data points
  addTAE(SFdilep8, SF8);
  addTAE(SFljets8, SF8);
  //style of ratio
  SF8->SetLineWidth(3.);
  SF8->SetMarkerSize(0.1);
  SF8->SetMarkerStyle(20);
  SF8->SetMarkerColor(kWhite);
  SF8->SetLineColor(kWhite);

  // g) combined 7+8TeV data points
  addTAE(SF7, SF);
  addTAE(SF8, SF);
  //style of ratio
  SF->SetLineWidth(3.);
  SF->SetMarkerSize(0.1);
  SF->SetMarkerStyle(20);
  SF->SetMarkerColor(kWhite);
  SF->SetLineColor(kWhite);

  // ---
  //    dummy plots for axis
  // ---
  TH1F* dummy= new TH1F("","",1,0.,xmax);
  histogramStyle(*dummy, kSig);
  dummy->GetXaxis()->SetTitle("p_{T}^{t} [GeV]");
  dummy->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{dp_{T}^{t}} Ratio: (Data / Simulation)");
  dummy->GetYaxis()->SetTitleOffset(0.9*dummy->GetYaxis()->GetTitleOffset());
  dummy->SetMaximum(sepLeg? 1.3 : 1.8);
  dummy->SetMinimum(0.5);

  // ---
  //    legends
  // ---
  double x1=sepLeg ? 0.1 : 0.29;
  double x2=sepLeg ? 0.9 : 0.86;

  TLegend *leg0 = new TLegend(x1, sepLeg ? 0.65 : 0.69, x2, sepLeg? 0.92 : 0.87);
  leg0->SetFillStyle(0);
  leg0->SetTextSize(0.035);
  leg0->SetBorderSize(0);
  leg0->SetHeader("#font[22]{Data / MadGraph+PYTHIA(CTEQ6L1)}");

  TLegend *leg1 = new TLegend(x1, sepLeg ? 0.3 : 0.57, x2, sepLeg ? 0.55 : 0.69);
  leg1->SetFillStyle(0);
  leg1->SetTextSize(0.035);
  leg1->SetBorderSize(0);
  leg1->SetHeader("#font[22]{Fit: exp(a+b#upointx)}");

  if(plotsepfit) leg1->SetY1(leg1->GetY1()-0.2);

  // canvas
  std::vector<TCanvas*> plotCanvas_;
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle("data/MC top Pt ratio");
  // drawing
  dummy->Draw("axis");
  SF->Draw("p e1 same");
  SF7->Draw("p e1 same");
  SF8->Draw("p e1 same");
  SFljets->Draw("p e1 same");
  SFdilep->Draw("p e1 same");
  SFljets8->Draw("p e1 same");
  SFdilep8->Draw("p e1 same");
  // fit polynomial or exponential function
  TString def = "";
  if(func=="pol2")def="[0]*x*x+[1]*x+[2]";
  if(func=="exp" )def="exp([0]+[1]*x)";
  double fitLowEdge=0.;
  double fitHighEdge=xmax;
  // a) to all 8 and 7 TeV points
//   TF1* function=new TF1("function",def,fitLowEdge, fitHighEdge);
//   function->SetLineColor(kMagenta+2);
//   SF->Fit(function,"R","same",fitLowEdge, fitHighEdge);
//   for(int i=0; i<function->GetNumberFreeParameters(); i++){
//     function->SetParameter(i,round(function->GetParameter(i),3));
//   }
//   TString fitEntry="#splitline{}{#splitline{}{#splitline{}{#splitline{combined fit: ";
//   fitEntry+=function->GetExpFormula("p")+",}{                          #chi^{2}/ndof=";
//   fitEntry+=getTStringFromDouble(function->GetChisquare())+"/"+getTStringFromInt(function->GetNDF())+"}}}}";
//   fitEntry.ReplaceAll("+(","");
//   fitEntry.ReplaceAll("))",")");
//   leg0->AddEntry( function, fitEntry, "L");
  // b) to all 7 TeV points
  TF1* function7=new TF1("function7",def,fitLowEdge, fitHighEdge);
  function7->SetLineColor(fit7color);
  function7->SetLineWidth(6);
  function7->SetLineStyle(2);
  SF7->Fit(function7,"R","same",fitLowEdge, fitHighEdge);
  for(int i=0; i<function7->GetNumberFreeParameters(); i++){
    function7->SetParameter(i,round(function7->GetParameter(i),3));
  }
  //TString fitEntry7="fit 7 TeV: ";
  //fitEntry7+=function7->GetExpFormula("p");
  //fitEntry7+=",  #chi^{2}/ndof=";
  //fitEntry7+=getTStringFromDouble(function7->GetChisquare())+"/"+getTStringFromInt(function7->GetNDF());
  //fitEntry7.ReplaceAll("+(","");
  //fitEntry7.ReplaceAll("))",")");
  TString fitEntry7="7 TeV: ";
  if(plotfiterrors) fitEntry7+="              ";
  fitEntry7+="a=";
  fitEntry7+=getTStringFromDouble(function7->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntry7+="#pm";
    fitEntry7+=getTStringFromDouble(function7->GetParError(0) , 3);
  }
  fitEntry7+=", b=";
  fitEntry7+=getTStringFromDouble(function7->GetParameter(1), 5);
  if(plotfiterrors){
    fitEntry7+="#pm";
    fitEntry7+=getTStringFromDouble(function7->GetParError(1) , 5);
  }

  // b1) to l+jets 7 TeV points
  TF1* functionljets7=new TF1("functionljets7",def,fitLowEdge, fitHighEdge);
  functionljets7->SetLineColor(kRed+1);
  functionljets7->SetLineWidth(2);
  SFljets->Fit(functionljets7,"R"+optD,"same",fitLowEdge, fitHighEdge);
  for(int i=0; i<functionljets7->GetNumberFreeParameters(); i++){
    functionljets7->SetParameter(i,round(functionljets7->GetParameter(i),3));
  }
  //TString fitEntryljets7="fit 7 TeV l+jets: ";
  //fitEntryljets7+=functionljets7->GetExpFormula("p");
  //fitEntryljets7+=",  #chi^{2}/ndof=";
  //fitEntryljets7+=getTStringFromDouble(functionljets7->GetChisquare())+"/"+getTStringFromInt(functionljets7->GetNDF());
  //fitEntryljets7.ReplaceAll("+(","");
  //fitEntryljets7.ReplaceAll("))",")");
  TString fitEntryljets7="7 TeV l+jets:     ";
  fitEntryljets7+="a=";
  fitEntryljets7+=getTStringFromDouble(functionljets7->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntryljets7+="#pm";
    fitEntryljets7+=getTStringFromDouble(functionljets7->GetParError(0) , 3);
  }
  fitEntryljets7+=", b=";
  fitEntryljets7+=getTStringFromDouble(functionljets7->GetParameter(1), 5);
  if(plotfiterrors){
    fitEntryljets7+="#pm";
    fitEntryljets7+=getTStringFromDouble(functionljets7->GetParError(1) , 5);
  }

  // b2) to dilepton 7 TeV points
  TF1* functiondilep7=new TF1("functiondilep7",def,fitLowEdge, fitHighEdge);
  functiondilep7->SetLineColor(kOrange+7);
  functiondilep7->SetLineWidth(2);
  SFdilep->Fit(functiondilep7,"R"+optD,"same",fitLowEdge, fitHighEdge);
  for(int i=0; i<functiondilep7->GetNumberFreeParameters(); i++){
    functiondilep7->SetParameter(i,round(functiondilep7->GetParameter(i),3));
  }
  //TString fitEntrydilep7="fit 7 TeV dilepton: ";
  //fitEntrydilep7+=functiondilep7->GetExpFormula("p");
  //fitEntrydilep7+=",  #chi^{2}/ndof=";
  //fitEntrydilep7+=getTStringFromDouble(functiondilep7->GetChisquare())+"/"+getTStringFromInt(functiondilep7->GetNDF());
  //fitEntrydilep7.ReplaceAll("+(","");
  //fitEntrydilep7.ReplaceAll("))",")");
  TString fitEntrydilep7="7 TeV dilepton: ";
  fitEntrydilep7+="a=";
  fitEntrydilep7+=getTStringFromDouble(functiondilep7->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntrydilep7+="#pm";
    fitEntrydilep7+=getTStringFromDouble(functiondilep7->GetParError(0) , 3);
  }
  fitEntrydilep7+=", b=";
  if(plotfiterrors){
    fitEntrydilep7+=getTStringFromDouble(functiondilep7->GetParameter(1), 5);
    fitEntrydilep7+="#pm";
  }
  fitEntrydilep7+=getTStringFromDouble(functiondilep7->GetParError(1) , 5);

  // c) to all 8 TeV points
  TF1* function8=new TF1("function8",def,fitLowEdge, fitHighEdge);
  function8->SetLineWidth(6);
  function8->SetLineColor(fit8color);
  function8->SetLineStyle(2);
  SF8->Fit(function8,"R","same",fitLowEdge, fitHighEdge);
  for(int i=0; i<function8->GetNumberFreeParameters(); i++){
    function8->SetParameter(i,round(function8->GetParameter(i),3));
  }
  //TString fitEntry8="fit 8 TeV: ";
  //fitEntry8+=function8->GetExpFormula("p");
  //fitEntry8+=",  #chi^{2}/ndof=";
  //fitEntry8+=getTStringFromDouble(function8->GetChisquare())+"/"+getTStringFromInt(function8->GetNDF());
  //fitEntry8.ReplaceAll("+(","");
  //fitEntry8.ReplaceAll("))",")");
  TString fitEntry8="8 TeV: ";
  if(plotfiterrors) fitEntry8+="              ";
  fitEntry8+="a=";
  fitEntry8+=getTStringFromDouble(function8->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntry8+="#pm";
    fitEntry8+=getTStringFromDouble(function8->GetParError(0) , 3);
  }
  fitEntry8+=", b=";
  fitEntry8+=getTStringFromDouble(function8->GetParameter(1), 5);
  if(plotfiterrors){
    fitEntry8+="#pm";
    fitEntry8+=getTStringFromDouble(function8->GetParError(1) , 5);
  }

  // c1) to l+jets 8 TeV points
  TF1* functionljets8=new TF1("functionljets8",def,fitLowEdge, fitHighEdge);
  functionljets8->SetLineColor(kBlue);
  functionljets8->SetLineWidth(2);
  SFljets8->Fit(functionljets8,"R"+optD,"same",fitLowEdge, fitHighEdge);
  for(int i=0; i<functionljets8->GetNumberFreeParameters(); i++){
    functionljets8->SetParameter(i,round(functionljets8->GetParameter(i),3));
  }
  //TString fitEntryljets8="fit 8 TeV l+jets: ";
  //fitEntryljets8+=functionljets8->GetExpFormula("p");
  //fitEntryljets8+=",  #chi^{2}/ndof=";
  //fitEntryljets8+=getTStringFromDouble(functionljets8->GetChisquare())+"/"+getTStringFromInt(functionljets8->GetNDF());
  //fitEntryljets8.ReplaceAll("+(","");
  //fitEntryljets8.ReplaceAll("))",")");
  TString fitEntryljets8="8 TeV l+jets:     ";
  fitEntryljets8+="a=";
  fitEntryljets8+=getTStringFromDouble(functionljets8->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntryljets8+="#pm";
    fitEntryljets8+=getTStringFromDouble(functionljets8->GetParError(0) , 3);
  }
  fitEntryljets8+=", b=";
  fitEntryljets8+=getTStringFromDouble(functionljets8->GetParameter(1), 5);
  if(plotfiterrors){
    fitEntryljets8+="#pm";
    fitEntryljets8+=getTStringFromDouble(functionljets8->GetParError(1) , 5);
  }

  // c2) to dilepton 8 TeV points
  TF1* functiondilep8=new TF1("functiondilep8",def,fitLowEdge, fitHighEdge);
  functiondilep8->SetLineColor(kAzure+6);
  functiondilep8->SetLineWidth(2);
  
  SFdilep8->Fit(functiondilep8,"R"+optD,"same",fitLowEdge, fitHighEdge);
  for(int i=0; i<functiondilep8->GetNumberFreeParameters(); i++){
    functiondilep8->SetParameter(i,round(functiondilep8->GetParameter(i),3));
  }
  //TString fitEntrydilep8="fit 8 TeV dilepton: ";
  //fitEntrydilep8+=functiondilep8->GetExpFormula("p");
  //fitEntrydilep8+=",  #chi^{2}/ndof=";
  //fitEntrydilep8+=getTStringFromDouble(functiondilep8->GetChisquare())+"/"+getTStringFromInt(functiondilep8->GetNDF());
  //fitEntrydilep8.ReplaceAll("+(","");
  //fitEntrydilep8.ReplaceAll("))",")");
  TString fitEntrydilep8="8 TeV dilepton: ";
  fitEntrydilep8+="a=";
  fitEntrydilep8+=getTStringFromDouble(functiondilep8->GetParameter(0), 3);
  if(plotfiterrors){
    fitEntrydilep8+="#pm";
    fitEntrydilep8+=getTStringFromDouble(functiondilep8->GetParError(0) , 3);
  }
  fitEntrydilep8+=", b=";
  fitEntrydilep8+=getTStringFromDouble(functiondilep8->GetParameter(1), 5);
  if(plotfiterrors){
    fitEntrydilep8+="#pm";
    fitEntrydilep8+=getTStringFromDouble(functiondilep8->GetParError(1) , 5);
  }

  // Draw legend
  leg0->AddEntry(SFljets, "7 TeV e/#mu+jets  (TOP-11-013)"   , "P");
  leg0->AddEntry(SFdilep, "7 TeV ee/e#mu/#mu#mu (TOP-11-013)", "P");
  leg0->AddEntry(SFljets8,"8 TeV e/#mu+jets  (TOP-12-028)"   , "P");
  leg0->AddEntry(SFdilep8,"8 TeV ee/e#mu/#mu#mu (TOP-12-028)", "P");
  if(!sepLeg) leg0->Draw("same");
  leg1->AddEntry( function7, fitEntry7, "L");
  if(plotsepfit) leg1->AddEntry( functiondilep7, fitEntrydilep7, "L");
  if(plotsepfit) leg1->AddEntry( functionljets7, fitEntryljets7, "L");
  leg1->AddEntry( function8, fitEntry8, "L");
  if(plotsepfit) leg1->AddEntry( functiondilep8, fitEntrydilep8, "L");
  if(plotsepfit) leg1->AddEntry( functionljets8, fitEntryljets8, "L");
  if(!sepLeg) leg1->Draw("same");
  // Draw cms label
  TPaveText *label = new TPaveText();
  label -> SetX1NDC(gStyle->GetPadLeftMargin());
  label -> SetY1NDC(1.0-gStyle->GetPadTopMargin());
  label -> SetX2NDC(1.0-gStyle->GetPadRightMargin());
  label -> SetY2NDC(1.0);
  label -> SetTextFont(42);
  TString CMSlab="";
  if(!PHD) CMSlab+="CMS Preliminary, ";  
  CMSlab+="5.0/19.7 fb^{-1} at #sqrt{s} = 7/8 TeV";
  label -> AddText(CMSlab);
  label->SetFillStyle(0);
  label->SetBorderSize(0);
  label->SetTextSize(0.04);
  label->SetTextAlign(32);
  label-> Draw("same");
  // BCC label
  double positionX=xmax+0.045*xmax*(gStyle->GetCanvasDefW()/600.);
  double positionY=0.5;
  TLatex *bcclabel = new TLatex(positionX,positionY, " (horizontal BCC wrt. NNLO^{approx}, arXiv:1205.3453)");
  bcclabel->SetTextAlign(11);
  bcclabel->SetTextAngle(90);
  bcclabel->SetTextSize(0.035);
  bcclabel->Draw("same");
  if(grey) plotCanvas_[0]->SetGrayscale();
  //saving
  plotCanvas_[0]->Print("diffXSecFromSignal/plots/combined/2012/xSec/dataVsMadgraph7and8TeV.eps");
  plotCanvas_[0]->Print("diffXSecFromSignal/plots/combined/2012/xSec/dataVsMadgraph7and8TeV.png");

  // ---
  // ERROR band plot
  // ---
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle("data/MC top Pt errorband");
  // drawing
  dummy->GetYaxis()->SetTitle("(Data / Simulation) SF (#sqrt{s}=8 TeV)");
  dummy->GetYaxis()->SetRangeUser(0.35, 1.65);
  dummy->SetFillColor(10);
  dummy->SetLineColor(10);
  dummy->Draw("axis");
  // extract parameters
  double a=function8->GetParameter(0);
  double b=function8->GetParameter(1);
  // turning point
  double min=0;
  double max=500;
  double TP=-a/b;
  // get functions for high, low and central
  TF1* centralErr=new TF1("centralErr",def,min, max);
  centralErr->SetParameter(0, a);
  centralErr->SetParameter(1, b);
  TF1* upErr=new TF1("upErr",def,min, max);
  upErr->SetParameter(0, 2*a);
  upErr->SetParameter(1, 2*b);
  TF1* dnErr=new TF1("upErr",def,min, max);
  dnErr->SetParameter(0, 0.);
  dnErr->SetParameter(1, 0.);
  // draw errorbands
  upErr->SetFillStyle(1001);
  dnErr->SetFillStyle(1001);
  upErr->SetLineColor(10);
  dnErr->SetLineColor(10);
  upErr->SetFillColor(colorband);
  upErr->SetRange(min,TP);
  upErr->DrawClone("hist same");
  dnErr->SetFillColor(10);
  dnErr->SetLineColor(10);
  dnErr->SetRange(min,TP);
  dnErr->DrawClone("hist same");
  dnErr->SetFillColor(colorband);
  dnErr->SetLineColor(colorband);
  dnErr->SetRange(TP, max);
  dnErr->DrawClone("hist same");
  upErr->SetFillColor(10);
  upErr->SetLineColor(10);
  upErr->SetRange(TP, max);
  upErr->DrawClone("hist same");
  drawLine(TP, 0.35, TP, 1.05, 10, 2, 1);
  // draw central prediction
  centralErr->SetFillStyle(0);
  centralErr->SetFillColor(0);
  centralErr->SetLineColor(kBlue);
  centralErr->SetLineWidth(6);
  centralErr->SetLineColor(fit8color);
  centralErr->SetLineStyle(2);
  centralErr->Draw("hist same");
  // legend and labels
  dummy->Draw("axis same");
  TPaveText *label2 = new TPaveText();
  label2 -> SetX1NDC(gStyle->GetPadLeftMargin());
  label2 -> SetY1NDC(1.0-gStyle->GetPadTopMargin());
  label2 -> SetX2NDC(1.0-gStyle->GetPadRightMargin());
  label2 -> SetY2NDC(1.0);
  label2 -> SetTextFont(42);
  TString CMSlab2="";
  if(!PHD) CMSlab2+="CMS Preliminary, ";  
  CMSlab2+="19.7 fb^{-1} at #sqrt{s} = 8 TeV";
  label2->AddText(CMSlab2);
  label2->SetFillStyle(0);
  label2->SetBorderSize(0);
  label2->SetTextSize(0.04);
  label2->SetTextAlign(32);  
  double x12= 0.29;
  double x22= 0.86;
  label2->Draw("same");
  TLegend *leg3 = new TLegend(x12+0.05, 0.7, x22+0.05, 0.85);
  leg3->SetFillStyle(0);
  leg3->SetTextSize(0.035);
  leg3->SetBorderSize(0);
  leg3->SetHeader("#font[22]{Parametrisation: exp(a+b#upointx)}");
  TString entryErr=fitEntry8;
  entryErr.ReplaceAll("8 TeV: ", "");
  leg3->AddEntry(centralErr, entryErr , "L");
  leg3->AddEntry(dnErr     , "a,b #pm 100%", "F");
  leg3->Draw("same");
  //saving
  if(grey) plotCanvas_[1]->SetGrayscale();
  plotCanvas_[1]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweighting8TeVunc.eps");
  plotCanvas_[1]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweighting8TeVunc.png");
  
  // ratio legend
  if(sepLeg){
    addCanvas(plotCanvas_);
    plotCanvas_[plotCanvas_.size()-1]->cd(0);
    plotCanvas_[plotCanvas_.size()-1]->SetTitle("legend");
    leg0->Draw("same");
    leg1->Draw("same");
    if(grey) plotCanvas_[2]->SetGrayscale();
    plotCanvas_[2]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweightingLegend.eps");
    plotCanvas_[2]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweightingLegend.png");
  }
}
Exemplo n.º 2
0
void treeComparison(double luminosity = 19712, bool save = true, int verbose=1, TString inputFolderName= "RecentAnalysisRun8TeV_doubleKinFit", TString dataFile= "/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/elecDiffXSecData2012ABCDAll.root:/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/muonDiffXSecData2012ABCDAll.root", const std::string decayChannel = "combined", bool withRatioPlot=true, TString test="prob")
{
  // test= "prob" or "PV" 
  // data/MC -> MC/data
  bool invert=true;
  // linear fit in ratio?
  bool linFit=true;

  // ===================================
  // Define plotting order
  // ===================================
  std::vector<int> samples_;
  samples_.push_back(kSig);
  samples_.push_back(kBkg);
  samples_.push_back(kSTop);
  samples_.push_back(kWjets);
  samples_.push_back(kZjets);
  samples_.push_back(kDiBos);
  samples_.push_back(kQCD);
  samples_.push_back(kData);

  // ============================
  //  Set Root Style
  // ============================
		
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  myStyle.SetStripDecimals(true);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  gROOT->ForceStyle();
  TGaxis::SetMaxDigits(2);

  // user specific configuration
  TString testQuantity=""; // name of separator in tree
  TString treePath=""; // path of tree
  // values for splitting topPt (Val0<=plot1<Val1<=plot2<Val2)
  std::vector< double > Val_;
  TString treeExt="";
  if(test=="PV"){
    testQuantity="nPV";
    treePath="compositedKinematicsKinFit/tree";
    Val_.push_back(0. );
    Val_.push_back(8. );
    Val_.push_back(13.);
    Val_.push_back(17.);
    Val_.push_back(22.);
    Val_.push_back(50.);
    treeExt="Fit";
  }
  if(test=="prob"){
    testQuantity="chi2";
    treePath="analyzeTopRecoKinematicsKinFit/tree";
    Val_.push_back(0. );
    Val_.push_back(1.386); // chi2<1.386 ~prob>0.50
    Val_.push_back(2.1);   // chi2<2.1 ~prob>0.35
    Val_.push_back(3.219); // chi2<3.219 ~prob>0.20
    Val_.push_back(7.824); // chi2<7.824 ~prob>0.02
    Val_.push_back(99999.);
    treeExt="";
  }
  // default configurations
  unsigned int systematicVariation=sysNo;
  TString ttbarMC="Madgraph";
  bool scaleTtbarToMeasured=true;
  // adjust luminosity and data files for combined control plots
  double luminosityEl=constLumiElec;
  double luminosityMu=constLumiMuon;
  if(!dataFile.Contains(":")){
    std::cout << "wrong input filenames, should be dataFileEl:dataFileMu, but is ";
    std::cout << dataFile << std::endl;
    exit(0);
  }
  TString dataFileEl=getStringEntry(dataFile,1 , ":");
  TString dataFileMu=getStringEntry(dataFile,42, ":");
  // file container
  std::map<unsigned int, TFile*> files_, filesMu_, filesEl_;
  // file vector storage
  std::vector< std::map<unsigned int, TFile*> > fileList_;
  // get analysis files
  TString inputFolder="/afs/naf.desy.de/group/cms/scratch/tophh/"+inputFolderName;
  if(verbose>0) std::cout << "loading files from " << inputFolder << std::endl;
  if(decayChannel!="combined"){
    TString dataFiletemp= decayChannel=="muon" ? dataFileMu : dataFileEl;
    files_ = getStdTopAnalysisFiles(inputFolder, systematicVariation, dataFiletemp, decayChannel, ttbarMC);
    fileList_.push_back(files_);
  }
  else{
    filesMu_ = getStdTopAnalysisFiles(inputFolder, systematicVariation, dataFileMu, "muon"    , ttbarMC);
    filesEl_ = getStdTopAnalysisFiles(inputFolder, systematicVariation, dataFileEl, "electron", ttbarMC);
    fileList_.push_back(filesMu_);
    fileList_.push_back(filesEl_);
  }
  // topPt histogram template
  if(verbose>0) std::cout << "creating temp histo" << std::endl;
  TH1F* temp= (TH1F*)(((TH1F*)(fileList_.at(0)[kSig]->Get("analyzeTopRecoKinematicsKinFit/topPt"))->Clone()));
  temp->Rebin(20);
  temp->Reset("icms");
  temp->SetTitle("");
  temp->GetXaxis()->SetTitle("p_{T}^{t} #left[GeV#right]");
  temp->GetYaxis()->SetTitle("Top quarks");
  //axesStyle(*temp, "p_{T}^{t} #left[GeV#right]", "norm. Top quarks", 0., 0.15);
  temp->GetXaxis()->SetRangeUser(0.,500.);
  //temp->GetYaxis()->SetRangeUser(0.,0.2 );
  temp->SetStats(kFALSE);
  temp->SetLineWidth(3);
  temp->SetMarkerSize(1.25);
  int binMax=temp->GetNbinsX()+1;
  // container for all histos
  std::map< TString, std::map <unsigned int, TH1F*> > histo_;
  
  // determine number of channels
  unsigned int nchannels = decayChannel=="combined" ? 2 : 1;
  
  // loop decay channels
  if(verbose>0) std::cout << "looping channels" << std::endl;
  for(unsigned int channel=0; channel<nchannels; ++channel){
    std::map<unsigned int, TFile*> tempfiles_=fileList_.at(channel);
    std::string tempChannel= decayChannel!="combined" ? decayChannel : (channel==0 ? "muon" : "electron");
    if(verbose>1) std::cout << " - " << tempChannel << std::endl;
    TString channelExt=getTStringFromInt(channel);
    // loop samples
    for(unsigned int sample=kSig; sample<=kSAToptW; ++sample){
      bool note=false;
      // check if sample is relevant
      if(isValidsample(sample, systematicVariation)){
	if(verbose>1){
	  std::cout << "  -> processing " << sampleLabel(sample, tempChannel);
	  std::cout << " (file " << tempfiles_[sample]->GetName() << ")" << std::endl;
	}
	// calculate luminosity event weight
	double lumi=decayChannel!="combined" ? luminosity : (channel==0 ? luminosityMu : luminosityEl);
	double lumiwgt=lumiweight(sample, lumi, systematicVariation, tempChannel);
	if(verbose>1) std::cout << "     (lumiweight=" << lumiwgt << ")" << std::endl;
	// get trees
	TTree* tree = (TTree*)(tempfiles_[sample]->Get(treePath));
	if(!tree){
	  std::cout << "     !ERROR: tree not found!" << std::endl;
	  exit(0);
	}
	else if(verbose>1)  std::cout << "     (tree found, contains " << tree->GetEntries() << " entries)" << std::endl;
	// container for values read from tree
	std::map< TString, float > value_;
	// initialize map entries with 0 
	value_["weight"  ]=1.;
	value_["testQuantity"    ]=0.;
	value_["topPtLep"]=0.;
	value_["topPtHad"]=0.;
	// initialize branches
	tree->SetBranchStatus ("*", 0);
	tree->SetBranchStatus ("weight"  , 1);
	tree->SetBranchStatus ("topPtLep"+treeExt, 1);
	tree->SetBranchStatus ("topPtHad"+treeExt, 1);
	tree->SetBranchStatus (testQuantity     , 1);
	tree->SetBranchAddress(testQuantity     ,(&value_["testQuantity"    ]));
	tree->SetBranchAddress("weight"  ,(&value_["weight"  ]));
	tree->SetBranchAddress("topPtLep"+treeExt,(&value_["topPtLep"]));
	tree->SetBranchAddress("topPtHad"+treeExt,(&value_["topPtHad"]));
	// initialize result plots
	histo_["topPt"+channelExt     ][sample]=(TH1F*)(temp->Clone());
	for(int plot=1; plot<(int)Val_.size(); ++plot){
	  histo_["topPtProb"+getTStringFromInt(plot)+channelExt][sample]=(TH1F*)(temp->Clone());
	}
	if(verbose>1) std::cout << "     -> looping tree" << std::endl;
	// loop all events to fill plots
	for(unsigned int event=0; event<tree->GetEntries(); ++event){
	  // get event
	  tree->GetEntry(event);
	  // check if values are reasonable
	  if(!((value_["weight"]>0&&value_["weight"]<10)||(test!="PV"&&value_["weight"]==0.))){ 
	    if(!note){ std::cout << "!!! WARNING - some weights are strange (e.g." << value_["weight"] << ") !!!"<< std::endl; note=true; }
	    value_["weight"]=1.0;
	  }
	  // get relevant quantities
	  double weight=value_["weight"]*lumiwgt;
	  double filterQuantity  =value_["testQuantity"  ];
	  double topPtLep=value_["topPtLep"];
	  double topPtHad=value_["topPtHad"];
	  if(verbose>2){
	    std::cout << "      event #" << event+1 << "/" << tree->GetEntries() << ":" << std::endl;
	    std::cout << "      weight=" << weight << ", " << "testQuantity" << "=" << filterQuantity << ", topPtLep=" << topPtLep << ", topPtHad=" << topPtHad << std::endl;
	  }
	  // fill histo for all
	  histo_["topPt"+channelExt][sample]->Fill(topPtLep, weight);
	  histo_["topPt"+channelExt][sample]->Fill(topPtHad, weight);
	  // fill histo for different ranges of the filterQuantity
	  for(int plot=1; plot<(int)Val_.size(); ++plot){
	    TString nameNr=getTStringFromInt(plot);
	    if(filterQuantity>=Val_[plot-1]&&filterQuantity<Val_[plot]){
	      histo_["topPtProb"+nameNr+channelExt][sample]->Fill(topPtLep, weight);
	      histo_["topPtProb"+nameNr+channelExt][sample]->Fill(topPtHad, weight);
	    }
	  } // end for loop separation values
	} // end for loop tree events
      } // end if is valid sample
    } // end for loop samples
  } // end for loop decay channels

  // create final plots
  // -> combine decay channels and MC samples
  unsigned int kAllMC=42;
  // loop samples
  if(verbose>0) std::cout << "combining decay channels and MC samples" << std::endl;
  for(unsigned int sample=kSig; sample<=kSAToptW; ++sample){
    // check if sample is relevant
    if(isValidsample(sample, systematicVariation)){
      // loop decay channels
      for(unsigned int channel=0; channel<nchannels; ++channel){
	std::string tempChannel= decayChannel!="combined" ? decayChannel : (channel==0 ? "muon" : "electron");
	if(verbose>1) std::cout << " -> processing " << sampleLabel(sample, tempChannel) << "(" << tempChannel << ")" << std::endl;
	TString channelExt=getTStringFromInt(channel);
	// get plots for current channels
	std::vector <TH1F*> tempHist_;
        tempHist_.push_back((TH1F*)histo_["topPt"+channelExt     ][sample]->Clone());
	for(int plot=1; plot<(int)Val_.size(); ++plot){
	  TString nameNr=getTStringFromInt(plot);
	  tempHist_.push_back((TH1F*)histo_["topPtProb"+nameNr+channelExt][sample]->Clone());
	}
	std::vector <int> nevents_;
        for(int plot=0; plot<(int)Val_.size(); ++plot){
	  nevents_.push_back(tempHist_[plot]->Integral(0,binMax));
	}
	// add all channels for final histogram
	if(channel==0){
	  for(int plot=0; plot<(int)Val_.size(); ++plot){
	    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	    histo_["topPt"+nameNr][sample]=(TH1F*)tempHist_[plot]->Clone();
	  }
	}
	else{
          for(int plot=0; plot<(int)Val_.size(); ++plot){
            TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	    histo_["topPt"+nameNr][sample]->Add((TH1F*)tempHist_[plot]->Clone());
	  }
	}
	if(verbose>2){
	  std::cout << "    (#events(" << tempChannel << ")=";
	  for(int plot=0; plot<(int)Val_.size(); ++plot){
	    std::cout <<  nevents_[plot];
	    if(plot<(int)Val_.size()-1) std::cout << " / ";
	  }
	  std::cout << ")" << std::endl;
	}
      } // end channel for loop
      std::vector <double> neventsComb_;
      for(int plot=0; plot<(int)Val_.size(); ++plot){
	TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	neventsComb_.push_back(histo_["topPt"+nameNr][sample]->Integral(0,binMax));
      }
      if(verbose>1){
	std::cout << "    (#events=";
	for(int plot=0; plot<(int)Val_.size(); ++plot){
	  std::cout <<  neventsComb_[plot];
	  if(plot<(int)Val_.size()-1) std::cout << " / ";
	}
	std::cout << ")" << std::endl;
      }
      // combine all MC samples
      if(sample!=kData){
	if(sample==kSig){
	  for(int plot=0; plot<(int)Val_.size(); ++plot){
	    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	    histo_["topPt"+nameNr][kAllMC]=(TH1F*)histo_["topPt"+nameNr][sample]->Clone();
	  }
	}
	else{
	  for(int plot=0; plot<(int)Val_.size(); ++plot){
            TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	    histo_["topPt"+nameNr][kAllMC]->Add((TH1F*)histo_["topPt"+nameNr][sample]->Clone());
	  }
	}
	// MC histogram style
	for(int plot=0; plot<(int)Val_.size(); ++plot){
	  TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	  histogramStyle(*histo_["topPt"+nameNr][sample], sample, true);
	  //histo_["topPt"+nameNr][sample]->SetLineColor(histo_["topPt"+nameNr][sample]->GetFillColor());
	  histo_["topPt"+nameNr][sample]->SetLineWidth(1);
	}
      }
      else{
	// data histogram style
        for(int plot=0; plot<(int)Val_.size(); ++plot){
          TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	  histogramStyle(*histo_["topPt"+nameNr][sample], kData, false);
	}
      }
    } // end if sample is valid
  } // end sample for loop

  // print some interesting numbers
  // chosen slices
  std::vector< double >neventsMC_;
  if(verbose>0){
    std::cout << "slices in " << testQuantity << ":  all / ";
    for(int plot=1; plot<(int)Val_.size(); ++plot){
      std::cout <<  "[" << Val_[plot-1] << ".." << Val_[plot] << "]";
      if(plot<(int)Val_.size()-1) std::cout << "/ ";
    }
    std::cout << std::endl;
  }
  // total number of MC events
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    neventsMC_.push_back(histo_["topPt"+nameNr][kAllMC]->Integral(0,binMax));
  }
  if(verbose>0){
    std::cout << "#events( MC )=";
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      std::cout <<  neventsMC_[plot];
      if(plot<(int)Val_.size()-1) std::cout << ", ";
    }
    std::cout << std::endl;
  }
  // total number of data events
  std::vector< double >neventsData_;
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    neventsData_.push_back(histo_["topPt"+nameNr][kData]->Integral(0,binMax));
  }
  if(verbose>0){
    std::cout << "#events(Data)=";
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      std::cout <<  neventsData_[plot];
      if(plot<(int)Val_.size()-1) std::cout << " / ";
    }
    std::cout << std::endl;
  }
  // data over MC ratio
  if(verbose>0){
    std::cout << "(data/MC ratio=";
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      std::cout <<  neventsData_[plot]/neventsMC_[plot];
      if(plot<(int)Val_.size()-1) std::cout << " / ";
    }
    std::cout << ")" << std::endl;
  }

  // scale ttbar to match total number of events
  if(scaleTtbarToMeasured){
    if(verbose>0) std::cout << "scale ttbar component to match #data events " << std::endl;
    std::vector<double>neventsTop_, SFTop_;
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
      neventsTop_.push_back(histo_["topPt"+nameNr][kSig]->Integral(0,binMax)+histo_["topPt"+nameNr][kBkg]->Integral(0,binMax));
      SFTop_.push_back((neventsTop_[plot]+(neventsData_[plot]-neventsMC_[plot]))/neventsTop_[plot]);
    }
    // scale combined and top MC plots
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
      // subtract ttbar from all MC
      histo_["topPt"+nameNr][kAllMC]->Add((TH1F*)(histo_["topPt"+nameNr][kSig]->Clone()) , -1.);
      histo_["topPt"+nameNr][kAllMC]->Add((TH1F*)(histo_["topPt"+nameNr][kBkg]->Clone()) , -1.);
      // scale ttbar 
      histo_["topPt"+nameNr][kSig]->Scale(SFTop_[plot]);
      histo_["topPt"+nameNr][kBkg]->Scale(SFTop_[plot]);
      // re-add ttbar MC
      histo_["topPt"+nameNr][kAllMC]->Add((TH1F*)(histo_["topPt"+nameNr][kSig]->Clone()) );
      histo_["topPt"+nameNr][kAllMC]->Add((TH1F*)(histo_["topPt"+nameNr][kBkg]->Clone()) );
    }
    // printout
    std::vector<double>neventsMCscaled_;
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
      neventsMCscaled_.push_back(histo_["topPt"+nameNr][kAllMC]->Integral(0,binMax));
    }
    if(verbose>1){
      std::cout << "#events(scaledMC)=";
      for(int plot=0; plot<(int)Val_.size(); ++plot){
	std::cout << neventsMCscaled_[plot];
        if(plot<(int)Val_.size()-1) std::cout << " / ";
      }
      std::cout << std::endl;
      std::cout << "(data/scaledMC ratio=";
      for(int plot=0; plot<(int)Val_.size(); ++plot){
	std::cout <<  neventsData_[plot]/neventsMCscaled_[plot];
	if(plot<(int)Val_.size()-1) std::cout << " / ";
      }
      std::cout << ")" << std::endl;
    }
  };

  // combine single top subsamples
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    histo_["topPt"+nameNr][kSTop]=(TH1F*)histo_["topPt"+nameNr][kSAToptW]->Clone();
    for(int sample=(int)kSTops; sample<(int)kSAToptW; ++sample){
      // add to combined STop
      histo_["topPt"+nameNr][kSTop]->Add((TH1F*)histo_["topPt"+nameNr][sample]->Clone());
    } // end for loop single top subsamples
  } // end for loop plots

  // create MC histo stack plots
  int lastSample=-1;
  // loop samples
  if(verbose>0) std::cout << "creating MC stack histos" << std::endl;
  for(int sampleOri=(int)kDiBos; sampleOri>=(int)kSig; --sampleOri){
    // use previous defined order
    int sampleMod=samples_[sampleOri];
    if(verbose>1) std::cout << "processing " << sampleLabel(sampleMod, decayChannel) << "(= " << sampleMod <<", last sample=" << lastSample << ")" << std::endl;
    // exclude QCD and Diboson
    if(sampleMod!=kQCD&&sampleMod!=kDiBos){
      if(lastSample>-1){
	if(verbose>1) std::cout << "adding " << sampleLabel(lastSample, decayChannel) << " to " << sampleLabel(sampleMod, decayChannel) << std::endl;	 	
	// loop plots
	for(int plot=0; plot<(int)Val_.size(); ++plot){
	  TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
	  if(verbose>1) std::cout << "processing " << "topPt"+nameNr << std::endl;
	  // add to stack
	  if(!histo_.count("topPt"+nameNr)>0) std::cout << "WARNING: topPt"+nameNr+" does not exist in histo_!" << std::endl;
	  else if(!histo_["topPt"+nameNr].count(sampleMod )>0) std::cout << "WARNING: sample " << sampleMod << " does not exist in histo_[topPt"+nameNr+"]!" << std::endl;
	  else if(!histo_["topPt"+nameNr].count(lastSample)>0) std::cout << "WARNING: sample " << lastSample << " does not exist in histo_[topPt"+nameNr+"]!" << std::endl;
	  histo_["topPt"+nameNr][sampleMod]->Add((TH1F*)histo_["topPt"+nameNr][lastSample]->Clone());
	} // end for loop plots
	if(verbose>1) std::cout << "done" <<  std::endl;
      } // if not last sample
      if(verbose>1) std::cout << "lastSample set to " << sampleMod << std::endl;
      lastSample=sampleMod;
    } // end else if !QCD
  } // end for loop original sample ordering

  // printout
  std::vector<double>neventsMCstack_;
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    neventsMCstack_.push_back(histo_["topPt"+nameNr][kAllMC]->Integral(0,binMax));
  }
  if(verbose>1){
    std::cout << "#events(stack MC) =";
    for(int plot=0; plot<(int)Val_.size(); ++plot){
      std::cout << neventsMCstack_[plot];
      if(plot<(int)Val_.size()-1) std::cout << " / ";
    }
    std::cout << std::endl;
  }

  // all MC histogram style
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    histo_["topPt"+nameNr][kAllMC]->SetLineColor(kBlue);
    histo_["topPt"+nameNr][kAllMC]->SetMarkerColor(kBlue);
    histo_["topPt"+nameNr][kAllMC]->SetLineStyle(1);
  }
  
  std::vector<double> zeroerr_;
  for(int bin=0; bin<histo_["topPt"][kAllMC]->GetNbinsX(); ++bin) zeroerr_.push_back(0);

  // normalization
  // -> not done at the moment, scaled wrt Ndata for each plot separately

  //  Create canvas
  if(verbose>0)  std::cout << "creating canvas" << std::endl;
  std::vector<TCanvas*> plotCanvas_;
  for(unsigned int sample=0; sample<Val_.size(); sample++){
    addCanvas(plotCanvas_);
  }

  // create legends
  if(verbose>0)  std::cout << "creating legend" << std::endl;
  std::vector< TLegend* > leg_;
  TLegend *leg= new TLegend(0.73, 0.5, 0.91, 0.88);
  legendStyle(*leg,"");
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr   = plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);    
    TString sVallow  = plot==0 ? "" : getTStringFromDouble(Val_[plot-1], getRelevantDigits(Val_[plot-1]));
    TString sValhigh = plot==0 ? "" : getTStringFromDouble(Val_[plot  ], getRelevantDigits(Val_[plot ]));
    TString legHeader= plot==0 ? "KinFit, all" : sVallow+"#leq"+testQuantity+"<"+sValhigh;
    TLegend *templeg=(TLegend*)leg->Clone(); 
    templeg ->SetHeader(legHeader);
    templeg ->AddEntry(histo_["topPt"+nameNr][kData ], "data"   , "P");
    //templeg ->AddEntry(histo_["topPt"+nameNr][kAllMC], "all MC" , "L" );
    for(unsigned int sample=kSig; sample<kData; sample++){
      unsigned int sampleMod=samples_[sample];
      if(sampleMod!=kQCD&&sampleMod!=kDiBos) templeg ->AddEntry(histo_["topPt"+nameNr][sampleMod], sampleLabel(sampleMod, decayChannel), "F" );
    }
    leg_.push_back((TLegend*)(templeg->Clone()));
  }

  int canvasNumber=0;
  // do the plotting 
  if(verbose>0)  std::cout << "plotting " << std::endl;
  for(int plot=0; plot<(int)Val_.size(); ++plot){
    TString nameNr= plot==0 ? "" : "TestSlice"+getTStringFromInt(plot);
    TString title = plot==0 ? "topPtKinFit"+TString(decayChannel) : "topPt"+testQuantity+getTStringFromInt(plot)+TString(decayChannel);
    plotCanvas_[canvasNumber]->cd(0);
    plotCanvas_[canvasNumber]->SetTitle(title);
    // drawing
    // plots
    histo_["topPt"+nameNr][kSig]->SetMaximum(1.3*histo_["topPt"+nameNr][kData]->GetMaximum());
    histo_["topPt"+nameNr][kSig]->GetXaxis()->SetNoExponent(true);
    histo_["topPt"+nameNr][kSig]->GetYaxis()->SetNoExponent(true);
    histo_["topPt"+nameNr][kSig]->Draw("axis");
    // loop samples
    for(int sampleOri=(int)kSig; sampleOri<=(int)kDiBos; ++sampleOri){
      // use previous defined order
      int sampleMod=samples_[sampleOri];
      if(verbose>2) std::cout << "processing sample " << sampleMod << " ("+sampleLabel(sampleMod, decayChannel)+")" << std::endl; 
      // draw other MC samples, excluding QCD 
      if(sampleMod!=kQCD&&sampleMod!=kDiBos){
	if(verbose>2) std::cout << "-> drawing!" << sampleMod << std::endl;
	histo_["topPt"+nameNr][sampleMod]->Draw("hist same");	
      }
    } // end for loop ori samples
    //histo_["topPt"+nameNr][kAllMC]->Draw("hist same");
    histo_["topPt"+nameNr][kData ]->Draw("ep same");
    // legend
    leg_[plot]->Draw("same");
    // add labels for decay channel, luminosity, energy and CMS preliminary (if applicable)
    if      (decayChannel=="muon"    ) DrawDecayChLabel("#mu + Jets");
    else if (decayChannel=="electron") DrawDecayChLabel("e + Jets");
    else                               DrawDecayChLabel("e/#mu + Jets Combined");  
    DrawCMSLabels(true,luminosity);
    // draw ratio
    if(withRatioPlot){
      // labels of ratio
      TString ratioLabelNominator  ="N_{MC}";
      TString ratioLabelDenominator="N_{Data}";
      double ratMin= invert ? 0.75 : 0.30;
      double ratMax= invert ? 1.75 : 1.29;
      std::vector<double> err_;
      for(int bin=1; bin<histo_["topPt"+nameNr][kSig]->GetNbinsX(); ++bin){
	double ratio = histo_["topPt"+nameNr][kData]->GetBinContent(bin)/histo_["topPt"+nameNr][kSig]->GetBinContent(bin);
	if(invert) ratio=1./ratio;
	double val=ratio*(histo_["topPt"+nameNr][kData]->GetBinError(bin)/histo_["topPt"+nameNr][kData]->GetBinContent(bin));    
	if(val<0||val>histo_["topPt"+nameNr][kData]->GetBinContent(bin)) val=1.;
	err_.push_back(val);
      }      
      int rval1 = drawRatio(histo_["topPt"+nameNr][kData], histo_["topPt"+nameNr][kSig], ratMin, ratMax, myStyle, verbose, err_, ratioLabelNominator, ratioLabelDenominator, "p e", kBlack, true, 0.5, 505, invert, true, linFit);
      if (rval1!=0) std::cout << " Problem occured when creating ratio plot for " << nameNr << std::endl;
    }
    canvasNumber++;
  }
  
  // saving
  if(verbose>0) std::cout << "saving" << std::endl;
  if(save){
    TString outfolder="./diffXSecFromSignal/plots/combined/2012/topPtTest/";
    // eps and png
    if(verbose==0) gErrorIgnoreLevel=kWarning;
    saveCanvas(plotCanvas_, outfolder, "topPtTest"+testQuantity+TString(decayChannel), true, true, true);
  }
}
Exemplo n.º 3
0
void createPseudoDataFunc(double luminosity, const std::string decayChannel, TString specifier){
  // specifier="NoDistort" for closure test; "topPtUp", "topPtDown", "ttbarMassUp", "ttbarMassDown" or "data" for shape distortions; "1000" for Zprime
  // "verbose": set detail level of output ( 0: no output, 1: std output 2: output for debugging )
  int verbose=0;
  // "smear": say if you want to do a poisson smearing for each bin or just a combination for the different samples 
  bool smear=false;
  // "dataFile": absolute path of data file, used to define plots of interest
  TString dataFile= "";
  if(decayChannel.compare("electron")==0) dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/elecDiffXSecData2012ABCDAll.root";
  else                                    dataFile="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/muonDiffXSecData2012ABCDAll.root";
  // "useReweightedTop": use parton level reweighted ttbar signal file in pseudo data?
  bool useReweightedTop = (specifier.Contains("NoDistort")) ? false : true;
  // "zprime": include additional Zprime in pseudo data?
  bool zprime=specifier.Contains("1000") ? true : false;
  // naming for outputfile, constructed within macro
  TString outNameExtension="";

  // check input parameter validity
  // type of closure test
  if(!(specifier.Contains("NoDistort")||specifier.Contains("1000")||specifier.Contains("data")||specifier.Contains("topPtUp")||specifier.Contains("topPtDown")||specifier.Contains("ttbarMassUp")||specifier.Contains("ttbarMassDown")||specifier.Contains("topMass161p5")||specifier.Contains("topMass163p5")||specifier.Contains("topMass166p5")||specifier.Contains("topMass169p5")||specifier.Contains("topMass175p5")||specifier.Contains("topMass178p5")||specifier.Contains("topMass181p5")||specifier.Contains("topMass184p5"))){
    std::cout << "ERROR: invalid input specifier=" << specifier << std::endl;
    std::cout << "supported are: specifier=NoDistort,1000,data,topPtUp,topPtDown,ttbarMassUp,ttbarMassDown,topMass161p5,topMass163p5,topMass166p5,topMass169p5,topMass175p5,topMass178p5,topMass181p5,topMass184p5" << std::endl;
    exit(0);
  }
  // decay channel
  if(!(decayChannel.compare("electron")==0||decayChannel.compare("muon")==0)){
    std::cout << "ERROR: invalid input decayChannel=" << decayChannel << std::endl;
    std::cout << "supported are: decayChannel=muon,electron" << std::endl;
    exit(0);
  }
  

  //  ---
  //     create container for histos and files
  //  ---
  std::map<unsigned int, TFile*> files_;
  std::map< TString, std::map <unsigned int, TH1F*> > histo_;
  std::map< TString, std::map <unsigned int, TH2F*> > histo2_;

  //  ---
  //     parton level reweighted top distribution
  //  ---
  // a) name and path of rootfile
  // path
  TString nameTtbarReweighted="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/";
  // subfolder for reweighting systematics
  if(specifier!="NoDistort"&&!specifier.Contains("p5")){
    nameTtbarReweighted+="ttbarReweight/";
    // SG reweighting test
    if(decayChannel.compare("electron")==0) nameTtbarReweighted+="elecDiffXSec";
    else                                    nameTtbarReweighted+="muonDiffXSec";
    nameTtbarReweighted+="SigSysDistort"+specifier+"Summer12PF.root";
  }
  else{
    // SG sample for corresponding top mass
    int sys=sysNo; // == "NoDistort"
    if(     specifier=="topMass161p5") sys=sysTopMassDown4;
    else if(specifier=="topMass163p5") sys=sysTopMassDown3;
    else if(specifier=="topMass166p5") sys=sysTopMassDown2;
    else if(specifier=="topMass169p5") sys=sysTopMassDown;
    else if(specifier=="topMass175p5") sys=sysTopMassUp;
    else if(specifier=="topMass178p5") sys=sysTopMassUp2;
    else if(specifier=="topMass181p5") sys=sysTopMassUp3;
    else if(specifier=="topMass184p5") sys=sysTopMassUp4;
    nameTtbarReweighted+=TopFilename(kSig, sys, decayChannel);
  }
  // BG
  TString nameTtbarBGReweighted=nameTtbarReweighted;
  nameTtbarBGReweighted.ReplaceAll("Sig","Bkg");
  if(useReweightedTop&&!specifier.Contains("p5")) outNameExtension+="Reweighted"+specifier;
  // b) get average weight for reweighted samples
  double avWeight=1;
  if(useReweightedTop && specifier!="NoDistort"&& !specifier.Contains("p5")){
    TFile* ttbarRewfile = new (TFile)(nameTtbarReweighted);
    TString weightPlot="eventWeightDileptonModelVariation/modelWeightSum";
    histo_["avWeight"][kSig] = (TH1F*)(ttbarRewfile->Get(weightPlot)->Clone());
    avWeight=histo_ ["avWeight"][kSig]->GetBinContent(2)/histo_ ["avWeight"][kSig]->GetBinContent(1);
    histo_["avWeight"].erase(kSig);
    TFile* sigfile = new (TFile)("/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel));
    TString partonPlot="analyzeTopPartonLevelKinematics/ttbarMass";
    gROOT->cd();
    histo_["parton"   ][kSig] = (TH1F*)(sigfile     ->Get(partonPlot)->Clone());
    histo_["partonRew"][kSig] = (TH1F*)(ttbarRewfile->Get(partonPlot)->Clone());
    double avWeight2  = histo_["partonRew"][kSig]->Integral(0, histo_["partonRew"][kSig]->GetNbinsX()+1);
    avWeight2        /= histo_["parton"   ][kSig]->Integral(0, histo_["parton"   ][kSig]->GetNbinsX()+1);
    if(verbose>1){
      std::cout << "ratio unweighted/weighted" << std::endl;
      std::cout << avWeight  << " (from " << weightPlot << ")" << std::endl;
      std::cout << avWeight2 << TString(" (from entries in ")+partonPlot+" wrt /afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/"+TopFilename(kSig, sysNo, decayChannel)+"): " << std::endl;
    }
  }

  //  ---
  //     Z prime 
  //  ---
  // xSec scaling (default value chosen for M1000W100: 5pb)
  double xSecSF=1.0;
  // path & naming
  TString zprimeMass =specifier;
  TString zprimeWidth=specifier;
  zprimeWidth.ReplaceAll("1000", "100");
  TString nameZprime="/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/zprime/";
  if(decayChannel.compare("electron")==0) nameZprime+="elec";
  else                                    nameZprime+="muon";
  nameZprime+="DiffXSecZprimeM"+zprimeMass+"W"+zprimeWidth+"Summer12PF.root";
  // event weight wrt luminosity
  double zPrimeLumiWeight=1.;
  if     (zprimeMass=="1000") zPrimeLumiWeight=(xSecSF*5*luminosity)/104043;
  // naming of oututfile 
  TString xSecSFstr="";
  if      (xSecSF==0.5 ) xSecSFstr="x0p5";
  else if (xSecSF==0.25) xSecSFstr="x0p25";
  else if (xSecSF==0.1 ) xSecSFstr="x0p1";
  else if (xSecSF==0.03) xSecSFstr="x0p03";
  else if (xSecSF>1.   ) xSecSFstr="x"+getTStringFromDouble(xSecSF,0);
  if(zprime) outNameExtension="andM"+zprimeMass+"W"+zprimeWidth+xSecSFstr+"Zprime";
  // sample iteration limit
  int kLast  =kSAToptW;
  int kZprime=kLast+1;
  if(zprime) kLast=kZprime;

  if(zprime&&zPrimeLumiWeight==1){
    std::cout << "ERROR: chosen zprime weight is exactly 1!" << std::endl;
    exit(0);
  }
  
  // -------------------------
  // !!! choose luminosity !!!
  // -------------------------
  TString lum = getTStringFromInt(roundToInt(luminosity));
  // -----------------------------------------
  // !!! add all contributing samples here !!!
  // -----------------------------------------
  TString inputFolder = "/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV_doubleKinFit/";
  // save all default top analysis samples in files_
  files_ = getStdTopAnalysisFiles(inputFolder, sysNo, dataFile, decayChannel);
  // remove combined file dor single Top & DiBoson
  if(files_.count(kSTop )>0)files_.erase(kSTop );
  if(files_.count(kDiBos)>0)files_.erase(kDiBos);
  // remove combined QCD file for electron channel
  if(decayChannel.compare("electron")==0&&files_.count(kQCD)>0) files_.erase(kQCD);
  // remove all QCD files to be consistent with later treatment
  if(files_.count(kQCD)>0) files_.erase(kQCD);
  if(decayChannel.compare("electron")==0){
    for(int sample = kQCDEM1; sample<=kQCDBCE3; sample++){
      if(files_.count(sample)>0) files_.erase(sample);
    }
  }
  // add zprime
  if(zprime) files_[kZprime]=new (TFile)(nameZprime);
  // exchange default ttbar files with the reweighted ones
  if(useReweightedTop){ 
    files_[kSig]=new (TFile)(nameTtbarReweighted  );
    files_[kBkg]=new (TFile)(nameTtbarBGReweighted);
  }

  //  -----------------------------------------
  //     get list of all plots to be considered
  //  -----------------------------------------
  std::vector<TString> plotList_;
  TString currentFolder ="";
  TString currentPlot   ="";
  if(verbose>0) std::cout << std::endl << "searching for all plots in file " << files_[kData]->GetName() << std::endl;
  // go to data file for getting plot names
  files_[kData]->cd();
  // loop objects in file
  TIter fileIterator(gDirectory->GetListOfKeys());
  if(verbose>2){
    std::cout << "looping objects in in ";
    gDirectory->pwd();
  }
  TKey *fileKey;
  int count=0;
  while( (fileKey = (TKey*)fileIterator()) ){
    ++count;
    if(verbose>2) std::cout << "folderObject #" << count;
    TObject *fileObject = fileKey->ReadObj(); 
    // check if object is a directory
    if(!(fileObject->InheritsFrom("TDirectory"))&&(verbose>2)) std::cout << " is no directory" << count << std::endl;
    if(fileObject->InheritsFrom("TDirectory")){
      currentFolder = (TString)fileObject->GetName();
      if(verbose>2) std::cout << " ("+currentFolder+")" << std::endl;
      // go to directory
      ((TDirectory*)fileObject)->cd();
      if(verbose>2){
	std::cout << "looping objects in in ";
	gDirectory->pwd();
      }
      TIter folderIterator(gDirectory->GetListOfKeys());
      TKey *folderKey;
      int count2=0;
      while( (folderKey = (TKey*)folderIterator()) ) {
	++count2;
	TObject *folderObject = folderKey->ReadObj(); 
	currentPlot = (TString)folderObject->GetName();
	if(verbose>2) std::cout << "plotObject #" << count2 << " ("+currentPlot+")" << std::endl;
	// check if object is a TH1 
	if(folderObject->InheritsFrom("TH1")){
	  if(verbose>2) std::cout << "inherits from TH1";
	  // check if TH2 and neglect because a simple 
	  // re-smearing is here not possible
	  if((folderObject->InheritsFrom("TH2"))&&(verbose>2)) std::cout << " and from TH2" << std::endl;
	  else{
	    if(verbose>2) std::cout << " and NOT from TH2" << std::endl;
	    // add to list of plots
	    if(verbose>2) std::cout << "will be added to list of output plots" << std::endl;
	    plotList_.push_back(currentFolder+"/"+currentPlot);
	  }
	}
      }
    }
  }
  // close data file after getting plot names
  files_[kData]->Close();
  // remove data file from list of considered files
  if(files_.count(kData )>0)files_.erase(kData );
  // print list of files considered
  if(verbose>0){
    std::cout << std::endl << "the following files will be considered: " << std::endl;
    // loop files
    for(int sample = kSig; sample<=kLast; sample++){
      // check existence of folder in all existing files
      if(files_.count(sample)>0){
	std::cout << files_[sample]->GetName() << std::endl;
      }
    }
  }
  // print out the name of all plots
  if(verbose>0){
    std::cout << std::endl << "list of all plots to be considered: " << std::endl;
    // loop list of plots
    for(unsigned int plot=0; plot<plotList_.size(); ++plot){
      std::cout << "\"" << plotList_[plot] << "\"" << std::endl;
    }
    std::cout << plotList_.size() << " plots in total" << std::endl;
  }
  // ---------------------------------------
  // !!! load all hists !!!
  // ---------------------------------------
  unsigned int N1Dplots=plotList_.size();
  int Nplots=0;
  if(verbose>0) std::cout << std::endl << "loading plots: " << std::endl;
  // a) for std analysis file (& reweighted ttbar)
  getAllPlots(files_, plotList_, histo_, histo2_, N1Dplots, Nplots, verbose-1);
  if(verbose>0){
    std::cout << Nplots << " plots loaded from " << plotList_.size();
    std::cout << " requested" << std::endl << "empty plots are not counted" << std::endl;
  }
  // b) for zprime
  if(zprime){ 
    for(unsigned int plot=0; plot<plotList_.size(); ++plot){
      histo_[plotList_[plot]][kZprime] = (TH1F*)(files_[kZprime]->Get(plotList_[plot]));
    }
  }

  // ---------------------------------------
  // !!! definition of output file(name) !!!
  // ---------------------------------------
  //TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+(TString)decayChannel+"PseudoData"+lum+"pb"+outNameExtension+"8TeV.root";
  TString outputfile="/afs/naf.desy.de/user/g/goerner/WGspace/RecentAnalysisRun8TeV_doubleKinFit/pseudodata/"+pseudoDataFileName(specifier, decayChannel);
  TFile* out = new TFile(outputfile, "recreate");
  if(verbose>0) std::cout << std::endl << "outputfile: " << outputfile << std::endl;
  poisson(histo_, plotList_, decayChannel, *out, luminosity, verbose, smear, useReweightedTop, avWeight, zprime, zPrimeLumiWeight);

  // free memory
  for(std::map< TString, std::map <unsigned int, TH1F*> >::iterator histo=histo_.begin(); histo!=histo_.end(); ++histo){
    for(std::map <unsigned int, TH1F*>::iterator histoSub=histo->second.begin(); histoSub!=histo->second.end(); ++histoSub){
      if(histoSub->second) delete histoSub->second;
    }
    histo->second.clear();
  }
  histo_ .clear();
  for(std::map< TString, std::map <unsigned int, TH2F*> >::iterator histo2=histo2_.begin(); histo2!=histo2_.end(); ++histo2){
    for(std::map <unsigned int, TH2F*>::iterator histo2Sub=histo2->second.begin(); histo2Sub!=histo2->second.end(); ++histo2Sub){
      if(histo2Sub->second) delete histo2Sub->second;      
    }
    histo2->second.clear();
  }
  histo2_ .clear();
  for(std::map<unsigned int, TFile*>::const_iterator file=files_.begin(); file!=files_.end(); ++file){
    if(file->second){
      file->second->Close();	  
      delete file->second;
    }
  }
  files_ .clear();
  out->Close();
  delete out;

}
Exemplo n.º 4
0
void makeResultTables(std::string decayChannel = "combined", bool extrapolate=true, bool hadron=false, bool addCrossCheckVariables=false, bool useBCC=false, int verbose=1){
  
  // ============================
  //  Set Root Style
  // ============================

  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  TGaxis::SetMaxDigits(2);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");

  // ============================
  //  Open file
  // ============================
  if(extrapolate==true) hadron=false; 
  TString filename="diffXSecTopSemi";
  if(decayChannel=="combined") filename+="Lep";
  else if(decayChannel=="electron") filename+="Elec";
  else if(decayChannel=="muon"    ) filename+="Mu";
  if(extrapolate) filename+="Parton";
  else{
    if(hadron) filename+="Hadron";
    else filename+="Parton";
    filename+="PhaseSpace";
  }
  filename+=".root";
  if(verbose>0) std::cout << "opening file " << filename << std::endl;
  TFile* file = TFile::Open(filename, "READ");
  if(!file){
    std::cout << "ERROR: can not open file " << filename << std::endl;
    exit(0);
  }
  // dont associate new objects with file to be able to close it in the end
  gROOT->cd();
  // ============================
  //  Get plots
  // ============================
  // variables to be processed
  std::vector<TString> xSecVariables_;
  // a) top and ttbar quantities
  if(!hadron){
    xSecVariables_.insert(xSecVariables_.end(), xSecVariablesKinFit, xSecVariablesKinFit + sizeof(xSecVariablesKinFit)/sizeof(TString));
  }
  // b) lepton and b-jet quantities
  if(hadron||!extrapolate){
    xSecVariables_.insert(xSecVariables_.end(), xSecVariablesFinalState    , xSecVariablesFinalState     + sizeof(xSecVariablesFinalState    )/sizeof(TString));
  }
  // c) cross check variables presently only available for parton level cross-sections
  if (addCrossCheckVariables && !hadron){
    xSecVariables_.insert( xSecVariables_.end(),   xSecVariablesCCVar,     xSecVariablesCCVar     + sizeof(xSecVariablesCCVar    )/sizeof(TString)    );
    xSecVariables_.insert( xSecVariables_.end(),   xSecVariablesCCVarNorm, xSecVariablesCCVarNorm + sizeof(xSecVariablesCCVarNorm)/sizeof(TString));
  }

  for(unsigned int i=0; i<xSecVariables_.size(); ++i){
    TString plotName=xSecVariables_[i];
    if(verbose>0) std::cout << std::endl << "variable: " << plotName << std::endl;
    // get canvas for chosen cross section
    TCanvas* canvas = (TCanvas*)(file->Get("finalXSec/"+plotName+"Norm")->Clone());
    if(!canvas){
      std::cout << "ERROR: can not load canvas finalXSec/"+plotName+"Norm" << std::endl;
      exit(0);
    }
    // GET DATA: with final errors from canvas
    TGraphAsymmErrors* dataTot  = (TGraphAsymmErrors*)canvas->GetPrimitive("dataTotalError");
    TGraphAsymmErrors* dataStat = (TGraphAsymmErrors*)canvas->GetPrimitive("dataStatError" );
    TH1F* binned = (TH1F*)canvas->GetPrimitive(plotName);
    TH1F* binnedMCatNLO = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO");
    TH1F* binnedPowheg  = (TH1F*)canvas->GetPrimitive(plotName+"POWHEG");
    TH1F* binnedPowhegHerwig  = (TH1F*)canvas->GetPrimitive(plotName+"POWHEGHERWIG");
    TH1F* binnedNNLO    = (TH1F*)canvas->GetPrimitive(plotName+"nnlo");
    if(!dataTot){
      std::cout << "ERROR: can not load TGraphAsymmErrors dataTotalError in canvas finalXSec/"+plotName+"Norm" << std::endl;
      exit(0);
    }
    if(!dataStat){
      std::cout << "ERROR: can not load TGraphAsymmErrors dataStatError in canvas finalXSec/"+plotName+"Norm" << std::endl;
      exit(0);
    }
    if(!binned){
      std::cout << "ERROR: can not load TH1F topPt in canvas finalXSec/"+plotName << std::endl;
      exit(0);
    }
    // define range of relevant plots
    // INFO: keep this consistent with the range as defined in setXAxisRange
    //       and makevariableBinning in basicFunctions.h
    double xMin=-999999999;
    double xMax= 999999999;
    if(plotName.Contains     ("topPt"    )){ xMin=0.   ; xMax=401. ;} 
    else if(plotName.Contains("topY"     )){ xMin=-2.51; xMax=2.51 ;}
    else if(plotName.Contains("ttbarY"   )){ xMin=-2.51; xMax=2.51 ;}
    else if(plotName.Contains("ttbarMass")){ xMin=344. ; xMax=1601.;}
    else if(plotName.Contains("ttbarPt"  )){ xMin=0.   ; xMax=301. ;}
    else if(plotName.Contains("lepPt"    )){ xMin=29   ; xMax=201. ;}
    else if(plotName.Contains("lepEta"   )){ xMin=-2.11; xMax=2.11 ;}
    else if(plotName.Contains("bqPt"     )){ xMin=29.  ; xMax=401. ;}
    else if(plotName.Contains("bqEta"    )){ xMin=-2.41; xMax=2.41 ;}
    else if(plotName.Contains("bbbarPt"  )){ xMin=0.   ; xMax=800. ;}
    else if(plotName.Contains("bbbarMass")){ xMin=0.   ; xMax=1200.;}
    else if(plotName.Contains("ttbarDelPhi" )){ xMin=0. ; xMax=3.16;}
    else if(plotName.Contains("ttbarPhiStar")){ xMin=0. ; xMax=2.01;}
    else if(plotName.Contains("lbMass"      )){ xMin=0. ; xMax=501.;}
    else if(plotName.Contains("Njets"       )){ xMin=3. ; xMax=10. ;}
    else if(plotName.Contains("rhos"        )){ xMin=0. ; xMax=1.1 ;}

    // initialize ndof counter
    int ndof=0;    
    // initialize global chi2
    double chi2=0;
    double chi2Mc=0;
    double chi2Po=0;
    double chi2PoHer=0;
    double chi2NN=0;
    //  loop all bins
    for(int bin=1; bin<=binned->GetNbinsX(); ++bin){
      if(verbose>1) std::cout << "bin #" << bin;
      // collect information
      double MCxSec  =binned       ->GetBinContent(bin);
      double MCxSecMc=binnedMCatNLO ? binnedMCatNLO->GetBinContent(bin) : 0;
      double MCxSecPo=binnedPowheg  ? binnedPowheg ->GetBinContent(bin) : 0;
      double MCxSecPoHer=binnedPowhegHerwig ? binnedPowhegHerwig ->GetBinContent(bin) : 0;
      double MCxSecNN=binnedNNLO    ? binnedNNLO   ->GetBinContent(bin) : 0;
      // FIXME: current topY NNLO prediction is shifted by one! make sure this is still the case if you update the new prediction
      if(plotName.Contains("topY")) MCxSecNN=binnedNNLO ? binnedNNLO->GetBinContent(bin+1) : 0;
      double xSec=dataTot->GetY()[bin];
      double totError=dataTot->GetErrorYhigh(bin);
      double statError=dataStat->GetErrorYhigh(bin);
      double sysError=sqrt(totError*totError-statError*statError);
      double BCCxValue=dataTot->GetX()[bin];
      double xValueUp=binned->GetBinLowEdge(bin+1);
      double xValueDn=binned->GetBinLowEdge(bin);      
      if(verbose>1) std::cout << std::setprecision(2) << std::fixed << ", xvalue: " << BCCxValue << " (" << xValueDn << ".." << xValueUp << ")" << std::endl;
      // combine information in Latex line style in one TString
      int precXSec=6;
      int precErr=1;
      int precXBCC=2;
      int precX=1;
      if(plotName.Contains("Pt")){
	precXBCC=1;
	if(plotName.Contains("Lep"  )) precXBCC=2;
	if(plotName.Contains("ttbar")) precXBCC=0;
	precX=0;	
      }
      if(plotName.Contains("Eta")||plotName.Contains("Y")){
	precXBCC=3;
	precX=1;
      }
      if(plotName.Contains("Mass")){
	precXBCC=1;
	precX=0;
      }
//       if(plotName.Contains("ttbarY")){
// 	std::cout << std::endl << "xValueDn=" << xValueDn << std::endl;
// 	std::cout << "precX=" << precX << std::endl;
// 	std::cout << "xValueDn +5./(pow(10,precX+1))=" << xValueDn +5./(pow(10,precX   +1)) << std::endl;
// 	TString help=getTStringFromDouble(xValueDn +5./(pow(10,precX+1)), precX, true);
// 	std::cout << "rounded number=" << help << std::endl;
//       }
      TString out= "";
      if(useBCC){
	out+=getTStringFromDouble(BCCxValue, precXBCC);
	out+=" & ";
      }
      out+=fillspace(xValueDn, getBigitFromDouble(binned->GetBinLowEdge(binned->GetNbinsX()+1)));	  
      out+=getTStringFromDouble(xValueDn, precX);
      out+=" to ";	
      out+=fillspace(xValueUp, getBigitFromDouble(binned->GetBinLowEdge(binned->GetNbinsX()+1)));
      out+=getTStringFromDouble(xValueUp, precX);
      out+=" & ";
      out+=getTStringFromDouble(MCxSec, precXSec);
      out+=" & ";
      out+=getTStringFromDouble(xSec  , precXSec);
      out+=" & ";
      out+=fillspace(100*(statError/xSec), 2);
      out+=getTStringFromDouble(100*(statError/xSec),  precErr);
      out+=" & ";
      out+=fillspace(100*(sysError/xSec), 2);
      out+=getTStringFromDouble(100*(sysError/xSec ),  precErr);
      out+=" & ";	
      out+=fillspace(100*(totError/xSec), 2);		    
      out+=getTStringFromDouble(100*(totError/xSec ),  precErr);
      out+=" \\\\ ";
      bool append= (bin==1 ? false : true);
      TString txtfile="./diffXSecFromSignal/plots/"+TString(decayChannel)+"/2012/"+filename;
      txtfile.ReplaceAll(".root",plotName+".txt");
      writeToFile(out, txtfile, append);
      // chi2 for this distribution
      if(xValueDn>=xMin&&xValueUp<=xMax){
	++ndof;
	chi2+=                 ((std::abs(MCxSec  -xSec)/totError)*(std::abs(MCxSec  -xSec)/totError));
	if(MCxSecMc!=0)chi2Mc+=((std::abs(MCxSecMc-xSec)/totError)*(std::abs(MCxSecMc-xSec)/totError));
	if(MCxSecPo!=0)chi2Po+=((std::abs(MCxSecPo-xSec)/totError)*(std::abs(MCxSecPo-xSec)/totError));
	if(MCxSecPoHer!=0)chi2PoHer+=((std::abs(MCxSecPoHer-xSec)/totError)*(std::abs(MCxSecPoHer-xSec)/totError));
	if(MCxSecNN!=0)chi2NN+=((std::abs(MCxSecNN-xSec)/totError)*(std::abs(MCxSecNN-xSec)/totError));
	if(verbose>1) std::cout << "-> considered for chi2" << std::endl;
      }
      //std::cout << out << std::endl;
      //std::cout << BCCxValue << " &  " << xValueDn << " to  " << xValueUp << " & " << MCxSec << "  & " << xSec << " &  " << statError/xSec << " &  " << sysError/xSec << " &  " << totError/xSec << " \\\\ " << std::endl;
      if(verbose>1){
	std::cout << std::setprecision(7) << std::fixed << "data:     " << xSec << "+/-" << statError << "+/-" << sysError << std::endl;
	std::cout << std::setprecision(7) << std::fixed << "MadGraph+Pythia: " << MCxSec; 
	std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSec  -xSec)/totError << " std variations)" << std::endl;
	if(MCxSecMc!=0){
	std::cout << std::setprecision(7) << std::fixed << "MC@NLO+Herwig:   " << MCxSecMc;
	std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecMc-xSec)/totError << " std variations)" << std::endl;
	}
	if(MCxSecPo!=0){
	  std::cout << std::setprecision(7) << std::fixed << "Powheg+Pythia:   " << MCxSecPo;
	  std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecPo-xSec)/totError << " std variations)" << std::endl;
	}
	if(MCxSecPoHer!=0){
	  std::cout << std::setprecision(7) << std::fixed << "Powheg+Herwig:   " << MCxSecPoHer;
	  std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecPoHer-xSec)/totError << " std variations)" << std::endl;
	}
	if(MCxSecNN!=0){
	   std::cout << std::setprecision(7) << std::fixed << "NNLO:     " << MCxSecNN;
	   std::cout << std::setprecision(2) << std::fixed << " (" << std::abs(MCxSecNN-xSec)/totError << " std variations)" << std::endl;
	}
      }
      if(bin==binned->GetNbinsX()&&ndof!=0){
	chi2  /=ndof;
	chi2Mc/=ndof;
	chi2Po/=ndof;
	chi2PoHer/=ndof;
	chi2NN/=ndof;
	if(verbose>1) std::cout << std::endl;
	if(chi2  !=0   ){writeToFile("%chi2(MadGraph+Pythia): "+getTStringFromDouble(chi2     ), txtfile, true); if(verbose>0){std::cout << "chi2(MadGraph+Pythia): " << chi2      << std::endl;}}
	if(chi2Mc!=0   ){writeToFile("%chi2(MC@NLO+Herwig  ): "+getTStringFromDouble(chi2Mc   ), txtfile, true); if(verbose>0){std::cout << "chi2(MC@NLO+Herwig  ): " << chi2Mc    << std::endl;}}
	if(chi2Po!=0   ){writeToFile("%chi2(Powheg+Pythia  ): "+getTStringFromDouble(chi2Po   ), txtfile, true); if(verbose>0){std::cout << "chi2(Powheg+Pythia  ): " << chi2Po    << std::endl;}}
	if(chi2PoHer!=0){writeToFile("%chi2(Powheg+Herwig  ): "+getTStringFromDouble(chi2PoHer), txtfile, true); if(verbose>0){std::cout << "chi2(Powheg+Herwig  ): " << chi2PoHer << std::endl;}}
	if(chi2NN!=0   ){writeToFile("%chi2(NNLO/NLO+NNLL  ): "+getTStringFromDouble(chi2NN   ), txtfile, true); if(verbose>0){std::cout << "chi2(NNLO/NLO+NNLL  ): " << chi2NN    << std::endl;}}
      }
    }
  }
}