示例#1
0
int main(int argc, char *argv[])
{    
    QApplication a(argc, argv);

    QImage texture("pics/nana.jpg");
    if (texture.isNull()) {
        qDebug() << "Couldn't read the default texture. Shadow building, but forgot to set the run directory?";
        return 0;
    }
    QPixmap *canvas = new QPixmap(texture.width(), texture.height());

    QGraphicsScene scene;
    scene.setItemIndexMethod(QGraphicsScene::NoIndex);
    Boids boids(&scene, canvas, &texture);


    SettingsPanel settings;
    settings.move(1250, 200);

    BoidsView view(canvas);


    QGLWidget* viewport = new QGLWidget();
    view.setViewport(viewport);
    view.setOptimizationFlag(QGraphicsView::DontSavePainterState);

    view.setAutoFillBackground(false);
    view.setGeometry(50, 100, texture.width(), texture.height());
    view.setScene(&scene);
    view.setSceneRect(-view.width() / 2, -view.height() / 2, view.width(), view.height());
    view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view.setWindowTitle("Boids");

    QObject::connect(&view, SIGNAL(mousePositionChanged(float,float)), &boids, SLOT(setTargetLocation(float,float)));
    QObject::connect(&view, SIGNAL(enableSimulation(bool)), &boids, SLOT(enableSimulation(bool)));
    QObject::connect(&settings, SIGNAL(boidCountChanged(int)), &boids, SLOT(setBoidCount(int)));
    QObject::connect(&settings, SIGNAL(trailOpacityChanged(int)), &boids, SLOT(setTrailOpacity(int)));
    QObject::connect(&settings, SIGNAL(textureChanged(QString)), &boids, SLOT(loadTexture(QString)));
    QObject::connect(&settings, SIGNAL(clearCanvas()), &boids, SLOT(clearCanvas()));
    QObject::connect(&settings, SIGNAL(saveCanvas(QString)), &boids, SLOT(saveCanvas(QString)));
    QObject::connect(&settings, SIGNAL(colorEvolutionRateChanged(int)), &boids, SLOT(setColorEvolutionRate(int)));
    QObject::connect(&settings, SIGNAL(coloringModeChanged(Boids::ColoringMode)), &boids, SLOT(setColoringMode(Boids::ColoringMode)));
    QObject::connect(&boids, SIGNAL(canvasChanged(QPixmap*)), &view, SLOT(canvasChanged(QPixmap*)));
    QObject::connect(&settings, SIGNAL(maximumSpeedChanged(int)), &boids, SLOT(setMaxBoidSpeed(int)));
    QObject::connect(&settings, SIGNAL(minimumDistanceChanged(int)), &boids, SLOT(setMinimumDistance(int)));
    QObject::connect(&settings, SIGNAL(inertiaChanged(int)), &boids, SLOT(setInertia(int)));

    boids.setBoidCount(settings.boidCount());
    boids.setColorEvolutionRate(settings.colorEvolutionRate());
    boids.setColoringMode(settings.coloringMode());
    boids.setTrailOpacity(settings.trailOpacity());
    boids.setMaxBoidSpeed(settings.maximumSpeed());
    boids.setMinimumDistance(settings.minimumDistance());
    boids.setInertia(settings.inertia());

    view.show();
    settings.show();
    return a.exec();
}
示例#2
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    m_scene(new QGraphicsScene),
    m_turtleGraphics(new TurtleCanvasGraphicsItem),
    m_cmds(m_turtleGraphics),
    m_prefsDialog(new PreferencesDialog(this)),
    m_aboutDialog(new AboutDialog(this)),
    m_canvasSaveOptionsDialog(new CanvasSaveOptionsDialog(this)),
    m_settings("settings.ini")
{
    ui->setupUi(this);

    m_scene->addItem(m_turtleGraphics);
    ui->graphicsView->setScene(m_scene);
    ui->graphicsView->centerOn(0.0, 0.0);

    // Add the graphics view actions
    QAction* centerAction = new QAction("&Center View", NULL);
    QAction* clearAction  = new QAction("C&lear Canvas", NULL);
    ui->graphicsView->addAction(centerAction);
    ui->graphicsView->addAction(clearAction);
    connect(centerAction, SIGNAL(triggered()), this, SLOT(centerGraphicsScene()));
    connect(clearAction,  SIGNAL(triggered()), this, SLOT(clearCanvas()));

    ui->graphicsView->setContextMenuPolicy(Qt::ActionsContextMenu);

    ui->errorMessagesTextEdit->setTextColor(Qt::red);

    // These buttons are only enabled while a script is running.
    ui->haltButton->setEnabled(false);
    ui->pauseButton->setEnabled(false);
    ui->resumeButton->setEnabled(false);

    // Messages dock is hidden by default.
    ui->messagesDockWidget->hide();

    connect(m_turtleGraphics, SIGNAL(canvasResized()), this, SLOT(resizeGraphicsScene()));

    connect(ui->runButton,    SIGNAL(clicked()), this, SLOT(runScript()));
    connect(ui->haltButton,   SIGNAL(clicked()), this, SLOT(haltScript()));
    connect(ui->pauseButton,  SIGNAL(clicked()), this, SLOT(pauseScript()));
    connect(ui->resumeButton, SIGNAL(clicked()), this, SLOT(resumeScript()));

    connect(ui->action_Open_Script, SIGNAL(triggered()), this, SLOT(loadScript()));
    connect(ui->action_Save_Script, SIGNAL(triggered()), this, SLOT(saveScript()));
    connect(ui->action_Save_Canvas, SIGNAL(triggered()), this, SLOT(saveCanvas()));
    connect(ui->action_Preferences, SIGNAL(triggered()), m_prefsDialog, SLOT(show()));
    connect(ui->action_About,       SIGNAL(triggered()), m_aboutDialog,  SLOT(show()));

    connect(ui->action_Errors, SIGNAL(triggered(bool)), this, SLOT(showErrors()));
    connect(ui->action_Script_Output, SIGNAL(triggered(bool)),
            this, SLOT(showScriptOutputs()));

    connect(m_prefsDialog, SIGNAL(rejected()), this, SLOT(loadPreferences()));
    connect(m_prefsDialog, SIGNAL(accepted()), this, SLOT(applyPreferences()));
    connect(m_prefsDialog, SIGNAL(accepted()), this, SLOT(savePreferences()));

    connect(&m_cmds, SIGNAL(scriptError(QString)),
            this,    SLOT(showScriptError(QString)),
            Qt::QueuedConnection);

    connect(&m_cmds, SIGNAL(scriptMessageReceived()),
            this,    SLOT(showScriptOutput()),
            Qt::QueuedConnection);

    loadPreferences();
    applyPreferences();

    m_cmds.start();

    m_cmds.setRequirePaths("");
    for (const QString& path : m_settings.requirePaths())
    {
        m_cmds.addRequirePath(path);
    }

    for (const QString& filename : m_settings.startupScripts())
    {
        m_cmds.runScriptFile(filename);
    }

    // Don't connect this until all the startup scripts have run
    // to prevent the error messages box from being cleared by successful scripts.
    connect(&m_cmds, SIGNAL(scriptFinished(bool)),
            this,    SLOT(scriptFinished(bool)),
            Qt::QueuedConnection);
}
示例#3
0
void plotHist3D() {

  RiceStyle();

  gStyle->SetOptStat(0);

  TFile *f = new TFile("../rootfile/PbPb_eff_MC_v1.root");

  char ndir[256] = "HITrackCorrections";
  double ptmax = 300.;

  // sim-to-reco hists
  TH3F *hSim = (TH3F*) f->Get(Form("%s/hsim3D",ndir)); hSim->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hEff = (TH3F*) f->Get(Form("%s/heff3D",ndir)); hEff->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hMul = (TH3F*) f->Get(Form("%s/hmul3D",ndir)); hMul->GetYaxis()->SetRangeUser(0.2,ptmax);

  // reco-to-sim hists
  TH3F *hRec = (TH3F*) f->Get(Form("%s/hrec3D",ndir)); hRec->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hFak = (TH3F*) f->Get(Form("%s/hfak3D",ndir)); hFak->GetYaxis()->SetRangeUser(0.2,ptmax);
  TH3F *hSec = (TH3F*) f->Get(Form("%s/hsec3D",ndir)); hSec->GetYaxis()->SetRangeUser(0.2,ptmax);

  // ratio histograms
  TH3F *rEff = (TH3F*) hEff->Clone("rEff");
  TH3F *rMul = (TH3F*) hMul->Clone("rMul");
  TH3F *rFak = (TH3F*) hFak->Clone("rFak");
  TH3F *rSec = (TH3F*) hSec->Clone("rSec");

  //---------------------------------------------
  //---------------------------------------------

  // find bins corresponding to projections for below
  int ptbin04=hSim->GetYaxis()->FindBin(0.41);
  int ptbin10=hSim->GetYaxis()->FindBin(1.01);
  int ptbins=hSim->GetYaxis()->GetNbins();

  int etabin24m=hSim->GetXaxis()->FindBin(-2.39);
  int etabin24p=hSim->GetXaxis()->FindBin(2.39);
  int etabin10m=hSim->GetXaxis()->FindBin(-0.99);
  int etabin10p=hSim->GetXaxis()->FindBin(0.99);

  int occbin0 = hSim->GetZaxis()->FindBin(0);
  int occbin50 = hSim->GetZaxis()->FindBin(99);
  int occbin51 = hSim->GetZaxis()->FindBin(100);
  int occbin100 = hSim->GetZaxis()->FindBin(199);

  cout << "etabin10m: " << etabin10m << " etabin10p: " << etabin10p << endl;
  cout << "etabin10m: " << etabin24m << " etabin10p: " << etabin24p << endl;
  cout << "occbin0: " << occbin0 << "occbin50: " << occbin50 << endl;

  // projected hists: pt > 1.0 GeV/c, cBin (0,50%)
  TH1D* hSimEta = (TH1D*) hSim->ProjectionX("hSimEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hEffEta = (TH1D*) hEff->ProjectionX("hEffEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hMulEta = (TH1D*) hMul->ProjectionX("hMulEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hRecEta = (TH1D*) hRec->ProjectionX("hRecEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hFakEta = (TH1D*) hFak->ProjectionX("hFakEta",ptbin10,ptbins,occbin0,occbin50,"e");
  TH1D* hSecEta = (TH1D*) hSec->ProjectionX("hSecEta",ptbin10,ptbins,occbin0,occbin50,"e");

  // projected hists: pt > 1.0 GeV/c. cBin (50-100%)
  TH1D* hSimEta2 = (TH1D*) hSim->ProjectionX("hSimEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hEffEta2 = (TH1D*) hEff->ProjectionX("hEffEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hMulEta2 = (TH1D*) hMul->ProjectionX("hMulEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hRecEta2 = (TH1D*) hRec->ProjectionX("hRecEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hFakEta2 = (TH1D*) hFak->ProjectionX("hFakEta2",ptbin10,ptbins,occbin50,occbin100,"e");
  TH1D* hSecEta2 = (TH1D*) hSec->ProjectionX("hSecEta2",ptbin10,ptbins,occbin50,occbin100,"e");

  TH1D* hDumEta = new TH1D("hDumEta",";#eta",60,-2.4,2.4); hDumEta->SetMaximum(1.0); hDumEta->SetTitle("p_{T} > 1.0");
  hDumEta->GetXaxis()->CenterTitle(); hDumEta->GetYaxis()->SetTitleOffset(1.8);
  TH1D* hDumEta2 = (TH1D*) hDumEta->Clone("hDumEta2"); hDumEta2->SetMaximum(0.1); 
  TH1D* hDumEta3 = (TH1D*) hDumEta->Clone("hDumEta3"); hDumEta3->SetMaximum(0.00049); 

  // projected hists: abs(eta) < 1.0, cBin(0-50%)
  TH1D* hSimPt  = (TH1D*) hSim->ProjectionY("hSimPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hEffPt  = (TH1D*) hEff->ProjectionY("hEffPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hMulPt  = (TH1D*) hMul->ProjectionY("hMulPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hRecPt  = (TH1D*) hRec->ProjectionY("hRecPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hFakPt  = (TH1D*) hFak->ProjectionY("hFakPt",etabin10m,etabin10p,occbin0,occbin50,"e");
  TH1D* hSecPt  = (TH1D*) hSec->ProjectionY("hSecPt",etabin10m,etabin10p,occbin0,occbin50,"e");

  // projected hists: abs(eta) < 1.0, cBin(50-100%)
  TH1D* hSimPt2  = (TH1D*) hSim->ProjectionY("hSimPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hEffPt2  = (TH1D*) hEff->ProjectionY("hEffPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hMulPt2  = (TH1D*) hMul->ProjectionY("hMulPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hRecPt2  = (TH1D*) hRec->ProjectionY("hRecPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hFakPt2  = (TH1D*) hFak->ProjectionY("hFakPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  TH1D* hSecPt2  = (TH1D*) hSec->ProjectionY("hSecPt2",etabin10m,etabin10p,occbin50,occbin100,"e");
  
  TH1D* hDumPt = new TH1D("hDumPt",";p_{T} [GeV/c]",80,0.1,300.0); hDumPt->SetMaximum(1.0);
  hDumPt->GetXaxis()->CenterTitle(); hDumPt->GetYaxis()->SetTitleOffset(1.8); hDumPt->SetTitle("|#eta| < 1");
  TH1D* hDumPt2 = (TH1D*) hDumPt->Clone("hDumPt2"); hDumPt2->SetMaximum(0.1); 
  TH1D* hDumPt3 = (TH1D*) hDumPt->Clone("hDumPt3"); hDumPt3->SetMaximum(0.00049); 

  // Efficiency
  TGraphAsymmErrors *gEffEta = new TGraphAsymmErrors(); gEffEta->SetName("gEffEta");
  gEffEta->BayesDivide(hEffEta,hSimEta);
  gEffEta->SetMarkerStyle(25);
  gEffEta->SetLineStyle(2);
  gEffEta->SetLineColor(2);
  gEffEta->SetMarkerColor(2);

  TGraphAsymmErrors *gEffPt = new TGraphAsymmErrors(); gEffPt->SetName("gEffPt");
  gEffPt->BayesDivide(hEffPt,hSimPt);
  gEffPt->SetMarkerStyle(25);
  gEffPt->SetLineColor(2);
  gEffPt->SetMarkerColor(2);

  TGraphAsymmErrors *gEffEta2 = new TGraphAsymmErrors(); gEffEta2->SetName("gEffEta2");
  gEffEta2->BayesDivide(hEffEta2,hSimEta2);
  gEffEta2->SetMarkerStyle(24);
  gEffEta2->SetLineColor(4);
  gEffEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gEffPt2 = new TGraphAsymmErrors(); gEffPt2->SetName("gEffPt2");
  gEffPt2->BayesDivide(hEffPt2,hSimPt2);
  gEffPt2->SetMarkerStyle(24);
  gEffPt2->SetLineStyle(4);
  gEffPt2->SetLineColor(4);
  gEffPt2->SetMarkerColor(4);

  TLegend *legEta = new TLegend(0.35,0.15,0.65,0.30);
  legEta->SetFillColor(0); legEta->SetBorderSize(0);
  legEta->AddEntry(gEffEta,"0-50%","lp");
  legEta->AddEntry(gEffEta2,"50-100%","lp");

  TLegend *legPt = new TLegend(0.35,0.2,0.65,0.35);
  legPt->SetFillColor(0); legPt->SetBorderSize(0);
  legPt->AddEntry(gEffPt,"0-50%","lp");
  legPt->AddEntry(gEffPt2,"50-100%","lp");

  TCanvas* c7 = makeMultiCanvas("c7", "Efficiency Fraction", 2,1 );
  hDumEtaEff=(TH1F*) hDumEta->Clone("hDumEtaEff"); fixedFontHist1D(hDumEtaEff,1.05,1.2);
  hDumEtaEff->GetYaxis()->SetTitle("Absolute efficiency");
  hDumPtEff=(TH1F*) hDumPt->Clone("hDumPtEff"); fixedFontHist1D(hDumPtEff,1.05,1.2);
  hDumPtEff->GetYaxis()->SetTitle("Absolute efficiency");
  c7->cd(1); gPad->SetTicks(); c7->GetPad(1)->SetLeftMargin(0.12); c7->GetPad(1)->SetBottomMargin(0.13); c7->GetPad(1)->SetLogx(0); hDumEtaEff->Draw(); gEffEta->Draw("pc"); gEffEta2->Draw("pc"); legEta->Draw();
  c7->cd(2); gPad->SetTicks(); c7->GetPad(2)->SetLeftMargin(0.12); c7->GetPad(2)->SetBottomMargin(0.13); c7->GetPad(2)->SetLogx(); hDumPtEff->Draw(); gEffPt->Draw("pc"); gEffPt2->Draw("pc"); legPt->Draw();
  saveCanvas(c7, "files", "AbsoluteEfficiency3D");

  // Multiple Reco
  TGraphAsymmErrors *gMulEta = new TGraphAsymmErrors(); gMulEta->SetName("gMulEta");
  gMulEta->BayesDivide(hMulEta,hSimEta);
  gMulEta->SetMarkerStyle(25);
  gMulEta->SetLineStyle(2);
  gMulEta->SetLineColor(2);
  gMulEta->SetMarkerColor(2);

  TGraphAsymmErrors *gMulPt = new TGraphAsymmErrors(); gMulPt->SetName("gMulPt");
  gMulPt->BayesDivide(hMulPt,hSimPt);
  gMulPt->SetMarkerStyle(25);
  gMulPt->SetLineColor(2);
  gMulPt->SetMarkerColor(2);

  TGraphAsymmErrors *gMulEta2 = new TGraphAsymmErrors(); gMulEta2->SetName("gMulEta2");
  gMulEta2->BayesDivide(hMulEta2,hSimEta2);
  gMulEta2->SetMarkerStyle(24);
  gMulEta2->SetLineColor(4);
  gMulEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gMulPt2 = new TGraphAsymmErrors(); gMulPt2->SetName("gMulPt2");
  gMulPt2->BayesDivide(hMulPt2,hSimPt2);
  gMulPt2->SetMarkerStyle(24);
  gMulPt2->SetLineStyle(4);
  gMulPt2->SetLineColor(4);
  gMulPt2->SetMarkerColor(4);

  TCanvas *c8 = makeMultiCanvas("c8","Multiple Fraction", 2,1);
  hDumEtaMul=(TH1F*) hDumEta3->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaMul, 1.05,1.2); hDumEtaMul->GetYaxis()->SetRangeUser(0,0.0009);
  hDumEtaMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  hDumPtMul=(TH1F*) hDumPt3->Clone("hDumPtMul"); fixedFontHist1D(hDumPtMul, 1.05, 1.2); hDumPtMul->GetYaxis()->SetRangeUser(0,0.0009);
  hDumPtMul->GetYaxis()->SetTitle("Multiple Reconstruction Fraction");
  legEta2 = (TLegend*) legEta->Clone(); legEta2->SetY1(0.65); legEta2->SetY2(0.85);
  legPt2 = (TLegend*) legPt->Clone(); legPt2->SetY1(0.65); legPt2->SetY2(0.85);
  c8->cd(1); gPad->SetLogx(0); gPad->SetTicks(); c8->GetPad(1)->SetLeftMargin(0.12); c8->GetPad(1)->SetBottomMargin(0.13); hDumEtaMul->Draw(); gMulEta->Draw("pc"); gMulEta2->Draw("pc"); legEta2->Draw();
  c8->cd(2); gPad->SetLogx(1); gPad->SetTicks(); c8->GetPad(2)->SetLeftMargin(0.12); c8->GetPad(2)->SetBottomMargin(0.13); hDumPtMul->Draw(); gMulPt->Draw("pc"); gMulPt2->Draw("pc"); legPt2->Draw();
  saveCanvas(c8, "files", "MultipleReconstruction3D");
  
  // Fakes
  TGraphAsymmErrors *gFakEta = new TGraphAsymmErrors();  gFakEta->SetName("gFakEta");
  gFakEta->BayesDivide(hFakEta,hRecEta);
  gFakEta->SetMarkerStyle(25);
  gFakEta->SetLineStyle(2);
  gFakEta->SetLineColor(2);
  gFakEta->SetMarkerColor(2);

  TGraphAsymmErrors *gFakPt = new TGraphAsymmErrors(); gFakPt->SetName("gFakPt");
  gFakPt->BayesDivide(hFakPt,hRecPt);
  gFakPt->SetMarkerStyle(25);
  gFakPt->SetLineColor(2);
  gFakPt->SetMarkerColor(2);

  TGraphAsymmErrors *gFakEta2 = new TGraphAsymmErrors(); gFakEta2->SetName("gFakEta2");
  gFakEta2->BayesDivide(hFakEta2,hRecEta2);
  gFakEta2->SetMarkerStyle(24);
  gFakEta2->SetLineColor(4);
  gFakEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gFakPt2 = new TGraphAsymmErrors();  gFakPt2->SetName("gFakPt2");
  gFakPt2->BayesDivide(hFakPt2,hRecPt2);
  gFakPt2->SetMarkerStyle(24);
  gFakPt2->SetLineStyle(4);
  gFakPt2->SetLineColor(4);
  gFakPt2->SetMarkerColor(4);

  TCanvas* c9 = makeMultiCanvas("c9", "Fake Fraction", 2,1);
  hDumEtaFak=(TH1F*) hDumEta2->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaFak, 1.05,1.2); hDumEtaFak->GetYaxis()->SetRangeUser(0.,0.09);
  hDumEtaFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  hDumPtFak=(TH1F*) hDumPt2->Clone("hDumPtMul"); fixedFontHist1D(hDumPtFak, 1.05,1.2); hDumPtFak->GetYaxis()->SetRangeUser(0,1);
  hDumPtFak->GetYaxis()->SetTitle("Fake Reconstruction Fraction");
  c9->cd(1); hDumEtaFak->Draw(); gFakEta->Draw("pc"); gFakEta2->Draw("pc"); legEta2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.12); gPad->SetBottomMargin(0.13);
  c9->cd(2); hDumPtFak->Draw(); gFakPt->Draw("pc"); gFakPt2->Draw("pc"); legPt2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.12); gPad->SetBottomMargin(0.13); gPad->SetLogx(1);
  saveCanvas(c9, "files", "FakeRate3D");

  // Secondaries
  TGraphAsymmErrors *gSecEta = new TGraphAsymmErrors(); gSecEta->SetName("gSecEta");
  gSecEta->BayesDivide(hSecEta,hRecEta);
  gSecEta->SetMarkerStyle(25);
  gSecEta->SetLineStyle(2);
  gSecEta->SetLineColor(2);
  gSecEta->SetMarkerColor(2);

  TGraphAsymmErrors *gSecPt = new TGraphAsymmErrors(); gSecPt->SetName("gSecPt");
  gSecPt->BayesDivide(hSecPt,hRecPt);
  gSecPt->SetMarkerStyle(25);
  gSecPt->SetLineColor(2);
  gSecPt->SetMarkerColor(2);

  TGraphAsymmErrors *gSecEta2 = new TGraphAsymmErrors(); gSecEta2->SetName("gSecEta2");
  gSecEta2->BayesDivide(hSecEta2,hRecEta2);
  gSecEta2->SetMarkerStyle(24);
  gSecEta2->SetLineColor(4);
  gSecEta2->SetMarkerColor(4);

  TGraphAsymmErrors *gSecPt2 = new TGraphAsymmErrors();  gSecPt2->SetName("gSecPt2");
  gSecPt2->BayesDivide(hSecPt2,hRecPt2);
  gSecPt2->SetMarkerStyle(24);
  gSecPt2->SetLineStyle(4);
  gSecPt2->SetLineColor(4);
  gSecPt2->SetMarkerColor(4);

  TCanvas* c10 = makeMultiCanvas("c10", "Secondary Fraction", 2, 1);
  hDumEtaSec=(TH1F*) hDumEta2->Clone("hDumEtaMul"); fixedFontHist1D(hDumEtaSec, 1.05,1.3); hDumEtaSec->GetYaxis()->SetRangeUser(0.,0.012);
  hDumEtaSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  hDumPtSec=(TH1F*) hDumPt2->Clone("hDumPtMul"); fixedFontHist1D(hDumPtSec, 1.05, 1.3);hDumPtSec->GetYaxis()->SetRangeUser(0.,0.1);
  hDumPtSec->GetYaxis()->SetTitle("Non-Primary Reconstruction Fraction");
  c10->cd(1); hDumEtaSec->Draw(); gSecEta->Draw("pc"); gSecEta2->Draw("pc"); legEta2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.15); gPad->SetBottomMargin(0.13); 
  c10->cd(2); hDumPtSec->Draw(); gSecPt->Draw("pc"); gSecPt2->Draw("pc"); legPt2->Draw();
  gPad->SetTicks(); gPad->SetLeftMargin(0.15); gPad->SetBottomMargin(0.13); gPad->SetLogx(1);
  saveCanvas(c10, "files", "SecondaryReconstruction3D");

  TFile *fout = new TFile("test.root","RECREATE");
  gEffPt->Write(); gEffPt2->Write(); gEffEta->Write(); gEffEta2->Write();
  gMulPt->Write(); gMulPt2->Write(); gMulEta->Write(); gMulEta2->Write();
  gFakPt->Write(); gFakPt2->Write(); gFakEta->Write(); gFakEta2->Write();
  gSecPt->Write(); gSecPt2->Write(); gSecEta->Write(); gSecEta2->Write();
  fout->Close();
}
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);
  }
}
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);
        }
    }
}
示例#6
0
int bbSaveImage( bbImage *i,BBStr *str,int n ){
	debugImage( i,n );
	string t=*str;delete str;
	gxCanvas *c=i->getFrames()[n];
	return saveCanvas( c,t ) ? 1 : 0;
}
示例#7
0
int bbSaveBuffer( gxCanvas *c,BBStr *str ){
	debugCanvas( c );
	string t=*str;delete str;
	return saveCanvas( c,t ) ? 1 : 0;
}
示例#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);
  }
}