コード例 #1
0
void TestFrameLayout::headerPerPage()
{
    Helper helper;
    m_frames.clear();
    KWPage page = helper.pageManager->begin();
    KWFrameLayout bfl(helper.pageManager, m_frames);
    connect(&bfl, SIGNAL(newFrameSet(KWFrameSet*)), this, SLOT(addFS(KWFrameSet*)));

    KWPageStyle myStyle("myStyle");
    myStyle.setHeaderPolicy(Words::HFTypeUniform);
    helper.pageManager->addPageStyle(myStyle);
    KWPage page2 = helper.pageManager->appendPage(myStyle);
    QVERIFY(page.pageStyle() != page2.pageStyle());
    QCOMPARE(bfl.m_pageStyles.count(), 0);

    KWTextFrameSet *fs = bfl.getOrCreate(Words::OddPagesHeaderTextFrameSet, page);
    QVERIFY(fs);
    QCOMPARE(fs->textFrameSetType(), Words::OddPagesHeaderTextFrameSet);

    QCOMPARE(bfl.m_pageStyles.count(), 1);
    QVERIFY(bfl.m_pageStyles.contains(page.pageStyle()));
    KWFrameLayout::FrameSets fsets = bfl.m_pageStyles[page.pageStyle()];
    QCOMPARE(fsets.oddHeaders, fs);
    QCOMPARE(fsets.evenHeaders, (void*) 0);
    QCOMPARE(fsets.oddFooters, (void*) 0);
    QCOMPARE(fsets.evenFooters, (void*) 0);

    KWTextFrameSet *fs2 = bfl.getOrCreate(Words::OddPagesHeaderTextFrameSet, page2);
    QVERIFY(fs2);
    QCOMPARE(fs2->textFrameSetType(), Words::OddPagesHeaderTextFrameSet);

    QVERIFY(fs != fs2);
    QCOMPARE(bfl.getOrCreate(Words::OddPagesHeaderTextFrameSet, page2), fs2);
    QCOMPARE(bfl.getOrCreate(Words::OddPagesHeaderTextFrameSet, page), fs);

    QCOMPARE(bfl.m_pageStyles.count(), 2);
    QVERIFY(bfl.m_pageStyles.contains(page.pageStyle()));
    QVERIFY(bfl.m_pageStyles.contains(page2.pageStyle()));
    fsets = bfl.m_pageStyles[page.pageStyle()];
    QCOMPARE(fsets.oddHeaders, fs);
    QCOMPARE(fsets.evenHeaders, (void*) 0);
    QCOMPARE(fsets.oddFooters, (void*) 0);
    QCOMPARE(fsets.evenFooters, (void*) 0);
    KWFrameLayout::FrameSets fsets2 = bfl.m_pageStyles[page2.pageStyle()];
    QCOMPARE(fsets2.oddHeaders, fs2);
    QCOMPARE(fsets2.evenHeaders, (void*) 0);
    QCOMPARE(fsets2.oddFooters, (void*) 0);
    QCOMPARE(fsets2.evenFooters, (void*) 0);
}
コード例 #2
0
ファイル: qscilexerasm.cpp プロジェクト: rserg/just_asmide
void QsciLexerAsm::defaultPaint(QString data, QVector<QString> list, int start,int style)
{
    int cont = 0;
    foreach(QString str, list)
    {
        data = data.toLower();
        int len = data.count(str);
        for(int i = 0;i < len;++i)
        {
            int myfirst = data.indexOf(str + " ",cont);
            if(myfirst != -1)
            {
                cont += myfirst+1;
                this->startStyling(start+myfirst);
               // qDebug() << str;
                this->setStyling(str.length(), myStyle(style));
            }

            //this->startStyling(start+myfirst);
        }
    }
コード例 #3
0
ファイル: main.cpp プロジェクト: LI-COR/eddypro-gui
/// \fn int main(int argc, char *argv[])
/// \brief Entry point of the application.
///
/// \file main.cpp
/// \brief Entry point for the GUI application
///
/// This file contains main().
///////////////////
/// \brief main
/// \param argc
/// \param argv
/// \return
///
int main(int argc, char *argv[])
{
#if QT_DEBUG
    // logger creation
#endif

    // initialize resources at startup (qrc file loading)
#if defined(Q_OS_MAC)
    Q_INIT_RESOURCE(eddypro_mac);
#elif defined(Q_OS_WIN)
    Q_INIT_RESOURCE(eddypro_win);
#else
    Q_INIT_RESOURCE(eddypro_lin);
#endif

    qApp->setAttribute(Qt::AA_UseHighDpiPixmaps);

#if defined(Q_OS_MAC)
    qApp->setAttribute(Qt::AA_DontShowIconsInMenus);

    // workaround necessary in case of widget painting issues
//    qApp->setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
#endif

    QApplication::setColorSpec(QApplication::ManyColor);
//    QApplication::setDesktopSettingsAware(false);

    QApplication::setEffectEnabled(Qt::UI_AnimateMenu);
    QApplication::setEffectEnabled(Qt::UI_FadeMenu);
    QApplication::setEffectEnabled(Qt::UI_AnimateCombo);
    QApplication::setEffectEnabled(Qt::UI_AnimateTooltip);
    QApplication::setEffectEnabled(Qt::UI_FadeTooltip);

    ///
    /// A set of flags to workaroud issues in specific cases
    ///
    //  QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
    QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);
    //  QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
    //  QCoreApplication::setAttribute(Qt::AA_ForceRasterWidgets);
    //  QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
    //  QCoreApplication::setAttribute(Qt::AA_SetPalette);
    //  QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);

    QApplication app(argc, argv);
    app.setApplicationName(Defs::APP_NAME);
    app.setApplicationDisplayName(Defs::APP_NAME);
    app.setOrganizationName(Defs::ORG_NAME);
    app.setOrganizationDomain(Defs::ORG_DOMAIN);

    qDebug() << "currentUnicodeVersion" << QChar::currentUnicodeVersion();

    // fix order of library paths
    // see https://bugreports.qt-project.org/browse/QTBUG-40738
    QString executable = QLatin1String(argv[0]);
    QtHelper::prependApplicationPathToLibraryPaths(executable);
    qDebug() << "library paths" << QApplication::libraryPaths();

#if defined(Q_OS_MAC)
    // file to open at start
    auto fileToOpen = QString();
    // install event filter to open clicked files in Mac OS X
    OpenFileFilter openFileFilter;
    app.installEventFilter(&openFileFilter);
    app.processEvents();
    auto requestedFile = openFileFilter.fileRequested();
    if (requestedFile.endsWith(QStringLiteral(".eddypro")))
    {
        fileToOpen = requestedFile;
    }
#endif

    // custom ttf setup
    int fontId_1 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Regular.ttf"));
    Q_ASSERT(fontId_1 != -1);
    qDebug() << QFontDatabase::applicationFontFamilies(fontId_1);
    int fontId_2 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Italic.ttf"));
    Q_ASSERT(fontId_2 != -1);
    qDebug() << QFontDatabase::applicationFontFamilies(fontId_2);
    int fontId_3 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Bold.ttf"));
    Q_ASSERT(fontId_3 != -1);
    qDebug() << QFontDatabase::applicationFontFamilies(fontId_3);
    int fontId_4 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-Semibold.ttf"));
    Q_ASSERT(fontId_4 != -1);
    qDebug() << QFontDatabase::applicationFontFamilies(fontId_4);
    int fontId_5 = QFontDatabase::addApplicationFont(QStringLiteral(":/fonts/fonts/OpenSans-BoldItalic.ttf"));
    Q_ASSERT(fontId_5 != -1);
    qDebug() << QFontDatabase::applicationFontFamilies(fontId_5);

    // load translation file embedded in resources
    QTranslator appTranslator;
    bool ok = appTranslator.load(QStringLiteral(":/tra/en"));
    qDebug() << "loading translation:" << ok;
    app.installTranslator(&appTranslator);

    // working dir
    QDir dir = QDir::current();
    qDebug() << "current dir" << dir.absolutePath();

    QString currentWorkingDir = QDir::currentPath();
    QString installationDir = qApp->applicationDirPath();
    qDebug() << "currentWorkingDir" << currentWorkingDir;
    qDebug() << "installationDir" << installationDir;
    if (currentWorkingDir != installationDir)
    {
        QDir::setCurrent(installationDir);
    }
    qDebug() << "currentWorkingDir" << QDir::currentPath();
    qDebug() << "currentWorkingDir" << QCoreApplication::applicationDirPath();

    // styles
    qDebug() << "------------------------------------------------------------";
    qDebug() << "Default Style: " << app.style()->metaObject()->className();

    MyStyle myStyle(app.style()->objectName());
    app.setStyle(&myStyle);

#if defined(Q_OS_WIN)
    FileUtils::loadStyleSheetFile(QStringLiteral(":/css/winstyle"));
#elif defined(Q_OS_MAC)
    FileUtils::loadStyleSheetFile(QStringLiteral(":/css/macstyle"));
#elif defined(Q_OS_LINUX)
    FileUtils::loadStyleSheetFile(QStringLiteral(":/css/linstyle"));
#endif

    QString appEnvPath = FileUtils::setupEnv();
    if (appEnvPath.isEmpty())
    {
        WidgetUtils::critical(nullptr,
                              QObject::tr("Cannot proceed"),
                              QObject::tr("Home Path not available."));
        return 1000;
    }
    qDebug() << "appEnvPath" << appEnvPath;

    // check for command line arguments
    QTextStream stream(stdout);

//#ifdef QT_DEBUG
//    bool getLogFile = true;
//#else
    bool getLogFile = false;
//#endif
    QString filename = doArgs(app.arguments(), stream, &getLogFile);
    qDebug() << "filename:" << filename;
    qDebug() << "getLogFile:" << getLogFile;

#if defined(Q_OS_MAC)
    if (!fileToOpen.isEmpty())
    {
        filename = fileToOpen;
    }
#endif

    // log file
    QFile logFile(appEnvPath
                  + QLatin1Char('/')
                  + Defs::LOG_FILE_DIR
                  + QLatin1Char('/')
                  + Defs::APP_NAME_LCASE
                  + QStringLiteral("_gui.")
                  + Defs::LOG_FILE_EXT);
    if (getLogFile)
    {
        if (logFile.size() > 1048576)
            logFile.remove();

        if (logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            outputStream = new QTextStream(&logFile);
            QtMessageHandler oldMsgHandler(qInstallMessageHandler(logOutput));
            Q_UNUSED(oldMsgHandler);
        }
        else
        {
            qDebug() << "Error opening logFile file '" << Defs::APP_NAME_LCASE
                     << "'. All debug output redirected to console.";
        }
    }

    // create and show splash screen
    QPixmap pixmap(QStringLiteral(":/icons/splash-img"));
#if defined(Q_OS_MAC)
    pixmap.setDevicePixelRatio(2.0);
#endif
    CustomSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint);
    auto show_splash =
        GlobalSettings::getFirstAppPersistentSettings(Defs::CONFGROUP_GENERAL,
                                                      Defs::CONF_GEN_SHOW_SPLASH,
                                                      true).toBool();

