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");
  }
}
void MCstatisticsUncertainty(bool save = true, int verbose=0){
  
  // ============================
  //  Set Root Style
  // ============================
		
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  myStyle.SetStripDecimals(true);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  gROOT->ForceStyle();
  TGaxis::SetMaxDigits(2);


  // ============================
  //  load rootfiles
  // ============================
  std::vector<TFile* > file_;
  TString folder="RecentAnalysisRun8TeV_PromptReco_12fb_PAS";
  file_.push_back(TFile::Open("/afs/naf.desy.de/group/cms/scratch/tophh/"+folder+"/elecDiffXSecSigSummer12PF.root", "Open"));
  file_.push_back(TFile::Open("/afs/naf.desy.de/group/cms/scratch/tophh/"+folder+"/muonDiffXSecSigSummer12PF.root", "Open"));

  std::vector<TString> plotList_, axisLabel_;
  TString plots1D[ ] = {
    // KinFit plots before prob cut 
    "analyzeTopRecoKinematicsKinFit/topPt",
    //"analyzeTopRecoKinematicsKinFit/topPtTtbarSys",
    "analyzeTopRecoKinematicsKinFit/topY",
    "analyzeTopRecoKinematicsKinFit/topMass",
    "analyzeTopRecoKinematicsKinFit/ttbarPt",
    "analyzeTopRecoKinematicsKinFit/ttbarY",
    "analyzeTopRecoKinematicsKinFit/ttbarMass",
    "analyzeTopRecoKinematicsKinFit/ttbarHT",
    "analyzeTopRecoKinematicsKinFit/lepPt",
    "analyzeTopRecoKinematicsKinFit/lepEta",
    "analyzeTopRecoKinematicsKinFit/lightqPt",
    "analyzeTopRecoKinematicsKinFit/lightqEta",   
    "analyzeTopRecoKinematicsKinFit/bqPt",
    "analyzeTopRecoKinematicsKinFit/bqEta",
    "analyzeTopRecoKinematicsKinFit/bbbarPt",
    "analyzeTopRecoKinematicsKinFit/bbbarY",
    "analyzeTopRecoKinematicsKinFit/bbbarMass", 
    // KinFit plots after prob cut 
    "analyzeTopRecoKinematicsKinFitProbSel/topPt",
    //"analyzeTopRecoKinematicsKinFitProbSel/topPtTtbarSys",
    "analyzeTopRecoKinematicsKinFitProbSel/topY",
    "analyzeTopRecoKinematicsKinFitProbSel/topMass",
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarPt",
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarY",
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarMass",
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarHT",
    "analyzeTopRecoKinematicsKinFitProbSel/lepPt",
    "analyzeTopRecoKinematicsKinFitProbSel/lepEta",
    "analyzeTopRecoKinematicsKinFitProbSel/lightqPt",
    "analyzeTopRecoKinematicsKinFitProbSel/lightqEta",   
    "analyzeTopRecoKinematicsKinFitProbSel/bqPt",
    "analyzeTopRecoKinematicsKinFitProbSel/bqEta",
    "analyzeTopRecoKinematicsKinFitProbSel/bbbarPt",
    "analyzeTopRecoKinematicsKinFitProbSel/bbbarY",
    "analyzeTopRecoKinematicsKinFitProbSel/bbbarMass", 
  };
  TString plots2D[ ] = { 
    // b) response matrix top quantities
    "analyzeTopRecoKinematicsKinFit/topPt_"    ,  
    "analyzeTopRecoKinematicsKinFit/topY_"     ,
    // c) response matrix ttbar quantities
    "analyzeTopRecoKinematicsKinFit/ttbarMass_",
    "analyzeTopRecoKinematicsKinFit/ttbarPt_"  ,
    "analyzeTopRecoKinematicsKinFit/ttbarY_"   ,
    // KinFit plots after prob cut 
    // b) response matrix top quantities
    "analyzeTopRecoKinematicsKinFitProbSel/topPt_"    ,  
    "analyzeTopRecoKinematicsKinFitProbSel/topY_"     ,
    // c) response matrix ttbar quantities
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarMass_",
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarPt_"  ,
    "analyzeTopRecoKinematicsKinFitProbSel/ttbarY_"   ,
  };
  TString axisLabel1D[ ] = { 
    // KinFit plots before prob cut 
    "p_{T}^{t} #left[GeV#right];Top quarks;0;20",
    //"p_{T}^{t} #left[GeV#right] (t#bar{t} system);Events;0;20",
    "y^{t};Top quarks;0;1",
    "m^{t};Top quarks;0;10",
    "p_{T}^{t#bar{t}} #left[GeV#right];Top-quark pairs;0;20",
    "y^{t#bar{t}};Top-quark pairs;0;1",
    "m^{t#bar{t}} #left[GeV#right];Top-quark pairs;0;50",
    "H_{T}^{t#bar{t}}=#Sigma(E_{T}(jets)) #left[GeV#right];#frac{dN}{dH_{T}^{t#bar{t}}};0;20",
    "p_{T}^{l} #left[GeV#right];N^{l};0;10",
    "#eta^{l};Leptons;0;1",
    "p_{T}^{q} #left[GeV#right];tt jets;0;20",    
    "#eta^{q};tt jets;0;1",
    "p_{T}^{b} #left[GeV#right];b-jets;0;20",    
    "#eta^{b};b-jets;0;1",
    "p_{T}^{b#bar{b}}(assigned to t#bar{t} system) #left[GeV#right];Events;0;20",  
    "y^{b#bar{b}}(assigned to t#bar{t} system);Events;0;1",
    "m^{b#bar{b}}(assigned to t#bar{t} system) #left[GeV#right];Events;0;20",
    // KinFit plots after prob cut 
    "p_{T}^{t} #left[GeV#right];Top quarks;0;20",
    //"p_{T}^{t} #left[GeV#right] (t#bar{t} system);Events;0;20",
    "y^{t};Top quarks;0;1",
    "m^{t};Top quarks;0;10",
    "p_{T}^{t#bar{t}} #left[GeV#right];Top-quark pairs;0;20",
    "y^{t#bar{t}};Top-quark pairs;0;1",
    "m^{t#bar{t}} #left[GeV#right];Top-quark pairs;0;50",
    "H_{T}^{t#bar{t}}=#Sigma(E_{T}(jets)) #left[GeV#right];#frac{dN}{dH_{T}^{t#bar{t}}};0;20",
    "p_{T}^{l} #left[GeV#right];N^{l};0;10",
    "#eta^{l};Leptons;0;1",
    "p_{T}^{q} #left[GeV#right];tt jets;0;20",    
    "#eta^{q};tt jets;0;1",
    "p_{T}^{b} #left[GeV#right];b-jets;0;20",    
    "#eta^{b};b-jets;0;1",
    "p_{T}^{b#bar{b}}(assigned to t#bar{t} system) #left[GeV#right];Events;0;20",  
    "y^{b#bar{b}}(assigned to t#bar{t} system);Events;0;1",
    "m^{b#bar{b}}(assigned to t#bar{t} system) #left[GeV#right];Events;0;20",
  };

  // 2D: "x-axis title"/"y-axis title"
  TString axisLabel2D[ ] = {// reco - gen Match correlation plots (ttbar signal only)
    // b) response matrix Top quantities
    xSecLabelName("topPt"    )+" gen;"+xSecLabelName("topPt"     )+" reco",
    xSecLabelName("topY"     )+" gen;"+xSecLabelName("topY"     )+" reco",
    // c) response matrix ttbar quantities
    xSecLabelName("ttbarMass")+" gen;"+xSecLabelName("ttbarMass")+" reco",
    xSecLabelName("ttbarPt")+" gen;"+xSecLabelName("ttbarPt")+" reco",
    xSecLabelName("ttbarY")+" gen;"+xSecLabelName("ttbarY")+" reco" ,
    // KinFit plots after prob cut 
    // b) response matrix Top quantities
    xSecLabelName("topPt"    )+" gen;"+xSecLabelName("topPt"     )+" reco",
    xSecLabelName("topY"     )+" gen;"+xSecLabelName("topY"     )+" reco",
    // c) response matrix ttbar quantities
    xSecLabelName("ttbarMass")+" gen;"+xSecLabelName("ttbarMass")+" reco",
    xSecLabelName("ttbarPt")+" gen;"+xSecLabelName("ttbarPt")+" reco",
    xSecLabelName("ttbarY")+" gen;"+xSecLabelName("ttbarY")+" reco" ,
  };
  plotList_.insert(plotList_.begin(), plots1D, plots1D + sizeof(plots1D)/sizeof(TString));
  plotList_.insert(plotList_.end()  , plots2D, plots2D + sizeof(plots2D)/sizeof(TString));
  axisLabel_.insert(axisLabel_.begin(), axisLabel1D, axisLabel1D + sizeof(axisLabel1D)/sizeof(TString));
  axisLabel_.insert(axisLabel_.end()  , axisLabel2D, axisLabel2D + sizeof(axisLabel2D)/sizeof(TString));
  if(plotList_.size() != axisLabel_.size()){
    std::cout << "ERROR - 1D plots: Number of plots and axis label do not correspond .... Exiting macro!" << std::endl;
    exit(1);
  }
  double N1D=sizeof(plots1D)/sizeof(TString);
  // run automatically in batch mode if there are many canvas
  if(plotList_.size()>15) gROOT->SetBatch();

  // canvas container
  std::vector<TCanvas*> plotCanvas_;
  std::map< TString, std::map <unsigned int, TH1F*> > histo_;
  std::map< TString, std::map <unsigned int, TH2F*> > histo2D_;
  // create variable bin edges
  std::map<TString, std::vector<double> > binning_ = makeVariableBinning(false);
  // loop all plots
  for(int plot=0; plot<(int)plotList_.size(); ++plot){
    TString name=plotList_[plot];
    TString shortname=getStringEntry(name, 2, "/");
    shortname.ReplaceAll("_","");
    std::cout << std::endl << name << std::endl;
    int kdummy=42;
    // load 1D
    if(plot<N1D){
      std::cout << "1D" << std::endl;
      std::cout << "file 0" << std::endl;
      histo_[name][kdummy]=(TH1F*)file_[0]->Get(name);
      std::cout << "file 1" << std::endl;
      histo_[name][kdummy]->Add((TH1F*)file_[1]->Get(name));
    }
    // load 2D
    else{
      std::cout << "2D" << std::endl;
      std::cout << "file 0" << std::endl;
      histo2D_[name][kdummy]=(TH2F*)file_[0]->Get(name);
      std::cout << "file 1" << std::endl;
      histo2D_[name][kdummy]->Add((TH2F*)file_[1]->Get(name));
    }
    // rebinning
    // equidistant rebinning (1D only)
    std::cout << "rebinning" << std::endl;
    double reBinFactor = plot<N1D ? atof(((string)getStringEntry(axisLabel_[plot],4,";")).c_str()) : 1;
    if(reBinFactor>1&&binning_.count(shortname)==0){
      std::cout << "equidistant" << std::endl;
      if(plot<N1D) equalReBinTH1(reBinFactor, histo_, name, kdummy);
    }
    // variable binning
    else if(binning_.count(shortname)!=0){
      std::cout << "variable" << std::endl;
      // 1D
      if(plot<N1D){
	reBinTH1F(*histo_[name][kdummy], binning_[shortname], verbose-1);
      }
      // 2D
      else histo2D_[name][kdummy]=reBinTH2F(*histo2D_[name][kdummy], binning_[shortname], verbose);
    }
    // histostyle
    // 1D
    if(plot<N1D){
      histogramStyle(*histo_[name][kdummy], kSig, true);
      axesStyle(*histo_[name][kdummy], getStringEntry(axisLabel_[plot],1, ";"), getStringEntry(axisLabel_[plot],2, ";"));
      histo_[name][kdummy]->GetXaxis()->SetNoExponent(true);
    }
    // 2D
    else{
      histStyle2D(*histo2D_[name][kdummy],"",getStringEntry(axisLabel_[plot],1,";"),getStringEntry(axisLabel_[plot],2,";"));
      histo2D_[name][kdummy]->GetXaxis()->SetNoExponent(true);
      histo2D_[name][kdummy]->GetYaxis()->SetNoExponent(true);
    }
    // ============================
    //  create relative error plots
    // ============================
    int kdummy2=42*42;
    int digits=2;
    if(plot<N1D){
      // clone plot
      histo_[name][kdummy2]=(TH1F*)histo_[name][kdummy]->Clone(TString(histo_[name][kdummy]->GetName())+"relErr");
      // loop bins
      for(int bin=0; bin<= histo_[name][kdummy2]->GetNbinsX(); ++bin){
	// fill relative error in %
	histo_[name][kdummy2]->SetBinContent(bin, round(100./sqrt(histo_[name][kdummy2]->GetBinContent(bin)), digits));
      }
    }
    // 2D
    else{
      // clone plot
      histo2D_[name][kdummy2]=(TH2F*)histo2D_[name][kdummy]->Clone(TString(histo2D_[name][kdummy]->GetName())+"relErr");
      // loop bins
      for (Int_t ibinx = 0; ibinx <= histo2D_[name][kdummy]->GetNbinsX()+1; ibinx++) {
	for (Int_t ibiny = 0; ibiny <= histo2D_[name][kdummy]->GetNbinsY()+1; ibiny++) {
	  // fill relative error in %
	  double val=histo2D_[name][kdummy]->GetBinContent(ibinx, ibiny);
	  if (val <= 0.0) histo2D_[name][kdummy2]->SetBinContent(ibinx, ibiny, 0);
	  else histo2D_[name][kdummy2]->SetBinContent(ibinx, ibiny, round(100./sqrt(val), digits));
	}
      }
    }

    
    // ============================
    //  create canvas
    // ============================
    //char canvname[10];
    //sprintf(canvname,"canv%i",plot);  
    TString canvname=getStringEntry(name, 2, "/")+getStringEntry(name, 1, "/");
    plotCanvas_.push_back( new TCanvas( canvname, canvname, 600, 600) );  
    plotCanvas_[plotCanvas_.size()-1]->cd(0);
    if(plot>=N1D) plotCanvas_[plotCanvas_.size()-1]->SetRightMargin(4*myStyle.GetPadRightMargin());
    // ============================
    //  plotting
    // ============================
    if(plot<N1D){
      histo_[name][kdummy]->Draw("hist");
      histo_[name][kdummy2]->Draw("text same");
    }
    else{
      histo2D_[name][kdummy]->Draw("colz");
      histo2D_[name][kdummy2]->Draw("text same");
    }
    // draw cut label
    DrawDecayChLabel("e/#mu + Jets Combined");
  }
  if(save){
    saveCanvas(plotCanvas_, "./MCstats/", "MCstatisticsStudy", true, true);
  }
}
Example #3
0
void
NIImporter_ArcView::load() {
#ifdef HAVE_GDAL
    PROGRESS_BEGIN_MESSAGE("Loading data from '" + mySHPName + "'");
#if GDAL_VERSION_MAJOR < 2
    OGRRegisterAll();
    OGRDataSource* poDS = OGRSFDriverRegistrar::Open(mySHPName.c_str(), FALSE);
#else
    GDALAllRegister();
    GDALDataset* poDS = (GDALDataset*)GDALOpenEx(mySHPName.c_str(), GDAL_OF_VECTOR | GA_ReadOnly, NULL, NULL, NULL);
#endif
    if (poDS == NULL) {
        WRITE_ERROR("Could not open shape description '" + mySHPName + "'.");
        return;
    }

    // begin file parsing
    OGRLayer*  poLayer = poDS->GetLayer(0);
    poLayer->ResetReading();

    // build coordinate transformation
    OGRSpatialReference* origTransf = poLayer->GetSpatialRef();
    OGRSpatialReference destTransf;
    // use wgs84 as destination
    destTransf.SetWellKnownGeogCS("WGS84");
    OGRCoordinateTransformation* poCT = OGRCreateCoordinateTransformation(origTransf, &destTransf);
    if (poCT == NULL) {
        if (myOptions.isSet("shapefile.guess-projection")) {
            OGRSpatialReference origTransf2;
            origTransf2.SetWellKnownGeogCS("WGS84");
            poCT = OGRCreateCoordinateTransformation(&origTransf2, &destTransf);
        }
        if (poCT == 0) {
            WRITE_WARNING("Could not create geocoordinates converter; check whether proj.4 is installed.");
        }
    }

    OGRFeature* poFeature;
    poLayer->ResetReading();
    while ((poFeature = poLayer->GetNextFeature()) != NULL) {
        // read in edge attributes
        std::string id, name, from_node, to_node;
        if (!getStringEntry(poFeature, "shapefile.street-id", "LINK_ID", true, id)) {
            WRITE_ERROR("Needed field '" + id + "' (from node id) is missing.");
        }
        if (id == "") {
            WRITE_ERROR("Could not obtain edge id.");
            return;
        }

        getStringEntry(poFeature, "shapefile.street-id", "ST_NAME", true, name);
        name = StringUtils::replace(name, "&", "&amp;");

        if (!getStringEntry(poFeature, "shapefile.from-id", "REF_IN_ID", true, from_node)) {
            WRITE_ERROR("Needed field '" + from_node + "' (from node id) is missing.");
        }
        if (!getStringEntry(poFeature, "shapefile.to-id", "NREF_IN_ID", true, to_node)) {
            WRITE_ERROR("Needed field '" + to_node + "' (to node id) is missing.");
        }

        if (from_node == "" || to_node == "") {
            from_node = toString(myRunningNodeID++);
            to_node = toString(myRunningNodeID++);
        }

        std::string type;
        if (myOptions.isSet("shapefile.type-id") && poFeature->GetFieldIndex(myOptions.getString("shapefile.type-id").c_str()) >= 0) {
            type = poFeature->GetFieldAsString(myOptions.getString("shapefile.type-id").c_str());
        } else if (poFeature->GetFieldIndex("ST_TYP_AFT") >= 0) {
            type = poFeature->GetFieldAsString("ST_TYP_AFT");
        }
        SUMOReal width = myTypeCont.getWidth(type);
        SUMOReal speed = getSpeed(*poFeature, id);
        int nolanes = getLaneNo(*poFeature, id, speed);
        int priority = getPriority(*poFeature, id);
        if (nolanes == 0 || speed == 0) {
            if (myOptions.getBool("shapefile.use-defaults-on-failure")) {
                nolanes = myTypeCont.getNumLanes("");
                speed = myTypeCont.getSpeed("");
            } else {
                OGRFeature::DestroyFeature(poFeature);
                WRITE_ERROR("The description seems to be invalid. Please recheck usage of types.");
                return;
            }
        }
        if (mySpeedInKMH) {
            speed = speed / (SUMOReal) 3.6;
        }


        // read in the geometry
        OGRGeometry* poGeometry = poFeature->GetGeometryRef();
        OGRwkbGeometryType gtype = poGeometry->getGeometryType();
        assert(gtype == wkbLineString);
        UNUSED_PARAMETER(gtype); // ony used for assertion
        OGRLineString* cgeom = (OGRLineString*) poGeometry;
        if (poCT != 0) {
            // try transform to wgs84
            cgeom->transform(poCT);
        }

        PositionVector shape;
        for (int j = 0; j < cgeom->getNumPoints(); j++) {
            Position pos((SUMOReal) cgeom->getX(j), (SUMOReal) cgeom->getY(j));
            if (!NBNetBuilder::transformCoordinate(pos)) {
                WRITE_WARNING("Unable to project coordinates for edge '" + id + "'.");
            }
            shape.push_back_noDoublePos(pos);
        }

        // build from-node
        NBNode* from = myNodeCont.retrieve(from_node);
        if (from == 0) {
            Position from_pos = shape[0];
            from = myNodeCont.retrieve(from_pos);
            if (from == 0) {
                from = new NBNode(from_node, from_pos);
                if (!myNodeCont.insert(from)) {
                    WRITE_ERROR("Node '" + from_node + "' could not be added");
                    delete from;
                    continue;
                }
            }
        }
        // build to-node
        NBNode* to = myNodeCont.retrieve(to_node);
        if (to == 0) {
            Position to_pos = shape[-1];
            to = myNodeCont.retrieve(to_pos);
            if (to == 0) {
                to = new NBNode(to_node, to_pos);
                if (!myNodeCont.insert(to)) {
                    WRITE_ERROR("Node '" + to_node + "' could not be added");
                    delete to;
                    continue;
                }
            }
        }

        if (from == to) {
            WRITE_WARNING("Edge '" + id + "' connects identical nodes, skipping.");
            continue;
        }

        // retrieve the information whether the street is bi-directional
        std::string dir;
        int index = poFeature->GetDefnRef()->GetFieldIndex("DIR_TRAVEL");
        if (index >= 0 && poFeature->IsFieldSet(index)) {
            dir = poFeature->GetFieldAsString(index);
        }
        // add positive direction if wanted
        if (dir == "B" || dir == "F" || dir == "" || myOptions.getBool("shapefile.all-bidirectional")) {
            if (myEdgeCont.retrieve(id) == 0) {
                LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER;
                NBEdge* edge = new NBEdge(id, from, to, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape, name, id, spread);
                myEdgeCont.insert(edge);
                checkSpread(edge);
            }
        }
        // add negative direction if wanted
        if (dir == "B" || dir == "T" || myOptions.getBool("shapefile.all-bidirectional")) {
            if (myEdgeCont.retrieve("-" + id) == 0) {
                LaneSpreadFunction spread = dir == "B" || dir == "FALSE" ? LANESPREAD_RIGHT : LANESPREAD_CENTER;
                NBEdge* edge = new NBEdge("-" + id, to, from, type, speed, nolanes, priority, width, NBEdge::UNSPECIFIED_OFFSET, shape.reverse(), name, id, spread);
                myEdgeCont.insert(edge);
                checkSpread(edge);
            }
        }
        //
        OGRFeature::DestroyFeature(poFeature);
    }
#if GDAL_VERSION_MAJOR < 2
    OGRDataSource::DestroyDataSource(poDS);
#else
    GDALClose(poDS);
#endif
    PROGRESS_DONE_MESSAGE();
#else
    WRITE_ERROR("SUMO was compiled without GDAL support.");
#endif
}
void ATLASCompTreeSGsamples(bool save = true, int verbose=1, int binning=0, TString outputfolder="./diffXSecFromSignal/plots/combined/2012/ttgencomparison/") {
//void ATLASCompTreeSGsamples(bool save = true, int verbose=1, int binning=0, TString outputfolder="./ttgencomparison/"){
    // binning= 0:fine binning, 1:ATLAS, 2:CMS
    bool debug  = verbose>0 ? true : false;
    bool debug2 = verbose>1 ? true : false;
    bool excludeATLAS=true;

    // ============================
    //  documentation on how to run
    // ----------------------------
    // run via root -q -b -l ATLASCompTreeSGsamples.C++g
    // a) parameters
    // - choose binning via "binning"= 0:fine binning, 1:ATLAS, 2:CMS
    // - choose output level via "verbose"= 0: minimal, 1: detailed, 2: debug
    // - choose via "save" whether you want to save single plots as eps and in rootfile and all plots in one pdf
    // - choose destination where plots are save via "outputfolder"
    // - change the binning in "makeVariableBinningA"
    // have fun, Martin
    // ============================


    // ============================
    //  Set Root Style
    // ============================

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

    // ============================
    //  load rootfiles
    // ============================
    std::vector<TFile* > file_;
    //file_.push_back(TFile::Open("/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun/combinedDiffXSecSigFall11PFLarge.root"                                        , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/work/i/iasincru/public/TopLHCWG_DiffXSex_CMS/MC_theory_samples/CMSttbarMadGraphZ2Pythia6CTEQ6L1Fall11MCProductionCycle.root", "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/work/i/iasincru/public/TopLHCWG_DiffXSex_CMS/MC_theory_samples/CMSttbarPowhegZ2Pythia6CTEQ6MFall11MCProductionCycle.root"   , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/work/i/iasincru/public/TopLHCWG_DiffXSex_CMS/MC_theory_samples/CMSttbarPowhegAUET2Herwig6CTEQ6MFall11MCProductionCycle.root", "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/work/i/iasincru/public/TopLHCWG_DiffXSex_CMS/MC_theory_samples/[email protected]"     , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/AlpgenJimmyttbarlnqq.root"                                                     , "Open"));
    //file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/AlpGenPythia_P2011_CTEQ5L_ttbarlnqq.root"                                      , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/TTbar_PowHeg_Pythia_P2011C.root"                                               , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/TTbar_PowHeg_Pythia_AUET2.root"                                                , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/TTbar_PowHeg_Jimmy.root"                                                       , "Open"));
    file_.push_back(TFile::Open("/afs/cern.ch/user/d/disipio/public/toplhcwg/ntuples_atlas/T1_McAtNlo_Jimmy.root"                                                         , "Open"));

    // list plots of relevance
    std::vector<TString> plotList_, axisLabel_;
    TString plots1D[ ] = {
        // KinFit plots before prob cut
        "topPt",
        "topY",
        "ttbarPt",
        "ttbarY",
        "ttbarMass",
        //"decayChannel",
    };
    TString axisLabel1D[ ] = {
        // KinFit plots before prob cut
        "p_{T}^{t} #left[GeV#right];#Top quarks (norm.);0;20",
        "y^{t};#Top quarks (norm.);0;1",
        "p_{T}^{t#bar{t}} #left[GeV#right];t#bar{t} pairs (norm.);0;20",
        "y^{t#bar{t}};t#bar{t} pairs (norm.);0;1",
        "m^{t#bar{t}} #left[GeV#right];t#bar{t} pairs (norm.);0;50",
        //"t#bar{t} decay Channel;relative #Top-quark pairs;0;1",
    };

    plotList_ .insert(plotList_ .begin(), plots1D    , plots1D    + sizeof(plots1D    )/sizeof(TString));
    axisLabel_.insert(axisLabel_.begin(), axisLabel1D, axisLabel1D+ sizeof(axisLabel1D)/sizeof(TString));
    if(plotList_.size() != axisLabel_.size()) {
        std::cout << "ERROR - 1D plots: Number of plots and axis label do not correspond .... Exiting macro!" << std::endl;
        exit(1);
    }
    // run automatically in batch mode if there are many canvas
    if(plotList_.size()>15) gROOT->SetBatch();

    // create canvas container
    std::vector<TCanvas*> plotCanvas_, plotCanvas2_;
    // create legend
    TLegend* leg = new TLegend(0.4, 0.5, 0.85, 0.88);
    legendStyle(*leg ,"#bf{t#bar{t} simulation, #sqrt{s}=7 TeV}"       );
    TLegend* leg2= new TLegend(0.4, 0.6, 0.85, 0.88);
    legendStyle(*leg2,"#bf{t#bar{t} PYTHIA simulation, #sqrt{s}=7 TeV}");
    TLegend* leg3= new TLegend(0.4, 0.6, 0.85, 0.88);
    legendStyle(*leg3,"#bf{t#bar{t} HERWIG simulation, #sqrt{s}=7 TeV}");
    TLegend* leg4= new TLegend(0.4, 0.7, 0.85, 0.88);
    legendStyle(*leg4,"#bf{t#bar{t} default simulation, #sqrt{s}=7 TeV}");
    TLegend* leg5= new TLegend(0.4, 0.7, 0.85, 0.88);
    legendStyle(*leg5,"#bf{t#bar{t} Powheg simulation, #sqrt{s}=7 TeV}");

    // ============================
    //  get histos from tree
    // ============================
    unsigned int kfirst    =kMad;
    unsigned int klast     =kMcaA;
    unsigned int krelative1 =kPow;
    TString krelative1lab=excludeATLAS ? "#scale[0.85]{Powheg+Pythia}" : "#scale[0.85]{#splitline{Powheg+Pythia}{(CMS)}}";
    unsigned int krelative2 =kPow;
    TString krelative2lab=krelative1lab;
    unsigned int krelative3 =kPowHer;
    TString krelative3lab=excludeATLAS ? "#scale[0.85]{Powheg+Herwig}" : "#scale[0.85]{#splitline{Powheg+Herwig}{(CMS)}}";
    unsigned int krelative4 =kMad;
    TString krelative4lab="#scale[0.55]{MadGraph+Pythia (CMS)}";
    unsigned int krelative5 =kPowHer;
    TString krelative5lab=krelative3lab;
    TString treePath ="genTree/tree";
    TString treePathA="tree";
    std::map< TString, std::map <unsigned int, TH1F*> > histo_;
    std::map<TString, std::vector<double> > binning_=makeVariableBinningA(binning);
    std::map< unsigned int, double> Ntotev_;

    // get template histos
    std::vector<TH1F*> template_, template2_, template3_, template4_, template5_;
    if(debug) std::cout << "get template histos" << std::endl;
    // loop all plots
    for(int plot=0; plot<(int)plotList_.size(); ++plot) {
        TString thname="analyzeTopPartonLevelKinematics/"+plotList_[plot];
        if(debug) std::cout << thname << std::endl;
        //TH1F* temp=new TH1F(plotList_[plot], plotList_[plot], 100000, -5000., 5000.);
        TH1F* temp=new TH1F(plotList_[plot], plotList_[plot], binning_[plotList_[plot]].size()-1, &(binning_[plotList_[plot]][0]));
        //double rebinFactor =atof(((string)getStringEntry(axisLabel_[plot],4,";")).c_str());
        //temp->Rebin(rebinFactor);
        //reBinTH1F(*temp, binning_[plotList_[plot]], 2);
        temp->Reset("icms");
        temp->SetTitle("");
        temp->GetXaxis()->SetTitle(getStringEntry(axisLabel_[plot],1,";"));
        temp->GetYaxis()->SetTitle(getStringEntry(axisLabel_[plot],2,";"));
        temp->GetXaxis()->SetNoExponent(true);
        temp->SetStats(kFALSE);
        temp->SetLineWidth(3);
        temp->SetMarkerSize(1.25);
        //int binMax=temp->GetNbinsX()+1;
        template_ .push_back(temp);
        template2_.push_back(temp);
        template3_.push_back(temp);
        template4_.push_back(temp);
        template5_.push_back(temp);
    }
    if(debug) std::cout << "process trees" << std::endl;
    // loop all samples
    for(unsigned int sample=kfirst; sample<=klast; ++sample) {
        bool CMS = TString(file_.at(sample)->GetName()).Contains("CMS");
        if(debug) {
            std::cout << "sample " << sample;
            if(CMS)  std::cout << " (CMS)";
            else  std::cout << " (ATLAS)";
            std::cout << std::endl;
        }
        // get tree
        TString treePath2=treePath;
        if(!CMS)treePath2=treePathA;
        TTree* tree = (TTree*)(file_[sample]->Get(treePath2));
        if(!tree) {
            std::cout << "WARNING: tree " << treePath << " not found in sample " << sample << ", will continue and neglect this one " << std::endl;
            // exit(0);
        }
        // container for values read from tree
        std::map< TString, float  > value_;
        std::map< TString, float > valueA_;
        // initialize map entries with 0
        value_["weight"   ]=1;
        value_["topPt"    ]=0;
        value_["topbarPt" ]=0;
        value_["topY"     ]=0;
        value_["topbarY"  ]=0;
        value_["ttbarPt"  ]=0;
        value_["ttbarY"   ]=0;
        value_["ttbarMass"]=0;
        //value_["decayChannel"]=0;
        valueA_["weight"   ]=1;
        valueA_["topPt"    ]=0;
        valueA_["topbarPt" ]=0;
        valueA_["topY"     ]=0;
        valueA_["topbarY"  ]=0;
        valueA_["ttbarPt"  ]=0;
        valueA_["ttbarY"   ]=0;
        valueA_["ttbarMass"]=0;
        //valueA_["decayChannel"]=0;
        // initialize branches
        if(tree) {
            tree->SetBranchStatus("*", 0);
            tree->SetBranchStatus("weight"      ,1);
            tree->SetBranchStatus("topPt"       ,1);
            tree->SetBranchStatus("topbarPt"    ,1);
            tree->SetBranchStatus("topY"        ,1);
            tree->SetBranchStatus("topbarY"     ,1);
            tree->SetBranchStatus("ttbarPt"     ,1);
            tree->SetBranchStatus("ttbarY"      ,1);
            tree->SetBranchStatus("ttbarMass"   ,1);
            //tree->SetBranchStatus("decayChannel",1);
            if(CMS) {
                tree->SetBranchAddress("weight"      , (&value_["weight"   ]   ));
                tree->SetBranchAddress("topPt"       , (&value_["topPt"    ]   ));
                tree->SetBranchAddress("topbarPt"    , (&value_["topbarPt" ]   ));
                tree->SetBranchAddress("topY"        , (&value_["topY"     ]   ));
                tree->SetBranchAddress("topbarY"     , (&value_["topbarY"  ]   ));
                tree->SetBranchAddress("ttbarPt"     , (&value_["ttbarPt"  ]   ));
                tree->SetBranchAddress("ttbarY"      , (&value_["ttbarY"   ]   ));
                tree->SetBranchAddress("ttbarMass"   , (&value_["ttbarMass"]   ));
                //tree->SetBranchAddress("decayChannel", (&value_["decayChannel"]));
            }
            else {
                tree->SetBranchAddress("weight"      , (&valueA_["weight"   ]   ));
                tree->SetBranchAddress("topPt"       , (&valueA_["topPt"    ]   ));
                tree->SetBranchAddress("topbarPt"    , (&valueA_["topbarPt" ]   ));
                tree->SetBranchAddress("topY"        , (&valueA_["topY"     ]   ));
                tree->SetBranchAddress("topbarY"     , (&valueA_["topbarY"  ]   ));
                tree->SetBranchAddress("ttbarPt"     , (&valueA_["ttbarPt"  ]   ));
                tree->SetBranchAddress("ttbarY"      , (&valueA_["ttbarY"   ]   ));
                tree->SetBranchAddress("ttbarMass"   , (&valueA_["ttbarMass"]   ));
                //tree->SetBranchAddress("decayChannel", (&valueA_["decayChannel"]));
            }
        }

        // initialize histo
        if(debug) std::cout << "initialize histos from template" << std::endl;
        int color =kRed+7;
        TString sampleName="MadGraph+Pythia old";
        //if(     sample==kMadOld){ color =kRed+7  ; sampleName="MadGraph+Pythia old" ;}
        if(sample==kMad||sample==kAlp) {
            color =kRed    ;
            sample==kMad ? sampleName="MadGraph+Pythia" : sampleName="Alpgen+Herwig"     ;
            sample==kMad ? sampleName+="(Z2)" : sampleName+="(AUET2)"     ;
        }
        else if(sample==kPow||sample==kPowA||sample==kPowA2) {
            color =kGreen  ;
            sampleName="Powheg+Pythia";
            if(     sample==kPow  ) sampleName+="(Z2)";
            else if(sample==kPowA ) sampleName+="(P11)";
            else if(sample==kPowA2) {
                sampleName+="(AUET2)";
                color=kGreen+3;
            }
        }
        else if(sample==kPowHer||sample==kPowHerA) {
            color =kMagenta;
            sampleName="Powheg+Herwig(AUET2)";
        }
        else if(sample==kMca   ||sample==kMcaA   ) {
            color =kBlue   ;
            sampleName="MC@NLO+Herwig";
            if(sample==kMcaA) sampleName+="(AUET2)";
        }
        if(CMS&&!excludeATLAS) sampleName+="(CMS)"  ;
        else if(!CMS) {
            sampleName+="(ATLAS)";
            //color+=1;
        }
        for(int plot=0; plot<(int)plotList_.size(); ++plot) {
            // initialize result plots from template
            histo_[plotList_[plot]][sample]=(TH1F*)template_[plot]->Clone(plotList_[plot]+getTStringFromInt(sample));
            histo_[plotList_[plot]][sample]->SetLineColor(color);
            histo_[plotList_[plot]][sample]->SetMarkerColor(color);
            if(!CMS) {
                histo_[plotList_[plot]][sample]->SetLineStyle(2);
                if(sample==kPowA2) histo_[plotList_[plot]][sample]->SetLineStyle(3);
                histo_[plotList_[plot]][sample]->SetLineWidth(4.5);
            }
        }
        // Add legend entry
        if(CMS||!excludeATLAS) {
            std::cout << "sample: " << sample << std::endl;
            std::cout << "CMS? " <<  CMS << std::endl;
            std::cout << "excludeATLAS? " <<  excludeATLAS << std::endl;
            leg->AddEntry(histo_[plotList_[0]][sample], sampleName, "L");
            if( PythiaSample(sample)) leg2->AddEntry(histo_[plotList_[0]][sample], sampleName, "L");
            if(!PythiaSample(sample)) leg3->AddEntry(histo_[plotList_[0]][sample], sampleName, "L");
            if(sample==kMad||sample==kAlp) leg4->AddEntry(histo_[plotList_[0]][sample], sampleName, "L");
            if(sample==kPow||sample==kPowA||sample==kPowA2||sample==kPowHer||sample==kPowHerA) leg5->AddEntry(histo_[plotList_[0]][sample], sampleName, "L");
        }

        // loop tree
        if(tree&&(CMS||!excludeATLAS)) {
            if(debug) std::cout << "fill plots from tree" << std::endl;
            for(unsigned int event=0; event<tree->GetEntries(); ++event) {
                // get event
                tree->GetEntry(event);
                // get relevant quantities
                float weight       = CMS ? value_["weight"      ] : valueA_["weight"      ];
                //float decayChannel = CMS ? value_["decayChannel"] : valueA_["decayChannel"];
                float topPtLep     = CMS ? value_["topPt"       ] : valueA_["topPt"       ];
                float topPtHad     = CMS ? value_["topbarPt"    ] : valueA_["topbarPt"    ];
                float topYLep      = CMS ? value_["topY"        ] : valueA_["topY"        ];
                float topYHad      = CMS ? value_["topbarY"     ] : valueA_["topbarY"     ];
                float ttbarPt      = CMS ? value_["ttbarPt"     ] : valueA_["ttbarPt"     ];
                float ttbarY       = CMS ? value_["ttbarY"      ] : valueA_["ttbarY"      ];
                float ttbarMass    = CMS ? value_["ttbarMass"   ] : valueA_["ttbarMass"   ];
                // debugging output
                if(debug2) {
                    std::cout << "event " << event+1 << "/" << tree->GetEntries() << std::endl;
                    std::cout << "weight:       " << weight       << std::endl;
                    //std::cout << "decayChannel: " << decayChannel << std::endl;
                    std::cout << "topPtLep:     " << topPtLep     << std::endl;
                    std::cout << "topPtHad:     " << topPtHad     << std::endl;
                    std::cout << "topYLep:      " << topYLep      << std::endl;
                    std::cout << "topYHad:      " << topYHad      << std::endl;
                    std::cout << "ttbarPt:      " << ttbarPt      << std::endl;
                    std::cout << "ttbarMass:    " << ttbarMass    << std::endl;
                    std::cout << "ttbarY:       " << ttbarY       << std::endl;
                }
                // fill histo for all
                histo_["topPt"     ][sample]->Fill(topPtLep , weight);
                histo_["topPt"     ][sample]->Fill(topPtHad , weight);
                histo_["topY"      ][sample]->Fill(topYLep  , weight);
                histo_["topY"      ][sample]->Fill(topYHad  , weight);
                histo_["ttbarPt"   ][sample]->Fill(ttbarPt  , weight);
                histo_["ttbarY"    ][sample]->Fill(ttbarY   , weight);
                histo_["ttbarMass" ][sample]->Fill(ttbarMass, weight);
            } // end loop event
        } // end if tree
        // save N(events)
        if(sample==krelative1||sample==krelative2||sample==krelative3||sample==krelative4||sample==krelative5) Ntotev_[sample]=histo_[plotList_[0]][sample]->Integral(0.,histo_[plotList_[0]][sample]->GetNbinsX()+1);
        for(int plot=0; plot<(int)plotList_.size(); ++plot) {
            // normalize to unity
            histo_[plotList_[plot]][sample]->Scale(1./histo_[plotList_[plot]][sample]->Integral(0.,histo_[plotList_[plot]][sample]->GetNbinsX()+1));
        }
    } // end loop samples


    // create 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);
    label -> AddText(excludeATLAS ? "CMS simulation, #sqrt{s} = 7 TeV" : "TOPLHCWG Preliminary, #sqrt{s} = 7 TeV");
    label -> SetFillStyle(0);
    label -> SetBorderSize(0);
    label -> SetTextSize(0.04);
    label -> SetTextAlign(32);

    // ============================
    //  create canvas
    // ============================
    if(debug) std::cout << "create canvas" << std::endl;
    for(int set=1; set<=5; ++set) {
        // loop plots
        for(int plot=0; plot<(int)plotList_.size(); ++plot) {
            TString name=plotList_[plot];
            TH1F* temptemplate=0;
            if(set==1) temptemplate=(TH1F*)template_ [plot]->Clone(TString(template_ [plot]->GetName())+"1");
            if(set==2) temptemplate=(TH1F*)template2_[plot]->Clone(TString(template2_[plot]->GetName())+"2");
            if(set==3) temptemplate=(TH1F*)template3_[plot]->Clone(TString(template3_[plot]->GetName())+"3");
            if(set==4) temptemplate=(TH1F*)template4_[plot]->Clone(TString(template4_[plot]->GetName())+"4");
            if(set==5) temptemplate=(TH1F*)template5_[plot]->Clone(TString(template4_[plot]->GetName())+"5");
            TString nameExt= set==2 ? "PYTHIA" : (set==3 ? "HERWIG" : (set==4 ? "MadgraphAlpgen" : ( set==5 ? "Powheg" : "")));
            if(debug) std::cout << "plot " << name << std::endl;
            addCanvas(plotCanvas_);
            //######################################
            if(plotList_[plot].Contains("topPt")||plotList_[plot].Contains("ttbarPt")) {
                plotCanvas_[plotCanvas_.size()-1]->SetLogy(1);
                temptemplate->GetYaxis()->SetRangeUser(0.0001, 1000);
            }
            //######################################
            plotCanvas_[plotCanvas_.size()-1]->cd(0);
            plotCanvas_[plotCanvas_.size()-1]->SetName(name+nameExt);
            plotCanvas_[plotCanvas_.size()-1]->SetTitle(name+nameExt);
            temptemplate->SetMaximum(1.5*histo_[name][kPow]->GetMaximum());
            if(plotCanvas_[plotCanvas_.size()-1]->GetLogy()) temptemplate->SetMaximum(10*temptemplate->GetMaximum());
            if(plotList_[plot].Contains("Y")) temptemplate->SetMaximum(1.2*temptemplate->GetMaximum());
            if(plotList_[plot].Contains("ttbarMass")) temptemplate->SetLabelSize(0.03);
            //temptemplate->GetXaxis()->SetLabelSize(0);
            //temptemplate->GetXaxis()->SetTitleSize(0);
            temptemplate->Draw("AXIS");
            // draw all samples
            for(unsigned int sample=kfirst; sample<=klast; ++sample) {
                if(histo_[name].count(sample)>0&&(set==1||(set==2&&PythiaSample(sample))||(set==3&&!PythiaSample(sample))||(set==4&&(sample==kMad||sample==kAlp))||(set==5&&(sample==kPow||sample==kPowA||sample==kPowA2||sample==kPowHer||sample==kPowHerA)))&&(!excludeATLAS||!ATLASSample(sample))) {
                    if(debug) std::cout << " - draw sample " << sample << std::endl;
                    histo_[name][sample]->Draw("hist same");
                }
            }
            // legend
            TLegend* templeg=0;
            // - clone correct legend
            if     (set==1) templeg=(TLegend*)(leg ->Clone(TString("templeg")+plotList_[plot]+getTStringFromInt(set)));
            else if(set==2) templeg=(TLegend*)(leg2->Clone(TString("templeg")+plotList_[plot]+getTStringFromInt(set)));
            else if(set==3) templeg=(TLegend*)(leg3->Clone(TString("templeg")+plotList_[plot]+getTStringFromInt(set)));
            else if(set==4) templeg=(TLegend*)(leg4->Clone(TString("templeg")+plotList_[plot]+getTStringFromInt(set)));
            else if(set==5) templeg=(TLegend*)(leg5->Clone(TString("templeg")+plotList_[plot]+getTStringFromInt(set)));
            // - adjust legend position for different quantities
            if(plotList_[plot].Contains("topPt")) {
                templeg->SetX1(0.22);
                templeg->SetY1(0.4);
                templeg->SetX2(0.67);
                templeg->SetY2(0.61);
            }
            else if(plotList_[plot].Contains("topY")) {
                templeg->SetX1(0.4);
                templeg->SetY1(0.37);
                templeg->SetX2(0.85);
                templeg->SetY2(0.55);
            }
            else if(plotList_[plot].Contains("ttbarPt")) {
                templeg->SetX1(0.46);
                templeg->SetY1(0.63);
                templeg->SetX2(0.91);
                templeg->SetY2(0.87);
            }
            else if(plotList_[plot].Contains("ttbarY")) {
                templeg->SetX1(0.45);
                templeg->SetY1(0.68);
                templeg->SetX2(0.90);
                templeg->SetY2(0.88);
            }
            else if(plotList_[plot].Contains("ttbarMass")) {
                templeg->SetX1(0.44);
                templeg->SetY1(0.60);
                templeg->SetX2(0.89);
                templeg->SetY2(0.86);
            }
            // - draw it
            if(debug) std::cout << " - draw legend" << std::endl;
            templeg->Draw("same");
            label->Draw("same");
            if(debug) std::cout << " - draw label" << std::endl;
            // zero error
            std::vector<double> zeroerr_;
            for(int bin=0; bin<temptemplate->GetNbinsX(); ++bin) zeroerr_.push_back(0);
            // draw ratios
            if(debug) std::cout << " - draw ratios:" << std::endl;
            //bool first=true;
            unsigned int krelative=krelative1;
            TString krelativelab=krelative1lab;
            TString nominatorLabel= "simulation";
            if(set==2 ) {
                krelative=krelative2;
                krelativelab=krelative2lab;
            }
            if(set==3 ) {
                krelative=krelative3;
                krelativelab=krelative3lab;
            }
            if(set==4 ) {
                krelative=krelative4;
                krelativelab=krelative4lab;
                nominatorLabel= "#scale[0.55]{ATLAS Alpgen+Herwig}";
            }
            if(set==5 ) {
                krelative=krelative5;
                krelativelab=krelative5lab;
            }
            // ratio y axis min/max valuse
            double min=0.3;
            double max=1.7;
            if(binning>0) {
                min=0.7 ;
                max=1.3 ;
            }
            if(set==4)   {
                min=0.85;
                max=1.15;
            }
            if(binning==0&&(name.Contains("topPt")||name.Contains("ttbarY")))   {
                min=0.85;
                max=1.15;
            }
            // axis and labels for ratio plot
            drawRatio(temptemplate, temptemplate, min, max, myStyle, verbose, zeroerr_, nominatorLabel, krelativelab, "AXIS", kWhite);
            // draw errorband for relative MC
            if(histo_[name].count(krelative)>0) {
                std::vector<double> err_;
                for(int bin=0; bin<histo_[name][krelative]->GetNbinsX(); ++bin) {
                    err_.push_back(sqrt(histo_[name][krelative]->GetBinContent(bin)*1000000)); // NOTE: 1M events are assumed for the statistical error at the moment
                }
                TH1F* ratiotemp =(TH1F*)(histo_[name][krelative]->Clone(TString(histo_[name][krelative]->GetName())+"errup"));
                TH1F* ratiotemp2=(TH1F*)(histo_[name][krelative]->Clone(TString(histo_[name][krelative]->GetName())+"errdn"));
                TH1F* ratiotemp3=(TH1F*)(histo_[name][krelative]->Clone(TString(histo_[name][krelative]->GetName())+"errc" ));
                if(debug) std::cout << "draw uncertainty bands" << std::endl;
                for(int bin=0; bin<=histo_[name][krelative]->GetNbinsX()+1; ++bin) {
                    if(debug2) std::cout << "bin: #" << bin << " - ";
                    double Ntotev=Ntotev_[krelative];
                    double relUnc=1. / ( sqrt(histo_[name][krelative]->GetBinContent(bin)*Ntotev) );
                    // take care of empty bins
                    if(histo_[name][krelative]->GetBinContent(bin)==0.) {
                        relUnc=max-1.0;
                        ratiotemp ->SetBinContent(bin, 0.000001);
                        ratiotemp2->SetBinContent(bin, 0.000001);
                        ratiotemp3->SetBinContent(bin, 0.000001);
                    }
                    ratiotemp ->SetBinContent(bin, (1.+relUnc)*ratiotemp ->GetBinContent(bin));
                    ratiotemp2->SetBinContent(bin, (1.-relUnc)*ratiotemp2->GetBinContent(bin));
                    if(debug2) std::cout << "content: " << histo_[name][krelative]->GetBinContent(bin) << ", unc: " << relUnc << std::endl;
                }
                int ratioColor =kGray;
                int whiteColor=10;
                ratiotemp ->SetFillStyle(1001);
                ratiotemp2->SetFillStyle(1001);
                ratiotemp ->SetLineWidth(1);
                ratiotemp2->SetLineWidth(1);
                ratiotemp ->SetFillColor(ratioColor);
                ratiotemp2->SetFillColor(whiteColor);
                ratiotemp ->SetLineColor(ratioColor);
                ratiotemp2->SetLineColor(whiteColor);
                // central value+1sigma statistics filled in gray
                drawRatio(ratiotemp   , ratiotemp3, min, max, myStyle, verbose-1, zeroerr_, nominatorLabel, krelativelab, "hist same", ratioColor, false, 0.1);
                // central value+1sigma statistics filled in white
                drawRatio(ratiotemp2  , ratiotemp3, min, max, myStyle, verbose-1, zeroerr_, nominatorLabel, krelativelab, "hist same", whiteColor, false, 0.1);
                // redraw axis
                drawRatio(temptemplate, temptemplate, min, max, myStyle, verbose-1, zeroerr_, nominatorLabel, krelativelab, "AXIS same", kWhite);
            }
            for(unsigned int sample=kfirst; sample<=klast; ++sample) {
                if((histo_[name].count(sample)>0&&histo_[name].count(krelative)>0)&&((set==1)||(set==2&&PythiaSample(sample))||(set==3&&!PythiaSample(sample))||(set==4&&(sample==kAlp||sample==kMad))||(set==5&&(sample==kPow||sample==kPowA||sample==kPowA2||sample==kPowHer||sample==kPowHerA)))&&(!excludeATLAS||!ATLASSample(sample))) {
                    if(debug) std::cout << "   sample " << sample << " / sample " << krelative << std::endl;
                    //TString opt = first ? "hist" : "hist same";
                    TString opt = "hist same";
                    //if(first) first=false;
                    drawRatio(histo_[name][sample], histo_[name][krelative], min, max, myStyle, verbose, zeroerr_, nominatorLabel, krelativelab, opt, histo_[name][sample]->GetLineColor());
                }
            }
            //if(set>1) DrawLabel(TString(template_[plot]->GetXaxis()->GetTitle()), 0.2, 0.07, 0.95, 0.3, 32, 0.15);
            temptemplate->Draw("AXIS same");
        } // end for loop plot
    } // end for loop sep
    if(save) {
        TString name=outputfolder+"treeATLASCMScomparison";
        if(excludeATLAS) name+="CMSonly";
        TString name2=binning==1 ? "ATLASbinning" : (binning==2 ? "CMSbinning" : "FineBinning");
        if(debug) std::cout << "save plots as pictures" << std::endl;
        saveCanvas(plotCanvas_, name+name2, "", true, true, true);
        if(debug) std::cout << "save plots in rootfile" << std::endl;
        for(unsigned int i=0; i<plotCanvas_.size(); ++i) {
            if(debug) {
                std::cout << i+1 << "/" << plotCanvas_.size();
                std::cout << ": "<< plotCanvas_[i]->GetTitle();
                std::cout << "->" << name+".root" << " (subfolder " << name2 << ")" << std::endl;
            }
            saveToRootFile(name+".root", plotCanvas_[i], true, 0, name2);
        }
    }
}
Example #5
0
void poisson(std::map< TString, std::map <unsigned int, TH1F*> > histo_, std::vector<TString> plotList_, const std::string decayChannel, TFile& outputfile, int luminosity, const unsigned int verbose, bool smear, bool useReweightedTop, double avReweight, bool useZprime, double zPrimeLumiWeight){
  unsigned int kCombined=111;
  
  if(verbose>1){
    std::cout << "running function poisson" << std::endl;
    std::cout << "-----------------------------" << std::endl;
    std::cout << "luminosity: " << luminosity << std::endl;
    std::cout << "decayChannel: " << decayChannel << std::endl;
    std::cout << "smear: " << smear << std::endl;
    std::cout << "useReweightedTop: " << useReweightedTop << std::endl;
    std::cout << "avReweight: " << avReweight << std::endl;
    std::cout << "useZprime: " << useZprime << std::endl;
    std::cout << "zPrimeLumiWeight: " << zPrimeLumiWeight << std::endl;
    sleep(5);
  }
  // upper bound for looping events: in/exclude zprime
  int kLast  =kSAToptW;
  int kZprime=kLast+1;
  if(useZprime) kLast=kZprime;

  // go to output file
  outputfile.cd();
  //  ---
  //     combine plot from all files   
  //  ---
  if(verbose>0) std::cout << "start to combine plots " << std::endl;
  // loop plots
  for(unsigned int plot=0; plot<plotList_.size(); ++plot){
    if(verbose>1){
      std::cout << "plot " << plotList_[plot] << std::endl;
      std::cout << "considered samples: " << std::endl;
    }
    // indicate first plot existing in sample
    bool first=true;
    // loop samples
    for(int sample = kSig; sample<=kLast; sample++){
      // check if plot exists
      if((histo_.count(plotList_[plot])>0)&&(histo_[plotList_[plot]].count(sample))){
	// take care of non existing plots
	if(!(useZprime&&sample==kZprime&&plotList_[plot].Contains("PUControlDistributions"))){
	  // do lumiweighting
	  if     (useZprime       &&sample==kZprime) histo_[plotList_[plot]][sample]->Scale(zPrimeLumiWeight);
	  else histo_[plotList_[plot]][sample]->Scale(lumiweight(sample, luminosity, sysNo, decayChannel));
	  // for reweighted ttbar: weight to keep same normalization
	  if(useReweightedTop&&(sample==kSig||sample==kBkg)) histo_[plotList_[plot]][sample]->Scale(1.0/avReweight);
	  // first subsample (should be ttbar signal)
	  // -> create histogram map entry
	  if(first){ 
	    histo_[plotList_[plot]][kCombined] = (TH1F*)(histo_[plotList_[plot]][sample]->Clone());
	    first=false;
	  }
	  // add other subsample
	  else{ 
	    histo_[plotList_[plot]][kCombined]->Add((TH1F*)(histo_[plotList_[plot]][sample]->Clone()),1.0);
	  }
	  if(verbose>1){ 
	    if(useZprime&&sample==kZprime) std::cout << "z prime, weight " << zPrimeLumiWeight << std::endl;
	    else if(useReweightedTop&&(sample==kSig||sample==kBkg))  std::cout << "reweighted "+sampleLabel(sample,decayChannel)+", weight " << 1.0/avReweight << std::endl;
	    else std::cout << sampleLabel(sample,decayChannel) << ", weight " << lumiweight(sample, luminosity, sysNo, decayChannel) << std::endl;
	  }
	}
      }
    }
  }

  //  ---
  //     poisson smearing   
  //  ---
  if(verbose>0) std::cout << "start to do the poisson smearing plots " << std::endl;
  // loop plots
  for(unsigned int plot=0; plot<plotList_.size(); ++plot){
    // check if plot exists
    if((histo_.count(plotList_[plot])>0)&&(histo_[plotList_[plot]].count(kCombined))){
      if(verbose>1) std::cout << "plot " << plotList_[plot] << std::endl;
      // do the poisson smearing
      if(smear){
	TRandom3 rnd(0);
	for(int ibin=0; ibin<=histo_[plotList_[plot]][kCombined]->GetNbinsX()+1; ++ibin){
	  int evts=histo_[plotList_[plot]][kCombined]->GetBinContent(ibin);
	  evts=rnd.Poisson(histo_[plotList_[plot]][kCombined]->GetBinContent(ibin));
	  histo_[plotList_[plot]][kCombined]->SetBinContent(ibin, evts);
	  histo_[plotList_[plot]][kCombined]->SetBinError(ibin, sqrt(evts));
	}
      }
      // do the saving
      // use the same directory as in the input files
      TString directory=getStringEntry(plotList_[plot], 1);
      TString plotName=getStringEntry(plotList_[plot], 2);
      if(verbose>1) std::cout << "check existence of directory " << directory << std::endl;
      if((outputfile.GetDirectory(directory)!=0)&&(verbose>1)) std::cout << "already existing" << std::endl;
      if(outputfile.GetDirectory(directory)==0){
	if(verbose>1) std::cout << "not existing - will create it" << directory << std::endl;
	outputfile.mkdir(directory);
      }
      outputfile.cd(directory);
      if(verbose>1) std::cout << "save plot" << directory << std::endl;
      // save plot
      histo_[plotList_[plot]][kCombined]->Write(plotName);
    }
  }
}
Example #6
0
void addDistributions(bool save = true, unsigned int verbose=2, 
		      TString inputFolderName="RecentAnalysisRun8TeV",
		      TString dataFile= "/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV/analyzeDiffXData2012ABCAllElec.root:/afs/naf.desy.de/group/cms/scratch/tophh/RecentAnalysisRun8TeV/analyzeDiffXData2012ABCAllMuon.root",
		      std::string decayChannel = "combined"){
  // FIXME: bool for testing
  bool test=true;

  // ============================
  //  Prescription
  // ============================
  // The intention of this macro is to add all plots needed 
  // for the calculation of an additional cross section
  // to the analysis rootfiles (e.g.: reco Plot, gen Plot, 
  // gen-reco correlation plot for MC AND Data)

  // ============================
  //  Set ROOT Style
  // ============================
 
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  TGaxis::SetMaxDigits(2);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  gROOT->ForceStyle();	
  
  // ============================
  //  Name Conventions
  // ============================
  // a) enumerator sample convention (as defined in basicFunctions.h)
  //    kSig,    kBkg,    kZjets,  kWjets, 
  //    kQCD,    kSTop,   kDiBos,  kData, 
  //    kQCDEM1, kQCDEM2, kQCDEM3, kQCDBCE1, kQCDBCE2, kQCDBCE3,  
  //    kWW,     kWZ,     kZZ, 
  //    kSTops,  kSATops, kSTopt,  kSATopt,  kSToptW , kSAToptW};
  //
  // b) decayChannel convention: "elec", "muon"
  //
  // c) enumerator systematic Variations (as defined in basicFunctions.h)
  //
  //         0: sysNo                                                       
  //         1: sysLumiUp                   2: sysLumiDown                 
  //         3: sysPUUp                     4: sysPUDown                   
  //         5: sysJESUp                    6: sysJESDown                  
  //         7: sysJERUp                    8: sysJERDown                  
  //         9: sysLepEffSFNormUp          10: sysLepEffSFNormDown         
  //        11: sysLepEffSFShapeUpEta      12: sysLepEffSFShapeDownEta     
  //        13: sysLepEffSFShapeUpPt       14: sysLepEffSFShapeDownPt      
  //        15: sysBtagSFUp                16: sysBtagSFDown               
  //        17: sysBtagSFShapeUpPt65       18: sysBtagSFShapeDownPt65      
  //        19: sysBtagSFShapeUpEta0p7     20: sysBtagSFShapeDownEta0p7    
  //        21: sysMisTagSFUp              22: sysMisTagSFDown             
  //        23: sysTopScaleUp              24: sysTopScaleDown             
  //        25: sysVBosonScaleUp           26: sysVBosonScaleDown          
  //        27: sysSingleTopScaleUp        28: sysSingleTopScaleDown       
  //        29: sysTopMatchUp              30: sysTopMatchDown             
  //        31: sysVBosonMatchUp           32: sysVBosonMatchDown          
  //        33: sysTopMassUp               34: sysTopMassDown              
  //        35: sysQCDUp                   36: sysQCDDown                  
  //        37: sysSTopUp                  38: sysSTopDown                 
  //        39: sysDiBosUp                 40: sysDiBosDown                
  //        41: sysPDFUp                   42: sysPDFDown                  
  //        43: sysHadUp                   44: sysHadDown                  
  //        45: sysGenMCatNLO              46: sysGenPowheg  
  //        47: ENDOFSYSENUM
  


  // ===========================================
  //  Part A: get list of all relevant rootfiles
  // ===========================================
  TString inputFolder= "/afs/naf.desy.de/group/cms/scratch/tophh/"+inputFolderName;
  std::vector <std::string> decayChannels_;
  if(decayChannel=="combined"){
    decayChannels_.push_back("muon"    );
    decayChannels_.push_back("electron");
  }
  else{
    if(decayChannel=="electron") decayChannels_.push_back("electron");
    if(decayChannel=="muon"    ) decayChannels_.push_back("muon"    );
  }
  std::vector <TString> rootFiles_; 
  // loop decay channels
  for(int channelix =0; channelix<(int)decayChannels_.size(); ++channelix){
    std::string channel=decayChannels_[channelix];
    // all default samples + ttbar Powheg/MC@NLO
    for(int sample = kSig; sample<=kBkgMca; sample++){
      if(!(sample>kQCD&&sample<=kData)&&!((sample==kQCD&&channel.compare("electron")==0)||(sample>=kQCDEM1&&sample<=kQCDBCE3&&channel.compare("muon")==0))) rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysNo, channel));
    }
    // JES+JER for all samples
    for(int sample = kSig; sample<=kSAToptW; sample++){
      for(int sys=sysJESUp; sys<=sysJERDown; ++sys){
	if(!(sample>kQCD&&sample<=kData)&&!((sample==kQCD&&channel.compare("electron")==0)||(sample>=kQCDEM1&&sample<=kQCDBCE3&&channel.compare("muon")==0))) rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sys, channel));
      }
    }
    //Ttbar Scale, Matching and Mass samples
    for(int sample = kSig; sample<=kBkg; sample++){
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopScaleUp  , channel));       
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopScaleDown, channel));
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopMatchUp  , channel));
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopMatchDown, channel));
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopMassUp   , channel));
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopMatchDown, channel));
    }
    // V+jets Scale and Matching Sample
    for(int sample = kZjets; sample<=kWjets; sample++){
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysVBosonScaleUp  , channel)); 
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysVBosonScaleDown, channel)); 
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysVBosonMatchUp  , channel)); 
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysVBosonMatchDown, channel));
    }
    // single Top Scale Sample
    for(int sample = kSToptW1; sample<=kSAToptW3; sample++){
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopScaleUp  , channel)); 
      rootFiles_.push_back(inputFolder+"/"+TopFilename(sample, sysTopScaleDown, channel)); 
    }
  }
  // data
  if(!dataFile.Contains(":")){
    rootFiles_.push_back(dataFile);
  }
  else{
    rootFiles_.push_back(getStringEntry(dataFile,1 , ":"));
    rootFiles_.push_back(getStringEntry(dataFile,42, ":"));
  }
  
  // testing: use only one local rootfile
  if(test){
    TString testfile="./muonDiffXSecSigSummer12PF.root";
    if(testfile!=""){
      rootFiles_.clear();
      rootFiles_.push_back(testfile);
      if(rootFiles_.size()>1){
	std::cout << "ERROR in testfile setup" << std::endl;
	exit(0);
      }
    }
  }
    
  // info output
  if(verbose==1){
    std::cout << "The following files will be considered:" << std::endl;
    for(unsigned int file=0; file<rootFiles_.size(); ++file){
      std::cout << rootFiles_[file] << std::endl;
    }
  }

  // ===========================================
  //  Part B: get list of plots you want to add
  // ===========================================
  TString recoTreeLocation="analyzeTopRecoKinematicsKinFit";
  TString genTreeLocation ="analyzeTopPartonLevelKinematics";
  TString outputRecoFolderLocation=recoTreeLocation;
  TString outputGenFolderLocation=genTreeLocation;
  TString newVarName="topSquarePt";
  TString newVarBinning="16000,0,160000";
  TString expression="topPt*topPt";
  TString eventWeight="weight";
  TString withCondition=" ";
  TString infostream=recoTreeLocation+":"+genTreeLocation+":"+outputRecoFolderLocation+":"+outputGenFolderLocation+":"+newVarName+":"+newVarBinning+":"+expression+":"+eventWeight+":"+withCondition;
  if(verbose>0) std::cout << infostream << std::endl;

  // ===================
  //  Part C: do the job
  // ===================

  createEntry(infostream, rootFiles_, save, verbose);
}
Example #7
0
void createEntry(TString infostream, std::vector<TString> fileList_, bool save, unsigned int verbose){

  // extract relavant information from infostream
  TString recoTreeLocation        =getStringEntry(infostream,1,":");
  TString genTreeLocation         =getStringEntry(infostream,2,":");
  TString outputRecoFolderLocation=getStringEntry(infostream,3,":");
  TString outputGenFolderLocation =getStringEntry(infostream,4,":");
  TString newVarName              =getStringEntry(infostream,5,":");
  TString newVarBinning           =getStringEntry(infostream,6,":");
  TString fillFrom                =getStringEntry(infostream,7,":");
  TString eventWeight             =getStringEntry(infostream,8,":");
  TString withCondition           =getStringEntry(infostream,9,":");

  //loop files
  for(unsigned int fileix=0; fileix<fileList_.size(); ++fileix){
    TString name=fileList_[fileix];
    if(verbose>1) std::cout  << std::endl << "processing file " << name << std::endl;
    // check if ttbarSG file is processed
    bool ttbarSG= (name.Contains("Sig")) ? true : false;
    bool ttbarCentral = (ttbarSG&&!(name.Contains("Up")||name.Contains("Down")||name.Contains("Mcatnlo")||name.Contains("Powheg"))) ? true : false;
    // container for values read from tree
    std::map< TString, float > value_;
    // A open file
    TFile* file = TFile::Open(name, "Update");
    if(!file||file->IsZombie()) std::cout << "ERROR: file " << name << " does not exist or is broken" << std::endl;
    else{
      file->cd();
      // B1 open reco tree
      TTree* recotree=(TTree*)(file->Get(recoTreeLocation+"/tree")->Clone());
      if(!recotree||recotree->IsZombie()){
	std::cout << "ERROR: can not load the chosen recotree " << recoTreeLocation+"/tree in file " << name << std::endl;
      }
      else{
	// info output
	if(fileix==0&&verbose>1) std::cout << "recotree: " << recoTreeLocation+"/tree" << std::endl;
	// activate all branches
	recotree->SetBranchStatus("*",1);
	// get all branches from recotree
	TObjArray* branches=recotree->GetListOfBranches();
	// loop all branches
	TObjArrayIter branch(branches);
	TObject* object;
	while ( ( object = branch() ) ) {
	  // get single branch
	  TString branchname=(TString)object->GetName();
	  // info output
	  if(fileix==0&&verbose>1) std::cout << "->reco branch : " << branchname << std::endl;	  
	  // set branch address for access
	  recotree->SetBranchAddress(branchname,(&value_[branchname]));
	}
	// B2a create reco histo
	int nbins =(getStringEntry(newVarBinning,1,",")).Atoi();
	double min=(getStringEntry(newVarBinning,2,",")).Atof();
	double max=(getStringEntry(newVarBinning,3,",")).Atof();
	TH1F* newRecPlot=new TH1F( newVarName+"Rec", newVarName, nbins , min , max);
	// B2b create reco branch entry 
	Float_t newRec1;
	Float_t newRec2;
	TBranch *newRecBranch1 = recotree->Branch(newVarName+"Lep", &newRec1, newVarName+"Lep"+"/F");
	TBranch *newRecBranch2 = recotree->Branch(newVarName+"Had", &newRec2, newVarName+"Had"+"/F");
	// info output
	if(fileix==0&&verbose>1){
	  std::cout << "will add new reco plot: new TH1F(" << newVarName << ", " << newVarName;
	  std::cout << ", " << nbins <<  ", " << min << ", " << max << ") in " << outputRecoFolderLocation << std::endl;
	  std::cout << "will add new branches " << newVarName+"Lep" << " and " << newVarName+"Had";
	  std::cout << ") in tree " << recoTreeLocation+"/tree" << std::endl;
	}
	// B3a create gen-reco histo
	TH2F* newRecGenPlot;
	Float_t newRecGen1;
	Float_t newRecGen2;
	TBranch *newRecGenBranch1 =0;
	TBranch *newRecGenBranch2 =0;
	if(ttbarSG){
	  newRecGenPlot=new TH2F( newVarName+"_", newVarName+"_", nbins , min , max, nbins , min , max);
	  if(fileix==0&&verbose>1){
	    std::cout << "will add new gen-reco plot: new TH2F(" << newVarName+"_" << ", " << newVarName+"_";
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ", " << std::endl;
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ")" << std::endl;
	  }
	  // B3b create gen branch entry 
	  newRecGenBranch1 = recotree->Branch(newVarName+"Lep"+"PartonTruth", &newRecGen1, newVarName+"Lep"+"PartonTruth"+"/F");
	  newRecGenBranch2 = recotree->Branch(newVarName+"Had"+"PartonTruth", &newRecGen2, newVarName+"Had"+"PartonTruth"+"/F");
	}
	// B4 fill reco plots from tree
	// loop recotree
	for(unsigned int event=0; event<recotree->GetEntries(); ++event){
	  recotree->GetEntry(event);
	  // B4a fill rec branch
	  newRec1=value_["topPtLep"]*value_["topPtLep"];
	  newRec2=value_["topPtHad"]*value_["topPtHad"];
	  newRecBranch1->Fill();
	  newRecBranch2->Fill();
	  // B4b fill rec plot
	  newRecPlot->Fill(newRec1, value_["weight"]);
	  newRecPlot->Fill(newRec2, value_["weight"]);
	  // fill rec-gen plot
	  if(newRecGenPlot){
	    newRecGen1=value_["topPtLepPartonTruth"]*value_["topPtLepPartonTruth"];
	    newRecGen2=value_["topPtHadPartonTruth"]*value_["topPtHadPartonTruth"];
	    newRecGenBranch1->Fill();
	    newRecGenBranch2->Fill();
	    newRecGenPlot->Fill(newRecGen1, newRec1, value_["weight"]);
	    newRecGenPlot->Fill(newRecGen2, newRec2, value_["weight"]);	    
	  }
	}
	// B5 saving
	if(save){
	  if(fileList_.size()==1){
	    TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", ""));
	    if(newRecPlot   ) saveToRootFile("test.root", newRecPlot   , true, 1, outputRecoFolderLocation+"/"+debugName);
	    if(newRecGenPlot) saveToRootFile("test.root", newRecGenPlot, true, 1, outputRecoFolderLocation+"/"+debugName);
	  }
	  file->cd(outputRecoFolderLocation);
	  if(newRecPlot   ) newRecPlot   ->Write(newRecPlot->GetTitle()   , TObject::kOverwrite);
	  if(newRecGenPlot) newRecGenPlot->Write(newRecGenPlot->GetTitle(), TObject::kOverwrite);
	  if(recotree) recotree->Write(recotree->GetTitle(), TObject::kOverwrite);
	  file->cd();
	} // end if save
      } // end if recotree
      if(ttbarSG){
	if(verbose>1) std::cout << "-> ttbarSG file! gen and reco-gen will be derived" << std::endl;
	// C open gen tree
	TTree* gentree=(TTree*)(file->Get(genTreeLocation+"/tree")->Clone());
	if(!gentree||gentree->IsZombie()){
	  std::cout << "ERROR: can not load the chosen gentree " << genTreeLocation+"/tree in file " << name << std::endl;
	}
	else{
	  // info output
	  if(fileix==0&&verbose>1) std::cout << "gentree: " << genTreeLocation+"/tree" << std::endl;
	  // activate all branches
	  gentree->SetBranchStatus("*",1);
	  // get all branches from recotree
	  TObjArray* branches=gentree->GetListOfBranches();
	  // loop all branches
	  TObjArrayIter branch(branches);
	  TObject* object;
	  while ( ( object = branch() ) ) {
	    // get single branch
	    TString branchname=(TString)object->GetName();
	    // info output
	    if(fileix==0&&verbose>1) std::cout << "->gen branch : " << branchname << std::endl;	  
	    // set branch address for access
	    gentree->SetBranchAddress(branchname,(&value_[branchname]));
	  }
	  // C2a create gen histo
	  int nbins =(getStringEntry(newVarBinning,1,",")).Atoi();
	  double min=(getStringEntry(newVarBinning,2,",")).Atof();
	  double max=(getStringEntry(newVarBinning,3,",")).Atof();
	  TH1F* newGenPlot=new TH1F( newVarName+"Gen", newVarName, nbins , min , max);
	  // C2b create gen branch entry 
	  Float_t newGen1;
	  Float_t newGen2;
	  TBranch *newGenBranch1 = gentree->Branch(newVarName+"Lep", &newGen1, newVarName+"Lep"+"/F");
	  TBranch *newGenBranch2 = gentree->Branch(newVarName+"Had", &newGen2, newVarName+"Had"+"/F");
	  // info output
	  if(fileix==0&&verbose>1){
	    std::cout << "will add new gen plot: new TH1F(" << newVarName << ", " << newVarName;
	    std::cout << ", " << nbins <<  ", " << min << ", " << max << ")" << std::endl;
	  }
	  // C3 fill gen plots from tree
	  // loop gentree
	  for(unsigned int event=0; event<gentree->GetEntries(); ++event){
	    gentree->GetEntry(event);
	    // C3a fill gen branches
	    newGen1=value_["topPtLep"]*value_["topPtLep"];
	    newGen2=value_["topPtHad"]*value_["topPtHad"];
	    newGenBranch1->Fill();
	    newGenBranch2->Fill();
	    // C3b fill gen plot
	    newGenPlot->Fill(newGen1, value_["weight"]);
	    newGenPlot->Fill(newGen2, value_["weight"]);
	  }
	  // C4 saving
	  if(save){
	    if(fileList_.size()==1){
	      TString debugName=((getStringEntry(name, 42, "/")).ReplaceAll(".root", ""));
	      if(newGenPlot   ) saveToRootFile("test.root", newGenPlot   , true, 1, outputGenFolderLocation+"/"+debugName );
	    }
	    file->cd(outputGenFolderLocation);
	    if(newGenPlot) newGenPlot->Write(newGenPlot->GetTitle(), TObject::kOverwrite);
	    if(gentree ) gentree->Write(gentree->GetTitle(), TObject::kOverwrite);
	    file->cd();
	  } // end if save
	  // D process additional folders
	  if(verbose>1&&ttbarCentral) std::cout << "   -> central ttbarSG file! need to process additional folders for systematic variations" << std::endl;
	} // end if gentree
      } // end if ttbarSG
    } // end if file
    // close file
    file->Close();
  } // end loop files
}
Example #8
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);
  }
}