AlCaHEMuonFilter

Counters

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
// system include files
#include <atomic>
#include <memory>
#include <cmath>
#include <iostream>
#include <sstream>
#include <fstream>

// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDFilter.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/Common/interface/TriggerNames.h"

#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/TriggerResults.h"
#include "DataFormats/HLTReco/interface/TriggerEvent.h"
#include "DataFormats/MuonReco/interface/Muon.h"
#include "DataFormats/MuonReco/interface/MuonFwd.h"

#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
#include "Calibration/IsolatedParticles/interface/CaloPropagateTrack.h"

#include "MagneticField/Engine/interface/MagneticField.h"
#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h"
#include "Geometry/CaloGeometry/interface/CaloGeometry.h"
#include "Geometry/Records/interface/CaloGeometryRecord.h"

//#define EDM_ML_DEBUG
//
// class declaration
//

namespace alCaHEMuonFilter {
  struct Counters {
    Counters() : nAll_(0), nGood_(0), nFinal_(0) {}
    mutable std::atomic<unsigned int> nAll_, nGood_, nFinal_;
  };
}  // namespace alCaHEMuonFilter

class AlCaHEMuonFilter : public edm::stream::EDFilter<edm::GlobalCache<alCaHEMuonFilter::Counters> > {
public:
  explicit AlCaHEMuonFilter(edm::ParameterSet const&, const alCaHEMuonFilter::Counters* count);
  ~AlCaHEMuonFilter() override;

  static std::unique_ptr<alCaHEMuonFilter::Counters> initializeGlobalCache(edm::ParameterSet const&) {
    return std::make_unique<alCaHEMuonFilter::Counters>();
  }

  bool filter(edm::Event&, edm::EventSetup const&) override;
  void endStream() override;
  static void globalEndJob(const alCaHEMuonFilter::Counters* counters);
  static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);

private:
  void beginRun(edm::Run const&, edm::EventSetup const&) override;
  void endRun(edm::Run const&, edm::EventSetup const&) override;

  // ----------member data ---------------------------
  HLTConfigProvider hltConfig_;
  unsigned int nRun_, nAll_, nGood_, nFinal_;
  const std::vector<std::string> trigNames_;
  const std::string processName_;
  const edm::InputTag triggerResults_, labelMuon_;
  const bool pfCut_;
  const double trackIsoCut_, caloIsoCut_, pfIsoCut_, muonptCut_, muonetaCut_;
  const int preScale_;
  const edm::EDGetTokenT<edm::TriggerResults> tok_trigRes_;
  const edm::EDGetTokenT<reco::MuonCollection> tok_Muon_;
  const edm::ESGetToken<CaloGeometry, CaloGeometryRecord> tok_geom_;
  const edm::ESGetToken<MagneticField, IdealMagneticFieldRecord> tok_magField_;
};

//
// constants, enums and typedefs
//

//
// static data member definitions
//

//
// constructors and destructor
//
AlCaHEMuonFilter::AlCaHEMuonFilter(edm::ParameterSet const& iConfig, const alCaHEMuonFilter::Counters* count)
    : nRun_(0),
      nAll_(0),
      nGood_(0),
      nFinal_(0),
      trigNames_(iConfig.getParameter<std::vector<std::string> >("triggers")),
      processName_(iConfig.getParameter<std::string>("processName")),
      triggerResults_(iConfig.getParameter<edm::InputTag>("triggerResultLabel")),
      labelMuon_(iConfig.getParameter<edm::InputTag>("muonLabel")),
      pfCut_(iConfig.getParameter<bool>("pfCut")),
      trackIsoCut_(iConfig.getParameter<double>("trackIsolationCut")),
      caloIsoCut_(iConfig.getParameter<double>("caloIsolationCut")),
      pfIsoCut_(iConfig.getParameter<double>("pfIsolationCut")),
      muonptCut_(iConfig.getParameter<double>("muonPtCut")),
      muonetaCut_(iConfig.getParameter<double>("muonEtaCut")),
      preScale_(iConfig.getParameter<int>("preScale") > 0 ? iConfig.getParameter<int>("preScale") : 1),
      tok_trigRes_(consumes<edm::TriggerResults>(triggerResults_)),
      tok_Muon_(consumes<reco::MuonCollection>(labelMuon_)),
      tok_geom_(esConsumes<CaloGeometry, CaloGeometryRecord>()),
      tok_magField_(esConsumes<MagneticField, IdealMagneticFieldRecord>()) {
  // load the parameters and define tokens for access

  edm::LogVerbatim("HEMuon") << "Parameters read from config file \n"
                             << "Process " << processName_ << "  Prescale " << preScale_ << "  Isolation Cuts "
                             << trackIsoCut_ << ":" << caloIsoCut_ << "\n";
  for (unsigned int k = 0; k < trigNames_.size(); ++k)
    edm::LogVerbatim("HEMuon") << "Trigger[" << k << "] " << trigNames_[k] << "\n";
}  // AlCaHEMuonFilter::AlCaHEMuonFilter  constructor