#if defined(Q_OS_MAC)
    auto is_full_screen_set =
        GlobalSettings::getFirstAppPersistentSettings(Defs::CONFGROUP_WINDOW,
                                                      Defs::CONF_WIN_FULLSCREEN,
                                                      true).toBool();
    if (is_full_screen_set)
    {
        show_splash = false;
    }
#endif
    qDebug() << "show_splash:" << show_splash;

    if (show_splash)
    {
        QFont splashFont;
        splashFont.setFamily(QStringLiteral("Open Sans"));
        splashFont.setBold(false);
        splashFont.setPixelSize(12);

        splash.setFont(splashFont);
        splash.setMessageRect(QRect(0, 427, 600, 25), Qt::AlignCenter); // Setting the message position.
        splash.show();
        splash.showStatusMessage(QObject::tr("Initializing..."));
    }
    qApp->processEvents();

    QLocale::setDefault(QLocale::C);

    if (show_splash)
    {
        splash.showStatusMessage(QObject::tr("Loading..."));
        splash.setProgressValue(20);
        splash.setProgressValue(30);
        splash.repaint();
    }
    qApp->processEvents();

//#if defined(Q_OS_MAC)
//    MainWindow mainWin(filename, appEnvPath, &splash, 0,
//                       Qt::WindowFlags()
//                       Window|WindowTitleHint|WindowSystemMenuHint|WindowMinMaxButtonsHint|WindowCloseButtonHint|WindowFullscreenButtonHint
//                       Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint
//                       );
//#elif defined(Q_OS_WIN)
    MainWindow mainWin(filename, appEnvPath, &splash);
//#endif

    if (show_splash)
    {
        splash.setProgressValue(40);
        splash.setProgressValue(50);
        splash.setProgressValue(60);
    }
    mainWin.show();

    if (show_splash)
    {
        splash.setProgressValue(70);
        splash.setProgressValue(80);
        splash.clearMessage();
        splash.showStatusMessage(QObject::tr("Loading complete."));
        splash.setProgressValue(90);
        splash.setProgressValue(100);
        splash.repaint();
    }
//    qApp->processEvents();

    qDebug() << "applicationDisplayName" << qApp->applicationDisplayName();

#if defined(Q_OS_MAC)
    qDebug() << "____________________________________________________";
    auto docExtraction = extractDocs(installationDir);
    qDebug() << "docs.zip extraction:" << docExtraction;
    qDebug() << "____________________________________________________";
#endif
    qDebug() << "++++++++++++++++++++++++++++++++++++++++++++++++++++";

    const int returnVal = app.exec();

    // cleanup
