Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
#include "HLTriggerOffline/Btag/interface/HLTBTagPerformanceAnalyzer.h"
#include <algorithm>
#include <set>

using namespace edm;
using namespace reco;

namespace {
  // find the index of the object key of an association vector closest to a given
  // jet, within a given distance
  template <typename T, typename V>
  int closestJet(const RefToBase<reco::Jet> jet, const edm::AssociationVector<T, V> &association, double distance) {
    int closest = -1;
    for (unsigned int i = 0; i < association.size(); ++i) {
      double d = ROOT::Math::VectorUtil::DeltaR(jet->momentum(), association[i].first->momentum());
      if (d < distance) {
        distance = d;
        closest = i;
      }
    }
    return closest;
  }

  std::set<std::string> const keepSetJet{"jetNSecondaryVertices",
                                         "jetNSelectedTracks",
                                         "jetNTracks",
                                         "Jet_JP",
                                         "chargedHadronEnergyFraction",
                                         "neutralHadronEnergyFraction",
                                         "photonEnergyFraction",
                                         "electronEnergyFraction",
                                         "muonEnergyFraction",
                                         "chargedHadronMultiplicity",
                                         "neutralHadronMultiplicity",
                                         "photonMultiplicity",
                                         "electronMultiplicity",
                                         "muonMultiplicity",
                                         "hadronMultiplicity",
                                         "hadronPhotonMultiplicity",
                                         "totalMultiplicity"};

  std::set<std::string> const keepSetTrack{
      "trackChi2",       "trackNTotalHits",    "trackNPixelHits",   "trackSip3dVal",    "trackSip3dSig",
      "trackSip2dVal",   "trackSip2dSig",      "trackPtRel",        "trackDeltaR",      "trackPtRatio",
      "trackSip3dSig_0", "trackSip3dSig_1",    "trackSip3dSig_2",   "trackSip3dSig_3",  "trackMomentum",
      "trackEta",        "trackPhi",           "trackDecayLenVal",  "trackDecayLenSig", "trackJetDistVal",
      "trackJetDistSig", "trackSumJetEtRatio", "trackSumJetDeltaR", "trackEtaRel"

  };
  std::set<std::string> const keepSetVtx{"vertexMass",
                                         "vertexNTracks"
                                         "vertexFitProb",
                                         "vertexCategory",
                                         "vertexEnergyRatio",
                                         "vertexJetDeltaR",
                                         "vertexBoostOverSqrtJetPt",
                                         "flightDistance1dVal",
                                         "flightDistance1dSig",
                                         "flightDistance2dVal",
                                         "flightDistance2dSig",
                                         "flightDistance3dVal",
                                         "flightDistance3dSig"};

  auto initializeKeepSet() {
    std::set<std::string> ret;
    // Make a combined set of inputs avaiable
    std::set_union(std::begin(keepSetJet),
                   std::end(keepSetJet),
                   std::begin(keepSetTrack),
                   std::end(keepSetTrack),
                   std::inserter(ret, std::begin(ret)));
    std::set_union(std::begin(ret),
                   std::end(ret),
                   std::begin(keepSetVtx),
                   std::end(keepSetVtx),
                   std::inserter(ret, std::begin(ret)));
    return ret;
  }
  std::set<std::string> const keepSet = initializeKeepSet();
}  // namespace