AlCaHEMuonFilter::~AlCaHEMuonFilter() {}

//
// member functions
//

// ------------ method called on each new Event  ------------
bool AlCaHEMuonFilter::filter(edm::Event& iEvent, edm::EventSetup const& iSetup) {
  bool accept(false);
  ++nAll_;
#ifdef EDM_ML_DEBUG
  edm::LogVerbatim("HEMuon") << "AlCaHEMuonFilter::Run " << iEvent.id().run() << " Event " << iEvent.id().event()
                             << " Luminosity " << iEvent.luminosityBlock() << " Bunch " << iEvent.bunchCrossing()
                             << std::endl;
#endif
  //Step1: Find if the event passes one of the chosen triggers
  /////////////////////////////TriggerResults
  edm::Handle<edm::TriggerResults> triggerResults = iEvent.getHandle(tok_trigRes_);
  if (triggerResults.isValid()) {
    bool ok(false);
    std::vector<std::string> modules;
    const edm::TriggerNames& triggerNames = iEvent.triggerNames(*triggerResults);
    const std::vector<std::string>& triggerNames_ = triggerNames.triggerNames();
    for (unsigned int iHLT = 0; iHLT < triggerResults->size(); iHLT++) {
      int hlt = triggerResults->accept(iHLT);
      for (unsigned int i = 0; i < trigNames_.size(); ++i) {
        if (triggerNames_[iHLT].find(trigNames_[i]) != std::string::npos) {
          if (hlt > 0) {
            ok = true;
          }
#ifdef EDM_ML_DEBUG
          edm::LogVerbatim("HEMuon") << "AlCaHEMuonFilter::Trigger " << triggerNames_[iHLT] << " Flag " << hlt << ":"
                                     << ok << std::endl;
#endif
        }
      }
    }
    if (ok) {
      //Step2: Get geometry/B-field information
      //Get magnetic field
      const MagneticField* bField = &(iSetup.getData(tok_magField_));
      const CaloGeometry* geo = &(iSetup.getData(tok_geom_));

      // Relevant blocks from iEvent
      edm::Handle<reco::MuonCollection> muonHandle = iEvent.getHandle(tok_Muon_);
#ifdef EDM_ML_DEBUG
      edm::LogVerbatim("HEMuon") << "AlCaHEMuonFilter::Muon Handle " << muonHandle.isValid();
#endif
      if (muonHandle.isValid()) {
        for (reco::MuonCollection::const_iterator RecMuon = muonHandle->begin(); RecMuon != muonHandle->end();
             ++RecMuon) {
#ifdef EDM_ML_DEBUG
          edm::LogVerbatim("HEMuon") << "AlCaHEMuonFilter::Muon:Track " << RecMuon->track().isNonnull()
                                     << " innerTrack " << RecMuon->innerTrack().isNonnull() << " outerTrack "
                                     << RecMuon->outerTrack().isNonnull() << " globalTrack "
                                     << RecMuon->globalTrack().isNonnull() << std::endl;
#endif
          if ((RecMuon->track().isNonnull()) && (RecMuon->innerTrack().isNonnull()) &&
              (RecMuon->outerTrack().isNonnull()) && (RecMuon->globalTrack().isNonnull())) {
            bool ptCut = RecMuon->pt() < muonptCut_;
            bool etaCut = fabs(RecMuon->eta()) < muonetaCut_;
            if (ptCut || etaCut)
              continue;

            const reco::Track* pTrack = (RecMuon->innerTrack()).get();
            spr::propagatedTrackID trackID = spr::propagateCALO(pTrack, geo, bField, false);
#ifdef EDM_ML_DEBUG
            edm::LogVerbatim("HEMuon") << "AlCaHEMuonFilter::Propagate: ECAL " << trackID.okECAL << " to HCAL "
                                       << trackID.okHCAL << std::endl;
#endif
            double trackIso = RecMuon->isolationR03().sumPt;
            double caloIso = RecMuon->isolationR03().emEt + RecMuon->isolationR03().hadEt;
            double isolR04 =
                ((RecMuon->pfIsolationR04().sumChargedHadronPt +
                  std::max(0.,
                           RecMuon->pfIsolationR04().sumNeutralHadronEt + RecMuon->pfIsolationR04().sumPhotonEt -
                               (0.5 * RecMuon->pfIsolationR04().sumPUPt))) /
                 RecMuon->pt());
            bool isoCut = (pfCut_) ? (isolR04 < pfIsoCut_) : ((trackIso < trackIsoCut_) && (caloIso < caloIsoCut_));
            if ((trackID.okECAL) && (trackID.okHCAL) && isoCut) {
              accept = true;
              break;
            }
          }
        }
      }
    }
  }
  // Step 4:  Return the acceptance flag
  if (accept) {
    ++nGood_;
    if (((nGood_ - 1) % preScale_) != 0) {
      accept = false;
    } else {
      ++nFinal_;
    }
  }
  return accept;

}  // AlCaHEMuonFilter::filter