//    if (logFile)
//    {
//        logFile->close();
//        delete logFile;
//    }

    if (outputStream)
    {
        delete outputStream;
    }

    return returnVal;
}
コード例 #4
0
void getMCcorrectionfactors(TString func = "exp"){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  // ---
  // ERROR band plot
  // ---
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle("data/MC top Pt errorband");
  // drawing
  dummy->GetYaxis()->SetTitle("(Data / Simulation) SF (#sqrt{s}=8 TeV)");
  dummy->GetYaxis()->SetRangeUser(0.35, 1.65);
  dummy->SetFillColor(10);
  dummy->SetLineColor(10);
  dummy->Draw("axis");
  // extract parameters
  double a=function8->GetParameter(0);
  double b=function8->GetParameter(1);
  // turning point
  double min=0;
  double max=500;
  double TP=-a/b;
  // get functions for high, low and central
  TF1* centralErr=new TF1("centralErr",def,min, max);
  centralErr->SetParameter(0, a);
  centralErr->SetParameter(1, b);
  TF1* upErr=new TF1("upErr",def,min, max);
  upErr->SetParameter(0, 2*a);
  upErr->SetParameter(1, 2*b);
  TF1* dnErr=new TF1("upErr",def,min, max);
  dnErr->SetParameter(0, 0.);
  dnErr->SetParameter(1, 0.);
  // draw errorbands
  upErr->SetFillStyle(1001);
  dnErr->SetFillStyle(1001);
  upErr->SetLineColor(10);
  dnErr->SetLineColor(10);
  upErr->SetFillColor(colorband);
  upErr->SetRange(min,TP);
  upErr->DrawClone("hist same");
  dnErr->SetFillColor(10);
  dnErr->SetLineColor(10);
  dnErr->SetRange(min,TP);
  dnErr->DrawClone("hist same");
  dnErr->SetFillColor(colorband);
  dnErr->SetLineColor(colorband);
  dnErr->SetRange(TP, max);
  dnErr->DrawClone("hist same");
  upErr->SetFillColor(10);
  upErr->SetLineColor(10);
  upErr->SetRange(TP, max);
  upErr->DrawClone("hist same");
  drawLine(TP, 0.35, TP, 1.05, 10, 2, 1);
  // draw central prediction
  centralErr->SetFillStyle(0);
  centralErr->SetFillColor(0);
  centralErr->SetLineColor(kBlue);
  centralErr->SetLineWidth(6);
  centralErr->SetLineColor(fit8color);
  centralErr->SetLineStyle(2);
  centralErr->Draw("hist same");
  // legend and labels
  dummy->Draw("axis same");
  TPaveText *label2 = new TPaveText();
  label2 -> SetX1NDC(gStyle->GetPadLeftMargin());
  label2 -> SetY1NDC(1.0-gStyle->GetPadTopMargin());
  label2 -> SetX2NDC(1.0-gStyle->GetPadRightMargin());
  label2 -> SetY2NDC(1.0);
  label2 -> SetTextFont(42);
  TString CMSlab2="";
  if(!PHD) CMSlab2+="CMS Preliminary, ";  
  CMSlab2+="19.7 fb^{-1} at #sqrt{s} = 8 TeV";
  label2->AddText(CMSlab2);
  label2->SetFillStyle(0);
  label2->SetBorderSize(0);
  label2->SetTextSize(0.04);
  label2->SetTextAlign(32);  
  double x12= 0.29;
  double x22= 0.86;
  label2->Draw("same");
  TLegend *leg3 = new TLegend(x12+0.05, 0.7, x22+0.05, 0.85);
  leg3->SetFillStyle(0);
  leg3->SetTextSize(0.035);
  leg3->SetBorderSize(0);
  leg3->SetHeader("#font[22]{Parametrisation: exp(a+b#upointx)}");
  TString entryErr=fitEntry8;
  entryErr.ReplaceAll("8 TeV: ", "");
  leg3->AddEntry(centralErr, entryErr , "L");
  leg3->AddEntry(dnErr     , "a,b #pm 100%", "F");
  leg3->Draw("same");
  //saving
  if(grey) plotCanvas_[1]->SetGrayscale();
  plotCanvas_[1]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweighting8TeVunc.eps");
  plotCanvas_[1]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweighting8TeVunc.png");
  
  // ratio legend
  if(sepLeg){
    addCanvas(plotCanvas_);
    plotCanvas_[plotCanvas_.size()-1]->cd(0);
    plotCanvas_[plotCanvas_.size()-1]->SetTitle("legend");
    leg0->Draw("same");
    leg1->Draw("same");
    if(grey) plotCanvas_[2]->SetGrayscale();
    plotCanvas_[2]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweightingLegend.eps");
    plotCanvas_[2]->Print("diffXSecFromSignal/plots/combined/2012/xSec/topPtReweightingLegend.png");
  }
}
コード例 #5
0
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);
  }
}
コード例 #6
0
TCanvas* getExtrapolFak(TString plotName, TString label, int verbose, TString outputFileFull, TString outputFileParton, TString outputFileHadron){

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

  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  TGaxis::SetMaxDigits(2);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  
  // open files
  TFile* fileFull   = TFile::Open(outputFileFull  , "READ");
  TFile* fileParton = TFile::Open(outputFileParton, "READ");
  TFile* fileHadron = TFile::Open(outputFileHadron, "READ");
  // dont associate new objects with file to be able to close it in the end
  gROOT->cd();
  // get canvas^3 for chosen cross section
  TCanvas* canvasFull   = (TCanvas*)(fileFull  ->Get("xSec/sysNo/"+plotName+"Norm")->Clone());
  TCanvas* canvasParton = (TCanvas*)(fileParton->Get("xSec/sysNo/"+plotName+"Norm")->Clone());
  TCanvas* canvasHadron = (TCanvas*)(fileHadron->Get("xSec/sysNo/"+plotName+"Norm")->Clone());
  
  // get data histos 
  TH1F* dataFull      = killEmptyBins((TH1F*)((canvasFull  ->GetPrimitive(plotName+"kData"))->Clone()));
  TH1F* dataRawParton = killEmptyBins((TH1F*)((canvasParton->GetPrimitive(plotName+"kData"))->Clone()));
  TH1F* dataRawHadron = killEmptyBins((TH1F*)((canvasHadron->GetPrimitive(plotName+"kData"))->Clone()));
  
  // use always the correct PS definition:
  //     hadron level for b-quarks and lepton
  //     parton level for all others
  TH1F* dataPS = ( (plotName.Contains("bq")||plotName.Contains("lep")) ? (TH1F*)dataRawHadron->Clone() : (TH1F*)dataRawParton->Clone() );

  // adjust style and labels
  TString PSlabel = ( (plotName.Contains("bq")||plotName.Contains("lep")) ? "hadron" : "parton" );
  int color = kBlue;
  if(PSlabel=="hadron") color-=4;
  dataPS->SetLineColor(color);
  dataPS->SetMarkerColor(color);
  histogramStyle(*dataFull, kData);
  dataFull->SetLineWidth(3);
  dataPS->SetLineWidth(3);
  if     (plotName=="lepPt") dataFull->GetXaxis()->SetRangeUser(0.,199.);
  else if(plotName=="bqPt" ) dataFull->GetXaxis()->SetRangeUser(0.,399.);
  else                       setXAxisRange(dataFull, plotName);
  double max=dataFull->GetMaximum();
  if(max<dataPS->GetMaximum()) max=dataPS->GetMaximum();
  dataFull->SetMaximum(1.3*max);
  dataFull->GetXaxis()->SetTitle(xSecLabelName(plotName));
  TString label2=label;
  TString label3="";
  if(label.Contains("/[GeV]")){
    label2.ReplaceAll("/[GeV]","");
    label3=" / [GeV]";
  }
  label2.ReplaceAll("/ ","");
  dataFull->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{d"+label2+"}"+label3);
  dataFull->GetYaxis()->SetNoExponent(false);
  dataFull->GetXaxis()->SetNoExponent(true);
  dataFull->SetTitle("");

  // create legend
  TLegend *leg0 = new TLegend(0.65, 0.762, 0.95, 0.89);
  leg0->SetFillStyle(0);
  leg0->SetBorderSize(0);
  leg0->SetHeader("phase spaces");
  leg0->AddEntry(dataFull, "extrapol. parton lv","L");
  leg0->AddEntry(dataPS  , "restricted "+PSlabel+" lv","L");

  // create label
  TPaveText *headerlabel = new TPaveText();
  headerlabel -> SetX1NDC(gStyle->GetPadLeftMargin());
  headerlabel -> SetY1NDC(1.0-gStyle->GetPadTopMargin());
  headerlabel -> SetX2NDC(1.0-gStyle->GetPadRightMargin());
  headerlabel -> SetY2NDC(1.0);
  headerlabel -> SetTextFont(42);
  headerlabel -> AddText("comparing 2011 data results");
  headerlabel->SetFillStyle(0);
  headerlabel->SetBorderSize(0);
  headerlabel->SetTextSize(0.04);
  headerlabel->SetTextAlign(32);

  // create extrapolation factor / ratio canvas
  std::vector<TCanvas*> plotCanvas_;
  addCanvas(plotCanvas_);
  plotCanvas_[0]->cd();
  plotCanvas_[0]->Draw();
  dataFull->Draw("hist");
  dataPS->Draw("hist same");
  leg0->Draw("same");
  headerlabel->Draw("same");
  DrawDecayChLabel("e/#mu + Jets Combined");
  drawRatio(dataPS, dataFull, 0., 2.4, myStyle, verbose, std::vector<double>(0), PSlabel+" PS", "extrapolated", "hist", kBlack);

  // close files
  fileFull  ->Close();
  fileParton->Close();
  fileHadron->Close();
  
  // return
  return plotCanvas_[0];
}
コード例 #7
0
void testTL1Resolution()
{
    std::shared_ptr<TStyle> myStyle(new TStyle(TDRStyle()));
    SetMyStyle(55, 0.07, myStyle.get());

    // Basic
    std::string sample = "Data";
    std::string triggerName = "SingleMu";
    std::string triggerTitle = "Single Muon";

    std::string run = "2016B_v1";
    std::string outDirBase = "/afs/cern.ch/work/s/sbreeze/L1TriggerStudiesOutput";
    std::vector<std::string> puType = {"0PU12","13PU19","20PU"};
    std::vector<int> puBins = {0,13,20,999};

    // std::string inDir = "/afs/cern.ch/work/s/sbreeze/public/jets_and_sums/160511_l1t-integration-v48p2/SingleMu/Ntuples";
    // std::string inDir = "/afs/cern.ch/work/s/sbreeze/public/jets_and_sums/160519_l1t-integration-v53p1/SingleMu_273301/Ntuples";
    // std::string inDir = "/afs/cern.ch/work/s/sbreeze/public/jets_and_sums/160602_r273450_SingleMu_l1t-int-v53p1";
    // std::string inDir = "/afs/cern.ch/work/s/sbreeze/public/jets_and_sums/160607_combinedRuns_SingleMu";
    std::string inDir = "/afs/cern.ch/work/s/sbreeze/public/jets_and_sums/160704_SingleMu2016Bv1_l1t-int-v67p0";
    std::shared_ptr<TL1EventClass> event(new TL1EventClass(inDir));

    std::vector<std::shared_ptr<TL1Resolution>> resolution;

    // caloMetBE
    resolution.emplace_back(new TL1Resolution());
    std::string outDir = outDirBase+"/"+resolution.front()->GetDate()+"_"+sample+"_"+"run-"+run+"_"+triggerName+"/Resolutions/";
    resolution[0]->SetBins(bins());
    resolution[0]->SetX("caloMetBE","Offline E_{T}^{miss}");
    resolution[0]->SetY("l1Met","L1 E_{T}^{miss}");
    resolution[0]->SetOutName(triggerName+"_caloMetBE_over_l1Met");
    resolution[0]->AddRelTitle("recoCaloMetBE","Offline E_{T}^{miss} (GeV)");
    resolution[0]->AddRelBins({20.,40.,60.,80.,100.,120.,140.});
    resolution[0]->SetAddMark("no HF, Offline E_{T}^{miss} > 40 GeV");

    // caloMet
    resolution.emplace_back(new TL1Resolution());
    resolution[1]->SetBins(bins());
    resolution[1]->SetX("caloMet","Offline E_{T}^{miss}");
    resolution[1]->SetY("l1MetHF","L1 E_{T}^{miss}");
    resolution[1]->SetOutName(triggerName+"_caloMet_over_l1MetHF");
    resolution[1]->AddRelTitle("recoCaloMetBE","Offline E_{T}^{miss} (GeV)");
    resolution[1]->AddRelBins({20.,40.,60.,80.,100.,120.,140.});
    resolution[1]->SetAddMark("HF, Offline E_{T}^{miss} > 40 GeV");

    // mht
    //resolution.emplace_back(new TL1Resolution());
    //resolution[1]->SetBins(bins());
    //resolution[1]->SetX("mht","Offline H_{T}^{miss}");
    //resolution[1]->SetY("l1mht","L1 H_{T}^{miss}");
    //resolution[1]->SetOutName(triggerName+"_recalcMht_over_l1Mht");
    //resolution[1]->AddRelTitle("recoMht","Offline H_{T}^{miss} (GeV)");
    //resolution[1]->AddRelBins({0.,10.,20.,30.,40.,50.,60.,70.,80.,100.});
    ////resolution[1]->SetAddMark("L1 ETM > 40 GeV");

    //// caloEttBE
    //resolution.emplace_back(new TL1Resolution());
    //resolution[2]->SetBins(bins());
    //resolution[2]->SetX("caloEttBE","Offline Total E_{T}");
    //resolution[2]->SetY("l1ett","L1 Total E_{T}");
    //resolution[2]->SetOutName(triggerName+"_caloEttBE_over_l1Ett");
    //resolution[2]->AddRelTitle("recoEtt","Offline Total E_{T} (GeV)");
    //resolution[2]->AddRelBins({0.,10.,20.,30.,40.,50.,60.,70.,80.,100.});
    ////resolution[2]->SetAddMark("L1 ETM > 40 GeV");

    //// htt
    //resolution.emplace_back(new TL1Resolution());
    //resolution[3]->SetBins(bins());
    //resolution[3]->SetX("htt","Offline Total H_{T}");
    //resolution[3]->SetY("l1htt","L1 Total H_{T}");
    //resolution[3]->SetOutName(triggerName+"_htt_over_l1Htt");
    //resolution[3]->AddRelTitle("recoHtt","Offline Total H_{T} (GeV)");
    //resolution[3]->AddRelBins({0.,10.,20.,30.,40.,50.,60.,70.,80.,100.});
    //resolution[3]->SetAddMark("Offline HTT > 100 GeV");

    // caloMetBE Phi
    //double p = TMath::Pi();
    //resolution.emplace_back(new TL1Resolution());
    //resolution[4]->SetBins(bins());
    //resolution[4]->SetX("caloMetBEPhi","Offline E_{T}^{miss} Phi");
    //resolution[4]->SetY("l1metphi","L1 E_{T}^{miss} Phi");
    //resolution[4]->SetOutName(triggerName+"_caloMetBEPhi_over_l1MetPhi");
    //resolution[4]->AddRelTitle("recoCaloMetPhiBE","Offline E_{T}^{miss} Phi");
    //resolution[4]->AddRelBins({-p,-0.75*p,-0.5*p,-0.25*p,0.,0.25*p,0.5*p,0.75*p,p});
    //resolution[0]->SetAddMark("L1 ETM > 40 GeV");

    // mht Phi
    //resolution.emplace_back(new TL1Resolution());
    //resolution[5]->SetBins(bins());
    //resolution[5]->SetX("mhtPhi","Offline H_{T}^{miss} Phi");
    //resolution[5]->SetY("l1httphi","L1 Total H_{T} Phi");
    //resolution[5]->SetOutName(triggerName+"_recalcMhtPhi_over_l1MhtPhi");
    //resolution[5]->AddRelTitle("recoMhtPhi","Offline H_{T}^{miss} Phi");
    //resolution[5]->AddRelBins({-p,-0.75*p,-0.5*p,-0.25*p,0.,0.25*p,0.5*p,0.75*p,p});
    //resolution[0]->SetAddMark("L1 ETM > 40 GeV");

    for(auto it=resolution.begin(); it!=resolution.end(); ++it)
    {
        (*it)->SetSample(sample,"");
        (*it)->SetTrigger(triggerName,triggerTitle);
        (*it)->SetRun(run);
        (*it)->SetOutDir(outDir);
        (*it)->SetPuType(puType);
        (*it)->SetPuBins(puBins);
        (*it)->InitPlots();
    }
    
    unsigned NEntries = event->GetPEvent()->GetNEntries();
    while( event->Next() )
    {
        unsigned position = event->GetPEvent()->GetPosition()+1;
        TL1Progress::PrintProgressBar(position, NEntries);

        int pu = event->GetPEvent()->fVertex->nVtx;
        auto sums = event->GetPEvent()->fSums;

        if( !event->fMuonFilterPassFlag ) continue;

        // MET
        double recoMet = sums->caloMetBE;
        double l1Met = event->fL1Met;

        double recoMetHF = sums->caloMet;
        double l1MetHF = event->fL1MetHF;
        if( event->fMetFilterPassFlag )
        {
            if( recoMet > 40.0 && l1Met != 0.0 )
                resolution[0]->Fill(recoMet, l1Met, pu);
            //resolution[0]->RelFill(recoMet, l1Met, pu, {recoMet});
            if( recoMetHF > 40.0 && l1MetHF != 0.0 )
                resolution[1]->Fill(recoMetHF, l1MetHF, pu);
        }

        // MET Phi
        //double recoMetPhi = event->GetPEvent()->fSums->caloMetPhiBE;
        //double l1MetPhi = event->fL1MetPhi;
        //if( recoMet != 0.0 && l1Met != 0.0 )
        //    resolution[4]->Fill(FoldPhi(recoMetPhi), FoldPhi(l1MetPhi), pu);
        //resolution[4]->RelFill(FoldPhi(recoMetPhi), FoldPhi(l1MetPhi), pu, {FoldPhi(recoMetPhi)});

    }

//    resolution[0]->DrawPlots();
//    resolution[3]->DrawPlots();
    for(auto it=resolution.begin(); it!=resolution.end(); ++it)
        (*it)->DrawPlots();
        
}
コード例 #8
0
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);
        }
    }
}
コード例 #9
0
TCanvas* getRatio(TString plotName, int verbose, TString outputFile){
  // ============================
  //  Set Root Style
  // ============================
  TStyle myStyle("HHStyle","HHStyle");
  setHHStyle(myStyle);
  TGaxis::SetMaxDigits(2);
  myStyle.cd();
  gROOT->SetStyle("HHStyle");
  
  // draw data uncertainties as bands
  bool bands=true;

  // compare current with old result
  bool compare=false;
  TString oldResult="/afs/naf.desy.de/group/cms/scratch/tophh/tmp/OldCombination/";

  // open file
  TFile* file = TFile::Open(outputFile, "READ");
  // dont associate new objects with file to be able to close it in the end
  gROOT->cd();
  // get canvas for chosen cross section
  TCanvas* canvas = (TCanvas*)(file->Get("finalXSec/"+plotName+"Norm")->Clone());
  // GET DATA: with final errors from canvas
  TGraphAsymmErrors* dataRaw  = (TGraphAsymmErrors*)canvas->GetPrimitive("dataTotalError");
  TGraphAsymmErrors* dataStat = (TGraphAsymmErrors*)canvas->GetPrimitive("dataStatError");
  // GET DATA: create rebinned histo
  std::map< TString, std::vector<double> > binning_ = makeVariableBinning();
  int Nbins = std::abs(binning_[plotName][binning_[plotName].size()-1]-binning_[plotName][0])*100;
  if(plotName.Contains("topY")) Nbins/=10;
  if(verbose>1) std::cout << Nbins << std::endl;
  TH1F* datatemp= new TH1F("data"+plotName, "data"+plotName, Nbins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
  reBinTH1F(*datatemp, binning_[plotName], 0);
  // GET DATA: refill TGraphAsymmErrors to rebinned histo
  for(int bin=1; bin<=datatemp->GetNbinsX(); ++bin){
    if(verbose>1){
      std::cout << "bin: " << bin << std::endl;
      std::cout << dataRaw->GetY()[bin];
    }
    datatemp->SetBinContent(bin, dataRaw->GetY()[bin]);
    double err=dataRaw->GetErrorYhigh(bin);
    if(err<dataRaw->GetErrorYlow(bin)) err=dataRaw->GetErrorYlow(bin);
    if(verbose>1) std::cout << " +- " << err << std::endl;
    datatemp->SetBinError(bin, err);
  }
  // GET DATA: delete empty bins
  TH1F* data=killEmptyBins((TH1F*)datatemp->Clone(), verbose);
  data->GetXaxis()->SetTitle(xSecLabelName(plotName));
  if(verbose>1){
    for(int bin=1; bin<=data->GetNbinsX(); ++bin){
      std::cout << "bin: " << bin << std::endl;
      std::cout << data->GetBinContent(bin) << " +- " << data->GetBinError(bin) << std::endl;
    }
  }

  // GET THEORY: binned curves from canvas
  TH1F* plotNNLO     = (TH1F*)canvas->GetPrimitive(plotName+"nnlo"   );
  TH1F* plotMadGraph = (TH1F*)canvas->GetPrimitive(plotName          );
  TH1F* plotmcatnlo  = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO2");
  if(!plotmcatnlo) plotmcatnlo  = (TH1F*)canvas->GetPrimitive(plotName+"MC@NLO");
  TGraphAsymmErrors* plotmcatnloerror = (TGraphAsymmErrors*)canvas->GetPrimitive(plotName+"MC@NLOerrorBand");
  TH1F* plotpowheg   = (TH1F*)canvas->GetPrimitive(plotName+"POWHEG");
  TH1F* plotpowhegherwig = (TH1F*)canvas->GetPrimitive(plotName+"POWHEGHERWIG");
  std::vector<TH1F*>hist_;
  // GET THEORY: delete empty bins
  // a) peturbative QCD
  TH1F* finalNNLO=0;
  if(plotNNLO        ){
    // delete empty bins
    TH1F* tempNNLO=killEmptyBins(plotNNLO, verbose);
    std::cout << tempNNLO->GetName() << std::endl;  
    // delete bins put of range
    int Nnnlobins = std::abs(binning_[plotName][binning_[plotName].size()-1]-binning_[plotName][0])*10;
    finalNNLO=new TH1F(tempNNLO->GetName(),tempNNLO->GetTitle(), Nnnlobins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
    reBinTH1F(*finalNNLO, binning_[plotName], 0);
    for(int bin=0; bin<=tempNNLO->GetNbinsX()+1; ++bin){
      double binlowedge=tempNNLO->GetBinLowEdge(bin); 
      if(plotName.Contains("topPt")&&binlowedge==1.) binlowedge=0.;
      //std::cout << "binlowedge: " << binlowedge << std::endl;      
      for(int binf=0; binf<=finalNNLO->GetNbinsX()+1; ++binf){
	//std::cout << "scanlowedge: " << finalNNLO->GetBinLowEdge(binf) << std::endl;
	if(binlowedge==finalNNLO->GetBinLowEdge(binf)){
	  //std::cout << "fits!" << std::endl;
	  finalNNLO->SetBinContent(binf, tempNNLO->GetBinContent(bin)) ;
	  finalNNLO->SetBinError(binf, tempNNLO->GetBinError(bin)); 
	}
      }
    }
  }
  // b) MC@NLO errorbands
  if(plotmcatnloerror&&plotmcatnlo){
    TH1F*   plotmcatnloerror1 =(TH1F*)((killEmptyBins(plotmcatnlo, verbose))->Clone((TString)plotmcatnloerror->GetName()+"Up"));
    TH1F*   plotmcatnloerror2 =(TH1F*)((killEmptyBins(plotmcatnlo, verbose))->Clone((TString)plotmcatnloerror->GetName()+"Dn"));
    for(int p=0; p<plotmcatnloerror->GetN(); ++p){
      plotmcatnloerror1->SetBinContent(p, plotmcatnloerror->GetErrorYhigh(p)+plotmcatnloerror->GetY()[p]);
      plotmcatnloerror2->SetBinContent(p, plotmcatnloerror->GetY()[p]-plotmcatnloerror->GetErrorYlow(p));
    }
    plotmcatnloerror1->SetLineStyle(1);
    plotmcatnloerror2->SetLineStyle(1);
    hist_.push_back( killEmptyBins(plotmcatnloerror1, verbose) );
    hist_.push_back( killEmptyBins(plotmcatnloerror2, verbose) );
  }
  // a1) Ahrens
  if(finalNNLO&&(plotName.Contains("ttbarMass")||plotName.Contains("ttbarPt"))) hist_.push_back(finalNNLO);
  // c) MC theories
  if(plotMadGraph    ) hist_.push_back( killEmptyBins(plotMadGraph    , verbose) );
  if(plotmcatnlo     ) hist_.push_back( killEmptyBins(plotmcatnlo     , verbose) );
  if(plotpowheg      ) hist_.push_back( killEmptyBins(plotpowheg      , verbose) );
  if(plotpowhegherwig) hist_.push_back( killEmptyBins(plotpowhegherwig, verbose) );
  // a2) Kidonakis
  if(finalNNLO&&(plotName.Contains("topY")||plotName.Contains("topPt"))) hist_.push_back(finalNNLO);
  if(compare){
    // reference results from a different analysis setup
    // GET DATA2: with final errors from canvas
    TString modfile=oldResult;
    modfile+=outputFile;
    TFile* file2 = TFile::Open(modfile, "READ");
    TCanvas* canvas2 = (TCanvas*)(file2->Get("finalXSec/"+plotName+"Norm")->Clone());
    TGraphAsymmErrors* data2Raw     = (TGraphAsymmErrors*)canvas2->GetPrimitive("dataTotalError");
    TH1F* data2temp= new TH1F("data"+plotName, "data"+plotName, Nbins, binning_[plotName][0], binning_[plotName][binning_[plotName].size()-1]);
    reBinTH1F(*data2temp, binning_[plotName], 0);
    // GET DATA2: refill TGraphAsymmErrors to rebinned histo
    for(int bin=1; bin<=data2temp->GetNbinsX(); ++bin){
      data2temp->SetBinContent(bin, data2Raw->GetY()[bin]);
      double err=data2Raw->GetErrorYhigh(bin);
      if(err<data2Raw->GetErrorYlow(bin)) err=data2Raw->GetErrorYlow(bin);
      data2temp->SetBinError(bin, err);
    }
    // GET DATA: delete empty bins
    TH1F* data2=killEmptyBins((TH1F*)data2temp->Clone(), verbose);
    data2->GetXaxis()->SetTitle(xSecLabelName(plotName));
    for(int bin=1; bin<=data2->GetNbinsX(); ++bin){
      std::cout << plotName << "bin: " << bin << std::endl;
      std::cout << "old: " << data2->GetBinContent(bin) << " +- " << data2->GetBinError(bin) << std::endl;
      if(data->GetNbinsX()==data2->GetNbinsX()) std::cout << "new: " << data->GetBinContent(bin)  << " +- " << data->GetBinError(bin)  << std::endl;
      if(bin==data2->GetNbinsX()) std::cout << std::endl;
    }
    data2->SetFillStyle(0);
    data2->SetMarkerColor(kBlack);
    data2->SetLineColor(kBlack);
    data2->SetLineWidth(3);
    hist_.push_back(data2);
  }

  // set axis colors to white because otherwise it spoils the ratio plot on top of it
  plotMadGraph->GetXaxis()->SetLabelColor(0);
  plotMadGraph->GetXaxis()->SetTitleColor(0);
  
  // create ratio canvas
  std::vector<TCanvas*> plotCanvas_;
  double max= 1.5;
  double min= 0.5;
  if(plotName.Contains("lepPt"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.29 : 1.29;}
  if(plotName.Contains("lepEta"   )){min=bands ? 0.85 : 0.75;max=bands ? 1.35 : 1.25;}
  if(plotName.Contains("bqPt"     )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.5  : 1.5 ;}
  if(plotName.Contains("bqEta"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  if(plotName.Contains("bbbarMass")){min=bands ? 0.3  : 0.3 ;max=bands ? 1.85 : 1.75;}
  if(plotName.Contains("bbbarPt"  )){min=bands ? 0.61 : 0.61;max=bands ? 1.49 : 1.39;}
  if(plotName.Contains("Njets"    )){min=bands ? 0.15 : 0.15;max=bands ? 1.95 : 1.95;}
  if(plotName.Contains("rhos"     )){min=bands ? 0.1  : 0.1 ;max=bands ? 2.59 : 1.9; }
  if(plotName.Contains("lbMass"   )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.45 : 1.35;}
  if(plotName.Contains("topPt"    )){
    if(     plotName.Contains("Sub" )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.59 : 1.59;}
    else if(plotName.Contains("Lead")){min=bands ? 0.7  : 0.7 ;max=bands ? 1.59 : 1.59;}
    else                              {min=bands ? 0.75 : 0.75;max=bands ? 1.59 : 1.59;}
  }
  if(plotName.Contains("topY"       )){min=bands ? 0.85 : 0.85;max=bands ? 1.19 : 1.15;}
  if(plotName.Contains("ttbarPt"    )){min=bands ? 0.5  : 0.5 ;max=bands ? 1.79 : 1.39;}
  if(plotName.Contains("ttbarY"     )){min=bands ? 0.8  : 0.8 ;max=bands ? 1.39 : 1.29;}
  if(plotName.Contains("ttbarMass"  )){min=bands ? 0.7  : 0.7 ;max=bands ? 1.5  : 1.5 ;}
  if(plotName.Contains("topPtTtbar" )){min=bands ? 0.6  : 0.6 ;max=bands ? 1.79 : 1.79;}
  if(plotName.Contains("ttbarDelPhi")){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  if(plotName.Contains("PhiStar"    )){min=bands ? 0.85 : 0.85;max=bands ? 1.25 : 1.15;}
  plotCanvas_.push_back(drawFinalResultRatio(data, min, max, myStyle, 0, hist_, (TCanvas*)(canvas->Clone()), -1, -1, dataStat, false, true, bands));
  plotCanvas_[0]->Draw();
  plotCanvas_[0]->Update();
  // close file
  file->Close();
  // return
  return plotCanvas_[0];
}
コード例 #10
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);
}
コード例 #11
0
void ATLASCMSCOMPARISON(TString quantity="ttbarMass"){

  bool cmssim=true;

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

  // ---
  //    top Pt 7 TeV
  // ---
  int Nbins7=7;
  if(     quantity=="topPt"    ) Nbins7=7;
  else if(quantity=="ttbarMass") Nbins7=5;
  else if(quantity=="ttbarY"   ) Nbins7=6;

  // CMS data
  TGraphAsymmErrors* CMSdata7 = new TGraphAsymmErrors(Nbins7);
  if(quantity=="topPt"){
    CMSdata7->SetPoint( 0, 25.0 , 0.004032 ); 
    CMSdata7->SetPoint( 1, 75.0 , 0.006746 ); 
    CMSdata7->SetPoint( 2, 125.0, 0.004737 ); 
    CMSdata7->SetPoint( 3, 175.0, 0.002506 ); 
    CMSdata7->SetPoint( 4, 225.0, 0.001140 ); 
    CMSdata7->SetPoint( 5, 300.0, 0.000334 ); 
    CMSdata7->SetPoint( 6, 575.0, 0.000019 ); 
    
    CMSdata7->SetPointError( 0, 25., 25., ( 5.5/100)*0.004032, ( 5.5/100)*0.004032 );
    CMSdata7->SetPointError( 1, 25., 25., ( 4.1/100)*0.006746, ( 4.1/100)*0.006746 );
    CMSdata7->SetPointError( 2, 25., 25., ( 4.0/100)*0.004737, ( 4.0/100)*0.004737 );
    CMSdata7->SetPointError( 3, 25., 25., ( 5.4/100)*0.002506, ( 5.4/100)*0.002506 );
    CMSdata7->SetPointError( 4, 25., 25., ( 5.6/100)*0.001140, ( 5.6/100)*0.001140 );
    CMSdata7->SetPointError( 5, 50., 50., ( 8.4/100)*0.000334, ( 8.4/100)*0.000334 );
    CMSdata7->SetPointError( 6, 225.,225., (14.1/100)*0.000019, (14.1/100)*0.000019 );
  }
  else if(quantity=="ttbarMass"){
    CMSdata7->SetPoint( 0, 350.0 , 0.002588 ); 
    CMSdata7->SetPoint( 1, 500.0 , 0.002685 ); 
    CMSdata7->SetPoint( 2, 625.0 , 0.000953 ); 
    CMSdata7->SetPoint( 3, 825.0 , 0.000232 ); 
    CMSdata7->SetPoint( 4, 1725.0, 0.000008 ); 
    
    CMSdata7->SetPointError( 0, 100., 100., ( 4.9 /100)*0.002588, (4.9 /100)*0.002588 );
    CMSdata7->SetPointError( 1, 50. , 50. , ( 6.9 /100)*0.002685, (6.9 /100)*0.002685 );
    CMSdata7->SetPointError( 2, 75. , 75. , ( 7.7 /100)*0.000953, (7.7 /100)*0.000953 );
    CMSdata7->SetPointError( 3, 125., 125., ( 14.4/100)*0.000232, (14.4/100)*0.000232 );
    CMSdata7->SetPointError( 4, 775., 775., ( 27.6/100)*0.000008, (27.6/100)*0.000008 );
  }
  else if(quantity=="ttbarY"){
    CMSdata7->SetPoint( 0, -1.75, 0.082140 ); 
    CMSdata7->SetPoint( 1, -0.75, 0.318979 ); 
    CMSdata7->SetPoint( 2, -0.25, 0.427823 ); 
    CMSdata7->SetPoint( 3,  0.25, 0.44591  ); 
    CMSdata7->SetPoint( 4,  0.75, 0.318820 ); 
    CMSdata7->SetPoint( 5,  1.75, 0.080457 );

    CMSdata7->SetPointError( 0, 0.75, 0.75, (8.1/100)*0.082140, (8.1/100)*0.082140 );
    CMSdata7->SetPointError( 1, 0.25, 0.25, (3.3/100)*0.318979, (3.3/100)*0.318979 );
    CMSdata7->SetPointError( 2, 0.25, 0.25, (3.0/100)*0.427823, (3.0/100)*0.427823 );
    CMSdata7->SetPointError( 3, 0.25, 0.25, (3.5/100)*0.44591 , (3.5/100)*0.44591  );
    CMSdata7->SetPointError( 4, 0.25, 0.25, (3.5/100)*0.318820, (3.5/100)*0.318820 );
    CMSdata7->SetPointError( 5, 0.75, 0.75, (5.9/100)*0.080457, (5.9/100)*0.080457 );
  }

  CMSdata7->SetLineWidth(3.);
  CMSdata7->SetMarkerSize(1.2);
  CMSdata7->SetMarkerStyle(24);
  CMSdata7->SetLineStyle(1);
  CMSdata7->SetMarkerColor(kBlue);
  CMSdata7->SetLineColor(kBlue);
  CMSdata7->SetFillStyle(3004);
  CMSdata7->SetFillColor(kBlue);

  // CMS MadGraph+Pythia(Z2*)
  TGraphAsymmErrors* CMSMadGraph7 = new TGraphAsymmErrors(Nbins7);
  if(quantity=="topPt"){
    CMSMadGraph7->SetPoint( 0, 25.0 , 0.003331 ); 
    CMSMadGraph7->SetPoint( 1, 75.0 , 0.006495 ); 
    CMSMadGraph7->SetPoint( 2, 125.0, 0.005077 ); 
    CMSMadGraph7->SetPoint( 3, 175.0, 0.002748 ); 
    CMSMadGraph7->SetPoint( 4, 225.0, 0.001282 ); 
    CMSMadGraph7->SetPoint( 5, 300.0, 0.000413 ); 
    CMSMadGraph7->SetPoint( 6, 575.0, 0.000027 ); 

    CMSMadGraph7->SetPointError( 0, 25., 25., 0., 0. );
    CMSMadGraph7->SetPointError( 1, 25., 25., 0., 0. );
    CMSMadGraph7->SetPointError( 2, 25., 25., 0., 0. );
    CMSMadGraph7->SetPointError( 3, 25., 25., 0., 0. );
    CMSMadGraph7->SetPointError( 4, 25., 25., 0., 0. );
    CMSMadGraph7->SetPointError( 5, 50., 50., 0., 0. );
    CMSMadGraph7->SetPointError( 6, 225., 225., 0., 0. );
  }
  else if(quantity=="ttbarMass"){
    CMSMadGraph7->SetPoint( 0, 350.0 , 0.002541 ); 
    CMSMadGraph7->SetPoint( 1, 500.0 , 0.002759 ); 
    CMSMadGraph7->SetPoint( 2, 625.0 , 0.000988 ); 
    CMSMadGraph7->SetPoint( 3, 825.0 , 0.000222 ); 
    CMSMadGraph7->SetPoint( 4, 1725.0, 0.000008 ); 
    
    CMSMadGraph7->SetPointError( 0, 100., 100., 0., 0. );
    CMSMadGraph7->SetPointError( 1, 50. , 50. , 0., 0. );
    CMSMadGraph7->SetPointError( 2, 75. , 75. , 0., 0. );
    CMSMadGraph7->SetPointError( 3, 125., 125., 0., 0. );
    CMSMadGraph7->SetPointError( 4, 775., 775., 0., 0. );
  }
  else if(quantity=="ttbarY"){
    CMSMadGraph7->SetPoint( 0, -1.75, 0.088374 ); 
    CMSMadGraph7->SetPoint( 1, -0.75, 0.319964 ); 
    CMSMadGraph7->SetPoint( 2, -0.25, 0.414022 ); 
    CMSMadGraph7->SetPoint( 3,  0.25, 0.415108 ); 
    CMSMadGraph7->SetPoint( 4,  0.75, 0.320370 ); 
    CMSMadGraph7->SetPoint( 5,  1.75, 0.088218 );

    CMSMadGraph7->SetPointError( 0, 0.75, 0.75, 0., 0. );
    CMSMadGraph7->SetPointError( 1, 0.25, 0.25, 0., 0. );
    CMSMadGraph7->SetPointError( 2, 0.25, 0.25, 0., 0. );
    CMSMadGraph7->SetPointError( 3, 0.25, 0.25, 0., 0. );
    CMSMadGraph7->SetPointError( 4, 0.25, 0.25, 0., 0. );
    CMSMadGraph7->SetPointError( 5, 0.75, 0.75, 0., 0. ); 
  }

  CMSMadGraph7->SetLineWidth(3.);
  CMSMadGraph7->SetMarkerSize(1.2);
  CMSMadGraph7->SetLineStyle(1);
  CMSMadGraph7->SetMarkerStyle(20);
  CMSMadGraph7->SetMarkerColor(kAzure+6);
  CMSMadGraph7->SetLineColor(kAzure+6);


  // ATLAS data
  TGraphAsymmErrors* ATLASdata7 = new TGraphAsymmErrors(Nbins7);
  if(quantity=="topPt"){
    ATLASdata7->SetPoint( 0, 25.0 , 0.0034  ); 
    ATLASdata7->SetPoint( 1, 75.0 , 0.0067  ); 
    ATLASdata7->SetPoint( 2, 125.0, 0.0052  ); 
    ATLASdata7->SetPoint( 3, 175.0, 0.00266 ); 
    ATLASdata7->SetPoint( 4, 225.0, 0.00114 ); 
    ATLASdata7->SetPoint( 5, 300.0, 0.00033 ); 
    ATLASdata7->SetPoint( 6, 575.0, 0.000018); 

    ATLASdata7->SetPointError( 0, 25., 25., (4.47 /100)*0.0034  , (4.47 /100)*0.0034   );
    ATLASdata7->SetPointError( 1, 25., 25., (1.41 /100)*0.0067  , (1.41 /100)*0.0067   );
    ATLASdata7->SetPointError( 2, 25., 25., (2.83 /100)*0.0052  , (2.83 /100)*0.0052   );
    ATLASdata7->SetPointError( 3, 25., 25., (3.61 /100)*0.00266 , (3.61 /100)*0.00266  );
    ATLASdata7->SetPointError( 4, 25., 25., (3.61 /100)*0.00114 , (3.61 /100)*0.00114  );
    ATLASdata7->SetPointError( 5, 50., 50., (5.83 /100)*0.00033 , (5.83 /100)*0.00033  );
    ATLASdata7->SetPointError( 6, 225., 225., (11.66/100)*0.000018, (11.66/100)*0.000018 );
  }
  else if(quantity=="ttbarMass"){
    ATLASdata7->SetPoint( 0, 350.0 , 0.00250   ); 
    ATLASdata7->SetPoint( 1, 500.0 , 0.00273   ); 
    ATLASdata7->SetPoint( 2, 625.0 , 0.00102   ); 
    ATLASdata7->SetPoint( 3, 825.0 , 0.00023   ); 
    ATLASdata7->SetPoint( 4, 1725.0, 0.0000076 ); 
    
    ATLASdata7->SetPointError( 0, 100., 100., 0.00008   , 0.00008  );
    ATLASdata7->SetPointError( 1, 50. , 50. , 0.00007   , 0.00007  );
    ATLASdata7->SetPointError( 2, 75. , 75. , 0.00004   , 0.00004  );
    ATLASdata7->SetPointError( 3, 125., 125., 0.00001   , 0.00001  );
    ATLASdata7->SetPointError( 4, 775., 775., 0.0000005, 0.0000005 );
  }
  else if(quantity=="ttbarY"){
    ATLASdata7->SetPoint( 0, -1.75, 0.081 ); 
    ATLASdata7->SetPoint( 1, -0.75, 0.321 ); 
    ATLASdata7->SetPoint( 2, -0.25, 0.436 ); 
    ATLASdata7->SetPoint( 3,  0.25, 0.423 ); 
    ATLASdata7->SetPoint( 4,  0.75, 0.321 ); 
    ATLASdata7->SetPoint( 5,  1.75, 0.087 );

    ATLASdata7->SetPointError( 0, 0.75, 0.75, 0.003, 0.003);
    ATLASdata7->SetPointError( 1, 0.25, 0.25, 0.009, 0.009);
    ATLASdata7->SetPointError( 2, 0.25, 0.25, 0.009, 0.009);
    ATLASdata7->SetPointError( 3, 0.25, 0.25, 0.007, 0.007);
    ATLASdata7->SetPointError( 4, 0.25, 0.25, 0.005, 0.005);
    ATLASdata7->SetPointError( 5, 0.75, 0.75, 0.005, 0.005);
  }
  ATLASdata7->SetLineWidth(3.);
  ATLASdata7->SetMarkerSize(1.2);
  ATLASdata7->SetMarkerStyle(22);
  ATLASdata7->SetLineStyle(2);
  ATLASdata7->SetMarkerColor(kRed);
  ATLASdata7->SetLineColor(kRed);
  ATLASdata7->SetFillStyle(3005);
  ATLASdata7->SetFillColor(kRed);

  // ---
  //    dummy plots for axis
  // ---
  // create variable bin edges
  std::map<TString, std::vector<double> > binning_ = makeVariableBinning(false);
  std::vector<double> newTopBins_;
  if(quantity=="topPt"){
    newTopBins_.push_back(0.);
    newTopBins_.push_back(50.);
    newTopBins_.push_back(100.);
    newTopBins_.push_back(150.);
    newTopBins_.push_back(200.);
    newTopBins_.push_back(250.);
    newTopBins_.push_back(350.);
    newTopBins_.push_back(800.);
  }

  else if(quantity=="ttbarMass"){
    newTopBins_.push_back(250.);
    newTopBins_.push_back(450.);
    newTopBins_.push_back(550.);
    newTopBins_.push_back(700.);
    newTopBins_.push_back(950.);
    newTopBins_.push_back(2500.);
  }
  else if(quantity=="ttbarY"   ){
    newTopBins_.push_back(-2.5);
    newTopBins_.push_back(-1.0);
    newTopBins_.push_back(-0.5);
    newTopBins_.push_back(0.  );
    newTopBins_.push_back(0.5 );
    newTopBins_.push_back(1.0 );
    newTopBins_.push_back(2.5 );
  }

  binning_[quantity]=newTopBins_;
  double start=0.;
  double range=800.;
  int Nfinebins=800;
  if(quantity=="topPt"){ Nfinebins=800; start=0.; range=800.;}
  else if(quantity=="ttbarMass"){ Nfinebins=2250; start=250.; range=2500.; }
  else if(quantity=="ttbarY"   ){ Nfinebins=500 ; start=-2.5; range=2.5;}
  TH1F* dummy= new TH1F("","",Nfinebins,start,range);
  reBinTH1F(*dummy, binning_[quantity], 0);
  histogramStyle(*dummy, kSig);
  TString label="p_{T}^{t} [GeV]";
  TString label2="p_{T}^{t}";
  if(quantity=="topPt"){label="p_{T}^{t} [GeV]"; label2="p_{T}^{t}";}
  else if(quantity=="ttbarMass"){ label="m^{t#bar{t}} [GeV]"; label2="m^{t#bar{t}}"; }
  else if(quantity=="ttbarY"   ){ label="y^{t#bar{t}}"; label2=label; }
  dummy->GetXaxis()->SetTitle(label);
  dummy->GetYaxis()->SetTitle(TString("#frac{1}{#sigma} #frac{d#sigma}{")+label2+"}");
  double max=0.01;
  double min=0.;
  if(quantity=="topPt"    ){max=0.01 ; min=0.;}
  if(quantity=="ttbarMass"){max=0.004; min=0.;}
  if(quantity=="ttbarY"   ){max=1.0  ; min=0.;}
  dummy->SetMaximum(max);
  dummy->SetMinimum(min);
  TH1F* A=convertToHist(ATLASdata7, dummy, Nbins7);
  TH1F* C=convertToHist(CMSdata7  , dummy, Nbins7);
  histogramStyle(*A, kSig, true, 1.2, kRed);
  A->SetLineWidth(3.);
  A->SetMarkerSize(1.2);
  A->SetMarkerStyle(22);
  A->SetLineStyle(1);
  A->SetMarkerColor(kRed);
  A->SetLineColor(kRed);
  A->SetFillStyle(3005);
  histogramStyle(*C, kSig, true, 1.2, kBlue);
  C->SetLineWidth(3.);
  C->SetMarkerSize(1.2);
  C->SetMarkerStyle(24);
  C->SetLineStyle(1);
  C->SetMarkerColor(kBlue);
  C->SetLineColor(kBlue);
  C->SetFillStyle(3004);
  TH1F* M=convertToHist(CMSMadGraph7  , dummy, Nbins7);
  histogramStyle(*M, kSig, false, 1.2, kAzure+6);
  M->SetLineWidth(3.);
  M->SetMarkerSize(1.2);
  M->SetMarkerStyle(22);
  M->SetLineStyle(1);
  M->SetMarkerColor(kAzure+6);
  M->SetLineColor(kAzure+6);

  // ---
  //    legend
  // ---
  TLegend *leg0 = new TLegend(0.45, 0.65, 0.95, 0.85);
  leg0->SetFillStyle(0);
  leg0->SetBorderSize(0);
  leg0->SetHeader("#sqrt{s}=7TeV data (e/#mu channel)");
  TLegend *leg1=(TLegend*)leg0->Clone(); 
  if(cmssim) leg0->AddEntry( CMSMadGraph7, "CMS MadGraph+Pythia(Z2*)", "LP");
  leg0->AddEntry( CMSdata7    , "CMS data in ATLAS binning"   , "LP");
  leg0->AddEntry( ATLASdata7  , "ATLAS data" , "LP");
  leg1->AddEntry( ATLASdata7  , "ATLAS (ATLAS-CONF-2013-099)" , "FP");
  leg1->AddEntry( CMSdata7    , "CMS (TOP-11-013 in ATLAS binning)"   , "FP");
  if(cmssim) leg1->AddEntry( CMSMadGraph7, "CMS MadGraph+Pythia(Z2*)", "LP");


  // ---
  //    privatworklabel
  // ---
  TPaveText *privatworklabel = new TPaveText();
  privatworklabel -> SetX1NDC(gStyle->GetPadLeftMargin());
  privatworklabel -> SetY1NDC(1.0-gStyle->GetPadTopMargin());
  privatworklabel -> SetX2NDC(1.0-gStyle->GetPadRightMargin());
  privatworklabel -> SetY2NDC(1.0);
  privatworklabel -> SetTextFont(42);
  privatworklabel -> AddText("private work");
  privatworklabel->SetFillStyle(0);
  privatworklabel->SetBorderSize(0);
  privatworklabel->SetTextSize(0.04);
  privatworklabel->SetTextAlign(32);

  // canvas
  std::vector<TCanvas*> plotCanvas_;
  // a) linear
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle(quantity+" measurement comparison");
  // drawing
  dummy->Draw("axis");
  if(cmssim) CMSMadGraph7->Draw("p e1 same");
  ATLASdata7  ->Draw("p e2 same");
  CMSdata7    ->Draw("p e2 same");
  leg0 ->Draw("same");
  privatworklabel->Draw("same");
  // b) log scale
  TH1F* dummy2=(TH1F*)dummy->Clone();
  dummy2->SetMinimum(0.00001);
  dummy2->SetMaximum(max*10);
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle(quantity+" measurement comparison");
  plotCanvas_[plotCanvas_.size()-1]->SetLogy();
  // drawing
  dummy2->Draw("axis");
  if(cmssim) CMSMadGraph7->Draw("p e1 same");
  CMSdata7    ->Draw("p e2 same");
  ATLASdata7  ->Draw("p e2 same");
  leg0 ->Draw("same");
  privatworklabel->Draw("same");
  // c) both data with bands
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle(quantity+" measurement comparison");
  // drawing
  dummy->Draw("axis");
  //DrawSteps(C, "e2 same");
  //C->Draw("e2 same");
  //DrawSteps(A, "e2 same");
  //A->Draw("e2 same");
  if(cmssim) CMSMadGraph7->Draw("p e1 same");
  CMSdata7    ->Draw("p e2 same");
  ATLASdata7  ->Draw("p e2 same");
  // new pad for log plot
  TPad *rPad = new TPad("rPad","",0.4,0.15,0.95,0.85);
  rPad->SetFillStyle(0);
  rPad->SetFillColor(0);
  rPad->SetBorderSize(0);
  rPad->SetBorderMode(0);
  rPad->SetLogy(0);
  rPad->SetLogx(0);
  rPad->SetTicky(1);
  rPad->Draw("");
  rPad->cd();
  // log plot curves
  rPad->SetLogy();
  dummy2->Draw("axis");
  if(cmssim) CMSMadGraph7->Draw("p e1 same");
  CMSdata7    ->Draw("p e2 same");
  ATLASdata7  ->Draw("p e2 same");
  leg1->Draw("same");
  privatworklabel->Draw("same");
  // d) both data with ratio
  addCanvas(plotCanvas_);
  plotCanvas_[plotCanvas_.size()-1]->cd(0);
  plotCanvas_[plotCanvas_.size()-1]->SetTitle(quantity+" measurement comparison");
  // drawing
  dummy->Draw("axis");
  if(cmssim) CMSMadGraph7->Draw("p e1 same");
  //DrawSteps(C, "e2 same");
  //C->Draw("e2 same");
  //DrawSteps(A, "e2 same");
  //A->Draw("e2 same");
  CMSdata7    ->Draw("p e2 same");
  ATLASdata7  ->Draw("p e2 same");
  leg1 ->Draw("same");
  privatworklabel->Draw("same");
  std::vector<double> errA_;
  for(int bin=1; bin<=Nbins7; ++bin){
    errA_.push_back((ATLASdata7->GetY()[bin-1]/CMSdata7->GetY()[bin-1])*((ATLASdata7->GetErrorYhigh(bin-1)/ATLASdata7->GetY()[bin-1])));
  }
  std::vector<double> errC_;
  for(int bin=1; bin<=Nbins7; ++bin){
    errC_.push_back((CMSdata7->GetErrorYhigh(bin-1)/CMSdata7->GetY()[bin-1]));
  }
  if(cmssim){
    std::vector<double> errM_;
    for(int bin=1; bin<=Nbins7; ++bin){
      errM_.push_back(0.);
      //errM_.push_back((CMSMadGraph7->GetY()[bin-1]/CMSdata7->GetY()[bin-1])*((CMSMadGraph7->GetErrorYhigh(bin-1)/CMSMadGraph7->GetY()[bin-1])));
    }
    drawRatio(M, C, 0.5, 1.5,  myStyle, 0, errM_, "x", "CMS data", "hist ", kAzure+6, false, 0.7);
    drawRatio(C, C, 0.5, 1.5,  myStyle, 0, errC_, "x", "CMS data", "p e2 same"     , kBlue, true, 0.7);

  }
  else drawRatio(C, C, 0.5, 1.5,  myStyle, 0, errC_, "x", "CMS data", "p e2"     , kBlue, true, 0.7);
  drawRatio(A, C, 0.5, 1.5,  myStyle, 0, errA_, "x", "CMS data", "p e2 same", kRed , true, 0.7);

  //saving
  TString path="./diffXSecFromSignal/plots/combined/2012/comparisonATLAS/";
  plotCanvas_[0]->Print(path+quantity+"ATLASvsCMS7TeV.eps");
  plotCanvas_[0]->Print(path+quantity+"ATLASvsCMS7TeV.png");
  plotCanvas_[1]->Print(path+quantity+"ATLASvsCMS7TeVLog.eps");
  plotCanvas_[1]->Print(path+quantity+"ATLASvsCMS7TeVLog.png");
  plotCanvas_[2]->Print(path+quantity+"ATLASvsCMS7TeVNoratio.eps");
  plotCanvas_[2]->Print(path+quantity+"ATLASvsCMS7TeVNoratio.png");
  plotCanvas_[plotCanvas_.size()-1]->Print(path+quantity+"ATLASvsCMS7TeVratio.eps");
  plotCanvas_[plotCanvas_.size()-1]->Print(path+quantity+"ATLASvsCMS7TeVratio.png");
  plotCanvas_[plotCanvas_.size()-1]->SetTitle(quantity);
  saveToRootFile("ATLASvsCMSDataComparisonPlots.root", plotCanvas_[plotCanvas_.size()-1], true, 0,"");
}
コード例 #12
0
ファイル: treeComparison.C プロジェクト: eschliec/TopAnalysis
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);
  }
}
コード例 #13
0
void makeResultTables(std::string decayChannel = "combined", bool extrapolate=true, bool hadron=false, bool addCrossCheckVariables=false, bool useBCC=false, int verbose=1){
  
  // ============================
  //  Set Root Style
  // ============================

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

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

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

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