// constructors and destructor
HLTBTagPerformanceAnalyzer::HLTBTagPerformanceAnalyzer(const edm::ParameterSet &iConfig) {
  mainFolder_ = iConfig.getParameter<std::string>("mainFolder");
  hlTriggerResults_ = consumes<edm::TriggerResults>(iConfig.getParameter<InputTag>("TriggerResults"));
  JetTagCollection_ =
      edm::vector_transform(iConfig.getParameter<std::vector<edm::InputTag>>("JetTag"),
                            [this](edm::InputTag const &tag) { return mayConsume<reco::JetTagCollection>(tag); });
  //        shallowTagInfosTokenCalo_ =
  //        consumes<std::vector<reco::ShallowTagInfo> >
  //        (edm::InputTag("hltDeepCombinedSecondaryVertexBJetTagsInfosCalo"));
  shallowTagInfosTokenPf_ =
      consumes<std::vector<reco::ShallowTagInfo>>(edm::InputTag("hltDeepCombinedSecondaryVertexBJetTagsInfos"));
  m_mcPartons = consumes<JetFlavourMatchingCollection>(iConfig.getParameter<InputTag>("mcPartons"));
  hltPathNames_ = iConfig.getParameter<std::vector<std::string>>("HLTPathNames");
  edm::ParameterSet mc = iConfig.getParameter<edm::ParameterSet>("mcFlavours");
  m_mcLabels = mc.getParameterNamesForType<std::vector<unsigned int>>();

  EDConsumerBase::labelsForToken(m_mcPartons, label);
  m_mcPartons_Label = label.module;

  for (unsigned int i = 0; i < JetTagCollection_.size(); i++) {
    EDConsumerBase::labelsForToken(JetTagCollection_[i], label);
    JetTagCollection_Label.push_back(label.module);
  }

  EDConsumerBase::labelsForToken(hlTriggerResults_, label);
  hlTriggerResults_Label = label.module;

  for (unsigned int i = 0; i < m_mcLabels.size(); ++i)
    m_mcFlavours.push_back(mc.getParameter<std::vector<unsigned int>>(m_mcLabels[i]));
  m_mcMatching = m_mcPartons_Label != "none";

  m_mcRadius = 0.3;

  HCALSpecialsNames[HEP17] = "HEP17";
  HCALSpecialsNames[HEP18] = "HEP18";
  HCALSpecialsNames[HEM17] = "HEM17";
}

HLTBTagPerformanceAnalyzer::~HLTBTagPerformanceAnalyzer() {
  // do anything here that needs to be done at desctruction time
  // (e.g. close files, deallocate resources etc.)
}

void HLTBTagPerformanceAnalyzer::dqmBeginRun(const edm::Run &iRun, const edm::EventSetup &iSetup) {
  triggerConfChanged_ = true;
  EDConsumerBase::labelsForToken(hlTriggerResults_, label);

  hltConfigProvider_.init(iRun, iSetup, label.process, triggerConfChanged_);
  const std::vector<std::string> &allHltPathNames = hltConfigProvider_.triggerNames();

  // fill hltPathIndexs_ with the trigger number of each hltPathNames_
  for (size_t trgs = 0; trgs < hltPathNames_.size(); trgs++) {
    unsigned int found = 1;
    int it_mem = -1;
    for (size_t it = 0; it < allHltPathNames.size(); ++it) {
      found = allHltPathNames.at(it).find(hltPathNames_[trgs]);
      if (found == 0) {
        it_mem = (int)it;
      }
    }  // for allallHltPathNames
    hltPathIndexs_.push_back(it_mem);
  }  // for hltPathNames_

  // fill _isfoundHLTs for each hltPathNames_
  for (size_t trgs = 0; trgs < hltPathNames_.size(); trgs++) {
    if (hltPathIndexs_[trgs] < 0) {
      _isfoundHLTs.push_back(false);
    } else {
      _isfoundHLTs.push_back(true);
    }
  }
}