// ------------ method called once each job just after ending the event loop  ------------
void AlCaHEMuonFilter::endStream() {
  globalCache()->nAll_ += nAll_;
  globalCache()->nGood_ += nGood_;
  globalCache()->nFinal_ += nFinal_;
}

void AlCaHEMuonFilter::globalEndJob(const alCaHEMuonFilter::Counters* count) {
  edm::LogVerbatim("HEMuon") << "Selects " << count->nFinal_ << " out of " << count->nGood_ << " good events out of "
                             << count->nAll_ << " total # of events\n";
}

// ------------ method called when starting to processes a run  ------------
void AlCaHEMuonFilter::beginRun(edm::Run const& iRun, edm::EventSetup const& iSetup) {
  bool changed(false);
  bool flag = hltConfig_.init(iRun, iSetup, processName_, changed);
  edm::LogVerbatim("HEMuon") << "Run[" << nRun_ << "] " << iRun.run() << " hltconfig.init " << flag << std::endl;
}

// ------------ method called when ending the processing of a run  ------------
void AlCaHEMuonFilter::endRun(edm::Run const& iRun, edm::EventSetup const&) {
  edm::LogVerbatim("HEMuon") << "endRun[" << nRun_ << "] " << iRun.run() << "\n";
  nRun_++;
}

// ------------ method fills 'descriptions' with the allowed parameters for the module  ------------
void AlCaHEMuonFilter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  //The following says we do not know what parameters are allowed so do no validation
  // Please change this to state exactly what you do use, even if it is no parameters
  edm::ParameterSetDescription desc;
  std::vector<std::string> triggers = {"HLT_IsoMu", "HLT_Mu"};
  desc.add<std::string>("processName", "HLT");
  desc.add<edm::InputTag>("triggerResultLabel", edm::InputTag("TriggerResults", "", "HLT"));
  desc.add<edm::InputTag>("muonLabel", edm::InputTag("muons"));
  desc.add<std::vector<std::string> >("triggers", triggers);
  desc.add<double>("muonPtCut", 5.0);
  desc.add<double>("muonEtaCut", 1.305);
  desc.add<bool>("pfCut", true);
  desc.add<double>("pfIsolationCut", 0.15);
  desc.add<double>("trackIsolationCut", 3.0);
  desc.add<double>("caloIsolationCut", 5.0);
  desc.add<int>("preScale", 1);
  descriptions.add("alcaHEMuonFilter", desc);
}

//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(AlCaHEMuonFilter);