void HLTBTagPerformanceAnalyzer::analyze(const edm::Event &iEvent, const edm::EventSetup &iSetup) {
  bool trigRes = false;
  bool MCOK = false;
  using namespace edm;

  // get triggerResults
  Handle<TriggerResults> TriggerResulsHandler;
  Handle<reco::JetFlavourMatchingCollection> h_mcPartons;
  if (hlTriggerResults_Label.empty() || hlTriggerResults_Label == "NULL") {
    edm::LogInfo("NoTriggerResults") << "TriggerResults ==> Empty";
    return;
  }
  iEvent.getByToken(hlTriggerResults_, TriggerResulsHandler);
  if (TriggerResulsHandler.isValid())
    trigRes = true;
  if (!trigRes) {
    edm::LogInfo("NoTriggerResults") << "TriggerResults ==> not readable";
    return;
  }
  const TriggerResults &triggerResults = *(TriggerResulsHandler.product());

  // get partons
  if (m_mcMatching && !m_mcPartons_Label.empty() && m_mcPartons_Label != "NULL") {
    iEvent.getByToken(m_mcPartons, h_mcPartons);
    if (h_mcPartons.isValid())
      MCOK = true;
  }

  // fill the 1D and 2D DQM plot
  Handle<reco::JetTagCollection> JetTagHandler;
  for (unsigned int ind = 0; ind < hltPathNames_.size(); ind++) {
    bool BtagOK = false;
    JetTagMap JetTag;
    if (!_isfoundHLTs[ind])
      continue;  // if the hltPath is not in the event, skip the event
    if (!triggerResults.accept(hltPathIndexs_[ind]))
      continue;  // if the hltPath was not accepted skip the event

    // get JetTagCollection
    if (!JetTagCollection_Label[ind].empty() && JetTagCollection_Label[ind] != "NULL") {
      iEvent.getByToken(JetTagCollection_[ind], JetTagHandler);
      iEvent.getByToken(shallowTagInfosTokenPf_, shallowTagInfosPf);
      //                        iEvent.getByToken(shallowTagInfosTokenCalo_,
      //                        shallowTagInfosCalo);
      if (JetTagHandler.isValid())
        BtagOK = true;
    }

    // fill JetTag map
    if (BtagOK)
      for (auto iter = JetTagHandler->begin(); iter != JetTagHandler->end(); iter++) {
        JetTag.insert(JetTagMap::value_type(iter->first, iter->second));
      }
    else {
      edm::LogInfo("NoCollection") << "Collection " << JetTagCollection_Label[ind] << " ==> not found";
      return;
    }
    // fill Inputs for All
    if (shallowTagInfosPf.isValid()) {
      for (auto &info : *(shallowTagInfosPf)) {
        TaggingVariableList vars = info.taggingVariables();
        for (auto entry = vars.begin(); entry != vars.end(); ++entry) {
          if (keepSet.find(TaggingVariableTokens[entry->first]) !=
              keepSet.end()) {  // if Input name in defined list to keep
            try {
              H1_.at(ind)[TaggingVariableTokens[entry->first]]->Fill(std::fmax(0.0, entry->second));
            } catch (const std::exception &e) {
              continue;
            }
          } else
            continue;
        }
      }
    } else {
      edm::LogInfo("NoCollection") << "No shallowTagInfosPf collection";
    }
    // fill tagging
    for (auto &BtagJT : JetTag) {
      std::map<HCALSpecials, bool> inmodule;
      inmodule[HEP17] = (BtagJT.first->phi() >= -0.87) && (BtagJT.first->phi() < -0.52) && (BtagJT.first->eta() > 1.3);
      inmodule[HEP18] = (BtagJT.first->phi() >= -0.52) && (BtagJT.first->phi() < -0.17) && (BtagJT.first->eta() > 1.3);
      inmodule[HEM17] = (BtagJT.first->phi() >= -0.87) && (BtagJT.first->phi() < -0.52) && (BtagJT.first->eta() < -1.3);

      // fill 1D btag plot for 'all'
      H1_.at(ind)[JetTagCollection_Label[ind]]->Fill(std::fmax(0.0, BtagJT.second));
      for (const auto &i : HCALSpecialsNames) {
        if (inmodule[i.first])
          H1mod_.at(ind)[JetTagCollection_Label[ind]][i.first]->Fill(std::fmax(0.0, BtagJT.second));
      }
      if (MCOK) {
        int m = closestJet(BtagJT.first, *h_mcPartons, m_mcRadius);
        unsigned int flavour = (m != -1) ? abs((*h_mcPartons)[m].second.getFlavour()) : 0;
        for (unsigned int i = 0; i < m_mcLabels.size(); ++i) {
          std::string flavour_str = m_mcLabels[i];
          flavours_t flav_collection = m_mcFlavours[i];
          auto it = std::find(flav_collection.begin(), flav_collection.end(), flavour);
          if (it == flav_collection.end())
            continue;
          std::string label = JetTagCollection_Label[ind] + "__";
          label += flavour_str;
          H1_.at(ind)[label]->Fill(std::fmax(0.0, BtagJT.second));  // fill 1D btag plot for 'b,c,uds'
          for (const auto &j : HCALSpecialsNames) {
            if (inmodule[j.first])
              H1mod_.at(ind)[label][j.first]->Fill(
                  std::fmax(0.0, BtagJT.second));  // fill 1D btag plot for 'b,c,uds' in
                                                   // modules (HEP17 etc.)
          }
          label = JetTagCollection_Label[ind] + "___";
          label += flavour_str;
          std::string labelEta = label;
          std::string labelPhi = label;
          std::string labelEtaPhi = label;
          std::string labelEtaPhi_threshold = label;
          label += "_disc_pT";
          H2_.at(ind)[label]->Fill(std::fmax(0.0, BtagJT.second),
                                   BtagJT.first->pt());  // fill 2D btag, jetPt plot for 'b,c,uds'
          for (const auto &j : HCALSpecialsNames) {
            if (inmodule[j.first])
              H2mod_.at(ind)[label][j.first]->Fill(std::fmax(0.0, BtagJT.second), BtagJT.first->pt());
          }
          labelEta += "_disc_eta";
          H2Eta_.at(ind)[labelEta]->Fill(std::fmax(0.0, BtagJT.second),
                                         BtagJT.first->eta());  // fill 2D btag, jetEta plot for 'b,c,uds'
          labelPhi += "_disc_phi";
          H2Phi_.at(ind)[labelPhi]->Fill(std::fmax(0.0, BtagJT.second),
                                         BtagJT.first->phi());  // fill 2D btag, jetPhi plot for 'b,c,uds'
          labelEtaPhi += "_eta_phi";
          H2EtaPhi_.at(ind)[labelEtaPhi]->Fill(BtagJT.first->eta(),
                                               BtagJT.first->phi());  // fill 2D btag, jetPhi plot for 'b,c,uds'
          labelEtaPhi_threshold += "_eta_phi_disc05";
          if (BtagJT.second > 0.5) {
            H2EtaPhi_threshold_.at(ind)[labelEtaPhi_threshold]->Fill(
                BtagJT.first->eta(),
                BtagJT.first->phi());  // fill 2D btag, jetPhi plot for 'b,c,uds'
          }
        }  /// for flavour
      }  /// if MCOK
    }  /// for BtagJT
  }  // for triggers
}

//// ------------ method called once each job just before starting event loop
///------------
void HLTBTagPerformanceAnalyzer::bookHistograms(DQMStore::IBooker &ibooker,
                                                edm::Run const &iRun,
                                                edm::EventSetup const &iSetup) {
  // book the DQM plots for each path and for each flavour
  using namespace std;
  assert(hltPathNames_.size() == JetTagCollection_.size());
  std::string dqmFolder;
  for (unsigned int ind = 0; ind < hltPathNames_.size(); ind++) {
    float btagL = 0.;
    float btagU = 1.;
    int btagBins = 100;
    dqmFolder = Form("%s/Discriminator/%s", mainFolder_.c_str(), hltPathNames_[ind].c_str());
    H1_.push_back(std::map<std::string, MonitorElement *>());
    H2_.push_back(std::map<std::string, MonitorElement *>());
    H1mod_.push_back(std::map<std::string, std::map<HCALSpecials, MonitorElement *>>());
    H2mod_.push_back(std::map<std::string, std::map<HCALSpecials, MonitorElement *>>());
    H2Eta_.push_back(std::map<std::string, MonitorElement *>());
    H2Phi_.push_back(std::map<std::string, MonitorElement *>());
    H2EtaPhi_.push_back(std::map<std::string, MonitorElement *>());
    H2EtaPhi_threshold_.push_back(std::map<std::string, MonitorElement *>());
    ibooker.setCurrentFolder(dqmFolder);

    // book 1D btag plot for 'all'
    if (!JetTagCollection_Label[ind].empty() && JetTagCollection_Label[ind] != "NULL") {
      H1_.back()[JetTagCollection_Label[ind]] = ibooker.book1D(
          JetTagCollection_Label[ind] + "_all", JetTagCollection_Label[ind] + "_all", btagBins, btagL, btagU);
      H1_.back()[JetTagCollection_Label[ind]]->setAxisTitle(JetTagCollection_Label[ind] + "discriminant", 1);
      // Input storing
      ibooker.setCurrentFolder(dqmFolder + "/inputs");
      ibooker.setCurrentFolder(dqmFolder + "/inputs/Jet");
      for (int i = 0; i < 100; i++) {
        if (keepSetJet.find(TaggingVariableTokens[i]) != keepSetJet.end()) {  // if input name in defined set
          std::string inpt = TaggingVariableTokens[i];
          H1_.back()[inpt] = ibooker.book1D(inpt, inpt, 105, -5, 100.);
          H1_.back()[inpt]->setAxisTitle(inpt, 1);
        } else
          continue;
      }
      ibooker.setCurrentFolder(dqmFolder + "/inputs/Track");
      for (int i = 0; i < 100; i++) {
        if (keepSetTrack.find(TaggingVariableTokens[i]) != keepSetTrack.end()) {  // if input name in defined set
          std::string inpt = TaggingVariableTokens[i];
          H1_.back()[inpt] = ibooker.book1D(inpt, inpt, 105, -5, 100.);
          H1_.back()[inpt]->setAxisTitle(inpt, 1);
        } else
          continue;
      }
      ibooker.setCurrentFolder(dqmFolder + "/inputs/Vertex");
      for (int i = 0; i < 100; i++) {
        if (keepSetVtx.find(TaggingVariableTokens[i]) != keepSetVtx.end()) {  // if input name in defined set
          std::string inpt = TaggingVariableTokens[i];
          H1_.back()[inpt] = ibooker.book1D(inpt, inpt, 105, -5, 100.);
          H1_.back()[inpt]->setAxisTitle(inpt, 1);
        } else
          continue;
      }

      for (const auto &i : HCALSpecialsNames) {
        ibooker.setCurrentFolder(dqmFolder + "/" + i.second);
        H1mod_.back()[JetTagCollection_Label[ind]][i.first] = ibooker.book1D(
            JetTagCollection_Label[ind] + "_all", JetTagCollection_Label[ind] + "_all", btagBins, btagL, btagU);
        H1mod_.back()[JetTagCollection_Label[ind]][i.first]->setAxisTitle(JetTagCollection_Label[ind] + "discriminant",
                                                                          1);
      }
      ibooker.setCurrentFolder(dqmFolder);
    }
    int nBinsPt = 60;
    double pTmin = 30;
    double pTMax = 330;
    int nBinsPhi = 54;
    double phimin = -M_PI;
    double phiMax = M_PI;
    int nBinsEta = 40;
    double etamin = -2.4;
    double etaMax = 2.4;

    for (unsigned int i = 0; i < m_mcLabels.size(); ++i) {
      std::string flavour = m_mcLabels[i];
      std::string label;
      std::string labelEta;
      std::string labelPhi;
      std::string labelEtaPhi;
      std::string labelEtaPhi_threshold;
      if (!JetTagCollection_Label[ind].empty() && JetTagCollection_Label[ind] != "NULL") {
        label = JetTagCollection_Label[ind] + "__";
        label += flavour;

        // book 1D btag plot for 'b,c,light,g'
        H1_.back()[label] = ibooker.book1D(
            label, Form("%s %s", JetTagCollection_Label[ind].c_str(), flavour.c_str()), btagBins, btagL, btagU);
        H1_.back()[label]->setAxisTitle("disc", 1);
        for (const auto &j : HCALSpecialsNames) {
          ibooker.setCurrentFolder(dqmFolder + "/" + j.second);
          H1mod_.back()[label][j.first] = ibooker.book1D(
              label, Form("%s %s", JetTagCollection_Label[ind].c_str(), flavour.c_str()), btagBins, btagL, btagU);
          H1mod_.back()[label][j.first]->setAxisTitle("disc", 1);
        }
        ibooker.setCurrentFolder(dqmFolder);
        label = JetTagCollection_Label[ind] + "___";
        labelEta = label;
        labelPhi = label;
        labelEtaPhi = label;
        labelEtaPhi_threshold = label;
        label += flavour + "_disc_pT";
        labelEta += flavour + "_disc_eta";
        labelPhi += flavour + "_disc_phi";
        labelEtaPhi += flavour + "_eta_phi";
        labelEtaPhi_threshold += flavour + "_eta_phi_disc05";

        // book 2D btag plot for 'b,c,light,g'
        H2_.back()[label] = ibooker.book2D(label, label, btagBins, btagL, btagU, nBinsPt, pTmin, pTMax);
        H2_.back()[label]->setAxisTitle("pT", 2);
        H2_.back()[label]->setAxisTitle("disc", 1);
        for (const auto &j : HCALSpecialsNames) {
          ibooker.setCurrentFolder(dqmFolder + "/" + j.second);
          H2mod_.back()[label][j.first] = ibooker.book2D(label, label, btagBins, btagL, btagU, nBinsPt, pTmin, pTMax);
          H2mod_.back()[label][j.first]->setAxisTitle("pT", 2);
          H2mod_.back()[label][j.first]->setAxisTitle("disc", 1);
        }
        ibooker.setCurrentFolder(dqmFolder);
        H2Eta_.back()[labelEta] = ibooker.book2D(labelEta, labelEta, btagBins, btagL, btagU, nBinsEta, etamin, etaMax);
        H2Eta_.back()[labelEta]->setAxisTitle("eta", 2);
        H2Eta_.back()[labelEta]->setAxisTitle("disc", 1);
        H2Phi_.back()[labelPhi] = ibooker.book2D(labelPhi, labelPhi, btagBins, btagL, btagU, nBinsPhi, phimin, phiMax);
        H2Phi_.back()[labelPhi]->setAxisTitle("phi", 2);
        H2Phi_.back()[labelPhi]->setAxisTitle("disc", 1);
        H2EtaPhi_.back()[labelEtaPhi] =
            ibooker.book2D(labelEtaPhi, labelEtaPhi, nBinsEta, etamin, etaMax, nBinsPhi, phimin, phiMax);
        H2EtaPhi_.back()[labelEtaPhi]->setAxisTitle("phi", 2);
        H2EtaPhi_.back()[labelEtaPhi]->setAxisTitle("eta", 1);
        H2EtaPhi_threshold_.back()[labelEtaPhi_threshold] = ibooker.book2D(
            labelEtaPhi_threshold, labelEtaPhi_threshold, nBinsEta, etamin, etaMax, nBinsPhi, phimin, phiMax);
        H2EtaPhi_threshold_.back()[labelEtaPhi_threshold]->setAxisTitle("phi", 2);
        H2EtaPhi_threshold_.back()[labelEtaPhi_threshold]->setAxisTitle("eta", 1);
      }
    }  /// for mc.size()
  }  /// for hltPathNames_.size()
}

// define this as a plug-in
DEFINE_FWK_MODULE(HLTBTagPerformanceAnalyzer);