diff --git a/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronIDHeavyObjectCache.h b/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronIDHeavyObjectCache.h index 0356c3de940b3..225b959c78e91 100644 --- a/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronIDHeavyObjectCache.h +++ b/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronIDHeavyObjectCache.h @@ -6,13 +6,13 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include -namespace reco { +namespace reco { class BeamSpot; - class PreId; -} + class PreId; +} // namespace reco namespace lowptgsfeleid { - + class Features { public: // KF track @@ -22,7 +22,7 @@ namespace lowptgsfeleid { // GSF track float gsf_nhits_ = -1.; float gsf_chi2red_ = -1.; - // SC + // SC float sc_E_ = -1.; float sc_eta_ = -1.; float sc_etaWidth_ = -1.; @@ -43,28 +43,25 @@ namespace lowptgsfeleid { float rho_ = -1.; float brem_frac_ = -1.; float ele_pt_ = -1.; + public: std::vector get(); - void set( const reco::GsfElectronRef& ele, double rho ); + void set(const reco::GsfElectronRef& ele, double rho); }; - - class HeavyObjectCache { + class HeavyObjectCache { public: - - HeavyObjectCache( const edm::ParameterSet& ); + HeavyObjectCache(const edm::ParameterSet&); std::vector modelNames() const { return names_; } - double eval( const std::string& name, const reco::GsfElectronRef&, double rho ) const; - - private: + double eval(const std::string& name, const reco::GsfElectronRef&, double rho) const; + private: std::vector names_; - std::vector< std::unique_ptr > models_; + std::vector > models_; std::vector thresholds_; - }; -} +} // namespace lowptgsfeleid -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronIDHeavyObjectCache_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronIDHeavyObjectCache_h diff --git a/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronSeedHeavyObjectCache.h b/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronSeedHeavyObjectCache.h index 3216410b1a65e..fe3807b8415fc 100644 --- a/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronSeedHeavyObjectCache.h +++ b/RecoEgamma/EgammaElectronProducers/interface/LowPtGsfElectronSeedHeavyObjectCache.h @@ -6,13 +6,13 @@ #include "RecoEcal/EgammaCoreTools/interface/EcalClusterLazyTools.h" #include -namespace reco { +namespace reco { class BeamSpot; - class PreId; -} + class PreId; +} // namespace reco namespace lowptgsfeleseed { - + class Features { public: float trk_pt_ = -1.; @@ -39,38 +39,34 @@ namespace lowptgsfeleseed { float preid_gsf_dpt_ = -1.; float preid_trk_gsf_chiratio_ = -1.; float preid_gsf_chi2red_ = -1.; - float trk_dxy_sig_ = -1.; // must be last (not used by unbiased model) + float trk_dxy_sig_ = -1.; // must be last (not used by unbiased model) public: std::vector get(); - void set( const reco::PreId& ecal, - const reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ); + void set(const reco::PreId& ecal, + const reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools); }; class HeavyObjectCache { - public: - - HeavyObjectCache( const edm::ParameterSet& ); + HeavyObjectCache(const edm::ParameterSet&); std::vector modelNames() const { return names_; } - bool eval( const std::string& name, - reco::PreId& ecal, - reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ) const; - - private: + bool eval(const std::string& name, + reco::PreId& ecal, + reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools) const; + private: std::vector names_; - std::vector< std::unique_ptr > models_; + std::vector > models_; std::vector thresholds_; - }; -} +} // namespace lowptgsfeleseed -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedHeavyObjectCache_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedHeavyObjectCache_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/ElectronNHitSeedProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/ElectronNHitSeedProducer.cc index 35a2f1a87c679..82f035dc0578e 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/ElectronNHitSeedProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/ElectronNHitSeedProducer.cc @@ -1,21 +1,19 @@ //****************************************************************************** // // Part of the refactorisation of of the E/gamma pixel matching for 2017 pixels -// This refactorisation converts the monolithic approach to a series of -// independent producer modules, with each modules performing a specific +// This refactorisation converts the monolithic approach to a series of +// independent producer modules, with each modules performing a specific // job as recommended by the 2017 tracker framework // // // The module produces the ElectronSeeds, similarly to ElectronSeedProducer // although with a varible number of required hits -// +// // // Author : Sam Harper (RAL), 2017 // //******************************************************************************* - - #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" @@ -41,139 +39,123 @@ class ElectronNHitSeedProducer : public edm::stream::EDProducer<> { public: - - - explicit ElectronNHitSeedProducer( const edm::ParameterSet & ) ; - ~ElectronNHitSeedProducer() override =default; - - void produce( edm::Event &, const edm::EventSetup & ) final; - + explicit ElectronNHitSeedProducer(const edm::ParameterSet&); + ~ElectronNHitSeedProducer() override = default; + + void produce(edm::Event&, const edm::EventSetup&) final; + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: - TrajSeedMatcher matcher_; - - std::vector> > superClustersTokens_; - edm::EDGetTokenT initialSeedsToken_ ; - edm::EDGetTokenT > verticesToken_; - edm::EDGetTokenT beamSpotToken_ ; + + std::vector>> superClustersTokens_; + edm::EDGetTokenT initialSeedsToken_; + edm::EDGetTokenT> verticesToken_; + edm::EDGetTokenT beamSpotToken_; edm::EDGetTokenT measTkEvtToken_; - }; namespace { - template - edm::Handle getHandle(const edm::Event& event,const edm::EDGetTokenT& token) - { + template + edm::Handle getHandle(const edm::Event& event, const edm::EDGetTokenT& token) { edm::Handle handle; - event.getByToken(token,handle); + event.getByToken(token, handle); return handle; } - template - GlobalPoint convertToGP(const T& orgPoint){ - return GlobalPoint(orgPoint.x(),orgPoint.y(),orgPoint.z()); + template + GlobalPoint convertToGP(const T& orgPoint) { + return GlobalPoint(orgPoint.x(), orgPoint.y(), orgPoint.z()); } - int getLayerOrDiskNr(DetId detId,const TrackerTopology& trackerTopo) - { - if(detId.subdetId()==PixelSubdetector::PixelBarrel){ + int getLayerOrDiskNr(DetId detId, const TrackerTopology& trackerTopo) { + if (detId.subdetId() == PixelSubdetector::PixelBarrel) { return trackerTopo.pxbLayer(detId); - }else if(detId.subdetId()==PixelSubdetector::PixelEndcap){ + } else if (detId.subdetId() == PixelSubdetector::PixelEndcap) { return trackerTopo.pxfDisk(detId); - }else return -1; + } else + return -1; } - - reco::ElectronSeed::PMVars - makeSeedPixelVar(const TrajSeedMatcher::MatchInfo& matchInfo, - const TrackerTopology& trackerTopo) - { - - int layerOrDisk = getLayerOrDiskNr(matchInfo.detId,trackerTopo); + + reco::ElectronSeed::PMVars makeSeedPixelVar(const TrajSeedMatcher::MatchInfo& matchInfo, + const TrackerTopology& trackerTopo) { + int layerOrDisk = getLayerOrDiskNr(matchInfo.detId, trackerTopo); reco::ElectronSeed::PMVars pmVars; - pmVars.setDet(matchInfo.detId,layerOrDisk); - pmVars.setDPhi(matchInfo.dPhiPos,matchInfo.dPhiNeg); - pmVars.setDRZ(matchInfo.dRZPos,matchInfo.dRZNeg); - + pmVars.setDet(matchInfo.detId, layerOrDisk); + pmVars.setDPhi(matchInfo.dPhiPos, matchInfo.dPhiNeg); + pmVars.setDRZ(matchInfo.dRZPos, matchInfo.dRZNeg); + return pmVars; - } + } -} +} // namespace -ElectronNHitSeedProducer::ElectronNHitSeedProducer( const edm::ParameterSet& pset): - matcher_(pset.getParameter("matcherConfig")), - initialSeedsToken_(consumes(pset.getParameter("initialSeeds"))), - verticesToken_(consumes >(pset.getParameter("vertices"))), - beamSpotToken_(consumes(pset.getParameter("beamSpot"))), - measTkEvtToken_(consumes(pset.getParameter("measTkEvt"))) -{ - const auto superClusTags = pset.getParameter >("superClusters"); - for(const auto& scTag : superClusTags){ +ElectronNHitSeedProducer::ElectronNHitSeedProducer(const edm::ParameterSet& pset) + : matcher_(pset.getParameter("matcherConfig")), + initialSeedsToken_(consumes(pset.getParameter("initialSeeds"))), + verticesToken_(consumes>(pset.getParameter("vertices"))), + beamSpotToken_(consumes(pset.getParameter("beamSpot"))), + measTkEvtToken_(consumes(pset.getParameter("measTkEvt"))) { + const auto superClusTags = pset.getParameter>("superClusters"); + for (const auto& scTag : superClusTags) { superClustersTokens_.emplace_back(consumes>(scTag)); } - produces() ; + produces(); } -void ElectronNHitSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) -{ +void ElectronNHitSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("initialSeeds",edm::InputTag("hltElePixelSeedsCombined")); - desc.add("vertices",edm::InputTag()); - desc.add("beamSpot",edm::InputTag("hltOnlineBeamSpot")); - desc.add("measTkEvt",edm::InputTag("hltSiStripClusters")); - desc.add >("superClusters",std::vector{edm::InputTag{"hltEgammaSuperClustersToPixelMatch"}}); - desc.add("matcherConfig",TrajSeedMatcher::makePSetDescription()); - - descriptions.add("electronNHitSeedProducer",desc); + desc.add("initialSeeds", edm::InputTag("hltElePixelSeedsCombined")); + desc.add("vertices", edm::InputTag()); + desc.add("beamSpot", edm::InputTag("hltOnlineBeamSpot")); + desc.add("measTkEvt", edm::InputTag("hltSiStripClusters")); + desc.add>("superClusters", + std::vector{edm::InputTag{"hltEgammaSuperClustersToPixelMatch"}}); + desc.add("matcherConfig", TrajSeedMatcher::makePSetDescription()); + + descriptions.add("electronNHitSeedProducer", desc); } -void ElectronNHitSeedProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void ElectronNHitSeedProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { edm::ESHandle trackerTopoHandle; iSetup.get().get(trackerTopoHandle); - + matcher_.doEventSetup(iSetup); - matcher_.setMeasTkEvtHandle(getHandle(iEvent,measTkEvtToken_)); + matcher_.setMeasTkEvtHandle(getHandle(iEvent, measTkEvtToken_)); auto eleSeeds = std::make_unique(); - - auto initialSeedsHandle = getHandle(iEvent,initialSeedsToken_); - auto beamSpotHandle = getHandle(iEvent,beamSpotToken_); - GlobalPoint primVtxPos = convertToGP(beamSpotHandle->position()); + auto initialSeedsHandle = getHandle(iEvent, initialSeedsToken_); - for(const auto& superClustersToken : superClustersTokens_){ - auto superClustersHandle = getHandle(iEvent,superClustersToken); - for(auto& superClusRef : *superClustersHandle){ + auto beamSpotHandle = getHandle(iEvent, beamSpotToken_); + GlobalPoint primVtxPos = convertToGP(beamSpotHandle->position()); + for (const auto& superClustersToken : superClustersTokens_) { + auto superClustersHandle = getHandle(iEvent, superClustersToken); + for (auto& superClusRef : *superClustersHandle) { //the eta of the supercluster when mustache clustered is slightly biased due to bending in magnetic field //the eta of its seed cluster is a better estimate of the orginal position - GlobalPoint caloPosition(GlobalPoint::Polar(superClusRef->seed()->position().theta(), //seed theta - superClusRef->position().phi(), //supercluster phi - superClusRef->position().r())); //supercluster r - - - const std::vector matchedSeeds = - matcher_.compatibleSeeds(*initialSeedsHandle,caloPosition, - primVtxPos,superClusRef->energy()); - - for(auto& matchedSeed : matchedSeeds){ - reco::ElectronSeed eleSeed(matchedSeed.seed()); - reco::ElectronSeed::CaloClusterRef caloClusRef(superClusRef); - eleSeed.setCaloCluster(caloClusRef); - eleSeed.setNrLayersAlongTraj(matchedSeed.nrValidLayers()); - for(auto& matchInfo : matchedSeed.matches()){ - eleSeed.addHitInfo(makeSeedPixelVar(matchInfo,*trackerTopoHandle)); - } - eleSeeds->emplace_back(eleSeed); + GlobalPoint caloPosition(GlobalPoint::Polar(superClusRef->seed()->position().theta(), //seed theta + superClusRef->position().phi(), //supercluster phi + superClusRef->position().r())); //supercluster r + + const std::vector matchedSeeds = + matcher_.compatibleSeeds(*initialSeedsHandle, caloPosition, primVtxPos, superClusRef->energy()); + + for (auto& matchedSeed : matchedSeeds) { + reco::ElectronSeed eleSeed(matchedSeed.seed()); + reco::ElectronSeed::CaloClusterRef caloClusRef(superClusRef); + eleSeed.setCaloCluster(caloClusRef); + eleSeed.setNrLayersAlongTraj(matchedSeed.nrValidLayers()); + for (auto& matchInfo : matchedSeed.matches()) { + eleSeed.addHitInfo(makeSeedPixelVar(matchInfo, *trackerTopoHandle)); + } + eleSeeds->emplace_back(eleSeed); } } - } iEvent.put(std::move(eleSeeds)); } - - DEFINE_FWK_MODULE(ElectronNHitSeedProducer); diff --git a/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.cc index 1d22e2c573af4..5a48b1a6e97ea 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.cc @@ -56,89 +56,87 @@ #include -using namespace reco ; +using namespace reco; -ElectronSeedProducer::ElectronSeedProducer( const edm::ParameterSet& iConfig ) - : applyHOverECut_(true), hcalHelper_(nullptr), - caloGeom_(nullptr), caloGeomCacheId_(0), caloTopo_(nullptr), caloTopoCacheId_(0) - { - auto const& conf = iConfig.getParameter("SeedConfiguration") ; +ElectronSeedProducer::ElectronSeedProducer(const edm::ParameterSet& iConfig) + : applyHOverECut_(true), + hcalHelper_(nullptr), + caloGeom_(nullptr), + caloGeomCacheId_(0), + caloTopo_(nullptr), + caloTopoCacheId_(0) { + auto const& conf = iConfig.getParameter("SeedConfiguration"); auto legacyConfSeeds = conf.getParameter("initialSeeds"); - if (legacyConfSeeds.label().empty()) - {//new format - initialSeeds_ = edm::vector_transform(conf.getParameter >( "initialSeedsVector" ), - [this](edm::InputTag const & tag){return consumes(tag);}); - } - else - { - initialSeeds_ = {consumes(conf.getParameter("initialSeeds"))}; - } + if (legacyConfSeeds.label().empty()) { //new format + initialSeeds_ = + edm::vector_transform(conf.getParameter>("initialSeedsVector"), + [this](edm::InputTag const& tag) { return consumes(tag); }); + } else { + initialSeeds_ = {consumes(conf.getParameter("initialSeeds"))}; + } SCEtCut_ = conf.getParameter("SCEtCut"); - fromTrackerSeeds_ = conf.getParameter("fromTrackerSeeds") ; - prefilteredSeeds_ = conf.getParameter("preFilteredSeeds") ; + fromTrackerSeeds_ = conf.getParameter("fromTrackerSeeds"); + prefilteredSeeds_ = conf.getParameter("preFilteredSeeds"); auto theconsumes = consumesCollector(); // new beamSpot tag - beamSpotTag_ = consumes(conf.getParameter("beamSpot")); + beamSpotTag_ = consumes(conf.getParameter("beamSpot")); // for H/E - applyHOverECut_ = conf.getParameter("applyHOverECut") ; - if (applyHOverECut_) - { - ElectronHcalHelper::Configuration hcalCfg ; - hcalCfg.hOverEConeSize = conf.getParameter("hOverEConeSize") ; - if (hcalCfg.hOverEConeSize>0) - { - hcalCfg.useTowers = true ; - hcalCfg.hcalTowers = - consumes(conf.getParameter("hcalTowers")) ; - hcalCfg.hOverEPtMin = conf.getParameter("hOverEPtMin") ; - } - hcalHelper_ = new ElectronHcalHelper(hcalCfg) ; - - allowHGCal_ = conf.getParameter("allowHGCal"); - if( allowHGCal_ ) { - const edm::ParameterSet& hgcCfg = conf.getParameterSet("HGCalConfig"); - hgcClusterTools_.reset( new hgcal::ClusterTools(hgcCfg, theconsumes) ); - } - - maxHOverEBarrel_=conf.getParameter("maxHOverEBarrel") ; - maxHOverEEndcaps_=conf.getParameter("maxHOverEEndcaps") ; - maxHBarrel_=conf.getParameter("maxHBarrel") ; - maxHEndcaps_=conf.getParameter("maxHEndcaps") ; - } + applyHOverECut_ = conf.getParameter("applyHOverECut"); + if (applyHOverECut_) { + ElectronHcalHelper::Configuration hcalCfg; + hcalCfg.hOverEConeSize = conf.getParameter("hOverEConeSize"); + if (hcalCfg.hOverEConeSize > 0) { + hcalCfg.useTowers = true; + hcalCfg.hcalTowers = consumes(conf.getParameter("hcalTowers")); + hcalCfg.hOverEPtMin = conf.getParameter("hOverEPtMin"); + } + hcalHelper_ = new ElectronHcalHelper(hcalCfg); + + allowHGCal_ = conf.getParameter("allowHGCal"); + if (allowHGCal_) { + const edm::ParameterSet& hgcCfg = conf.getParameterSet("HGCalConfig"); + hgcClusterTools_.reset(new hgcal::ClusterTools(hgcCfg, theconsumes)); + } + + maxHOverEBarrel_ = conf.getParameter("maxHOverEBarrel"); + maxHOverEEndcaps_ = conf.getParameter("maxHOverEEndcaps"); + maxHBarrel_ = conf.getParameter("maxHBarrel"); + maxHEndcaps_ = conf.getParameter("maxHEndcaps"); + } applySigmaIEtaIEtaCut_ = conf.getParameter("applySigmaIEtaIEtaCut"); // apply sigma_ieta_ieta cut - if (applySigmaIEtaIEtaCut_ == true) - { - maxSigmaIEtaIEtaBarrel_ = conf.getParameter("maxSigmaIEtaIEtaBarrel"); - maxSigmaIEtaIEtaEndcaps_ = conf.getParameter("maxSigmaIEtaIEtaEndcaps"); - } + if (applySigmaIEtaIEtaCut_ == true) { + maxSigmaIEtaIEtaBarrel_ = conf.getParameter("maxSigmaIEtaIEtaBarrel"); + maxSigmaIEtaIEtaEndcaps_ = conf.getParameter("maxSigmaIEtaIEtaEndcaps"); + } edm::ParameterSet rpset = conf.getParameter("RegionPSet"); ElectronSeedGenerator::Tokens esg_tokens; esg_tokens.token_bs = beamSpotTag_; esg_tokens.token_vtx = mayConsume(conf.getParameter("vertices")); - esg_tokens.token_measTrkEvt= consumes(conf.getParameter("measurementTrackerEvent")); + esg_tokens.token_measTrkEvt = + consumes(conf.getParameter("measurementTrackerEvent")); - matcher_ = new ElectronSeedGenerator(conf,esg_tokens) ; + matcher_ = new ElectronSeedGenerator(conf, esg_tokens); // get collections from config if (applySigmaIEtaIEtaCut_ == true) { - ebRecHitCollection_ = consumes (iConfig.getParameter("ebRecHitCollection")); - eeRecHitCollection_ = consumes (iConfig.getParameter("eeRecHitCollection")); + ebRecHitCollection_ = consumes(iConfig.getParameter("ebRecHitCollection")); + eeRecHitCollection_ = consumes(iConfig.getParameter("eeRecHitCollection")); } - superClusters_[0]= - consumes(iConfig.getParameter("barrelSuperClusters")) ; - superClusters_[1]= - consumes(iConfig.getParameter("endcapSuperClusters")) ; + superClusters_[0] = + consumes(iConfig.getParameter("barrelSuperClusters")); + superClusters_[1] = + consumes(iConfig.getParameter("endcapSuperClusters")); // Construction of SeedFilter was in beginRun() with the comment // below, but it has to be done here because of ConsumesCollector @@ -148,117 +146,103 @@ ElectronSeedProducer::ElectronSeedProducer( const edm::ParameterSet& iConfig ) // we must redo the SeedFilter for each run. if (prefilteredSeeds_) { SeedFilter::Tokens sf_tokens; - sf_tokens.token_bs = beamSpotTag_; - sf_tokens.token_vtx = consumes >(rpset.getParameter ("VertexProducer")); + sf_tokens.token_bs = beamSpotTag_; + sf_tokens.token_vtx = consumes>(rpset.getParameter("VertexProducer")); edm::ConsumesCollector iC = consumesCollector(); seedFilter_.reset(new SeedFilter(conf, sf_tokens, iC)); } //register your products - produces() ; + produces(); } -void ElectronSeedProducer::beginRun(edm::Run const&, edm::EventSetup const&) -{} +void ElectronSeedProducer::beginRun(edm::Run const&, edm::EventSetup const&) {} -void ElectronSeedProducer::endRun(edm::Run const&, edm::EventSetup const&) -{} +void ElectronSeedProducer::endRun(edm::Run const&, edm::EventSetup const&) {} -ElectronSeedProducer::~ElectronSeedProducer() - { - delete hcalHelper_ ; - delete matcher_ ; - } +ElectronSeedProducer::~ElectronSeedProducer() { + delete hcalHelper_; + delete matcher_; +} -void ElectronSeedProducer::produce(edm::Event& e, const edm::EventSetup& iSetup) - { - LogDebug("ElectronSeedProducer") <<"[ElectronSeedProducer::produce] entering " ; +void ElectronSeedProducer::produce(edm::Event& e, const edm::EventSetup& iSetup) { + LogDebug("ElectronSeedProducer") << "[ElectronSeedProducer::produce] entering "; - edm::Handle theBeamSpot ; - e.getByToken(beamSpotTag_,theBeamSpot) ; + edm::Handle theBeamSpot; + e.getByToken(beamSpotTag_, theBeamSpot); - if (hcalHelper_) - { - hcalHelper_->checkSetup(iSetup) ; - hcalHelper_->readEvent(e) ; - if( allowHGCal_ ) { + if (hcalHelper_) { + hcalHelper_->checkSetup(iSetup); + hcalHelper_->readEvent(e); + if (allowHGCal_) { hgcClusterTools_->getEventSetup(iSetup); hgcClusterTools_->getEvent(e); } - } + } // get calo geometry - if (caloGeomCacheId_!=iSetup.get().cacheIdentifier()) { + if (caloGeomCacheId_ != iSetup.get().cacheIdentifier()) { iSetup.get().get(caloGeom_); - caloGeomCacheId_=iSetup.get().cacheIdentifier(); + caloGeomCacheId_ = iSetup.get().cacheIdentifier(); } - if (caloTopoCacheId_!=iSetup.get().cacheIdentifier()){ - caloTopoCacheId_=iSetup.get().cacheIdentifier(); + if (caloTopoCacheId_ != iSetup.get().cacheIdentifier()) { + caloTopoCacheId_ = iSetup.get().cacheIdentifier(); iSetup.get().get(caloTopo_); } matcher_->setupES(iSetup); // get initial TrajectorySeeds if necessary - if (fromTrackerSeeds_) - { - if (!prefilteredSeeds_) - { - theInitialSeedColls.clear(); - for (auto const& seeds : initialSeeds_) - { - edm::Handle hSeeds; - e.getByToken(seeds, hSeeds); - theInitialSeedColls.push_back(hSeeds.product()); - } - theInitialSeedColl = nullptr;// not needed in this case - - } - else - { - theInitialSeedColls.clear();//reset later - theInitialSeedColl = new TrajectorySeedCollection ; - } - } - else - { - // not needed in this case - theInitialSeedColls.clear(); - theInitialSeedColl = nullptr ; - } - - ElectronSeedCollection * seeds = new ElectronSeedCollection ; + if (fromTrackerSeeds_) { + if (!prefilteredSeeds_) { + theInitialSeedColls.clear(); + for (auto const& seeds : initialSeeds_) { + edm::Handle hSeeds; + e.getByToken(seeds, hSeeds); + theInitialSeedColls.push_back(hSeeds.product()); + } + theInitialSeedColl = nullptr; // not needed in this case + + } else { + theInitialSeedColls.clear(); //reset later + theInitialSeedColl = new TrajectorySeedCollection; + } + } else { + // not needed in this case + theInitialSeedColls.clear(); + theInitialSeedColl = nullptr; + } + + ElectronSeedCollection* seeds = new ElectronSeedCollection; // loop over barrel + endcap - for (unsigned int i=0; i<2; i++) { - edm::Handle clusters ; - e.getByToken(superClusters_[i],clusters); - SuperClusterRefVector clusterRefs ; - std::vector hoe1s, hoe2s ; - filterClusters(*theBeamSpot,clusters,/*mhbhe_,*/clusterRefs,hoe1s,hoe2s,e, iSetup); - if ((fromTrackerSeeds_) && (prefilteredSeeds_)) - { filterSeeds(e,iSetup,clusterRefs) ; } - matcher_->run(e,iSetup,clusterRefs,hoe1s,hoe2s,theInitialSeedColls,*seeds); + for (unsigned int i = 0; i < 2; i++) { + edm::Handle clusters; + e.getByToken(superClusters_[i], clusters); + SuperClusterRefVector clusterRefs; + std::vector hoe1s, hoe2s; + filterClusters(*theBeamSpot, clusters, /*mhbhe_,*/ clusterRefs, hoe1s, hoe2s, e, iSetup); + if ((fromTrackerSeeds_) && (prefilteredSeeds_)) { + filterSeeds(e, iSetup, clusterRefs); + } + matcher_->run(e, iSetup, clusterRefs, hoe1s, hoe2s, theInitialSeedColls, *seeds); } // store the accumulated result std::unique_ptr pSeeds(seeds); - ElectronSeedCollection::iterator is ; - for ( is=pSeeds->begin() ; is!=pSeeds->end() ; is++ ) { - edm::RefToBase caloCluster = is->caloCluster() ; - SuperClusterRef superCluster = caloCluster.castTo() ; - LogDebug("ElectronSeedProducer") - << "new seed with " - << (*is).nHits() << " hits" - << ", charge " << (*is).getCharge() - << " and cluster energy " << superCluster->energy() - << " PID "<begin(); is != pSeeds->end(); is++) { + edm::RefToBase caloCluster = is->caloCluster(); + SuperClusterRef superCluster = caloCluster.castTo(); + LogDebug("ElectronSeedProducer") << "new seed with " << (*is).nHits() << " hits" + << ", charge " << (*is).getCharge() << " and cluster energy " + << superCluster->energy() << " PID " << superCluster.id(); } e.put(std::move(pSeeds)); - if (fromTrackerSeeds_ && prefilteredSeeds_) delete theInitialSeedColl; - } - + if (fromTrackerSeeds_ && prefilteredSeeds_) + delete theInitialSeedColl; +} //=============================== // Filter the superclusters @@ -266,88 +250,84 @@ void ElectronSeedProducer::produce(edm::Event& e, const edm::EventSetup& iSetup) // - with HoE using calo cone //=============================== -void ElectronSeedProducer::filterClusters - ( const reco::BeamSpot & bs, - const edm::Handle & superClusters, - SuperClusterRefVector & sclRefs, - std::vector & hoe1s, std::vector & hoe2s, - edm::Event & event, const edm::EventSetup & setup) - { - - std::vector sigmaIEtaIEtaEB_; - std::vector sigmaIEtaIEtaEE_; - - for (unsigned int i=0;isize();++i) - { - const SuperCluster & scl = (*superClusters)[i] ; - double sclEta = EleRelPoint(scl.position(),bs.position()).eta() ; - if (scl.energy()/cosh(sclEta)>SCEtCut_) - { -// if ((applyHOverECut_==true)&&((hcalHelper_->hcalESum(scl)/scl.energy()) > maxHOverE_)) -// { continue ; } -// sclRefs.push_back(edm::Ref(superClusters,i)) ; - double had1, had2, had, scle ; - - bool HoeVeto = false ; - if (applyHOverECut_==true) - { - had1 = hcalHelper_->hcalESumDepth1(scl); - had2 = hcalHelper_->hcalESumDepth2(scl); - had = had1+had2 ; - scle = scl.energy() ; - int det_group = scl.seed()->hitsAndFractions()[0].first.det() ; - int detector = scl.seed()->hitsAndFractions()[0].first.subdetId() ; - if ( detector==EcalBarrel && (hadgetClusterHadronFraction(*(scl.seed())); - had1 = had_fraction*scl.seed()->energy(); - had2 = 0.; - HoeVeto= ( had_fraction >= 0.f && had_fraction < maxHOverEEndcaps_ ); - } - if (HoeVeto) - { - sclRefs.push_back(edm::Ref(superClusters,i)) ; - hoe1s.push_back(had1/scle) ; - hoe2s.push_back(had2/scle) ; - } +void ElectronSeedProducer::filterClusters(const reco::BeamSpot& bs, + const edm::Handle& superClusters, + SuperClusterRefVector& sclRefs, + std::vector& hoe1s, + std::vector& hoe2s, + edm::Event& event, + const edm::EventSetup& setup) { + std::vector sigmaIEtaIEtaEB_; + std::vector sigmaIEtaIEtaEE_; + + for (unsigned int i = 0; i < superClusters->size(); ++i) { + const SuperCluster& scl = (*superClusters)[i]; + double sclEta = EleRelPoint(scl.position(), bs.position()).eta(); + if (scl.energy() / cosh(sclEta) > SCEtCut_) { + // if ((applyHOverECut_==true)&&((hcalHelper_->hcalESum(scl)/scl.energy()) > maxHOverE_)) + // { continue ; } + // sclRefs.push_back(edm::Ref(superClusters,i)) ; + double had1, had2, had, scle; + + bool HoeVeto = false; + if (applyHOverECut_ == true) { + had1 = hcalHelper_->hcalESumDepth1(scl); + had2 = hcalHelper_->hcalESumDepth2(scl); + had = had1 + had2; + scle = scl.energy(); + int det_group = scl.seed()->hitsAndFractions()[0].first.det(); + int detector = scl.seed()->hitsAndFractions()[0].first.subdetId(); + if (detector == EcalBarrel && (had < maxHBarrel_ || had / scle < maxHOverEBarrel_)) + HoeVeto = true; + else if (!allowHGCal_ && detector == EcalEndcap && (had < maxHEndcaps_ || had / scle < maxHOverEEndcaps_)) + HoeVeto = true; + else if (allowHGCal_ && EcalTools::isHGCalDet((DetId::Detector)det_group)) { + float had_fraction = hgcClusterTools_->getClusterHadronFraction(*(scl.seed())); + had1 = had_fraction * scl.seed()->energy(); + had2 = 0.; + HoeVeto = (had_fraction >= 0.f && had_fraction < maxHOverEEndcaps_); } - else - { - sclRefs.push_back(edm::Ref(superClusters,i)) ; - hoe1s.push_back(std::numeric_limits::infinity()) ; - hoe2s.push_back(std::numeric_limits::infinity()) ; + if (HoeVeto) { + sclRefs.push_back(edm::Ref(superClusters, i)); + hoe1s.push_back(had1 / scle); + hoe2s.push_back(had2 / scle); } - } - - if (applySigmaIEtaIEtaCut_ == true) - { - noZS::EcalClusterLazyTools lazyTool_noZS(event, setup, ebRecHitCollection_, eeRecHitCollection_); - std::vector vCov = lazyTool_noZS.localCovariances(*(scl.seed())); - int detector = scl.seed()->hitsAndFractions()[0].first.subdetId() ; - if (detector==EcalBarrel) sigmaIEtaIEtaEB_ .push_back(edm::isNotFinite(vCov[0]) ? 0. : sqrt(vCov[0])); - if (detector==EcalEndcap) sigmaIEtaIEtaEE_ .push_back(edm::isNotFinite(vCov[0]) ? 0. : sqrt(vCov[0])); + } else { + sclRefs.push_back(edm::Ref(superClusters, i)); + hoe1s.push_back(std::numeric_limits::infinity()); + hoe2s.push_back(std::numeric_limits::infinity()); } - } - LogDebug("ElectronSeedProducer")<<"Filtered out "<size() ; - } - -void ElectronSeedProducer::filterSeeds - ( edm::Event & event, const edm::EventSetup & setup, - reco::SuperClusterRefVector & sclRefs ) - { - for ( unsigned int i=0 ; iseeds(event,setup,sclRefs[i],theInitialSeedColl) ; + } + + if (applySigmaIEtaIEtaCut_ == true) { + noZS::EcalClusterLazyTools lazyTool_noZS(event, setup, ebRecHitCollection_, eeRecHitCollection_); + std::vector vCov = lazyTool_noZS.localCovariances(*(scl.seed())); + int detector = scl.seed()->hitsAndFractions()[0].first.subdetId(); + if (detector == EcalBarrel) + sigmaIEtaIEtaEB_.push_back(edm::isNotFinite(vCov[0]) ? 0. : sqrt(vCov[0])); + if (detector == EcalEndcap) + sigmaIEtaIEtaEE_.push_back(edm::isNotFinite(vCov[0]) ? 0. : sqrt(vCov[0])); + } + } + LogDebug("ElectronSeedProducer") << "Filtered out " << sclRefs.size() << " superclusters from " + << superClusters->size(); +} + +void ElectronSeedProducer::filterSeeds(edm::Event& event, + const edm::EventSetup& setup, + reco::SuperClusterRefVector& sclRefs) { + for (unsigned int i = 0; i < sclRefs.size(); ++i) { + seedFilter_->seeds(event, setup, sclRefs[i], theInitialSeedColl); theInitialSeedColls.push_back(theInitialSeedColl); - LogDebug("ElectronSeedProducer")<<"Number of Seeds: "<size() ; - } - } + LogDebug("ElectronSeedProducer") << "Number of Seeds: " << theInitialSeedColl->size(); + } +} -void -ElectronSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { +void ElectronSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("endcapSuperClusters",edm::InputTag("particleFlowSuperClusterECAL","particleFlowSuperClusterECALEndcapWithPreshower")); + desc.add( + "endcapSuperClusters", + edm::InputTag("particleFlowSuperClusterECAL", "particleFlowSuperClusterECALEndcapWithPreshower")); { edm::ParameterSetDescription psd0, psd1, psd2, psd3, psd4; psd1.add("maxElement", 0); @@ -360,83 +340,84 @@ ElectronSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descripti psd2.add("originHalfLength", 15.0); psd2.add("useZInVertex", true); psd2.add("deltaEtaRegion", 0.1); - psd2.add("ptMin", 1.5 ); + psd2.add("ptMin", 1.5); psd2.add("originRadius", 0.2); psd2.add("VertexProducer", edm::InputTag("dummyVertices")); psd0.add("RegionPSet", psd2); - - psd0.add("PhiMax2B",0.002); - psd0.add("hOverEPtMin",0.0); - psd0.add("PhiMax2F",0.003); - psd0.add("searchInTIDTEC",true); - psd0.add("pPhiMax1",0.125); - psd0.add("HighPtThreshold",35.0); - psd0.add("r2MinF",-0.15); - psd0.add("maxHBarrel",0.0); - psd0.add("DeltaPhi1Low",0.23); - psd0.add("DeltaPhi1High",0.08); - psd0.add("ePhiMin1",-0.125); - psd0.add("hcalTowers",edm::InputTag("towerMaker")); - psd0.add("LowPtThreshold",5.0); - psd0.add("maxHOverEBarrel",0.15); + + psd0.add("PhiMax2B", 0.002); + psd0.add("hOverEPtMin", 0.0); + psd0.add("PhiMax2F", 0.003); + psd0.add("searchInTIDTEC", true); + psd0.add("pPhiMax1", 0.125); + psd0.add("HighPtThreshold", 35.0); + psd0.add("r2MinF", -0.15); + psd0.add("maxHBarrel", 0.0); + psd0.add("DeltaPhi1Low", 0.23); + psd0.add("DeltaPhi1High", 0.08); + psd0.add("ePhiMin1", -0.125); + psd0.add("hcalTowers", edm::InputTag("towerMaker")); + psd0.add("LowPtThreshold", 5.0); + psd0.add("maxHOverEBarrel", 0.15); psd0.add("maxSigmaIEtaIEtaBarrel", 0.5); psd0.add("maxSigmaIEtaIEtaEndcaps", 0.5); - psd0.add("dynamicPhiRoad",true); - psd0.add("ePhiMax1",0.075); - psd0.add("measurementTrackerName",""); - psd0.add("SizeWindowENeg",0.675); - psd0.add("nSigmasDeltaZ1",5.0); - psd0.add("rMaxI",0.2); - psd0.add("maxHEndcaps",0.0); - psd0.add("preFilteredSeeds",false); - psd0.add("r2MaxF",0.15); - psd0.add("hOverEConeSize",0.15); - psd0.add("pPhiMin1",-0.075); - psd0.add("initialSeeds",edm::InputTag(""));//keep for be compatibility - psd0.add>("initialSeedsVector",{{"newCombinedSeeds"}}); - psd0.add("deltaZ1WithVertex",25.0); - psd0.add("SCEtCut",0.0); - psd0.add("z2MaxB",0.09); - psd0.add("fromTrackerSeeds",true); - psd0.add("hcalRecHits",edm::InputTag("hbhereco")); - psd0.add("z2MinB",-0.09); - psd0.add("rMinI",-0.2); - psd0.add("maxHOverEEndcaps",0.15); - psd0.add("hOverEHBMinE",0.7); - psd0.add("useRecoVertex",false); - psd0.add("beamSpot",edm::InputTag("offlineBeamSpot")); - psd0.add("measurementTrackerEvent",edm::InputTag("MeasurementTrackerEvent")); - psd0.add("vertices",edm::InputTag("offlinePrimaryVerticesWithBS")); - psd0.add("applyHOverECut",true); + psd0.add("dynamicPhiRoad", true); + psd0.add("ePhiMax1", 0.075); + psd0.add("measurementTrackerName", ""); + psd0.add("SizeWindowENeg", 0.675); + psd0.add("nSigmasDeltaZ1", 5.0); + psd0.add("rMaxI", 0.2); + psd0.add("maxHEndcaps", 0.0); + psd0.add("preFilteredSeeds", false); + psd0.add("r2MaxF", 0.15); + psd0.add("hOverEConeSize", 0.15); + psd0.add("pPhiMin1", -0.075); + psd0.add("initialSeeds", edm::InputTag("")); //keep for be compatibility + psd0.add>("initialSeedsVector", {{"newCombinedSeeds"}}); + psd0.add("deltaZ1WithVertex", 25.0); + psd0.add("SCEtCut", 0.0); + psd0.add("z2MaxB", 0.09); + psd0.add("fromTrackerSeeds", true); + psd0.add("hcalRecHits", edm::InputTag("hbhereco")); + psd0.add("z2MinB", -0.09); + psd0.add("rMinI", -0.2); + psd0.add("maxHOverEEndcaps", 0.15); + psd0.add("hOverEHBMinE", 0.7); + psd0.add("useRecoVertex", false); + psd0.add("beamSpot", edm::InputTag("offlineBeamSpot")); + psd0.add("measurementTrackerEvent", edm::InputTag("MeasurementTrackerEvent")); + psd0.add("vertices", edm::InputTag("offlinePrimaryVerticesWithBS")); + psd0.add("applyHOverECut", true); psd0.add("ebRecHitCollection", edm::InputTag("ecalRecHit", "EcalRecHitsEB")); psd0.add("eeRecHitCollection", edm::InputTag("ecalRecHit", "EcalRecHitsEE")); psd0.add("applySigmaIEtaIEtaCut", false); - psd0.add("DeltaPhi2F",0.012); - psd0.add("PhiMin2F",-0.003); - psd0.add("hOverEHFMinE",0.8); - psd0.add("DeltaPhi2B",0.008); - psd0.add("PhiMin2B",-0.002); - psd0.add("allowHGCal",false); - - psd3.add("ComponentName",std::string("SeedFromConsecutiveHitsCreator")); - psd3.add("propagator",std::string("PropagatorWithMaterial")); - psd3.add("SeedMomentumForBOFF",5.0); - psd3.add("OriginTransverseErrorMultiplier",1.0); - psd3.add("MinOneOverPtError",1.0); - psd3.add("magneticField",std::string("")); - psd3.add("TTRHBuilder",std::string("WithTrackAngle")); - psd3.add("forceKinematicWithRegionDirection",false); - - psd4.add("HGCEEInput",edm::InputTag("HGCalRecHit","HGCEERecHits")); - psd4.add("HGCFHInput",edm::InputTag("HGCalRecHit","HGCHEFRecHits")); - psd4.add("HGCBHInput",edm::InputTag("HGCalRecHit","HGCHEBRecHits")); - - psd0.add("HGCalConfig",psd4); - - psd0.add("SeedCreatorPSet",psd3); - - desc.add("SeedConfiguration",psd0); + psd0.add("DeltaPhi2F", 0.012); + psd0.add("PhiMin2F", -0.003); + psd0.add("hOverEHFMinE", 0.8); + psd0.add("DeltaPhi2B", 0.008); + psd0.add("PhiMin2B", -0.002); + psd0.add("allowHGCal", false); + + psd3.add("ComponentName", std::string("SeedFromConsecutiveHitsCreator")); + psd3.add("propagator", std::string("PropagatorWithMaterial")); + psd3.add("SeedMomentumForBOFF", 5.0); + psd3.add("OriginTransverseErrorMultiplier", 1.0); + psd3.add("MinOneOverPtError", 1.0); + psd3.add("magneticField", std::string("")); + psd3.add("TTRHBuilder", std::string("WithTrackAngle")); + psd3.add("forceKinematicWithRegionDirection", false); + + psd4.add("HGCEEInput", edm::InputTag("HGCalRecHit", "HGCEERecHits")); + psd4.add("HGCFHInput", edm::InputTag("HGCalRecHit", "HGCHEFRecHits")); + psd4.add("HGCBHInput", edm::InputTag("HGCalRecHit", "HGCHEBRecHits")); + + psd0.add("HGCalConfig", psd4); + + psd0.add("SeedCreatorPSet", psd3); + + desc.add("SeedConfiguration", psd0); } - desc.add("barrelSuperClusters",edm::InputTag("particleFlowSuperClusterECAL","particleFlowSuperClusterECALBarrel")); - descriptions.add("ecalDrivenElectronSeeds",desc); + desc.add("barrelSuperClusters", + edm::InputTag("particleFlowSuperClusterECAL", "particleFlowSuperClusterECALBarrel")); + descriptions.add("ecalDrivenElectronSeeds", desc); } diff --git a/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.h index b6b96f4e59808..a0e27543405d7 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/ElectronSeedProducer.h @@ -8,11 +8,10 @@ // Description: Calls ElectronSeedGenerator // to find TrajectorySeeds. - -class ElectronSeedGenerator ; -class SeedFilter ; -class EgammaHcalIsolation ; -class ElectronHcalHelper ; +class ElectronSeedGenerator; +class SeedFilter; +class EgammaHcalIsolation; +class ElectronHcalHelper; #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" @@ -24,10 +23,9 @@ class ElectronHcalHelper ; #include "RecoCaloTools/Selectors/interface/CaloDualConeSelector.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" -namespace edm - { - class ConfigurationDescriptions ; - } +namespace edm { + class ConfigurationDescriptions; +} #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" @@ -39,78 +37,74 @@ namespace edm #include "RecoLocalCalo/HGCalRecAlgos/interface/ClusterTools.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterLazyTools.h" -class ElectronSeedProducer : public edm::stream::EDProducer<> - { - public: - - //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; - - explicit ElectronSeedProducer( const edm::ParameterSet & ) ; - void beginRun( edm::Run const&, edm::EventSetup const & ) final; - void endRun( edm::Run const&, edm::EventSetup const & ) final; - ~ElectronSeedProducer() override ; - - void produce( edm::Event &, const edm::EventSetup & ) final; - - static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - private: - - void filterClusters - ( const reco::BeamSpot & bs, - const edm::Handle & superClusters, - reco::SuperClusterRefVector &sclRefs, - std::vector & hoe1s, std::vector & hoe2s, edm::Event& e, const edm::EventSetup& setup ) ; - void filterSeeds(edm::Event& e, const edm::EventSetup& setup, reco::SuperClusterRefVector &sclRefs); - - edm::EDGetTokenT superClusters_[2] ; - std::vector> initialSeeds_ ; - edm::EDGetTokenT beamSpotTag_ ; - edm::EDGetTokenT ebRecHitCollection_; - edm::EDGetTokenT eeRecHitCollection_; - - ElectronSeedGenerator * matcher_ ; - std::unique_ptr seedFilter_; - - TrajectorySeedCollection * theInitialSeedColl ;//created on the fly - std::vector theInitialSeedColls ; - - // for the filter - // H/E - // edm::InputTag hcalRecHits_; - bool applyHOverECut_ ; - ElectronHcalHelper * hcalHelper_ ; - // edm::ESHandle caloGeom_ ; - // unsigned long long caloGeomCacheId_ ; - edm::ESHandle caloGeom_ ; - unsigned long long caloGeomCacheId_ ; - edm::ESHandle caloTopo_; - unsigned long long caloTopoCacheId_; - // EgammaHcalIsolation * hcalIso_ ; - //// CaloDualConeSelector * doubleConeSel_ ; - // double maxHOverE_ ; - double maxHOverEBarrel_ ; - double maxHOverEEndcaps_ ; - double maxHBarrel_ ; - double maxHEndcaps_ ; - // double hOverEConeSize_; - // double hOverEHBMinE_; - // double hOverEHFMinE_; - // super cluster Et cut - double SCEtCut_; - - bool applySigmaIEtaIEtaCut_; - double maxSigmaIEtaIEtaBarrel_; - double maxSigmaIEtaIEtaEndcaps_; - - bool fromTrackerSeeds_; - bool prefilteredSeeds_; - - bool allowHGCal_; - std::unique_ptr hgcClusterTools_; - - } ; +class ElectronSeedProducer : public edm::stream::EDProducer<> { +public: + //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + + explicit ElectronSeedProducer(const edm::ParameterSet&); + void beginRun(edm::Run const&, edm::EventSetup const&) final; + void endRun(edm::Run const&, edm::EventSetup const&) final; + ~ElectronSeedProducer() override; + + void produce(edm::Event&, const edm::EventSetup&) final; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + void filterClusters(const reco::BeamSpot& bs, + const edm::Handle& superClusters, + reco::SuperClusterRefVector& sclRefs, + std::vector& hoe1s, + std::vector& hoe2s, + edm::Event& e, + const edm::EventSetup& setup); + void filterSeeds(edm::Event& e, const edm::EventSetup& setup, reco::SuperClusterRefVector& sclRefs); + + edm::EDGetTokenT superClusters_[2]; + std::vector> initialSeeds_; + edm::EDGetTokenT beamSpotTag_; + edm::EDGetTokenT ebRecHitCollection_; + edm::EDGetTokenT eeRecHitCollection_; + + ElectronSeedGenerator* matcher_; + std::unique_ptr seedFilter_; + + TrajectorySeedCollection* theInitialSeedColl; //created on the fly + std::vector theInitialSeedColls; + + // for the filter + // H/E + // edm::InputTag hcalRecHits_; + bool applyHOverECut_; + ElectronHcalHelper* hcalHelper_; + // edm::ESHandle caloGeom_ ; + // unsigned long long caloGeomCacheId_ ; + edm::ESHandle caloGeom_; + unsigned long long caloGeomCacheId_; + edm::ESHandle caloTopo_; + unsigned long long caloTopoCacheId_; + // EgammaHcalIsolation * hcalIso_ ; + //// CaloDualConeSelector * doubleConeSel_ ; + // double maxHOverE_ ; + double maxHOverEBarrel_; + double maxHOverEEndcaps_; + double maxHBarrel_; + double maxHEndcaps_; + // double hOverEConeSize_; + // double hOverEHBMinE_; + // double hOverEHFMinE_; + // super cluster Et cut + double SCEtCut_; + + bool applySigmaIEtaIEtaCut_; + double maxSigmaIEtaIEtaBarrel_; + double maxSigmaIEtaIEtaEndcaps_; + + bool fromTrackerSeeds_; + bool prefilteredSeeds_; + + bool allowHGCal_; + std::unique_ptr hgcClusterTools_; +}; #endif - - - diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.cc index 2d3f0ac0ad9cb..ef866a43e8a3f 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.cc @@ -18,78 +18,73 @@ #include -using namespace reco ; +using namespace reco; -void GEDGsfElectronCoreProducer::fillDescriptions( edm::ConfigurationDescriptions & descriptions ) -{ - edm::ParameterSetDescription desc ; - GsfElectronCoreBaseProducer::fillDescription(desc) ; - desc.add("GEDEMUnbiased",edm::InputTag("GEDPFCandidates")) ; +void GEDGsfElectronCoreProducer::fillDescriptions(edm::ConfigurationDescriptions &descriptions) { + edm::ParameterSetDescription desc; + GsfElectronCoreBaseProducer::fillDescription(desc); + desc.add("GEDEMUnbiased", edm::InputTag("GEDPFCandidates")); - descriptions.add("produceEcalDrivenGsfElectronCores",desc) ; + descriptions.add("produceEcalDrivenGsfElectronCores", desc); } -GEDGsfElectronCoreProducer::GEDGsfElectronCoreProducer( const edm::ParameterSet & config ) - : GsfElectronCoreBaseProducer(config) -{ - gedEMUnbiasedTag_ = consumes(config.getParameter("GEDEMUnbiased")) ; +GEDGsfElectronCoreProducer::GEDGsfElectronCoreProducer(const edm::ParameterSet &config) + : GsfElectronCoreBaseProducer(config) { + gedEMUnbiasedTag_ = consumes(config.getParameter("GEDEMUnbiased")); } -void GEDGsfElectronCoreProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { +void GEDGsfElectronCoreProducer::produce(edm::Event &event, const edm::EventSetup &setup) { // base input - GsfElectronCoreBaseProducer::initEvent(event,setup) ; - + GsfElectronCoreBaseProducer::initEvent(event, setup); + edm::Handle gedEMUnbiasedH_; - event.getByToken(gedEMUnbiasedTag_,gedEMUnbiasedH_); + event.getByToken(gedEMUnbiasedTag_, gedEMUnbiasedH_); // output auto electrons = std::make_unique(); - const PFCandidateCollection * pfCandidateCollection = gedEMUnbiasedH_.product(); - for ( unsigned int i=0 ; isize() ; ++i ) - produceElectronCore((*pfCandidateCollection)[i],electrons.get()) ; - + const PFCandidateCollection *pfCandidateCollection = gedEMUnbiasedH_.product(); + for (unsigned int i = 0; i < pfCandidateCollection->size(); ++i) + produceElectronCore((*pfCandidateCollection)[i], electrons.get()); + event.put(std::move(electrons)); - } +} -void GEDGsfElectronCoreProducer::produceElectronCore( const reco::PFCandidate & pfCandidate, reco::GsfElectronCoreCollection * electrons ) - { +void GEDGsfElectronCoreProducer::produceElectronCore(const reco::PFCandidate &pfCandidate, + reco::GsfElectronCoreCollection *electrons) { const GsfTrackRef gsfTrackRef = pfCandidate.gsfTrackRef(); - if(gsfTrackRef.isNull()) - return; + if (gsfTrackRef.isNull()) + return; reco::PFCandidateEGammaExtraRef extraRef = pfCandidate.egammaExtraRef(); - if(extraRef.isNull()) - return; + if (extraRef.isNull()) + return; - GsfElectronCore * eleCore = new GsfElectronCore(gsfTrackRef) ; + GsfElectronCore *eleCore = new GsfElectronCore(gsfTrackRef); - GsfElectronCoreBaseProducer::fillElectronCore(eleCore) ; + GsfElectronCoreBaseProducer::fillElectronCore(eleCore); SuperClusterRef scRef = extraRef->superClusterRef(); - SuperClusterRef scBoxRef = extraRef->superClusterPFECALRef(); + SuperClusterRef scBoxRef = extraRef->superClusterPFECALRef(); - for(const auto &convref : extraRef->conversionRef()) { + for (const auto &convref : extraRef->conversionRef()) { eleCore->addConversion(convref); } - - for(const auto &convref : extraRef->singleLegConversionRef()) { + + for (const auto &convref : extraRef->singleLegConversionRef()) { eleCore->addOneLegConversion(convref); } - - if (!scRef.isNull() || !scBoxRef.isNull()) - { - eleCore->setSuperCluster(scRef) ; - eleCore->setParentSuperCluster(scBoxRef) ; - electrons->push_back(*eleCore) ; - } - else - { edm::LogWarning("GEDGsfElectronCoreProducer")<<"Both superClusterRef and superClusterBoxRef of pfCandidate.egammaExtraRef() are Null" ; } - - delete eleCore ; - } - -GEDGsfElectronCoreProducer::~GEDGsfElectronCoreProducer() - {} + if (!scRef.isNull() || !scBoxRef.isNull()) { + eleCore->setSuperCluster(scRef); + eleCore->setParentSuperCluster(scBoxRef); + electrons->push_back(*eleCore); + } else { + edm::LogWarning("GEDGsfElectronCoreProducer") + << "Both superClusterRef and superClusterBoxRef of pfCandidate.egammaExtraRef() are Null"; + } + + delete eleCore; +} + +GEDGsfElectronCoreProducer::~GEDGsfElectronCoreProducer() {} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.h index 4e5e603b2836d..d7143c40d1948 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronCoreProducer.h @@ -5,21 +5,18 @@ #include "DataFormats/EgammaCandidates/interface/GsfElectronCoreFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" -class GEDGsfElectronCoreProducer : public GsfElectronCoreBaseProducer - { - public: +class GEDGsfElectronCoreProducer : public GsfElectronCoreBaseProducer { +public: + static void fillDescriptions(edm::ConfigurationDescriptions&); - static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + explicit GEDGsfElectronCoreProducer(const edm::ParameterSet& conf); + ~GEDGsfElectronCoreProducer() override; + void produce(edm::Event&, const edm::EventSetup&) override; - explicit GEDGsfElectronCoreProducer( const edm::ParameterSet & conf ) ; - ~GEDGsfElectronCoreProducer() override ; - void produce( edm::Event&, const edm::EventSetup & ) override ; +private: + void produceElectronCore(const reco::PFCandidate& pfCandidate, reco::GsfElectronCoreCollection* electrons); - private: - - void produceElectronCore( const reco::PFCandidate & pfCandidate, reco::GsfElectronCoreCollection * electrons ) ; - - edm::EDGetTokenT gedEMUnbiasedTag_ ; - } ; + edm::EDGetTokenT gedEMUnbiasedTag_; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronFinalizer.h b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronFinalizer.h index c30aeb1c36161..d9bd5d842ec6d 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronFinalizer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronFinalizer.h @@ -15,22 +15,20 @@ #include #include -class GEDGsfElectronFinalizer : public edm::stream::EDProducer<> -{ - public: - explicit GEDGsfElectronFinalizer (const edm::ParameterSet &); - ~GEDGsfElectronFinalizer() override; - - void produce(edm::Event &, const edm::EventSetup&) override; - - private: +class GEDGsfElectronFinalizer : public edm::stream::EDProducer<> { +public: + explicit GEDGsfElectronFinalizer(const edm::ParameterSet &); + ~GEDGsfElectronFinalizer() override; + + void produce(edm::Event &, const edm::EventSetup &) override; + +private: edm::EDGetTokenT previousGsfElectrons_; edm::EDGetTokenT pfCandidates_; std::string outputCollectionLabel_; std::vector > > tokenElectronIsoVals_; std::unique_ptr gedRegression_; unsigned nDeps_; - }; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.cc index 3a4bef49eb068..236a5af4ff3ab 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.cc @@ -16,7 +16,6 @@ #include "DataFormats/GsfTrackReco/interface/GsfTrack.h" - #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidate.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateEGammaExtra.h" @@ -27,96 +26,92 @@ using namespace reco; -GEDGsfElectronProducer::GEDGsfElectronProducer( const edm::ParameterSet & cfg, const gsfAlgoHelpers::HeavyObjectCache* hoc ) - : GsfElectronBaseProducer(cfg,hoc) - , egmPFCandidateCollection_(consumes(cfg.getParameter("egmPFCandidatesTag"))) -{ - produces >(); +GEDGsfElectronProducer::GEDGsfElectronProducer(const edm::ParameterSet& cfg, + const gsfAlgoHelpers::HeavyObjectCache* hoc) + : GsfElectronBaseProducer(cfg, hoc), + egmPFCandidateCollection_( + consumes(cfg.getParameter("egmPFCandidatesTag"))) { + produces>(); } - // ------------ method called to produce the data ------------ -void GEDGsfElectronProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { +void GEDGsfElectronProducer::produce(edm::Event& event, const edm::EventSetup& setup) { matchWithPFCandidates(event); reco::GsfElectronCollection electrons; - algo_->completeElectrons(electrons, event, setup, globalCache()) ; - setMVAOutputs(electrons, globalCache(),gsfMVAOutputMap_, event.get(inputCfg_.vtxCollectionTag)); - for(auto& el : electrons) el.setMvaInput(gsfMVAInputMap_.find(el.gsfTrack())->second); // set MVA inputs - fillEvent(electrons, event) ; + algo_->completeElectrons(electrons, event, setup, globalCache()); + setMVAOutputs(electrons, globalCache(), gsfMVAOutputMap_, event.get(inputCfg_.vtxCollectionTag)); + for (auto& el : electrons) + el.setMvaInput(gsfMVAInputMap_.find(el.gsfTrack())->second); // set MVA inputs + fillEvent(electrons, event); // ValueMap auto valMap_p = std::make_unique>(); edm::ValueMap::Filler valMapFiller(*valMap_p); - fillGsfElectronValueMap(event,valMapFiller); + fillGsfElectronValueMap(event, valMapFiller); valMapFiller.fill(); - event.put(std::move(valMap_p)); + event.put(std::move(valMap_p)); // Done with the ValueMap - } +} -void GEDGsfElectronProducer::fillGsfElectronValueMap(edm::Event & event, edm::ValueMap::Filler & filler) -{ +void GEDGsfElectronProducer::fillGsfElectronValueMap(edm::Event& event, + edm::ValueMap::Filler& filler) { // Read the collection of PFCandidates edm::Handle pfCandidates; - + bool found = event.getByToken(egmPFCandidateCollection_, pfCandidates); - if(!found) { - edm::LogError("GEDGsfElectronProducer") - <<" cannot get PFCandidates! "; + if (!found) { + edm::LogError("GEDGsfElectronProducer") << " cannot get PFCandidates! "; } //Loop over the collection of PFFCandidates reco::PFCandidateCollection::const_iterator it = pfCandidates->begin(); - reco::PFCandidateCollection::const_iterator itend = pfCandidates->end() ; + reco::PFCandidateCollection::const_iterator itend = pfCandidates->end(); std::vector values; - for ( ; it != itend ; ++it) { + for (; it != itend; ++it) { reco::GsfElectronRef myRef; // First check that the GsfTrack is non null - if( it->gsfTrackRef().isNonnull()) { + if (it->gsfTrackRef().isNonnull()) { // now look for the corresponding GsfElectron - const auto itcheck = std::find_if( orphanHandle()->begin(),orphanHandle()->end(), - [it](const auto& ele) {return (ele.gsfTrack() == it->gsfTrackRef());} ); + const auto itcheck = std::find_if(orphanHandle()->begin(), orphanHandle()->end(), [it](const auto& ele) { + return (ele.gsfTrack() == it->gsfTrackRef()); + }); if (itcheck != orphanHandle()->end()) { - // Build the Ref from the handle and the index - myRef = reco::GsfElectronRef(orphanHandle(),itcheck-orphanHandle()->begin()); + // Build the Ref from the handle and the index + myRef = reco::GsfElectronRef(orphanHandle(), itcheck - orphanHandle()->begin()); } } values.push_back(myRef); } - filler.insert(pfCandidates,values.begin(),values.end()); + filler.insert(pfCandidates, values.begin(), values.end()); } - -// Something more clever has to be found. The collections are small, so the timing is not +// Something more clever has to be found. The collections are small, so the timing is not // an issue here; but it is clearly suboptimal -void GEDGsfElectronProducer::matchWithPFCandidates(edm::Event & event) -{ +void GEDGsfElectronProducer::matchWithPFCandidates(edm::Event& event) { gsfMVAInputMap_.clear(); gsfMVAOutputMap_.clear(); // Read the collection of PFCandidates edm::Handle pfCandidates; - + bool found = event.getByToken(egmPFCandidateCollection_, pfCandidates); - if(!found) { - edm::LogError("GEDGsfElectronProducer") - <<" cannot get PFCandidates! "; + if (!found) { + edm::LogError("GEDGsfElectronProducer") << " cannot get PFCandidates! "; } //Loop over the collection of PFFCandidates reco::PFCandidateCollection::const_iterator it = pfCandidates->begin(); - reco::PFCandidateCollection::const_iterator itend = pfCandidates->end() ; - - for ( ; it != itend ; ++it) { + reco::PFCandidateCollection::const_iterator itend = pfCandidates->end(); + + for (; it != itend; ++it) { reco::GsfElectronRef myRef; // First check that the GsfTrack is non null - if( it->gsfTrackRef().isNonnull()) { - + if (it->gsfTrackRef().isNonnull()) { reco::GsfElectron::MvaOutput myMvaOutput; // at the moment, undefined - myMvaOutput.status = it->egammaExtraRef()->electronStatus() ; + myMvaOutput.status = it->egammaExtraRef()->electronStatus(); gsfMVAOutputMap_[it->gsfTrackRef()] = myMvaOutput; reco::GsfElectron::MvaInput myMvaInput; @@ -130,12 +125,10 @@ void GEDGsfElectronProducer::matchWithPFCandidates(edm::Event & event) } } - void GEDGsfElectronProducer::setMVAOutputs(reco::GsfElectronCollection& electrons, const gsfAlgoHelpers::HeavyObjectCache* hoc, const std::map& mvaOutputs, - reco::VertexCollection const& vertices) const -{ + reco::VertexCollection const& vertices) const { for (auto el = electrons.begin(); el != electrons.end(); el++) { float mva_NIso_Value = hoc->sElectronMVAEstimator->mva(*el, vertices); float mva_Iso_Value = hoc->iElectronMVAEstimator->mva(*el, vertices.size()); diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.h index 7229ee4ab3cdc..a2320965b5e9f 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GEDGsfElectronProducer.h @@ -6,26 +6,23 @@ #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include -class GEDGsfElectronProducer : public GsfElectronBaseProducer - { - public: - - explicit GEDGsfElectronProducer( const edm::ParameterSet &, const gsfAlgoHelpers::HeavyObjectCache* ) ; - void produce( edm::Event &, const edm::EventSetup & ) override ; - - private: - edm::EDGetTokenT egmPFCandidateCollection_; - std::map gsfMVAInputMap_; - std::map gsfMVAOutputMap_; - - private: - void fillGsfElectronValueMap(edm::Event & event, edm::ValueMap::Filler & filler); - void matchWithPFCandidates(edm::Event & event); - void setMVAOutputs(reco::GsfElectronCollection & electrons, - const gsfAlgoHelpers::HeavyObjectCache*, - const std::map & mvaOutputs, - reco::VertexCollection const& vertices) const; - - } ; +class GEDGsfElectronProducer : public GsfElectronBaseProducer { +public: + explicit GEDGsfElectronProducer(const edm::ParameterSet&, const gsfAlgoHelpers::HeavyObjectCache*); + void produce(edm::Event&, const edm::EventSetup&) override; + +private: + edm::EDGetTokenT egmPFCandidateCollection_; + std::map gsfMVAInputMap_; + std::map gsfMVAOutputMap_; + +private: + void fillGsfElectronValueMap(edm::Event& event, edm::ValueMap::Filler& filler); + void matchWithPFCandidates(edm::Event& event); + void setMVAOutputs(reco::GsfElectronCollection& electrons, + const gsfAlgoHelpers::HeavyObjectCache*, + const std::map& mvaOutputs, + reco::VertexCollection const& vertices) const; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronBaseProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronBaseProducer.h index 6cdeea696802d..d0250540bb1e6 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronBaseProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronBaseProducer.h @@ -12,67 +12,61 @@ #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" -namespace reco - { - class GsfElectron ; - } +namespace reco { + class GsfElectron; +} -namespace edm - { - class ParameterSet ; - class ConfigurationDescriptions ; - } +namespace edm { + class ParameterSet; + class ConfigurationDescriptions; +} // namespace edm #include "RecoEgamma/EgammaElectronAlgos/interface/GsfElectronAlgo.h" #include "DataFormats/Common/interface/Handle.h" -class GsfElectronBaseProducer : public edm::stream::EDProducer< edm::GlobalCache > - { - public: +class GsfElectronBaseProducer : public edm::stream::EDProducer> { +public: + static void fillDescriptions(edm::ConfigurationDescriptions&); - static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + explicit GsfElectronBaseProducer(const edm::ParameterSet&, const gsfAlgoHelpers::HeavyObjectCache*); + ~GsfElectronBaseProducer() override; - explicit GsfElectronBaseProducer( const edm::ParameterSet &, const gsfAlgoHelpers::HeavyObjectCache* ) ; - ~GsfElectronBaseProducer() override ; - - static std::unique_ptr - initializeGlobalCache( const edm::ParameterSet& conf ) { - return std::make_unique(conf); - } - - static void globalEndJob(gsfAlgoHelpers::HeavyObjectCache const* ) { + static std::unique_ptr initializeGlobalCache(const edm::ParameterSet& conf) { + return std::make_unique(conf); } - protected: - - std::unique_ptr algo_ ; + static void globalEndJob(gsfAlgoHelpers::HeavyObjectCache const*) {} - void beginEvent( edm::Event &, const edm::EventSetup & ) ; - void fillEvent( reco::GsfElectronCollection & electrons, edm::Event & event ) ; - const edm::OrphanHandle & orphanHandle() const { return orphanHandle_;} +protected: + std::unique_ptr algo_; - // configurables - GsfElectronAlgo::InputTagsConfiguration inputCfg_ ; - GsfElectronAlgo::StrategyConfiguration strategyCfg_ ; - const GsfElectronAlgo::CutsConfiguration cutsCfg_ ; - const GsfElectronAlgo::CutsConfiguration cutsCfgPflow_ ; - ElectronHcalHelper::Configuration hcalCfg_ ; - ElectronHcalHelper::Configuration hcalCfgPflow_ ; + void beginEvent(edm::Event&, const edm::EventSetup&); + void fillEvent(reco::GsfElectronCollection& electrons, edm::Event& event); + const edm::OrphanHandle& orphanHandle() const { return orphanHandle_; } - // used to make some provenance checks - edm::EDGetTokenT> pfMVA_; + // configurables + GsfElectronAlgo::InputTagsConfiguration inputCfg_; + GsfElectronAlgo::StrategyConfiguration strategyCfg_; + const GsfElectronAlgo::CutsConfiguration cutsCfg_; + const GsfElectronAlgo::CutsConfiguration cutsCfgPflow_; + ElectronHcalHelper::Configuration hcalCfg_; + ElectronHcalHelper::Configuration hcalCfgPflow_; - private : + // used to make some provenance checks + edm::EDGetTokenT> pfMVA_; - bool isPreselected( reco::GsfElectron const& ele ) const ; - void setAmbiguityData( reco::GsfElectronCollection & electrons, edm::Event const& event, bool ignoreNotPreselected = true ) const ; +private: + bool isPreselected(reco::GsfElectron const& ele) const; + void setAmbiguityData(reco::GsfElectronCollection& electrons, + edm::Event const& event, + bool ignoreNotPreselected = true) const; - // check expected configuration of previous modules - bool ecalSeedingParametersChecked_ ; - void checkEcalSeedingParameters( edm::ParameterSet const & ) ; - edm::OrphanHandle orphanHandle_; + // check expected configuration of previous modules + bool ecalSeedingParametersChecked_; + void checkEcalSeedingParameters(edm::ParameterSet const&); + edm::OrphanHandle orphanHandle_; - const edm::EDPutTokenT electronPutToken_; - } ; + const edm::EDPutTokenT electronPutToken_; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.cc index 7a3760da14eb8..ac627f0dd78f9 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.cc @@ -11,46 +11,41 @@ #include "GsfElectronCoreBaseProducer.h" -using namespace reco ; - -void GsfElectronCoreBaseProducer::fillDescription( edm::ParameterSetDescription & desc ) - { - desc.add("gsfPfRecTracks",edm::InputTag("pfTrackElec")) ; - desc.add("gsfTracks",edm::InputTag("electronGsfTracks")) ; - desc.add("ctfTracks",edm::InputTag("generalTracks")) ; - desc.add("useGsfPfRecTracks",true) ; - } - -GsfElectronCoreBaseProducer::GsfElectronCoreBaseProducer( const edm::ParameterSet & config ) - { - produces() ; - gsfPfRecTracksTag_ = mayConsume(config.getParameter("gsfPfRecTracks")) ; +using namespace reco; + +void GsfElectronCoreBaseProducer::fillDescription(edm::ParameterSetDescription& desc) { + desc.add("gsfPfRecTracks", edm::InputTag("pfTrackElec")); + desc.add("gsfTracks", edm::InputTag("electronGsfTracks")); + desc.add("ctfTracks", edm::InputTag("generalTracks")); + desc.add("useGsfPfRecTracks", true); +} + +GsfElectronCoreBaseProducer::GsfElectronCoreBaseProducer(const edm::ParameterSet& config) { + produces(); + gsfPfRecTracksTag_ = mayConsume(config.getParameter("gsfPfRecTracks")); gsfTracksTag_ = consumes(config.getParameter("gsfTracks")); ctfTracksTag_ = consumes(config.getParameter("ctfTracks")); - useGsfPfRecTracks_ = config.getParameter("useGsfPfRecTracks") ; - } - -GsfElectronCoreBaseProducer::~GsfElectronCoreBaseProducer() - {} + useGsfPfRecTracks_ = config.getParameter("useGsfPfRecTracks"); +} +GsfElectronCoreBaseProducer::~GsfElectronCoreBaseProducer() {} //======================================================================================= // For derived producers //======================================================================================= // to be called at the beginning of each new event -void GsfElectronCoreBaseProducer::initEvent( edm::Event & event, const edm::EventSetup & setup ) - { - if (useGsfPfRecTracks_) - { event.getByToken(gsfPfRecTracksTag_,gsfPfRecTracksH_) ; } - event.getByToken(gsfTracksTag_,gsfTracksH_) ; - event.getByToken(ctfTracksTag_,ctfTracksH_) ; - } - -void GsfElectronCoreBaseProducer::fillElectronCore( reco::GsfElectronCore * eleCore ) - { - const GsfTrackRef & gsfTrackRef = eleCore->gsfTrack() ; - - std::pair ctfpair = gsfElectronTools::getClosestCtfToGsf(gsfTrackRef,ctfTracksH_) ; - eleCore->setCtfTrack(ctfpair.first,ctfpair.second) ; - } +void GsfElectronCoreBaseProducer::initEvent(edm::Event& event, const edm::EventSetup& setup) { + if (useGsfPfRecTracks_) { + event.getByToken(gsfPfRecTracksTag_, gsfPfRecTracksH_); + } + event.getByToken(gsfTracksTag_, gsfTracksH_); + event.getByToken(ctfTracksTag_, ctfTracksH_); +} + +void GsfElectronCoreBaseProducer::fillElectronCore(reco::GsfElectronCore* eleCore) { + const GsfTrackRef& gsfTrackRef = eleCore->gsfTrack(); + + std::pair ctfpair = gsfElectronTools::getClosestCtfToGsf(gsfTrackRef, ctfTracksH_); + eleCore->setCtfTrack(ctfpair.first, ctfpair.second); +} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.h index 09ff1a88cfa93..18bcd2dfb2f58 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.h @@ -7,54 +7,45 @@ // // Description: - #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" -namespace reco - { - class GsfElectronCore ; - } +namespace reco { + class GsfElectronCore; +} -namespace edm - { - class ParameterSet ; - class ConfigurationDescriptions ; - } +namespace edm { + class ParameterSet; + class ConfigurationDescriptions; +} // namespace edm #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/ParticleFlowReco/interface/GsfPFRecTrackFwd.h" #include "DataFormats/GsfTrackReco/interface/GsfTrackFwd.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" -class GsfElectronCoreBaseProducer : public edm::stream::EDProducer<> - { - public: - - static void fillDescription( edm::ParameterSetDescription & ) ; - - explicit GsfElectronCoreBaseProducer( const edm::ParameterSet & conf ) ; - ~GsfElectronCoreBaseProducer() override ; - - - protected: - - // to be called by derived producers at the beginning of each new event - void initEvent( edm::Event & event, const edm::EventSetup & setup ) ; - edm::Handle gsfPfRecTracksH_ ; - edm::Handle gsfTracksH_ ; - edm::Handle ctfTracksH_ ; - bool useGsfPfRecTracks_ ; +class GsfElectronCoreBaseProducer : public edm::stream::EDProducer<> { +public: + static void fillDescription(edm::ParameterSetDescription&); - void fillElectronCore( reco::GsfElectronCore * ) ; + explicit GsfElectronCoreBaseProducer(const edm::ParameterSet& conf); + ~GsfElectronCoreBaseProducer() override; - private: +protected: + // to be called by derived producers at the beginning of each new event + void initEvent(edm::Event& event, const edm::EventSetup& setup); + edm::Handle gsfPfRecTracksH_; + edm::Handle gsfTracksH_; + edm::Handle ctfTracksH_; + bool useGsfPfRecTracks_; - edm::EDGetTokenT gsfPfRecTracksTag_ ; - edm::EDGetTokenT gsfTracksTag_ ; - edm::EDGetTokenT ctfTracksTag_ ; - } ; + void fillElectronCore(reco::GsfElectronCore*); +private: + edm::EDGetTokenT gsfPfRecTracksTag_; + edm::EDGetTokenT gsfTracksTag_; + edm::EDGetTokenT ctfTracksTag_; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.cc index 6873c9c28e92d..783316946bca9 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.cc @@ -15,7 +15,7 @@ #include -using namespace reco ; +using namespace reco; // void GsfElectronCoreEcalDrivenProducer::fillDescriptions( edm::ConfigurationDescriptions & descriptions ) // { @@ -24,68 +24,59 @@ using namespace reco ; // descriptions.add("produceEcalDrivenGsfElectronCores",desc) ; // } -GsfElectronCoreEcalDrivenProducer::GsfElectronCoreEcalDrivenProducer( const edm::ParameterSet & config ) - : GsfElectronCoreBaseProducer(config) - {} +GsfElectronCoreEcalDrivenProducer::GsfElectronCoreEcalDrivenProducer(const edm::ParameterSet& config) + : GsfElectronCoreBaseProducer(config) {} -void GsfElectronCoreEcalDrivenProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { +void GsfElectronCoreEcalDrivenProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // base input - GsfElectronCoreBaseProducer::initEvent(event,setup) ; + GsfElectronCoreBaseProducer::initEvent(event, setup); // output auto electrons = std::make_unique(); // loop on ecal driven tracks - if (useGsfPfRecTracks_) - { - const GsfPFRecTrackCollection * gsfPfRecTrackCollection = gsfPfRecTracksH_.product() ; - GsfPFRecTrackCollection::const_iterator gsfPfRecTrack ; - for ( gsfPfRecTrack=gsfPfRecTrackCollection->begin() ; - gsfPfRecTrack!=gsfPfRecTrackCollection->end() ; - ++gsfPfRecTrack ) - { - const GsfTrackRef gsfTrackRef = gsfPfRecTrack->gsfTrackRef() ; - produceEcalDrivenCore(gsfTrackRef,electrons.get()) ; - } - } - else - { - const GsfTrackCollection * gsfTrackCollection = gsfTracksH_.product() ; - for ( unsigned int i=0 ; isize() ; ++i ) - { - const GsfTrackRef gsfTrackRef = edm::Ref(gsfTracksH_,i) ; - produceEcalDrivenCore(gsfTrackRef,electrons.get()) ; - } - } + if (useGsfPfRecTracks_) { + const GsfPFRecTrackCollection* gsfPfRecTrackCollection = gsfPfRecTracksH_.product(); + GsfPFRecTrackCollection::const_iterator gsfPfRecTrack; + for (gsfPfRecTrack = gsfPfRecTrackCollection->begin(); gsfPfRecTrack != gsfPfRecTrackCollection->end(); + ++gsfPfRecTrack) { + const GsfTrackRef gsfTrackRef = gsfPfRecTrack->gsfTrackRef(); + produceEcalDrivenCore(gsfTrackRef, electrons.get()); + } + } else { + const GsfTrackCollection* gsfTrackCollection = gsfTracksH_.product(); + for (unsigned int i = 0; i < gsfTrackCollection->size(); ++i) { + const GsfTrackRef gsfTrackRef = edm::Ref(gsfTracksH_, i); + produceEcalDrivenCore(gsfTrackRef, electrons.get()); + } + } event.put(std::move(electrons)); - } - -void GsfElectronCoreEcalDrivenProducer::produceEcalDrivenCore( const GsfTrackRef & gsfTrackRef, GsfElectronCoreCollection * electrons ) - { - GsfElectronCore * eleCore = new GsfElectronCore(gsfTrackRef) ; - - if (!eleCore->ecalDrivenSeed()) - { delete eleCore ; return ; } - - GsfElectronCoreBaseProducer::fillElectronCore(eleCore) ; - - edm::RefToBase seed = gsfTrackRef->extra()->seedRef() ; - ElectronSeedRef elseed = seed.castTo() ; - edm::RefToBase caloCluster = elseed->caloCluster() ; - SuperClusterRef scRef = caloCluster.castTo() ; - if (!scRef.isNull()) - { - eleCore->setSuperCluster(scRef) ; - electrons->push_back(*eleCore) ; - } - else - { edm::LogWarning("GsfElectronCoreEcalDrivenProducer")<<"Seed CaloCluster is not a SuperCluster, unexpected..." ; } - - delete eleCore ; - } - -GsfElectronCoreEcalDrivenProducer::~GsfElectronCoreEcalDrivenProducer() - {} - +} + +void GsfElectronCoreEcalDrivenProducer::produceEcalDrivenCore(const GsfTrackRef& gsfTrackRef, + GsfElectronCoreCollection* electrons) { + GsfElectronCore* eleCore = new GsfElectronCore(gsfTrackRef); + + if (!eleCore->ecalDrivenSeed()) { + delete eleCore; + return; + } + + GsfElectronCoreBaseProducer::fillElectronCore(eleCore); + + edm::RefToBase seed = gsfTrackRef->extra()->seedRef(); + ElectronSeedRef elseed = seed.castTo(); + edm::RefToBase caloCluster = elseed->caloCluster(); + SuperClusterRef scRef = caloCluster.castTo(); + if (!scRef.isNull()) { + eleCore->setSuperCluster(scRef); + electrons->push_back(*eleCore); + } else { + edm::LogWarning("GsfElectronCoreEcalDrivenProducer") << "Seed CaloCluster is not a SuperCluster, unexpected..."; + } + + delete eleCore; +} + +GsfElectronCoreEcalDrivenProducer::~GsfElectronCoreEcalDrivenProducer() {} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.h index 0cdf434542b98..878e281851ca0 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreEcalDrivenProducer.h @@ -4,20 +4,16 @@ #include "GsfElectronCoreBaseProducer.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronCoreFwd.h" -class GsfElectronCoreEcalDrivenProducer : public GsfElectronCoreBaseProducer - { - public: +class GsfElectronCoreEcalDrivenProducer : public GsfElectronCoreBaseProducer { +public: + //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; - //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + explicit GsfElectronCoreEcalDrivenProducer(const edm::ParameterSet& conf); + ~GsfElectronCoreEcalDrivenProducer() override; + void produce(edm::Event&, const edm::EventSetup&) override; - explicit GsfElectronCoreEcalDrivenProducer( const edm::ParameterSet & conf ) ; - ~GsfElectronCoreEcalDrivenProducer() override ; - void produce( edm::Event&, const edm::EventSetup & ) override ; - - private: - - void produceEcalDrivenCore( const reco::GsfTrackRef & gsfTrackRef, reco::GsfElectronCoreCollection * electrons ) ; - - } ; +private: + void produceEcalDrivenCore(const reco::GsfTrackRef& gsfTrackRef, reco::GsfElectronCoreCollection* electrons); +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.cc index b56be488b9ca4..aa62917b6ac2c 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.cc @@ -16,7 +16,7 @@ #include -using namespace reco ; +using namespace reco; // void GsfElectronCoreProducer::fillDescriptions( edm::ConfigurationDescriptions & descriptions ) // { @@ -29,112 +29,95 @@ using namespace reco ; // descriptions.add("produceGsfElectronCores",desc) ; // } -GsfElectronCoreProducer::GsfElectronCoreProducer( const edm::ParameterSet & config ) - : GsfElectronCoreBaseProducer(config) - { - edCoresTag_ = consumes(config.getParameter("ecalDrivenGsfElectronCoresTag")); - pfCoresTag_ = consumes(config.getParameter("pflowGsfElectronCoresTag")); -// pfSuperClustersTag_ = config.getParameter("pfSuperClusters") ; -// pfSuperClusterTrackMapTag_ = config.getParameter("pfSuperClusterTrackMap") ; - } - -void GsfElectronCoreProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { +GsfElectronCoreProducer::GsfElectronCoreProducer(const edm::ParameterSet &config) + : GsfElectronCoreBaseProducer(config) { + edCoresTag_ = + consumes(config.getParameter("ecalDrivenGsfElectronCoresTag")); + pfCoresTag_ = + consumes(config.getParameter("pflowGsfElectronCoresTag")); + // pfSuperClustersTag_ = config.getParameter("pfSuperClusters") ; + // pfSuperClusterTrackMapTag_ = config.getParameter("pfSuperClusterTrackMap") ; +} + +void GsfElectronCoreProducer::produce(edm::Event &event, const edm::EventSetup &setup) { // base input - GsfElectronCoreBaseProducer::initEvent(event,setup) ; + GsfElectronCoreBaseProducer::initEvent(event, setup); // transient output - std::list electrons ; + std::list electrons; // event input - event.getByToken(edCoresTag_,edCoresH_) ; - event.getByToken(pfCoresTag_,pfCoresH_) ; -// event.getByToken(pfSuperClustersTag_,pfClustersH_) ; -// event.getByToken(pfSuperClusterTrackMapTag_,pfClusterTracksH_) ; + event.getByToken(edCoresTag_, edCoresH_); + event.getByToken(pfCoresTag_, pfCoresH_); + // event.getByToken(pfSuperClustersTag_,pfClustersH_) ; + // event.getByToken(pfSuperClusterTrackMapTag_,pfClusterTracksH_) ; // loop on pure tracker driven tracks - if (useGsfPfRecTracks_) - { - const GsfPFRecTrackCollection * gsfPfRecTrackCollection = gsfPfRecTracksH_.product() ; - GsfPFRecTrackCollection::const_iterator gsfPfRecTrack ; - for ( gsfPfRecTrack=gsfPfRecTrackCollection->begin() ; - gsfPfRecTrack!=gsfPfRecTrackCollection->end() ; - ++gsfPfRecTrack ) - { - const GsfTrackRef gsfTrackRef = gsfPfRecTrack->gsfTrackRef() ; - produceTrackerDrivenCore(gsfTrackRef,electrons) ; - } - } - else - { - const GsfTrackCollection * gsfTrackCollection = gsfTracksH_.product() ; - for ( unsigned int i=0 ; isize() ; ++i ) - { - const GsfTrackRef gsfTrackRef = edm::Ref(gsfTracksH_,i) ; - produceTrackerDrivenCore(gsfTrackRef,electrons) ; - } - } + if (useGsfPfRecTracks_) { + const GsfPFRecTrackCollection *gsfPfRecTrackCollection = gsfPfRecTracksH_.product(); + GsfPFRecTrackCollection::const_iterator gsfPfRecTrack; + for (gsfPfRecTrack = gsfPfRecTrackCollection->begin(); gsfPfRecTrack != gsfPfRecTrackCollection->end(); + ++gsfPfRecTrack) { + const GsfTrackRef gsfTrackRef = gsfPfRecTrack->gsfTrackRef(); + produceTrackerDrivenCore(gsfTrackRef, electrons); + } + } else { + const GsfTrackCollection *gsfTrackCollection = gsfTracksH_.product(); + for (unsigned int i = 0; i < gsfTrackCollection->size(); ++i) { + const GsfTrackRef gsfTrackRef = edm::Ref(gsfTracksH_, i); + produceTrackerDrivenCore(gsfTrackRef, electrons); + } + } // clone ecal driven electrons - const GsfElectronCoreCollection * edCoresCollection = edCoresH_.product() ; - GsfElectronCoreCollection::const_iterator edCoreIter ; - for - ( edCoreIter = edCoresCollection->begin() ; - edCoreIter != edCoresCollection->end() ; - edCoreIter++ ) - { electrons.push_back(edCoreIter->clone()) ; } + const GsfElectronCoreCollection *edCoresCollection = edCoresH_.product(); + GsfElectronCoreCollection::const_iterator edCoreIter; + for (edCoreIter = edCoresCollection->begin(); edCoreIter != edCoresCollection->end(); edCoreIter++) { + electrons.push_back(edCoreIter->clone()); + } // add pflow info - const GsfElectronCoreCollection * pfCoresCollection = pfCoresH_.product() ; - GsfElectronCoreCollection::const_iterator pfCoreIter ; - std::list::iterator eleCore ; - bool found ; - for ( eleCore = electrons.begin() ; eleCore != electrons.end() ; eleCore++ ) - { -// (*eleCore)->setParentSuperCluster((*pfClusterTracksH_)[(*eleCore)->gsfTrack()]) ; - found = false ; - for - ( pfCoreIter = pfCoresCollection->begin() ; - pfCoreIter != pfCoresCollection->end() ; - pfCoreIter++ ) - { - if (pfCoreIter->gsfTrack()==(*eleCore)->gsfTrack()) - { - if (found) - { - edm::LogWarning("GsfElectronCoreProducer")<<"associated pfGsfElectronCore already found" ; - } - else - { - found = true ; - (*eleCore)->setParentSuperCluster(pfCoreIter->parentSuperCluster()) ; - } - } - } - } + const GsfElectronCoreCollection *pfCoresCollection = pfCoresH_.product(); + GsfElectronCoreCollection::const_iterator pfCoreIter; + std::list::iterator eleCore; + bool found; + for (eleCore = electrons.begin(); eleCore != electrons.end(); eleCore++) { + // (*eleCore)->setParentSuperCluster((*pfClusterTracksH_)[(*eleCore)->gsfTrack()]) ; + found = false; + for (pfCoreIter = pfCoresCollection->begin(); pfCoreIter != pfCoresCollection->end(); pfCoreIter++) { + if (pfCoreIter->gsfTrack() == (*eleCore)->gsfTrack()) { + if (found) { + edm::LogWarning("GsfElectronCoreProducer") << "associated pfGsfElectronCore already found"; + } else { + found = true; + (*eleCore)->setParentSuperCluster(pfCoreIter->parentSuperCluster()); + } + } + } + } // store auto collection = std::make_unique(); - for ( eleCore = electrons.begin() ; eleCore != electrons.end() ; eleCore++ ) - { - if ((*eleCore)->superCluster().isNull()) - { LogDebug("GsfElectronCoreProducer")<<"GsfTrack with no associated SuperCluster at all." ; } - else - { collection->push_back(**eleCore) ; } - delete (*eleCore) ; - } + for (eleCore = electrons.begin(); eleCore != electrons.end(); eleCore++) { + if ((*eleCore)->superCluster().isNull()) { + LogDebug("GsfElectronCoreProducer") << "GsfTrack with no associated SuperCluster at all."; + } else { + collection->push_back(**eleCore); + } + delete (*eleCore); + } event.put(std::move(collection)); - } - -void GsfElectronCoreProducer::produceTrackerDrivenCore( const GsfTrackRef & gsfTrackRef, std::list & electrons ) - { - GsfElectronCore * eleCore = new GsfElectronCore(gsfTrackRef) ; - if (eleCore->ecalDrivenSeed()) - { delete eleCore ; return ; } - GsfElectronCoreBaseProducer::fillElectronCore(eleCore) ; - electrons.push_back(eleCore) ; - } - -GsfElectronCoreProducer::~GsfElectronCoreProducer() - {} - +} + +void GsfElectronCoreProducer::produceTrackerDrivenCore(const GsfTrackRef &gsfTrackRef, + std::list &electrons) { + GsfElectronCore *eleCore = new GsfElectronCore(gsfTrackRef); + if (eleCore->ecalDrivenSeed()) { + delete eleCore; + return; + } + GsfElectronCoreBaseProducer::fillElectronCore(eleCore); + electrons.push_back(eleCore); +} + +GsfElectronCoreProducer::~GsfElectronCoreProducer() {} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.h index 62232f855b6e8..30162337e2773 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreProducer.h @@ -6,30 +6,26 @@ #include "DataFormats/Common/interface/ValueMap.h" #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" -class GsfElectronCoreProducer : public GsfElectronCoreBaseProducer - { - public: - - //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; - - explicit GsfElectronCoreProducer( const edm::ParameterSet & ) ; - ~GsfElectronCoreProducer() override ; - void produce( edm::Event &, const edm::EventSetup & ) override ; - - private: - - edm::EDGetTokenT edCoresTag_ ; - edm::EDGetTokenT pfCoresTag_ ; -// edm::InputTag pfSuperClustersTag_ ; -// edm::InputTag pfSuperClusterTrackMapTag_ ; - - edm::Handle edCoresH_ ; - edm::Handle pfCoresH_ ; -// edm::Handle pfClustersH_ ; -// edm::Handle > pfClusterTracksH_ ; - - void produceTrackerDrivenCore( const reco::GsfTrackRef & gsfTrackRef, std::list & electrons ) ; - - } ; +class GsfElectronCoreProducer : public GsfElectronCoreBaseProducer { +public: + //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + + explicit GsfElectronCoreProducer(const edm::ParameterSet &); + ~GsfElectronCoreProducer() override; + void produce(edm::Event &, const edm::EventSetup &) override; + +private: + edm::EDGetTokenT edCoresTag_; + edm::EDGetTokenT pfCoresTag_; + // edm::InputTag pfSuperClustersTag_ ; + // edm::InputTag pfSuperClusterTrackMapTag_ ; + + edm::Handle edCoresH_; + edm::Handle pfCoresH_; + // edm::Handle pfClustersH_ ; + // edm::Handle > pfClusterTracksH_ ; + + void produceTrackerDrivenCore(const reco::GsfTrackRef &gsfTrackRef, std::list &electrons); +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.cc index 95dc245c27311..595aca58eed1e 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.cc @@ -16,22 +16,19 @@ #include "DataFormats/TrackingRecHit/interface/TrackingRecHitFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" - #include using namespace reco; -GsfElectronEcalDrivenProducer::GsfElectronEcalDrivenProducer( const edm::ParameterSet & cfg, const gsfAlgoHelpers::HeavyObjectCache* hoc ) - : GsfElectronBaseProducer(cfg,hoc) - {} +GsfElectronEcalDrivenProducer::GsfElectronEcalDrivenProducer(const edm::ParameterSet& cfg, + const gsfAlgoHelpers::HeavyObjectCache* hoc) + : GsfElectronBaseProducer(cfg, hoc) {} -GsfElectronEcalDrivenProducer::~GsfElectronEcalDrivenProducer() - {} +GsfElectronEcalDrivenProducer::~GsfElectronEcalDrivenProducer() {} // ------------ method called to produce the data ------------ -void GsfElectronEcalDrivenProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { +void GsfElectronEcalDrivenProducer::produce(edm::Event& event, const edm::EventSetup& setup) { reco::GsfElectronCollection electrons; - algo_->completeElectrons(electrons, event, setup, globalCache()) ; - fillEvent(electrons, event) ; - } + algo_->completeElectrons(electrons, event, setup, globalCache()); + fillEvent(electrons, event); +} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.h index 226f6902d20cb..d7cf6f4531550 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronEcalDrivenProducer.h @@ -4,14 +4,11 @@ #include "GsfElectronBaseProducer.h" -class GsfElectronEcalDrivenProducer : public GsfElectronBaseProducer - { - public: - - explicit GsfElectronEcalDrivenProducer( const edm::ParameterSet &, const gsfAlgoHelpers::HeavyObjectCache* ) ; - ~GsfElectronEcalDrivenProducer() override ; - void produce( edm::Event &, const edm::EventSetup & ) override ; - - } ; +class GsfElectronEcalDrivenProducer : public GsfElectronBaseProducer { +public: + explicit GsfElectronEcalDrivenProducer(const edm::ParameterSet &, const gsfAlgoHelpers::HeavyObjectCache *); + ~GsfElectronEcalDrivenProducer() override; + void produce(edm::Event &, const edm::EventSetup &) override; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.cc index 59436d5462db6..004579ac0a08d 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.cc @@ -34,113 +34,105 @@ using namespace reco; -GsfElectronFull5x5Filler::GsfElectronFull5x5Filler( const edm::ParameterSet & cfg ) - { - _source = consumes(cfg.getParameter("source")); - - ElectronHcalHelper::Configuration hcalCfg, hcalCfgPflow; - - hcalCfg.hOverEConeSize = cfg.getParameter("hOverEConeSize") ; - if (hcalCfg.hOverEConeSize>0) - { - hcalCfg.useTowers = true ; - hcalCfg.hcalTowers = - consumes(cfg.getParameter("hcalTowers")) ; - hcalCfg.hOverEPtMin = cfg.getParameter("hOverEPtMin") ; - } - hcalCfgPflow.hOverEConeSize = cfg.getParameter("hOverEConeSizePflow") ; - if (hcalCfgPflow.hOverEConeSize>0) - { - hcalCfgPflow.useTowers = true ; - hcalCfgPflow.hcalTowers = - consumes(cfg.getParameter("hcalTowers")) ; - hcalCfgPflow.hOverEPtMin = cfg.getParameter("hOverEPtMinPflow") ; - } - _hcalHelper.reset(new ElectronHcalHelper(hcalCfg)); - _hcalHelperPflow.reset(new ElectronHcalHelper(hcalCfg)); - - _ebRecHitsToken = consumes(cfg.getParameter("barrelRecHitCollectionTag")); - _eeRecHitsToken = consumes(cfg.getParameter("endcapRecHitCollectionTag")); - - produces(); - } - -GsfElectronFull5x5Filler::~GsfElectronFull5x5Filler() - {} +GsfElectronFull5x5Filler::GsfElectronFull5x5Filler(const edm::ParameterSet& cfg) { + _source = consumes(cfg.getParameter("source")); + + ElectronHcalHelper::Configuration hcalCfg, hcalCfgPflow; + + hcalCfg.hOverEConeSize = cfg.getParameter("hOverEConeSize"); + if (hcalCfg.hOverEConeSize > 0) { + hcalCfg.useTowers = true; + hcalCfg.hcalTowers = consumes(cfg.getParameter("hcalTowers")); + hcalCfg.hOverEPtMin = cfg.getParameter("hOverEPtMin"); + } + hcalCfgPflow.hOverEConeSize = cfg.getParameter("hOverEConeSizePflow"); + if (hcalCfgPflow.hOverEConeSize > 0) { + hcalCfgPflow.useTowers = true; + hcalCfgPflow.hcalTowers = consumes(cfg.getParameter("hcalTowers")); + hcalCfgPflow.hOverEPtMin = cfg.getParameter("hOverEPtMinPflow"); + } + _hcalHelper.reset(new ElectronHcalHelper(hcalCfg)); + _hcalHelperPflow.reset(new ElectronHcalHelper(hcalCfg)); + + _ebRecHitsToken = consumes(cfg.getParameter("barrelRecHitCollectionTag")); + _eeRecHitsToken = consumes(cfg.getParameter("endcapRecHitCollectionTag")); + + produces(); +} + +GsfElectronFull5x5Filler::~GsfElectronFull5x5Filler() {} // ------------ method called to produce the data ------------ -void GsfElectronFull5x5Filler::produce( edm::Event & event, const edm::EventSetup & setup ) - { - auto out = std::make_unique(); - - edm::Handle eles; - event.getByToken(_source,eles); - - event.getByToken(_ebRecHitsToken,_ebRecHits); - event.getByToken(_eeRecHitsToken,_eeRecHits); - - for( const auto& ele : *eles ) { - reco::GsfElectron temp(ele); - reco::GsfElectron::ShowerShape full5x5_ss; - calculateShowerShape_full5x5(temp.superCluster(),true,full5x5_ss); - temp.full5x5_setShowerShape(full5x5_ss); - out->push_back(temp); - } - - event.put(std::move(out)); - } - -void GsfElectronFull5x5Filler::beginLuminosityBlock(edm::LuminosityBlock const& lb, - edm::EventSetup const& es) { - edm::ESHandle caloGeom ; - edm::ESHandle caloTopo ; +void GsfElectronFull5x5Filler::produce(edm::Event& event, const edm::EventSetup& setup) { + auto out = std::make_unique(); + + edm::Handle eles; + event.getByToken(_source, eles); + + event.getByToken(_ebRecHitsToken, _ebRecHits); + event.getByToken(_eeRecHitsToken, _eeRecHits); + + for (const auto& ele : *eles) { + reco::GsfElectron temp(ele); + reco::GsfElectron::ShowerShape full5x5_ss; + calculateShowerShape_full5x5(temp.superCluster(), true, full5x5_ss); + temp.full5x5_setShowerShape(full5x5_ss); + out->push_back(temp); + } + + event.put(std::move(out)); +} + +void GsfElectronFull5x5Filler::beginLuminosityBlock(edm::LuminosityBlock const& lb, edm::EventSetup const& es) { + edm::ESHandle caloGeom; + edm::ESHandle caloTopo; es.get().get(caloGeom); es.get().get(caloTopo); _geometry = caloGeom.product(); _topology = caloTopo.product(); } -void GsfElectronFull5x5Filler::calculateShowerShape_full5x5( const reco::SuperClusterRef & theClus, bool pflow, reco::GsfElectron::ShowerShape & showerShape ) - { - const reco::CaloCluster & seedCluster = *(theClus->seed()) ; +void GsfElectronFull5x5Filler::calculateShowerShape_full5x5(const reco::SuperClusterRef& theClus, + bool pflow, + reco::GsfElectron::ShowerShape& showerShape) { + const reco::CaloCluster& seedCluster = *(theClus->seed()); // temporary, till CaloCluster->seed() is made available - DetId seedXtalId = seedCluster.hitsAndFractions()[0].first ; - int detector = seedXtalId.subdetId() ; - - const EcalRecHitCollection * recHits = nullptr ; - if (detector==EcalBarrel) - { - recHits = _ebRecHits.product() ; - } - else - { - recHits = _eeRecHits.product() ; - } - - std::vector covariances = noZS::EcalClusterTools::covariances(seedCluster,recHits,_topology,_geometry) ; - std::vector localCovariances = noZS::EcalClusterTools::localCovariances(seedCluster,recHits,_topology) ; - showerShape.sigmaEtaEta = sqrt(covariances[0]) ; - showerShape.sigmaIetaIeta = sqrt(localCovariances[0]) ; - if (!edm::isNotFinite(localCovariances[2])) showerShape.sigmaIphiIphi = sqrt(localCovariances[2]) ; - showerShape.e1x5 = noZS::EcalClusterTools::e1x5(seedCluster,recHits,_topology) ; - showerShape.e2x5Max = noZS::EcalClusterTools::e2x5Max(seedCluster,recHits,_topology) ; - showerShape.e5x5 = noZS::EcalClusterTools::e5x5(seedCluster,recHits,_topology) ; - showerShape.r9 = noZS::EcalClusterTools::e3x3(seedCluster,recHits,_topology)/theClus->rawEnergy() ; - - if (pflow) - { - showerShape.hcalDepth1OverEcal = _hcalHelperPflow->hcalESumDepth1(*theClus)/theClus->energy() ; - showerShape.hcalDepth2OverEcal = _hcalHelperPflow->hcalESumDepth2(*theClus)/theClus->energy() ; - showerShape.hcalTowersBehindClusters = _hcalHelperPflow->hcalTowersBehindClusters(*theClus) ; - showerShape.hcalDepth1OverEcalBc = _hcalHelperPflow->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters)/showerShape.e5x5 ; - showerShape.hcalDepth2OverEcalBc = _hcalHelperPflow->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters)/showerShape.e5x5 ; - } - else - { - showerShape.hcalDepth1OverEcal = _hcalHelper->hcalESumDepth1(*theClus)/theClus->energy() ; - showerShape.hcalDepth2OverEcal = _hcalHelper->hcalESumDepth2(*theClus)/theClus->energy() ; - showerShape.hcalTowersBehindClusters = _hcalHelper->hcalTowersBehindClusters(*theClus) ; - showerShape.hcalDepth1OverEcalBc = _hcalHelper->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters)/showerShape.e5x5 ; - showerShape.hcalDepth2OverEcalBc = _hcalHelper->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters)/showerShape.e5x5 ; - } - } + DetId seedXtalId = seedCluster.hitsAndFractions()[0].first; + int detector = seedXtalId.subdetId(); + + const EcalRecHitCollection* recHits = nullptr; + if (detector == EcalBarrel) { + recHits = _ebRecHits.product(); + } else { + recHits = _eeRecHits.product(); + } + + std::vector covariances = noZS::EcalClusterTools::covariances(seedCluster, recHits, _topology, _geometry); + std::vector localCovariances = noZS::EcalClusterTools::localCovariances(seedCluster, recHits, _topology); + showerShape.sigmaEtaEta = sqrt(covariances[0]); + showerShape.sigmaIetaIeta = sqrt(localCovariances[0]); + if (!edm::isNotFinite(localCovariances[2])) + showerShape.sigmaIphiIphi = sqrt(localCovariances[2]); + showerShape.e1x5 = noZS::EcalClusterTools::e1x5(seedCluster, recHits, _topology); + showerShape.e2x5Max = noZS::EcalClusterTools::e2x5Max(seedCluster, recHits, _topology); + showerShape.e5x5 = noZS::EcalClusterTools::e5x5(seedCluster, recHits, _topology); + showerShape.r9 = noZS::EcalClusterTools::e3x3(seedCluster, recHits, _topology) / theClus->rawEnergy(); + + if (pflow) { + showerShape.hcalDepth1OverEcal = _hcalHelperPflow->hcalESumDepth1(*theClus) / theClus->energy(); + showerShape.hcalDepth2OverEcal = _hcalHelperPflow->hcalESumDepth2(*theClus) / theClus->energy(); + showerShape.hcalTowersBehindClusters = _hcalHelperPflow->hcalTowersBehindClusters(*theClus); + showerShape.hcalDepth1OverEcalBc = + _hcalHelperPflow->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters) / showerShape.e5x5; + showerShape.hcalDepth2OverEcalBc = + _hcalHelperPflow->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters) / showerShape.e5x5; + } else { + showerShape.hcalDepth1OverEcal = _hcalHelper->hcalESumDepth1(*theClus) / theClus->energy(); + showerShape.hcalDepth2OverEcal = _hcalHelper->hcalESumDepth2(*theClus) / theClus->energy(); + showerShape.hcalTowersBehindClusters = _hcalHelper->hcalTowersBehindClusters(*theClus); + showerShape.hcalDepth1OverEcalBc = + _hcalHelper->hcalESumDepth1BehindClusters(showerShape.hcalTowersBehindClusters) / showerShape.e5x5; + showerShape.hcalDepth2OverEcalBc = + _hcalHelper->hcalESumDepth2BehindClusters(showerShape.hcalTowersBehindClusters) / showerShape.e5x5; + } +} diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.h index 9350c19ea969a..e9dd0ecc57adf 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronFull5x5Filler.h @@ -10,30 +10,29 @@ #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" -class GsfElectronFull5x5Filler : public edm::stream::EDProducer<> - { - public: - - //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; - - explicit GsfElectronFull5x5Filler( const edm::ParameterSet & ) ; - ~GsfElectronFull5x5Filler() override ; - void produce( edm::Event &, const edm::EventSetup & ) override ; - void calculateShowerShape_full5x5(const reco::SuperClusterRef & theClus, bool pflow, reco::GsfElectron::ShowerShape & showerShape); - - void beginLuminosityBlock(edm::LuminosityBlock const&, - edm::EventSetup const&) override; - - private: - edm::EDGetTokenT _source; - edm::EDGetTokenT _ebRecHitsToken, _eeRecHitsToken; - std::unique_ptr _hcalHelper, _hcalHelperPflow ; - edm::Handle _ebRecHits; - edm::Handle _eeRecHits; - const CaloTopology * _topology; - const CaloGeometry * _geometry; - - private: - }; +class GsfElectronFull5x5Filler : public edm::stream::EDProducer<> { +public: + //static void fillDescriptions( edm::ConfigurationDescriptions & ) ; + + explicit GsfElectronFull5x5Filler(const edm::ParameterSet &); + ~GsfElectronFull5x5Filler() override; + void produce(edm::Event &, const edm::EventSetup &) override; + void calculateShowerShape_full5x5(const reco::SuperClusterRef &theClus, + bool pflow, + reco::GsfElectron::ShowerShape &showerShape); + + void beginLuminosityBlock(edm::LuminosityBlock const &, edm::EventSetup const &) override; + +private: + edm::EDGetTokenT _source; + edm::EDGetTokenT _ebRecHitsToken, _eeRecHitsToken; + std::unique_ptr _hcalHelper, _hcalHelperPflow; + edm::Handle _ebRecHits; + edm::Handle _eeRecHits; + const CaloTopology *_topology; + const CaloGeometry *_geometry; + +private: +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.cc index ddade39c8ffe0..02866d98b5a9e 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.cc @@ -18,18 +18,14 @@ #include "DataFormats/TrackingRecHit/interface/TrackingRecHitFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" - #include using namespace reco; -GsfElectronProducer::GsfElectronProducer( const edm::ParameterSet & cfg, const gsfAlgoHelpers::HeavyObjectCache* hoc ) - : GsfElectronBaseProducer(cfg,hoc), pfTranslatorParametersChecked_(false) - {} - +GsfElectronProducer::GsfElectronProducer(const edm::ParameterSet& cfg, const gsfAlgoHelpers::HeavyObjectCache* hoc) + : GsfElectronBaseProducer(cfg, hoc), pfTranslatorParametersChecked_(false) {} -reco::GsfElectronCollection GsfElectronProducer::clonePreviousElectrons(edm::Event const& event) const -{ +reco::GsfElectronCollection GsfElectronProducer::clonePreviousElectrons(edm::Event const& event) const { reco::GsfElectronCollection electrons; auto coreElectrons = event.getHandle(inputCfg_.gsfElectronCores); @@ -50,71 +46,61 @@ reco::GsfElectronCollection GsfElectronProducer::clonePreviousElectrons(edm::Eve return electrons; } - -void GsfElectronProducer::produce( edm::Event & event, const edm::EventSetup & setup ) - { - auto electrons = clonePreviousElectrons(event) ; +void GsfElectronProducer::produce(edm::Event& event, const edm::EventSetup& setup) { + auto electrons = clonePreviousElectrons(event); // don't add pflow only electrons if one so wish - if (strategyCfg_.addPflowElectrons) - { algo_->completeElectrons(electrons, event, setup, globalCache()) ; } - addPflowInfo(electrons, event) ; - fillEvent(electrons, event) ; - } - -void GsfElectronProducer::beginEvent( edm::Event & event, const edm::EventSetup & setup ) - { + if (strategyCfg_.addPflowElectrons) { + algo_->completeElectrons(electrons, event, setup, globalCache()); + } + addPflowInfo(electrons, event); + fillEvent(electrons, event); +} + +void GsfElectronProducer::beginEvent(edm::Event& event, const edm::EventSetup& setup) { // extra configuration checks - if (!pfTranslatorParametersChecked_) - { - pfTranslatorParametersChecked_ = true ; - edm::Handle > pfMva ; - event.getByToken(pfMVA_,pfMva) ; - checkPfTranslatorParameters(edm::parameterSet(*pfMva.provenance())) ; - } + if (!pfTranslatorParametersChecked_) { + pfTranslatorParametersChecked_ = true; + edm::Handle > pfMva; + event.getByToken(pfMVA_, pfMva); + checkPfTranslatorParameters(edm::parameterSet(*pfMva.provenance())); + } // call to base class - return GsfElectronBaseProducer::beginEvent(event,setup) ; - } - -void GsfElectronProducer::checkPfTranslatorParameters( edm::ParameterSet const & pset ) - { - edm::ParameterSet mvaBlock = pset.getParameter("MVACutBlock") ; - double pfTranslatorMinMva = mvaBlock.getParameter("MVACut") ; - double pfTranslatorUndefined = -99. ; - if (strategyCfg_.applyPreselection&&(cutsCfgPflow_.minMVA("MVACutBlock"); + double pfTranslatorMinMva = mvaBlock.getParameter("MVACut"); + double pfTranslatorUndefined = -99.; + if (strategyCfg_.applyPreselection && (cutsCfgPflow_.minMVA < pfTranslatorMinMva)) { // For pure tracker seeded electrons, if MVA is under translatorMinMva, there is no supercluster // of any kind available, so GsfElectronCoreProducer has already discarded the electron. edm::LogWarning("GsfElectronAlgo|MvaCutTooLow") - <<"Parameter minMVAPflow ("<pfTranslatorUndefined) - { + if (cutsCfg_.minMVA > pfTranslatorUndefined) { edm::LogWarning("GsfElectronAlgo|IncompletePflowInformation") - <<"Parameter minMVA ("< > > IsolationValueMaps; IsolationValueMaps pfIsolationValues; @@ -177,11 +163,15 @@ void GsfElectronProducer::addPflowInfo(reco::GsfElectronCollection& electrons, e el.setMvaInput(pfElectron->mvaInput()); el.setMvaOutput(pfElectron->mvaOutput()); if (el.ecalDrivenSeed()) { - el.setP4(GsfElectron::P4_PFLOW_COMBINATION, pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION), - pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION), false); + el.setP4(GsfElectron::P4_PFLOW_COMBINATION, + pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION), + pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION), + false); } else { - el.setP4(GsfElectron::P4_PFLOW_COMBINATION, pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION), - pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION), true); + el.setP4(GsfElectron::P4_PFLOW_COMBINATION, + pfElectron->p4(GsfElectron::P4_PFLOW_COMBINATION), + pfElectron->p4Error(GsfElectron::P4_PFLOW_COMBINATION), + true); } double noCutMin = -999999999.; if (el.mva_e_pi() < noCutMin) { @@ -220,9 +210,7 @@ void GsfElectronProducer::addPflowInfo(reco::GsfElectronCollection& electrons, e } } - -void GsfElectronProducer::setPflowPreselectionFlag(GsfElectron& ele) const -{ +void GsfElectronProducer::setPflowPreselectionFlag(GsfElectron& ele) const { ele.setPassMvaPreselection(false); if (ele.core()->ecalDrivenSeed()) { diff --git a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.h index 789c67ed1bf06..c651e6ae6e165 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/GsfElectronProducer.h @@ -4,26 +4,22 @@ #include "GsfElectronBaseProducer.h" -class GsfElectronProducer : public GsfElectronBaseProducer - { - public: - - explicit GsfElectronProducer( const edm::ParameterSet &, const gsfAlgoHelpers::HeavyObjectCache* ) ; - void produce( edm::Event &, const edm::EventSetup & ) override ; - - protected: - - void beginEvent( edm::Event &, const edm::EventSetup & ) ; - - private : - - reco::GsfElectronCollection clonePreviousElectrons(edm::Event const& event) const ; - void addPflowInfo(reco::GsfElectronCollection & electrons, edm::Event const& event) const ; // now deprecated - void setPflowPreselectionFlag( reco::GsfElectron & ele ) const; - - // check expected configuration of previous modules - bool pfTranslatorParametersChecked_ ; - void checkPfTranslatorParameters( edm::ParameterSet const & ) ; - } ; +class GsfElectronProducer : public GsfElectronBaseProducer { +public: + explicit GsfElectronProducer(const edm::ParameterSet&, const gsfAlgoHelpers::HeavyObjectCache*); + void produce(edm::Event&, const edm::EventSetup&) override; + +protected: + void beginEvent(edm::Event&, const edm::EventSetup&); + +private: + reco::GsfElectronCollection clonePreviousElectrons(edm::Event const& event) const; + void addPflowInfo(reco::GsfElectronCollection& electrons, edm::Event const& event) const; // now deprecated + void setPflowPreselectionFlag(reco::GsfElectron& ele) const; + + // check expected configuration of previous modules + bool pfTranslatorParametersChecked_; + void checkPfTranslatorParameters(edm::ParameterSet const&); +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGSFToTrackLinker.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGSFToTrackLinker.cc index 9425828897271..76a1e158feeb8 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGSFToTrackLinker.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGSFToTrackLinker.cc @@ -22,72 +22,72 @@ class LowPtGSFToTrackLinker : public edm::global::EDProducer<> { public: - explicit LowPtGSFToTrackLinker(const edm::ParameterSet&); - ~LowPtGSFToTrackLinker() override; - - void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; - static void fillDescriptions(edm::ConfigurationDescriptions&); - + explicit LowPtGSFToTrackLinker(const edm::ParameterSet&); + ~LowPtGSFToTrackLinker() override; + + void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; + static void fillDescriptions(edm::ConfigurationDescriptions&); + private: - const edm::EDGetTokenT tracks_; - const edm::EDGetTokenT< std::vector > preid_; - const edm::EDGetTokenT< std::vector > gsftracks_; + const edm::EDGetTokenT tracks_; + const edm::EDGetTokenT > preid_; + const edm::EDGetTokenT > gsftracks_; }; -LowPtGSFToTrackLinker::LowPtGSFToTrackLinker(const edm::ParameterSet& iConfig) : - tracks_{consumes(iConfig.getParameter("tracks"))}, - preid_{consumes >(iConfig.getParameter("gsfPreID"))}, - gsftracks_{consumes >(iConfig.getParameter("gsfTracks"))} { - produces< edm::Association > (); - } +LowPtGSFToTrackLinker::LowPtGSFToTrackLinker(const edm::ParameterSet& iConfig) + : tracks_{consumes(iConfig.getParameter("tracks"))}, + preid_{consumes >(iConfig.getParameter("gsfPreID"))}, + gsftracks_{consumes >(iConfig.getParameter("gsfTracks"))} { + produces >(); +} LowPtGSFToTrackLinker::~LowPtGSFToTrackLinker() {} void LowPtGSFToTrackLinker::produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const { - edm::Handle > gsftracks; - iEvent.getByToken(gsftracks_, gsftracks); - - edm::Handle tracks; - iEvent.getByToken(tracks_, tracks); - - edm::Handle > preid; - iEvent.getByToken(preid_, preid); - - // collection sizes, for reference - const size_t ngsf = gsftracks->size(); - - //store mapping for association - std::vector gsf2track(ngsf, -1); - - //map Track --> GSF and fill GSF --> PackedCandidates and GSF --> Lost associations - for(unsigned int igsf=0; igsf < ngsf; ++igsf) { - reco::GsfTrackRef gref(gsftracks, igsf); - reco::TrackRef trk = preid->at( - gref->seedRef().castTo().index() - ).trackRef(); - - if(trk.id() != tracks.id()) { - throw cms::Exception("WrongCollection", "The reco::Track collection used to match against the GSF Tracks was not used to produce such tracks"); - } - - size_t trkid = trk.index(); - gsf2track[igsf] = trkid; - } - - // create output collections from the mappings - auto assoc = std::make_unique< edm::Association >(tracks); - edm::Association::Filler filler(*assoc); - filler.insert(gsftracks, gsf2track.begin(), gsf2track.end()); - filler.fill(); - iEvent.put(std::move(assoc)); + edm::Handle > gsftracks; + iEvent.getByToken(gsftracks_, gsftracks); + + edm::Handle tracks; + iEvent.getByToken(tracks_, tracks); + + edm::Handle > preid; + iEvent.getByToken(preid_, preid); + + // collection sizes, for reference + const size_t ngsf = gsftracks->size(); + + //store mapping for association + std::vector gsf2track(ngsf, -1); + + //map Track --> GSF and fill GSF --> PackedCandidates and GSF --> Lost associations + for (unsigned int igsf = 0; igsf < ngsf; ++igsf) { + reco::GsfTrackRef gref(gsftracks, igsf); + reco::TrackRef trk = preid->at(gref->seedRef().castTo().index()).trackRef(); + + if (trk.id() != tracks.id()) { + throw cms::Exception( + "WrongCollection", + "The reco::Track collection used to match against the GSF Tracks was not used to produce such tracks"); + } + + size_t trkid = trk.index(); + gsf2track[igsf] = trkid; + } + + // create output collections from the mappings + auto assoc = std::make_unique >(tracks); + edm::Association::Filler filler(*assoc); + filler.insert(gsftracks, gsf2track.begin(), gsf2track.end()); + filler.fill(); + iEvent.put(std::move(assoc)); } void LowPtGSFToTrackLinker::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { - edm::ParameterSetDescription desc; - desc.add("tracks", edm::InputTag("generalTracks")); - desc.add("gsfPreID", edm::InputTag("lowPtGsfElectronSeeds")); - desc.add("gsfTracks", edm::InputTag("lowPtGsfEleGsfTracks")); - descriptions.add("lowPtGsfToTrackLinksDefault", desc); + edm::ParameterSetDescription desc; + desc.add("tracks", edm::InputTag("generalTracks")); + desc.add("gsfPreID", edm::InputTag("lowPtGsfElectronSeeds")); + desc.add("gsfTracks", edm::InputTag("lowPtGsfEleGsfTracks")); + descriptions.add("lowPtGsfToTrackLinksDefault", desc); } DEFINE_FWK_MODULE(LowPtGSFToTrackLinker); diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.cc index e7b2c98cc0af9..cee4e57737a51 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.cc @@ -7,29 +7,29 @@ #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.h" -LowPtGsfElectronCoreProducer::LowPtGsfElectronCoreProducer( const edm::ParameterSet& config ) - : GsfElectronCoreBaseProducer(config) -{ - superClusterRefs_ = consumes< edm::ValueMap >(config.getParameter("superClusters")); +LowPtGsfElectronCoreProducer::LowPtGsfElectronCoreProducer(const edm::ParameterSet& config) + : GsfElectronCoreBaseProducer(config) { + superClusterRefs_ = + consumes >(config.getParameter("superClusters")); } LowPtGsfElectronCoreProducer::~LowPtGsfElectronCoreProducer() {} -void LowPtGsfElectronCoreProducer::produce( edm::Event& event, const edm::EventSetup& setup ) { - +void LowPtGsfElectronCoreProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // Output collection auto electrons = std::make_unique(); // Init - GsfElectronCoreBaseProducer::initEvent(event,setup) ; - if ( !useGsfPfRecTracks_ ) { edm::LogError("useGsfPfRecTracks_ is (redundantly) set to False!"); } + GsfElectronCoreBaseProducer::initEvent(event, setup); + if (!useGsfPfRecTracks_) { + edm::LogError("useGsfPfRecTracks_ is (redundantly) set to False!"); + } - edm::Handle< edm::ValueMap > superClusterRefs; - event.getByToken(superClusterRefs_,superClusterRefs); + edm::Handle > superClusterRefs; + event.getByToken(superClusterRefs_, superClusterRefs); // Create ElectronCore objects - for ( size_t ipfgsf = 0; ipfgsf < gsfPfRecTracksH_->size(); ++ipfgsf ) { - + for (size_t ipfgsf = 0; ipfgsf < gsfPfRecTracksH_->size(); ++ipfgsf) { // Refs to GSF(PF) objects and SC reco::GsfPFRecTrackRef pfgsf(gsfPfRecTracksH_, ipfgsf); reco::GsfTrackRef gsf = pfgsf->gsfTrackRef(); @@ -39,7 +39,7 @@ void LowPtGsfElectronCoreProducer::produce( edm::Event& event, const edm::EventS electrons->emplace_back(gsf); // Do not consider ECAL-driven objects - if( electrons->back().ecalDrivenSeed() ) { + if (electrons->back().ecalDrivenSeed()) { electrons->pop_back(); continue; } @@ -49,21 +49,18 @@ void LowPtGsfElectronCoreProducer::produce( edm::Event& event, const edm::EventS // Add super cluster information electrons->back().setSuperCluster(sc); - } event.put(std::move(electrons)); - } ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronCoreProducer::fillDescriptions( edm::ConfigurationDescriptions& descriptions ) -{ +void LowPtGsfElectronCoreProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; GsfElectronCoreBaseProducer::fillDescription(desc); - desc.add("superClusters",edm::InputTag("lowPtGsfElectronSuperClusters")); - descriptions.add("defaultLowPtGsfElectronCores",desc); + desc.add("superClusters", edm::InputTag("lowPtGsfElectronSuperClusters")); + descriptions.add("defaultLowPtGsfElectronCores", desc); } ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.h index 35e9fff1e3912..7b704390c65fd 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronCoreProducer.h @@ -7,22 +7,17 @@ #include "RecoEgamma/EgammaElectronProducers/plugins/GsfElectronCoreBaseProducer.h" class LowPtGsfElectronCoreProducer : public GsfElectronCoreBaseProducer { +public: + explicit LowPtGsfElectronCoreProducer(const edm::ParameterSet& conf); - public: - - explicit LowPtGsfElectronCoreProducer( const edm::ParameterSet& conf ); - ~LowPtGsfElectronCoreProducer() override; - - void produce( edm::Event&, const edm::EventSetup& ) override; - - static void fillDescriptions( edm::ConfigurationDescriptions& ); - private: + void produce(edm::Event&, const edm::EventSetup&) override; - edm::EDGetTokenT< edm::ValueMap > superClusterRefs_; + static void fillDescriptions(edm::ConfigurationDescriptions&); +private: + edm::EDGetTokenT > superClusterRefs_; }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronCoreProducer_h - +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronCoreProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.cc index f4c65dde72c11..a9a07d60c39c5 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.cc @@ -8,17 +8,16 @@ //////////////////////////////////////////////////////////////////////////////// // -LowPtGsfElectronIDProducer::LowPtGsfElectronIDProducer( const edm::ParameterSet& conf, - const lowptgsfeleid::HeavyObjectCache* ) : - gsfElectrons_(consumes(conf.getParameter("electrons"))), - rho_(consumes(conf.getParameter("rho"))), - names_(conf.getParameter< std::vector >("ModelNames")), - passThrough_(conf.getParameter("PassThrough")), - minPtThreshold_(conf.getParameter("MinPtThreshold")), - maxPtThreshold_(conf.getParameter("MaxPtThreshold")) -{ - for ( const auto& name : names_ ) { - produces< edm::ValueMap >(name); +LowPtGsfElectronIDProducer::LowPtGsfElectronIDProducer(const edm::ParameterSet& conf, + const lowptgsfeleid::HeavyObjectCache*) + : gsfElectrons_(consumes(conf.getParameter("electrons"))), + rho_(consumes(conf.getParameter("rho"))), + names_(conf.getParameter >("ModelNames")), + passThrough_(conf.getParameter("PassThrough")), + minPtThreshold_(conf.getParameter("MinPtThreshold")), + maxPtThreshold_(conf.getParameter("MaxPtThreshold")) { + for (const auto& name : names_) { + produces >(name); } } @@ -28,57 +27,58 @@ LowPtGsfElectronIDProducer::~LowPtGsfElectronIDProducer() {} //////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronIDProducer::produce( edm::Event& event, const edm::EventSetup& setup ) { - +void LowPtGsfElectronIDProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // Pileup edm::Handle rho; - event.getByToken(rho_,rho); - if ( !rho.isValid() ) { edm::LogError("Problem with rho handle"); } + event.getByToken(rho_, rho); + if (!rho.isValid()) { + edm::LogError("Problem with rho handle"); + } // Retrieve GsfElectrons from Event edm::Handle gsfElectrons; - event.getByToken(gsfElectrons_,gsfElectrons); - if ( !gsfElectrons.isValid() ) { edm::LogError("Problem with gsfElectrons handle"); } + event.getByToken(gsfElectrons_, gsfElectrons); + if (!gsfElectrons.isValid()) { + edm::LogError("Problem with gsfElectrons handle"); + } // Iterate through Electrons, evaluate BDT, and store result - std::vector< std::vector > output; - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - output.push_back( std::vector(gsfElectrons->size(),-999.) ); + std::vector > output; + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + output.push_back(std::vector(gsfElectrons->size(), -999.)); } - for ( unsigned int iele = 0; iele < gsfElectrons->size(); iele++ ) { - reco::GsfElectronRef ele(gsfElectrons,iele); + for (unsigned int iele = 0; iele < gsfElectrons->size(); iele++) { + reco::GsfElectronRef ele(gsfElectrons, iele); //if ( !passThrough_ && ( ele->pt() < minPtThreshold_ ) ) { continue; } - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - output[iname][iele] = globalCache()->eval( names_[iname], ele, *rho ); + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + output[iname][iele] = globalCache()->eval(names_[iname], ele, *rho); } } - + // Create and put ValueMap in Event - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - auto ptr = std::make_unique< edm::ValueMap >( edm::ValueMap() ); + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + auto ptr = std::make_unique >(edm::ValueMap()); edm::ValueMap::Filler filler(*ptr); filler.insert(gsfElectrons, output[iname].begin(), output[iname].end()); filler.fill(); - reco::GsfElectronRef ele(gsfElectrons,0); - event.put(std::move(ptr),names_[iname]); + reco::GsfElectronRef ele(gsfElectrons, 0); + event.put(std::move(ptr), names_[iname]); } - } ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronIDProducer::fillDescriptions( edm::ConfigurationDescriptions& descriptions ) -{ +void LowPtGsfElectronIDProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("electrons",edm::InputTag("lowPtGsfElectrons")); - desc.add("rho",edm::InputTag("fixedGridRhoFastjetAllTmp")); - desc.add< std::vector >("ModelNames",std::vector()); - desc.add< std::vector >("ModelWeights",std::vector()); - desc.add< std::vector >("ModelThresholds",std::vector()); - desc.add("PassThrough",false); - desc.add("MinPtThreshold",0.5); - desc.add("MaxPtThreshold",15.); - descriptions.add("defaultLowPtGsfElectronID",desc); + desc.add("electrons", edm::InputTag("lowPtGsfElectrons")); + desc.add("rho", edm::InputTag("fixedGridRhoFastjetAllTmp")); + desc.add >("ModelNames", std::vector()); + desc.add >("ModelWeights", std::vector()); + desc.add >("ModelThresholds", std::vector()); + desc.add("PassThrough", false); + desc.add("MinPtThreshold", 0.5); + desc.add("MaxPtThreshold", 15.); + descriptions.add("defaultLowPtGsfElectronID", desc); } ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.h index 2589ce9d1a8e8..9824fe48d462a 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronIDProducer.h @@ -9,37 +9,30 @@ #include #include -class LowPtGsfElectronIDProducer final : -public edm::stream::EDProducer< edm::GlobalCache > { - - public: - - explicit LowPtGsfElectronIDProducer( const edm::ParameterSet&, - const lowptgsfeleid::HeavyObjectCache* ); - +class LowPtGsfElectronIDProducer final + : public edm::stream::EDProducer > { +public: + explicit LowPtGsfElectronIDProducer(const edm::ParameterSet&, const lowptgsfeleid::HeavyObjectCache*); + ~LowPtGsfElectronIDProducer() override; - - static std::unique_ptr - initializeGlobalCache( const edm::ParameterSet& conf ) { + + static std::unique_ptr initializeGlobalCache(const edm::ParameterSet& conf) { return std::make_unique(lowptgsfeleid::HeavyObjectCache(conf)); } - - static void globalEndJob( lowptgsfeleid::HeavyObjectCache const* ) {} - void produce( edm::Event&, const edm::EventSetup& ) override; - - static void fillDescriptions( edm::ConfigurationDescriptions& ); + static void globalEndJob(lowptgsfeleid::HeavyObjectCache const*) {} + + void produce(edm::Event&, const edm::EventSetup&) override; - private: - + static void fillDescriptions(edm::ConfigurationDescriptions&); + +private: const edm::EDGetTokenT gsfElectrons_; const edm::EDGetTokenT rho_; const std::vector names_; const bool passThrough_; const double minPtThreshold_; const double maxPtThreshold_; - }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronIDProducer_h - +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronIDProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.cc index ca3c0dcf92222..8ad4d69947a89 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.cc @@ -8,16 +8,13 @@ #include "DataFormats/Candidate/interface/Candidate.h" #include "RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.h" -LowPtGsfElectronProducer::LowPtGsfElectronProducer( const edm::ParameterSet& cfg, - const gsfAlgoHelpers::HeavyObjectCache* hoc ) - : GsfElectronBaseProducer(cfg,hoc) -{} +LowPtGsfElectronProducer::LowPtGsfElectronProducer(const edm::ParameterSet& cfg, + const gsfAlgoHelpers::HeavyObjectCache* hoc) + : GsfElectronBaseProducer(cfg, hoc) {} -LowPtGsfElectronProducer::~LowPtGsfElectronProducer() -{} +LowPtGsfElectronProducer::~LowPtGsfElectronProducer() {} -void LowPtGsfElectronProducer::produce( edm::Event& event, const edm::EventSetup& setup ) -{ +void LowPtGsfElectronProducer::produce(edm::Event& event, const edm::EventSetup& setup) { reco::GsfElectronCollection electrons; algo_->completeElectrons(electrons, event, setup, globalCache()); fillEvent(electrons, event); diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.h index 6fcf40b99ea3c..d957c94b497b4 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronProducer.h @@ -4,18 +4,14 @@ #include "RecoEgamma/EgammaElectronProducers/plugins/GsfElectronBaseProducer.h" class LowPtGsfElectronProducer : public GsfElectronBaseProducer { - - public: - - explicit LowPtGsfElectronProducer( const edm::ParameterSet&, - const gsfAlgoHelpers::HeavyObjectCache* ); +public: + explicit LowPtGsfElectronProducer(const edm::ParameterSet&, const gsfAlgoHelpers::HeavyObjectCache*); ~LowPtGsfElectronProducer() override; - void produce( edm::Event&, const edm::EventSetup& ) override; - - private: + void produce(edm::Event&, const edm::EventSetup&) override; +private: }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronProducer_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.cc index 7d2a8b9f064c5..ea64ddce6150f 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.cc @@ -18,34 +18,30 @@ //////////////////////////////////////////////////////////////////////////////// // -LowPtGsfElectronSCProducer::LowPtGsfElectronSCProducer( const edm::ParameterSet& cfg ) : - gsfPfRecTracks_{consumes( cfg.getParameter("gsfPfRecTracks") )}, - ecalClusters_{consumes( cfg.getParameter("ecalClusters") )}, - dr2_{cfg.getParameter("MaxDeltaR2")} -{ +LowPtGsfElectronSCProducer::LowPtGsfElectronSCProducer(const edm::ParameterSet& cfg) + : gsfPfRecTracks_{consumes(cfg.getParameter("gsfPfRecTracks"))}, + ecalClusters_{consumes(cfg.getParameter("ecalClusters"))}, + dr2_{cfg.getParameter("MaxDeltaR2")} { produces(); produces(); - produces< edm::ValueMap >(); + produces >(); } //////////////////////////////////////////////////////////////////////////////// // -LowPtGsfElectronSCProducer::~LowPtGsfElectronSCProducer() -{} +LowPtGsfElectronSCProducer::~LowPtGsfElectronSCProducer() {} //////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSCProducer::produce( edm::Event& event, const edm::EventSetup& setup ) -{ - +void LowPtGsfElectronSCProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // Input GsfPFRecTracks collection - auto gsfPfRecTracks=edm::makeValid(event.getHandle(gsfPfRecTracks_)); + auto gsfPfRecTracks = edm::makeValid(event.getHandle(gsfPfRecTracks_)); // Input EcalClusters collection reco::PFClusterCollection const& ecalClusters = event.get(ecalClusters_); // Output SuperClusters collection and getRefBeforePut - auto superClusters = std::make_unique( reco::SuperClusterCollection() ); + auto superClusters = std::make_unique(reco::SuperClusterCollection()); superClusters->reserve(gsfPfRecTracks->size()); const reco::SuperClusterRefProd superClustersRefProd = event.getRefBeforePut(); @@ -53,63 +49,63 @@ void LowPtGsfElectronSCProducer::produce( edm::Event& event, const edm::EventSet std::vector superClustersValueMap; // Output CaloClusters collection - auto caloClusters = std::make_unique( reco::CaloClusterCollection() ); + auto caloClusters = std::make_unique(reco::CaloClusterCollection()); caloClusters->reserve(ecalClusters.size()); // Index[GSF track][trajectory point] for "best" CaloCluster - std::vector< std::vector > cluster_idx; - cluster_idx.reserve( gsfPfRecTracks->size()); + std::vector > cluster_idx; + cluster_idx.reserve(gsfPfRecTracks->size()); // Index[GSF track][trajectory point] for "best" PFCluster - std::vector< std::vector > pfcluster_idx; - pfcluster_idx.reserve( gsfPfRecTracks->size()); + std::vector > pfcluster_idx; + pfcluster_idx.reserve(gsfPfRecTracks->size()); // dr2min[GSF track][trajectory point] for "best" CaloCluster - std::vector< std::vector > cluster_dr2min; - cluster_dr2min.reserve( gsfPfRecTracks->size()); + std::vector > cluster_dr2min; + cluster_dr2min.reserve(gsfPfRecTracks->size()); // Construct list of trajectory points from the GSF track and electron brems - std::vector< std::vector > points; - points.reserve( gsfPfRecTracks->size()); - for ( auto const& trk: *gsfPfRecTracks) { + std::vector > points; + points.reserve(gsfPfRecTracks->size()); + for (auto const& trk : *gsfPfRecTracks) { // Extrapolated track std::vector traj; - traj.reserve(trk.PFRecBrem().size()+1); - traj.push_back( &trk.extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax) ); + traj.reserve(trk.PFRecBrem().size() + 1); + traj.push_back(&trk.extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax)); // Extrapolated brem trajectories - for ( auto const& brem : trk.PFRecBrem() ) { - traj.push_back( &brem.extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax) ); + for (auto const& brem : trk.PFRecBrem()) { + traj.push_back(&brem.extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax)); } auto size = traj.size(); points.push_back(std::move(traj)); // Size containers - cluster_idx.emplace_back(size,-1); - pfcluster_idx.emplace_back(size,-1); - cluster_dr2min.emplace_back(size,1.e6); + cluster_idx.emplace_back(size, -1); + pfcluster_idx.emplace_back(size, -1); + cluster_dr2min.emplace_back(size, 1.e6); } // For each cluster, find closest trajectory point ("global" arbitration at event level) - for ( size_t iclu = 0; iclu < ecalClusters.size(); ++iclu ) { // Cluster loop - std::pair point = std::make_pair(-1,-1); + for (size_t iclu = 0; iclu < ecalClusters.size(); ++iclu) { // Cluster loop + std::pair point = std::make_pair(-1, -1); float dr2min = 1.e6; - for ( size_t ipoint = 0; ipoint < points.size(); ++ipoint ) { // GSF track loop - for ( size_t jpoint = 0; jpoint < points[ipoint].size(); ++jpoint ) { // Traj point loop - if ( points[ipoint][jpoint]->isValid() ) { - float dr2 = reco::deltaR2( ecalClusters[iclu], points[ipoint][jpoint]->positionREP() ); - if ( dr2 < dr2min ) { - // Store nearest point to this cluster - dr2min = dr2; - point = std::make_pair(ipoint,jpoint); - } - } + for (size_t ipoint = 0; ipoint < points.size(); ++ipoint) { // GSF track loop + for (size_t jpoint = 0; jpoint < points[ipoint].size(); ++jpoint) { // Traj point loop + if (points[ipoint][jpoint]->isValid()) { + float dr2 = reco::deltaR2(ecalClusters[iclu], points[ipoint][jpoint]->positionREP()); + if (dr2 < dr2min) { + // Store nearest point to this cluster + dr2min = dr2; + point = std::make_pair(ipoint, jpoint); + } + } } } - if ( point.first >= 0 && point.second >= 0 && // if this cluster is matched to a point ... - dr2min < cluster_dr2min[point.first][point.second] ) { // ... and cluster is closest to the same point + if (point.first >= 0 && point.second >= 0 && // if this cluster is matched to a point ... + dr2min < cluster_dr2min[point.first][point.second]) { // ... and cluster is closest to the same point // Copy CaloCluster to new collection caloClusters->push_back(ecalClusters[iclu]); // Store cluster index for creation of SC later - cluster_idx[point.first][point.second] = caloClusters->size()-1; + cluster_idx[point.first][point.second] = caloClusters->size() - 1; pfcluster_idx[point.first][point.second] = iclu; cluster_dr2min[point.first][point.second] = dr2min; } @@ -119,8 +115,7 @@ void LowPtGsfElectronSCProducer::produce( edm::Event& event, const edm::EventSet const edm::OrphanHandle& caloClustersH = event.put(std::move(caloClusters)); // Loop through GSF tracks - for ( size_t itrk = 0; itrk < gsfPfRecTracks->size(); ++itrk ) { - + for (size_t itrk = 0; itrk < gsfPfRecTracks->size(); ++itrk) { // Used to create SC float energy = 0.; float X = 0., Y = 0., Z = 0.; @@ -131,29 +126,39 @@ void LowPtGsfElectronSCProducer::produce( edm::Event& event, const edm::EventSet // Find closest match in dr2 from points associated to given track int index = -1; float dr2 = 1.e6; - for ( size_t ipoint = 0; ipoint < cluster_idx[itrk].size(); ++ipoint ) { - if ( cluster_idx[itrk][ipoint] < 0 ) { continue; } - if ( cluster_dr2min[itrk][ipoint] < dr2 ) { - dr2 = cluster_dr2min[itrk][ipoint]; - index = cluster_idx[itrk][ipoint]; + for (size_t ipoint = 0; ipoint < cluster_idx[itrk].size(); ++ipoint) { + if (cluster_idx[itrk][ipoint] < 0) { + continue; + } + if (cluster_dr2min[itrk][ipoint] < dr2) { + dr2 = cluster_dr2min[itrk][ipoint]; + index = cluster_idx[itrk][ipoint]; } } - + // For each track, loop through points and use associated cluster - for ( size_t ipoint = 0; ipoint < cluster_idx[itrk].size(); ++ipoint ) { - if ( cluster_idx[itrk][ipoint] < 0 ) { continue; } - reco::CaloClusterPtr clu(caloClustersH,cluster_idx[itrk][ipoint]); - if ( clu.isNull() ) { continue; } - if ( !( cluster_dr2min[itrk][ipoint] < dr2_ || // Require cluster to be closer than dr2_ ... - index == cluster_idx[itrk][ipoint] ) ) { continue; } // ... unless it is the closest one ... - if ( seed.isNull() ) { seed = clu; } + for (size_t ipoint = 0; ipoint < cluster_idx[itrk].size(); ++ipoint) { + if (cluster_idx[itrk][ipoint] < 0) { + continue; + } + reco::CaloClusterPtr clu(caloClustersH, cluster_idx[itrk][ipoint]); + if (clu.isNull()) { + continue; + } + if (!(cluster_dr2min[itrk][ipoint] < dr2_ || // Require cluster to be closer than dr2_ ... + index == cluster_idx[itrk][ipoint])) { + continue; + } // ... unless it is the closest one ... + if (seed.isNull()) { + seed = clu; + } clusters.push_back(clu); energy += clu->correctedEnergy(); X += clu->position().X() * clu->correctedEnergy(); Y += clu->position().Y() * clu->correctedEnergy(); Z += clu->position().Z() * clu->correctedEnergy(); auto index = pfcluster_idx[itrk][ipoint]; - if(index < static_cast(ecalClusters.size())) { + if (index < static_cast(ecalClusters.size())) { barePtrs.push_back(&(ecalClusters[index])); } } @@ -162,68 +167,68 @@ void LowPtGsfElectronSCProducer::produce( edm::Event& event, const edm::EventSet Z /= energy; // Create SC - if ( seed.isNonnull() ) { - reco::SuperCluster sc(energy,math::XYZPoint(X,Y,Z)); + if (seed.isNonnull()) { + reco::SuperCluster sc(energy, math::XYZPoint(X, Y, Z)); sc.setCorrectedEnergy(energy); sc.setSeed(seed); sc.setClusters(clusters); PFClusterWidthAlgo pfwidth(barePtrs); sc.setEtaWidth(pfwidth.pflowEtaWidth()); sc.setPhiWidth(pfwidth.pflowPhiWidth()); - sc.rawEnergy(); // Cache the value of raw energy + sc.rawEnergy(); // Cache the value of raw energy superClusters->push_back(sc); // Populate ValueMap container - superClustersValueMap.push_back( reco::SuperClusterRef( superClustersRefProd, superClusters->size()-1 ) ); + superClustersValueMap.push_back(reco::SuperClusterRef(superClustersRefProd, superClusters->size() - 1)); } else { - superClustersValueMap.push_back( reco::SuperClusterRef( superClustersRefProd.id() ) ); + superClustersValueMap.push_back(reco::SuperClusterRef(superClustersRefProd.id())); } - } // GSF tracks + } // GSF tracks // Put SuperClusters in event event.put(std::move(superClusters)); - auto ptr = std::make_unique< edm::ValueMap >( edm::ValueMap() ); + auto ptr = std::make_unique >(edm::ValueMap()); edm::ValueMap::Filler filler(*ptr); filler.insert(gsfPfRecTracks, superClustersValueMap.begin(), superClustersValueMap.end()); filler.fill(); event.put(std::move(ptr)); - } //////////////////////////////////////////////////////////////////////////////// // -reco::PFClusterRef LowPtGsfElectronSCProducer::closestCluster( const reco::PFTrajectoryPoint& point, - const edm::Handle& clusters, - std::vector& matched ) { +reco::PFClusterRef LowPtGsfElectronSCProducer::closestCluster(const reco::PFTrajectoryPoint& point, + const edm::Handle& clusters, + std::vector& matched) { reco::PFClusterRef closest; - if ( point.isValid() ) { + if (point.isValid()) { float dr2min = dr2_; - for ( size_t ii = 0; ii < clusters->size(); ++ii ) { - if ( std::find( matched.begin(), matched.end(), ii ) == matched.end() ) { - float dr2 = reco::deltaR2( clusters->at(ii), point.positionREP() ); - if ( dr2 < dr2min ) { - closest = reco::PFClusterRef( clusters, ii ); - dr2min = dr2; - } + for (size_t ii = 0; ii < clusters->size(); ++ii) { + if (std::find(matched.begin(), matched.end(), ii) == matched.end()) { + float dr2 = reco::deltaR2(clusters->at(ii), point.positionREP()); + if (dr2 < dr2min) { + closest = reco::PFClusterRef(clusters, ii); + dr2min = dr2; + } } } - if ( dr2min < (dr2_ - 1.e-6) ) { matched.push_back( closest.index() ); } + if (dr2min < (dr2_ - 1.e-6)) { + matched.push_back(closest.index()); + } } return closest; } - + ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSCProducer::fillDescriptions( edm::ConfigurationDescriptions& descriptions ) -{ +void LowPtGsfElectronSCProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("gsfPfRecTracks",edm::InputTag("lowPtGsfElePfGsfTracks")); - desc.add("ecalClusters",edm::InputTag("particleFlowClusterECAL")); - desc.add("hcalClusters",edm::InputTag("particleFlowClusterHCAL")); - desc.add("MaxDeltaR2",0.5); - descriptions.add("defaultLowPtGsfElectronSuperClusters",desc); + desc.add("gsfPfRecTracks", edm::InputTag("lowPtGsfElePfGsfTracks")); + desc.add("ecalClusters", edm::InputTag("particleFlowClusterECAL")); + desc.add("hcalClusters", edm::InputTag("particleFlowClusterHCAL")); + desc.add("MaxDeltaR2", 0.5); + descriptions.add("defaultLowPtGsfElectronSuperClusters", desc); } ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.h index e0c33489c741b..10249c9d63459 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSCProducer.h @@ -11,27 +11,23 @@ #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" class LowPtGsfElectronSCProducer : public edm::stream::EDProducer<> { - - public: - - explicit LowPtGsfElectronSCProducer( const edm::ParameterSet& ); +public: + explicit LowPtGsfElectronSCProducer(const edm::ParameterSet&); ~LowPtGsfElectronSCProducer() override; - void produce( edm::Event&, const edm::EventSetup& ) override; + void produce(edm::Event&, const edm::EventSetup&) override; - static void fillDescriptions( edm::ConfigurationDescriptions& ); + static void fillDescriptions(edm::ConfigurationDescriptions&); - private: +private: + reco::PFClusterRef closestCluster(const reco::PFTrajectoryPoint& point, + const edm::Handle& clusters, + std::vector& matched); - reco::PFClusterRef closestCluster( const reco::PFTrajectoryPoint& point, - const edm::Handle& clusters, - std::vector& matched ); - const edm::EDGetTokenT gsfPfRecTracks_; const edm::EDGetTokenT ecalClusters_; const double dr2_; - }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSCProducer_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSCProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.cc index f6e7fcf988c1a..ae5221e849607 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.cc @@ -35,29 +35,28 @@ ////////////////////////////////////////////////////////////////////////////////////////// // -LowPtGsfElectronSeedProducer::LowPtGsfElectronSeedProducer( const edm::ParameterSet& conf, - const lowptgsfeleseed::HeavyObjectCache* ) : - field_(), - fitterPtr_(), - smootherPtr_(), - kfTracks_(), - pfTracks_(), - ecalClusters_{consumes(conf.getParameter("ecalClusters"))}, - hcalClusters_(), - ebRecHits_{consumes(conf.getParameter("EBRecHits"))}, - eeRecHits_{consumes(conf.getParameter("EERecHits"))}, - rho_(consumes(conf.getParameter("rho"))), - beamSpot_(consumes(conf.getParameter("BeamSpot"))), - fitter_(conf.getParameter("Fitter")), - smoother_(conf.getParameter("Smoother")), - builder_(conf.getParameter("TTRHBuilder")), - passThrough_(conf.getParameter("PassThrough")), - usePfTracks_(conf.getParameter("UsePfTracks")), - minPtThreshold_(conf.getParameter("MinPtThreshold")), - maxPtThreshold_(conf.getParameter("MaxPtThreshold")) -{ - if ( usePfTracks_ ) { - pfTracks_ = consumes(conf.getParameter("pfTracks")); +LowPtGsfElectronSeedProducer::LowPtGsfElectronSeedProducer(const edm::ParameterSet& conf, + const lowptgsfeleseed::HeavyObjectCache*) + : field_(), + fitterPtr_(), + smootherPtr_(), + kfTracks_(), + pfTracks_(), + ecalClusters_{consumes(conf.getParameter("ecalClusters"))}, + hcalClusters_(), + ebRecHits_{consumes(conf.getParameter("EBRecHits"))}, + eeRecHits_{consumes(conf.getParameter("EERecHits"))}, + rho_(consumes(conf.getParameter("rho"))), + beamSpot_(consumes(conf.getParameter("BeamSpot"))), + fitter_(conf.getParameter("Fitter")), + smoother_(conf.getParameter("Smoother")), + builder_(conf.getParameter("TTRHBuilder")), + passThrough_(conf.getParameter("PassThrough")), + usePfTracks_(conf.getParameter("UsePfTracks")), + minPtThreshold_(conf.getParameter("MinPtThreshold")), + maxPtThreshold_(conf.getParameter("MaxPtThreshold")) { + if (usePfTracks_) { + pfTracks_ = consumes(conf.getParameter("pfTracks")); hcalClusters_ = consumes(conf.getParameter("hcalClusters")); } kfTracks_ = consumes(conf.getParameter("tracks")); @@ -65,7 +64,7 @@ LowPtGsfElectronSeedProducer::LowPtGsfElectronSeedProducer( const edm::Parameter produces(); produces(); produces("HCAL"); - produces< edm::ValueMap >(); // indexed by edm::Ref.index() + produces >(); // indexed by edm::Ref.index() } ////////////////////////////////////////////////////////////////////////////////////////// @@ -74,26 +73,20 @@ LowPtGsfElectronSeedProducer::~LowPtGsfElectronSeedProducer() {} ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSeedProducer::beginLuminosityBlock( edm::LuminosityBlock const&, - edm::EventSetup const& setup ) -{ +void LowPtGsfElectronSeedProducer::beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const& setup) { setup.get().get(field_); } ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSeedProducer::produce( edm::Event& event, - const edm::EventSetup& setup ) -{ - +void LowPtGsfElectronSeedProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // Products auto seeds = std::make_unique(); auto ecalPreIds = std::make_unique(); auto hcalPreIds = std::make_unique(); - const edm::RefProd preIdsRefProd = - event.getRefBeforePut(); - + const edm::RefProd preIdsRefProd = event.getRefBeforePut(); + // HCAL clusters (only used with PF tracks) edm::Handle hcalClusters; @@ -102,114 +95,108 @@ void LowPtGsfElectronSeedProducer::produce( edm::Event& event, event.getByToken(kfTracks_, kfTracks); TrackIndxMap trksToPreIdIndx; - if ( usePfTracks_ ) { - + if (usePfTracks_) { edm::Handle pfTracks; event.getByToken(pfTracks_, pfTracks); - event.getByToken(hcalClusters_,hcalClusters); + event.getByToken(hcalClusters_, hcalClusters); //check consistency between kfTracks and pfTracks collection - for(auto& trk : *pfTracks){ - if(trk.trackRef().isNonnull()){ - if(trk.trackRef().id() != kfTracks.id()){ - throw cms::Exception("ConfigError") << "kfTracks is not the collection that pfTracks was built from, please fix this"; - } - break; //we only need one valid track ref to check this so end the loop + for (auto& trk : *pfTracks) { + if (trk.trackRef().isNonnull()) { + if (trk.trackRef().id() != kfTracks.id()) { + throw cms::Exception("ConfigError") + << "kfTracks is not the collection that pfTracks was built from, please fix this"; + } + break; //we only need one valid track ref to check this so end the loop } } - loop(pfTracks, // PF tracks - hcalClusters, - *seeds, - *ecalPreIds, - *hcalPreIds, - trksToPreIdIndx, - event, - setup); - - } else { - - loop(kfTracks, // KF tracks - hcalClusters, - *seeds, - *ecalPreIds, - *hcalPreIds, - trksToPreIdIndx, - event, - setup); - + loop(pfTracks, // PF tracks + hcalClusters, + *seeds, + *ecalPreIds, + *hcalPreIds, + trksToPreIdIndx, + event, + setup); + + } else { + loop(kfTracks, // KF tracks + hcalClusters, + *seeds, + *ecalPreIds, + *hcalPreIds, + trksToPreIdIndx, + event, + setup); } auto ecalPreIdsHandle = event.put(std::move(ecalPreIds)); - event.put(std::move(hcalPreIds),"HCAL"); + event.put(std::move(hcalPreIds), "HCAL"); event.put(std::move(seeds)); - auto preIdVMOut = std::make_unique< edm::ValueMap >(); + auto preIdVMOut = std::make_unique >(); edm::ValueMap::Filler mapFiller(*preIdVMOut); - fillPreIdRefValueMap(kfTracks,trksToPreIdIndx,ecalPreIdsHandle,mapFiller); + fillPreIdRefValueMap(kfTracks, trksToPreIdIndx, ecalPreIdsHandle, mapFiller); mapFiller.fill(); event.put(std::move(preIdVMOut)); - } ////////////////////////////////////////////////////////////////////////////////////////// // Return reco::Track from edm::Ref -reco::TrackRef LowPtGsfElectronSeedProducer::getBaseRef( edm::Handle< std::vector > handle, int idx ) const -{ - return reco::TrackRef(handle,idx); +reco::TrackRef LowPtGsfElectronSeedProducer::getBaseRef(edm::Handle > handle, int idx) const { + return reco::TrackRef(handle, idx); } -reco::TrackRef LowPtGsfElectronSeedProducer::getBaseRef( edm::Handle< std::vector > handle, int idx ) const -{ - return reco::PFRecTrackRef(handle,idx)->trackRef(); +reco::TrackRef LowPtGsfElectronSeedProducer::getBaseRef(edm::Handle > handle, + int idx) const { + return reco::PFRecTrackRef(handle, idx)->trackRef(); } ////////////////////////////////////////////////////////////////////////////////////////// -// Template function, instantiated for both reco::Tracks and reco::PFRecTracks +// Template function, instantiated for both reco::Tracks and reco::PFRecTracks template -void LowPtGsfElectronSeedProducer::loop( const edm::Handle< std::vector >& handle, // PF or KF tracks - edm::Handle& hcalClusters, - reco::ElectronSeedCollection& seeds, - reco::PreIdCollection& ecalPreIds, - reco::PreIdCollection& hcalPreIds, - TrackIndxMap& trksToPreIdIndx, - edm::Event& event, - const edm::EventSetup& setup ) -{ - +void LowPtGsfElectronSeedProducer::loop(const edm::Handle >& handle, // PF or KF tracks + edm::Handle& hcalClusters, + reco::ElectronSeedCollection& seeds, + reco::PreIdCollection& ecalPreIds, + reco::PreIdCollection& hcalPreIds, + TrackIndxMap& trksToPreIdIndx, + edm::Event& event, + const edm::EventSetup& setup) { // Pileup edm::Handle rho; - event.getByToken(rho_,rho); - + event.getByToken(rho_, rho); + // Beam spot edm::Handle spot; - event.getByToken(beamSpot_,spot); + event.getByToken(beamSpot_, spot); // Track fitter edm::ESHandle fitter; - setup.get().get(fitter_,fitter); + setup.get().get(fitter_, fitter); fitterPtr_ = fitter->clone(); // Track smoother edm::ESHandle smoother; - setup.get().get(smoother_,smoother); + setup.get().get(smoother_, smoother); smootherPtr_.reset(smoother->clone()); // RecHit cloner edm::ESHandle builder; - setup.get().get(builder_,builder); + setup.get().get(builder_, builder); TkClonerImpl hitCloner = static_cast(builder.product())->cloner(); fitterPtr_->setHitCloner(&hitCloner); smootherPtr_->setHitCloner(&hitCloner); // ECAL clusters edm::Handle ecalClusters; - event.getByToken(ecalClusters_,ecalClusters); + event.getByToken(ecalClusters_, ecalClusters); // Utility to access to shower shape vars - noZS::EcalClusterLazyTools ecalTools(event,setup,ebRecHits_,eeRecHits_); - + noZS::EcalClusterLazyTools ecalTools(event, setup, ebRecHits_, eeRecHits_); + // Ensure each cluster is only matched once to a track std::vector matchedEcalClusters; std::vector matchedHcalClusters; @@ -218,20 +205,23 @@ void LowPtGsfElectronSeedProducer::loop( const edm::Handle< std::vector >& ha seeds.reserve(handle->size()); ecalPreIds.reserve(handle->size()); hcalPreIds.reserve(handle->size()); - - // Iterate through (PF or KF) tracks - for ( unsigned int itrk = 0; itrk < handle.product()->size(); itrk++ ) { - edm::Ref< std::vector > templatedRef(handle,itrk); // TrackRef or PFRecTrackRef - reco::TrackRef trackRef = getBaseRef(handle,itrk); + // Iterate through (PF or KF) tracks + for (unsigned int itrk = 0; itrk < handle.product()->size(); itrk++) { + edm::Ref > templatedRef(handle, itrk); // TrackRef or PFRecTrackRef + reco::TrackRef trackRef = getBaseRef(handle, itrk); - if ( !(trackRef->quality(reco::TrackBase::qualityByName("highPurity"))) ) { continue; } - if ( !passThrough_ && ( trackRef->pt() < minPtThreshold_ ) ) { continue; } + if (!(trackRef->quality(reco::TrackBase::qualityByName("highPurity")))) { + continue; + } + if (!passThrough_ && (trackRef->pt() < minPtThreshold_)) { + continue; + } - // Create ElectronSeed - reco::ElectronSeed seed( *(trackRef->seedRef()) ); + // Create ElectronSeed + reco::ElectronSeed seed(*(trackRef->seedRef())); seed.setCtfTrack(trackRef); - + // Create PreIds unsigned int nModels = globalCache()->modelNames().size(); reco::PreId ecalPreId(nModels); @@ -242,356 +232,316 @@ void LowPtGsfElectronSeedProducer::loop( const edm::Handle< std::vector >& ha hcalPreId.setTrack(trackRef); // Add Track-Calo matching variables to PreIds - propagateTrackToCalo(templatedRef, - ecalClusters, - hcalClusters, - matchedEcalClusters, - matchedHcalClusters, - ecalPreId, - hcalPreId ); - + propagateTrackToCalo( + templatedRef, ecalClusters, hcalClusters, matchedEcalClusters, matchedHcalClusters, ecalPreId, hcalPreId); + // Add variables related to GSF tracks to PreId - lightGsfTracking(ecalPreId,trackRef,seed,setup); + lightGsfTracking(ecalPreId, trackRef, seed, setup); - // Decision based on BDT - bool result = decision(templatedRef,ecalPreId,hcalPreId,*rho,*spot,ecalTools); + // Decision based on BDT + bool result = decision(templatedRef, ecalPreId, hcalPreId, *rho, *spot, ecalTools); // If fails BDT, do not store seed - if ( !result ) { continue; } - + if (!result) { + continue; + } + // Store PreId ecalPreIds.push_back(ecalPreId); hcalPreIds.push_back(hcalPreId); - trksToPreIdIndx[trackRef.index()] = ecalPreIds.size()-1; + trksToPreIdIndx[trackRef.index()] = ecalPreIds.size() - 1; // Store ElectronSeed and corresponding edm::Ref.index() seeds.push_back(seed); - } - } ////////////////////////////////////////////////////////////////////////////////////////// // Template instantiation for reco::Tracks -template -void LowPtGsfElectronSeedProducer::loop( const edm::Handle< std::vector >&, - edm::Handle& hcalClusters, - reco::ElectronSeedCollection& seeds, - reco::PreIdCollection& ecalPreIds, - reco::PreIdCollection& hcalPreIds, - TrackIndxMap& trksToPreIdIndx, - edm::Event&, - const edm::EventSetup& ); +template void LowPtGsfElectronSeedProducer::loop(const edm::Handle >&, + edm::Handle& hcalClusters, + reco::ElectronSeedCollection& seeds, + reco::PreIdCollection& ecalPreIds, + reco::PreIdCollection& hcalPreIds, + TrackIndxMap& trksToPreIdIndx, + edm::Event&, + const edm::EventSetup&); ////////////////////////////////////////////////////////////////////////////////////////// // Template instantiation for reco::PFRecTracks -template -void LowPtGsfElectronSeedProducer::loop( const edm::Handle< std::vector >&, - edm::Handle& hcalClusters, - reco::ElectronSeedCollection& seeds, - reco::PreIdCollection& ecalPreIds, - reco::PreIdCollection& hcalPreIds, - TrackIndxMap& trksToPreIdIndx, - edm::Event&, - const edm::EventSetup& ); +template void LowPtGsfElectronSeedProducer::loop(const edm::Handle >&, + edm::Handle& hcalClusters, + reco::ElectronSeedCollection& seeds, + reco::PreIdCollection& ecalPreIds, + reco::PreIdCollection& hcalPreIds, + TrackIndxMap& trksToPreIdIndx, + edm::Event&, + const edm::EventSetup&); ////////////////////////////////////////////////////////////////////////////////////////// // Loops through both ECAL and HCAL clusters -void LowPtGsfElectronSeedProducer::propagateTrackToCalo( const reco::PFRecTrackRef& pfTrackRef, - const edm::Handle& ecalClusters, - const edm::Handle& hcalClusters, - std::vector& matchedEcalClusters, - std::vector& matchedHcalClusters, - reco::PreId& ecalPreId, - reco::PreId& hcalPreId ) -{ - propagateTrackToCalo( pfTrackRef, ecalClusters, matchedEcalClusters, ecalPreId, true ); - propagateTrackToCalo( pfTrackRef, hcalClusters, matchedHcalClusters, hcalPreId, false ); +void LowPtGsfElectronSeedProducer::propagateTrackToCalo(const reco::PFRecTrackRef& pfTrackRef, + const edm::Handle& ecalClusters, + const edm::Handle& hcalClusters, + std::vector& matchedEcalClusters, + std::vector& matchedHcalClusters, + reco::PreId& ecalPreId, + reco::PreId& hcalPreId) { + propagateTrackToCalo(pfTrackRef, ecalClusters, matchedEcalClusters, ecalPreId, true); + propagateTrackToCalo(pfTrackRef, hcalClusters, matchedHcalClusters, hcalPreId, false); } ////////////////////////////////////////////////////////////////////////////////////////// // Loops through ECAL or HCAL clusters (called twice) -void LowPtGsfElectronSeedProducer::propagateTrackToCalo( const reco::PFRecTrackRef& pfTrackRef, - const edm::Handle& clusters, - std::vector& matched, - reco::PreId& preId, - bool ecal ) -{ - +void LowPtGsfElectronSeedProducer::propagateTrackToCalo(const reco::PFRecTrackRef& pfTrackRef, + const edm::Handle& clusters, + std::vector& matched, + reco::PreId& preId, + bool ecal) { // Store info for PreId struct Info { reco::PFClusterRef cluRef = reco::PFClusterRef(); float dr2min = 1.e6; float deta = 1.e6; float dphi = 1.e6; - math::XYZPoint showerPos = math::XYZPoint(0.,0.,0.); + math::XYZPoint showerPos = math::XYZPoint(0., 0., 0.); } info; - + // Find closest "seed cluster" to KF track extrapolated to ECAL (or HCAL) reco::PFTrajectoryPoint point; - if ( ecal ) { point = pfTrackRef->extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax); } - else { point = pfTrackRef->extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::HCALEntrance); } - - if ( point.isValid() ) { + if (ecal) { + point = pfTrackRef->extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::ECALShowerMax); + } else { + point = pfTrackRef->extrapolatedPoint(reco::PFTrajectoryPoint::LayerType::HCALEntrance); + } + if (point.isValid()) { Info info; - for ( unsigned int iclu = 0; iclu < clusters.product()->size(); iclu++ ) { - - if ( std::find( matched.begin(), matched.end(), iclu ) == matched.end() ) { - - reco::PFClusterRef cluRef(clusters,iclu); - - // Determine dR squared - float dr2 = reco::deltaR2( cluRef->positionREP(), point.positionREP() ); - - if ( dr2 < info.dr2min ) { - info.dr2min = dr2; - info.cluRef = cluRef; - info.deta = cluRef->positionREP().eta() - point.positionREP().eta(); - info.dphi = - reco::deltaPhi( cluRef->positionREP().phi(), point.positionREP().phi() ) * - pfTrackRef->trackRef()->charge(); - info.showerPos = point.position(); - } - + for (unsigned int iclu = 0; iclu < clusters.product()->size(); iclu++) { + if (std::find(matched.begin(), matched.end(), iclu) == matched.end()) { + reco::PFClusterRef cluRef(clusters, iclu); + + // Determine dR squared + float dr2 = reco::deltaR2(cluRef->positionREP(), point.positionREP()); + + if (dr2 < info.dr2min) { + info.dr2min = dr2; + info.cluRef = cluRef; + info.deta = cluRef->positionREP().eta() - point.positionREP().eta(); + info.dphi = + reco::deltaPhi(cluRef->positionREP().phi(), point.positionREP().phi()) * pfTrackRef->trackRef()->charge(); + info.showerPos = point.position(); + } } } // Set PreId content if match found - if ( info.dr2min < 1.e5 ) { - float ep = info.cluRef->correctedEnergy() / std::sqrt( pfTrackRef->trackRef()->innerMomentum().mag2() ); - preId.setECALMatchingProperties( info.cluRef, - point.position(), // ECAL or HCAL surface - info.showerPos, // - info.deta, - info.dphi, - 0.f, // chieta - 0.f, // chiphi - pfTrackRef->trackRef()->normalizedChi2(), // chi2 - ep ); + if (info.dr2min < 1.e5) { + float ep = info.cluRef->correctedEnergy() / std::sqrt(pfTrackRef->trackRef()->innerMomentum().mag2()); + preId.setECALMatchingProperties(info.cluRef, + point.position(), // ECAL or HCAL surface + info.showerPos, // + info.deta, + info.dphi, + 0.f, // chieta + 0.f, // chiphi + pfTrackRef->trackRef()->normalizedChi2(), // chi2 + ep); } - } // clusters - + } // clusters } ////////////////////////////////////////////////////////////////////////////////////////// // Original implementation in GoodSeedProducer, loops over ECAL clusters only -void LowPtGsfElectronSeedProducer::propagateTrackToCalo( const reco::TrackRef& kfTrackRef, - const edm::Handle& ecalClusters, - const edm::Handle& hcalClusters, // not used - std::vector& matchedEcalClusters, - std::vector& matchedHcalClusters, // not used - reco::PreId& ecalPreId, - reco::PreId& hcalPreId /* not used */ ) -{ - +void LowPtGsfElectronSeedProducer::propagateTrackToCalo( + const reco::TrackRef& kfTrackRef, + const edm::Handle& ecalClusters, + const edm::Handle& hcalClusters, // not used + std::vector& matchedEcalClusters, + std::vector& matchedHcalClusters, // not used + reco::PreId& ecalPreId, + reco::PreId& hcalPreId /* not used */) { // Store info for PreId struct Info { reco::PFClusterRef cluRef = reco::PFClusterRef(); float dr2min = 1.e6; float deta = 1.e6; float dphi = 1.e6; - math::XYZPoint showerPos = math::XYZPoint(0.,0.,0.); + math::XYZPoint showerPos = math::XYZPoint(0., 0., 0.); } info; // Propagate 'electron' to ECAL surface - float energy = sqrt( mass_ + kfTrackRef->outerMomentum().Mag2() ); - XYZTLorentzVector mom = XYZTLorentzVector( kfTrackRef->outerMomentum().x(), - kfTrackRef->outerMomentum().y(), - kfTrackRef->outerMomentum().z(), - energy ); - XYZTLorentzVector pos = XYZTLorentzVector( kfTrackRef->outerPosition().x(), - kfTrackRef->outerPosition().y(), - kfTrackRef->outerPosition().z(), - 0. ); - math::XYZVector field(field_->inTesla(GlobalPoint(0,0,0))); - BaseParticlePropagator particle( RawParticle(mom,pos,kfTrackRef->charge()), 0, 0, field.z() ); + float energy = sqrt(mass_ + kfTrackRef->outerMomentum().Mag2()); + XYZTLorentzVector mom = XYZTLorentzVector( + kfTrackRef->outerMomentum().x(), kfTrackRef->outerMomentum().y(), kfTrackRef->outerMomentum().z(), energy); + XYZTLorentzVector pos = XYZTLorentzVector( + kfTrackRef->outerPosition().x(), kfTrackRef->outerPosition().y(), kfTrackRef->outerPosition().z(), 0.); + math::XYZVector field(field_->inTesla(GlobalPoint(0, 0, 0))); + BaseParticlePropagator particle(RawParticle(mom, pos, kfTrackRef->charge()), 0, 0, field.z()); particle.propagateToEcalEntrance(false); - if ( particle.getSuccess() == 0 ) { return; } - + if (particle.getSuccess() == 0) { + return; + } + // ECAL entry point for track - GlobalPoint ecal_pos(particle.particle().vertex().x(), - particle.particle().vertex().y(), - particle.particle().vertex().z()); + GlobalPoint ecal_pos( + particle.particle().vertex().x(), particle.particle().vertex().y(), particle.particle().vertex().z()); // Preshower limit - bool below_ps = pow(ecal_pos.z(),2.) > boundary_*ecal_pos.perp2(); - - // Iterate through ECAL clusters - for ( unsigned int iclu = 0; iclu < ecalClusters.product()->size(); iclu++ ) { - reco::PFClusterRef cluRef(ecalClusters,iclu); - - // Correct ecal_pos for shower depth - double shower_depth = reco::PFCluster::getDepthCorrection(cluRef->correctedEnergy(), - below_ps, - false); - GlobalPoint showerPos = ecal_pos + - GlobalVector(particle.particle().momentum().x(), - particle.particle().momentum().y(), - particle.particle().momentum().z()).unit() * shower_depth; + bool below_ps = pow(ecal_pos.z(), 2.) > boundary_ * ecal_pos.perp2(); + + // Iterate through ECAL clusters + for (unsigned int iclu = 0; iclu < ecalClusters.product()->size(); iclu++) { + reco::PFClusterRef cluRef(ecalClusters, iclu); + + // Correct ecal_pos for shower depth + double shower_depth = reco::PFCluster::getDepthCorrection(cluRef->correctedEnergy(), below_ps, false); + GlobalPoint showerPos = ecal_pos + GlobalVector(particle.particle().momentum().x(), + particle.particle().momentum().y(), + particle.particle().momentum().z()) + .unit() * + shower_depth; // Determine dR squared - float dr2 = reco::deltaR2( cluRef->positionREP(), showerPos ); + float dr2 = reco::deltaR2(cluRef->positionREP(), showerPos); // Find nearest ECAL cluster - if ( dr2 < info.dr2min ) { + if (dr2 < info.dr2min) { info.dr2min = dr2; info.cluRef = cluRef; - info.deta = std::abs( cluRef->positionREP().eta() - showerPos.eta() ); - info.dphi = - std::abs( reco::deltaPhi( cluRef->positionREP().phi(), showerPos.phi() )) * - kfTrackRef->charge(); + info.deta = std::abs(cluRef->positionREP().eta() - showerPos.eta()); + info.dphi = std::abs(reco::deltaPhi(cluRef->positionREP().phi(), showerPos.phi())) * kfTrackRef->charge(); info.showerPos = showerPos; } - } // Populate PreId object - math::XYZPoint point( ecal_pos.x(), - ecal_pos.y(), - ecal_pos.z() ); + math::XYZPoint point(ecal_pos.x(), ecal_pos.y(), ecal_pos.z()); // Set PreId content - ecalPreId.setECALMatchingProperties( info.cluRef, - point, - info.showerPos, - info.deta, - info.dphi, - 0.f, // chieta - 0.f, // chiphi - kfTrackRef->normalizedChi2(), // chi2 - info.cluRef->correctedEnergy() / std::sqrt( kfTrackRef->innerMomentum().mag2() ) ); // E/p - + ecalPreId.setECALMatchingProperties( + info.cluRef, + point, + info.showerPos, + info.deta, + info.dphi, + 0.f, // chieta + 0.f, // chiphi + kfTrackRef->normalizedChi2(), // chi2 + info.cluRef->correctedEnergy() / std::sqrt(kfTrackRef->innerMomentum().mag2())); // E/p } ////////////////////////////////////////////////////////////////////////////////////////// // Original implementation for "lightweight" GSF tracking -bool LowPtGsfElectronSeedProducer::lightGsfTracking( reco::PreId& preId, - const reco::TrackRef& trackRef, - const reco::ElectronSeed& seed, - const edm::EventSetup& setup ) -{ - +bool LowPtGsfElectronSeedProducer::lightGsfTracking(reco::PreId& preId, + const reco::TrackRef& trackRef, + const reco::ElectronSeed& seed, + const edm::EventSetup& setup) { Trajectory::ConstRecHitContainer hits; - for ( unsigned int ihit = 0; ihit < trackRef->recHitsSize(); ++ihit ) { - hits.push_back( trackRef->recHit(ihit)->cloneSH() ); + for (unsigned int ihit = 0; ihit < trackRef->recHitsSize(); ++ihit) { + hits.push_back(trackRef->recHit(ihit)->cloneSH()); } - - GlobalVector gv( trackRef->innerMomentum().x(), - trackRef->innerMomentum().y(), - trackRef->innerMomentum().z() ); - GlobalPoint gp( trackRef->innerPosition().x(), - trackRef->innerPosition().y(), - trackRef->innerPosition().z() ); - - GlobalTrajectoryParameters gtps( gp, - gv, - trackRef->charge(), - &*field_ ); - - TrajectoryStateOnSurface tsos( gtps, - trackRef->innerStateCovariance(), - *hits[0]->surface() ); + + GlobalVector gv(trackRef->innerMomentum().x(), trackRef->innerMomentum().y(), trackRef->innerMomentum().z()); + GlobalPoint gp(trackRef->innerPosition().x(), trackRef->innerPosition().y(), trackRef->innerPosition().z()); + + GlobalTrajectoryParameters gtps(gp, gv, trackRef->charge(), &*field_); + + TrajectoryStateOnSurface tsos(gtps, trackRef->innerStateCovariance(), *hits[0]->surface()); // Track fitted and smoothed under electron hypothesis - Trajectory traj1 = fitterPtr_->fitOne( seed, hits, tsos ); - if ( !traj1.isValid() ) { return false; } + Trajectory traj1 = fitterPtr_->fitOne(seed, hits, tsos); + if (!traj1.isValid()) { + return false; + } Trajectory traj2 = smootherPtr_->trajectory(traj1); - if ( !traj2.isValid() ) { return false; } + if (!traj2.isValid()) { + return false; + } // Set PreId content float chi2Ratio = trackRef->chi2() > 0. ? traj2.chiSquared() / trackRef->chi2() : -1.; float gsfReducedChi2 = chi2Ratio > -1. ? chi2Ratio * trackRef->normalizedChi2() : -1.; float ptOut = traj2.firstMeasurement().updatedState().globalMomentum().perp(); float ptIn = traj2.lastMeasurement().updatedState().globalMomentum().perp(); - float gsfDpt = ( ptIn > 0 ) ? fabs( ptOut - ptIn ) / ptIn : 0.; - preId.setTrackProperties(gsfReducedChi2,chi2Ratio,gsfDpt); + float gsfDpt = (ptIn > 0) ? fabs(ptOut - ptIn) / ptIn : 0.; + preId.setTrackProperties(gsfReducedChi2, chi2Ratio, gsfDpt); return true; - } ////////////////////////////////////////////////////////////////////////////////////////// // Decision based on OR of outputs from list of models -bool LowPtGsfElectronSeedProducer::decision( const reco::PFRecTrackRef& pfTrackRef, - reco::PreId& ecalPreId, - reco::PreId& hcalPreId, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ) -{ +bool LowPtGsfElectronSeedProducer::decision(const reco::PFRecTrackRef& pfTrackRef, + reco::PreId& ecalPreId, + reco::PreId& hcalPreId, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools) { bool result = false; - for ( auto& name: globalCache()->modelNames() ) { - result |= globalCache()->eval(name, - ecalPreId, - hcalPreId, - rho, - spot, - ecalTools); + for (auto& name : globalCache()->modelNames()) { + result |= globalCache()->eval(name, ecalPreId, hcalPreId, rho, spot, ecalTools); } - return passThrough_ || ( pfTrackRef->trackRef()->pt() > maxPtThreshold_ ) || result; + return passThrough_ || (pfTrackRef->trackRef()->pt() > maxPtThreshold_) || result; } ////////////////////////////////////////////////////////////////////////////////////////// -// -bool LowPtGsfElectronSeedProducer::decision( const reco::TrackRef& kfTrackRef, - reco::PreId& ecalPreId, - reco::PreId& hcalPreId, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ) -{ +// +bool LowPtGsfElectronSeedProducer::decision(const reco::TrackRef& kfTrackRef, + reco::PreId& ecalPreId, + reco::PreId& hcalPreId, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools) { // No implementation currently return passThrough_; } - -template -void LowPtGsfElectronSeedProducer::fillPreIdRefValueMap( edm::Handle tracksHandle, - const TrackIndxMap& trksToPreIdIndx, - const edm::OrphanHandle& preIdHandle, - edm::ValueMap::Filler & filler) -{ + +template +void LowPtGsfElectronSeedProducer::fillPreIdRefValueMap(edm::Handle tracksHandle, + const TrackIndxMap& trksToPreIdIndx, + const edm::OrphanHandle& preIdHandle, + edm::ValueMap::Filler& filler) { std::vector values; - unsigned ntracks=tracksHandle->size(); - for(unsigned itrack=0;itrack trackRef(tracksHandle,itrack); + unsigned ntracks = tracksHandle->size(); + for (unsigned itrack = 0; itrack < ntracks; ++itrack) { + edm::Ref trackRef(tracksHandle, itrack); auto preIdRefIt = trksToPreIdIndx.find(trackRef.index()); - if(preIdRefIt==trksToPreIdIndx.end()){ + if (preIdRefIt == trksToPreIdIndx.end()) { values.push_back(reco::PreIdRef()); - }else{ - edm::Ref preIdRef(preIdHandle,preIdRefIt->second); + } else { + edm::Ref preIdRef(preIdHandle, preIdRefIt->second); values.push_back(preIdRef); } } - filler.insert(tracksHandle,values.begin(),values.end()); + filler.insert(tracksHandle, values.begin(), values.end()); } ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSeedProducer::fillDescriptions( edm::ConfigurationDescriptions& descriptions ) -{ +void LowPtGsfElectronSeedProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("tracks",edm::InputTag("generalTracks")); - desc.add("pfTracks",edm::InputTag("lowPtGsfElePfTracks")); - desc.add("ecalClusters",edm::InputTag("particleFlowClusterECAL")); - desc.add("hcalClusters",edm::InputTag("particleFlowClusterHCAL")); - desc.add("EBRecHits",edm::InputTag("ecalRecHit","EcalRecHitsEB")); - desc.add("EERecHits",edm::InputTag("ecalRecHit","EcalRecHitsEE")); - desc.add("rho",edm::InputTag("fixedGridRhoFastjetAllTmp")); - desc.add("BeamSpot",edm::InputTag("offlineBeamSpot")); - desc.add("Fitter","GsfTrajectoryFitter_forPreId"); - desc.add("Smoother","GsfTrajectorySmoother_forPreId"); - desc.add("TTRHBuilder","WithAngleAndTemplate"); - desc.add< std::vector >("ModelNames",std::vector()); - desc.add< std::vector >("ModelWeights",std::vector()); - desc.add< std::vector >("ModelThresholds",std::vector()); - desc.add("PassThrough",false); - desc.add("UsePfTracks",true); - desc.add("MinPtThreshold",1.0); - desc.add("MaxPtThreshold",15.); - descriptions.add("lowPtGsfElectronSeeds",desc); + desc.add("tracks", edm::InputTag("generalTracks")); + desc.add("pfTracks", edm::InputTag("lowPtGsfElePfTracks")); + desc.add("ecalClusters", edm::InputTag("particleFlowClusterECAL")); + desc.add("hcalClusters", edm::InputTag("particleFlowClusterHCAL")); + desc.add("EBRecHits", edm::InputTag("ecalRecHit", "EcalRecHitsEB")); + desc.add("EERecHits", edm::InputTag("ecalRecHit", "EcalRecHitsEE")); + desc.add("rho", edm::InputTag("fixedGridRhoFastjetAllTmp")); + desc.add("BeamSpot", edm::InputTag("offlineBeamSpot")); + desc.add("Fitter", "GsfTrajectoryFitter_forPreId"); + desc.add("Smoother", "GsfTrajectorySmoother_forPreId"); + desc.add("TTRHBuilder", "WithAngleAndTemplate"); + desc.add >("ModelNames", std::vector()); + desc.add >("ModelWeights", std::vector()); + desc.add >("ModelThresholds", std::vector()); + desc.add("PassThrough", false); + desc.add("UsePfTracks", true); + desc.add("MinPtThreshold", 1.0); + desc.add("MaxPtThreshold", 15.); + descriptions.add("lowPtGsfElectronSeeds", desc); } ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.h index a0c05612b3328..ad93162cddb13 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedProducer.h @@ -24,99 +24,91 @@ #include "TrackingTools/PatternTools/interface/TrajectorySmoother.h" #include "TrackingTools/TrackFitters/interface/TrajectoryFitter.h" -class LowPtGsfElectronSeedProducer final : public edm::stream::EDProducer< edm::GlobalCache > -{ - - public: - using TrackIndxMap = std::unordered_map; - explicit LowPtGsfElectronSeedProducer( const edm::ParameterSet&, - const lowptgsfeleseed::HeavyObjectCache* ); +class LowPtGsfElectronSeedProducer final + : public edm::stream::EDProducer > { +public: + using TrackIndxMap = std::unordered_map; + explicit LowPtGsfElectronSeedProducer(const edm::ParameterSet&, const lowptgsfeleseed::HeavyObjectCache*); ~LowPtGsfElectronSeedProducer() override; - - static std::unique_ptr - initializeGlobalCache( const edm::ParameterSet& conf ) { + + static std::unique_ptr initializeGlobalCache(const edm::ParameterSet& conf) { return std::make_unique(lowptgsfeleseed::HeavyObjectCache(conf)); } - - static void globalEndJob( lowptgsfeleseed::HeavyObjectCache const* ) {} - - void beginLuminosityBlock( edm::LuminosityBlock const&, - edm::EventSetup const& ) override; - - void produce( edm::Event&, const edm::EventSetup& ) override; - - static void fillDescriptions( edm::ConfigurationDescriptions& ); - - private: // member functions - - template void loop( const edm::Handle< std::vector >& handle, - edm::Handle& hcalClusters, - reco::ElectronSeedCollection& seeds, - reco::PreIdCollection& ecalPreIds, - reco::PreIdCollection& hcalPreIds, - TrackIndxMap& trksToPreIdIndx, - edm::Event&, - const edm::EventSetup& ); + + static void globalEndJob(lowptgsfeleseed::HeavyObjectCache const*) {} + + void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; + + void produce(edm::Event&, const edm::EventSetup&) override; + + static void fillDescriptions(edm::ConfigurationDescriptions&); + +private: // member functions + template + void loop(const edm::Handle >& handle, + edm::Handle& hcalClusters, + reco::ElectronSeedCollection& seeds, + reco::PreIdCollection& ecalPreIds, + reco::PreIdCollection& hcalPreIds, + TrackIndxMap& trksToPreIdIndx, + edm::Event&, + const edm::EventSetup&); // Overloaded methods to retrieve reco::TrackRef - reco::TrackRef getBaseRef( edm::Handle< std::vector > handle, int idx ) const; - reco::TrackRef getBaseRef( edm::Handle< std::vector > handle, int idx ) const; + reco::TrackRef getBaseRef(edm::Handle > handle, int idx) const; + reco::TrackRef getBaseRef(edm::Handle > handle, int idx) const; // Overloaded methods to populate PreIds (using PF or KF tracks) - void propagateTrackToCalo( const reco::PFRecTrackRef& pfTrackRef, - const edm::Handle& ecalClusters, - const edm::Handle& hcalClusters, - std::vector& matchedEcalClusters, - std::vector& matchedHcalClusters, - reco::PreId& ecalPreId, - reco::PreId& hcalPreId ); - - void propagateTrackToCalo( const reco::PFRecTrackRef& pfTrackRef, - const edm::Handle& clusters, - std::vector& matchedClusters, - reco::PreId& preId, - bool ecal ); - - void propagateTrackToCalo( const reco::TrackRef& pfTrack, - const edm::Handle& ecalClusters, - const edm::Handle& hcalClusters, - std::vector& matchedEcalClusters, - std::vector& matchedHcalClusters, - reco::PreId& ecalPreId, - reco::PreId& hcalPreId ); - template - void fillPreIdRefValueMap( edm::Handle tracksHandle, - const TrackIndxMap& trksToPreIdIndx, - const edm::OrphanHandle& preIdHandle, - edm::ValueMap::Filler & filler); + void propagateTrackToCalo(const reco::PFRecTrackRef& pfTrackRef, + const edm::Handle& ecalClusters, + const edm::Handle& hcalClusters, + std::vector& matchedEcalClusters, + std::vector& matchedHcalClusters, + reco::PreId& ecalPreId, + reco::PreId& hcalPreId); + + void propagateTrackToCalo(const reco::PFRecTrackRef& pfTrackRef, + const edm::Handle& clusters, + std::vector& matchedClusters, + reco::PreId& preId, + bool ecal); + + void propagateTrackToCalo(const reco::TrackRef& pfTrack, + const edm::Handle& ecalClusters, + const edm::Handle& hcalClusters, + std::vector& matchedEcalClusters, + std::vector& matchedHcalClusters, + reco::PreId& ecalPreId, + reco::PreId& hcalPreId); + template + void fillPreIdRefValueMap(edm::Handle tracksHandle, + const TrackIndxMap& trksToPreIdIndx, + const edm::OrphanHandle& preIdHandle, + edm::ValueMap::Filler& filler); // Overloaded methods to evaluate BDTs (using PF or KF tracks) - bool decision( const reco::PFRecTrackRef& pfTrackRef, - reco::PreId& ecal, - reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ); - - bool decision( const reco::TrackRef& kfTrackRef, - reco::PreId& ecal, - reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ); + bool decision(const reco::PFRecTrackRef& pfTrackRef, + reco::PreId& ecal, + reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools); + + bool decision(const reco::TrackRef& kfTrackRef, + reco::PreId& ecal, + reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools); // Perform lightweight GSF tracking - bool lightGsfTracking( reco::PreId&, - const reco::TrackRef&, - const reco::ElectronSeed&, - const edm::EventSetup& ); + bool lightGsfTracking(reco::PreId&, const reco::TrackRef&, const reco::ElectronSeed&, const edm::EventSetup&); - private: // member data - +private: // member data edm::ESHandle field_; std::unique_ptr fitterPtr_; std::unique_ptr smootherPtr_; @@ -137,10 +129,9 @@ class LowPtGsfElectronSeedProducer final : public edm::stream::EDProducer< edm:: const double maxPtThreshold_; // pow( sinh(1.65), 2. ) - static constexpr double boundary_ = 2.50746495928*2.50746495928; + static constexpr double boundary_ = 2.50746495928 * 2.50746495928; // pow( ele_mass, 2. ) - static constexpr double mass_ = 0.000511*0.000511; - + static constexpr double mass_ = 0.000511 * 0.000511; }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedProducer_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.cc index a38504e3e7e97..996ca807ba155 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.cc @@ -12,12 +12,13 @@ //////////////////////////////////////////////////////////////////////////////// // -LowPtGsfElectronSeedValueMapsProducer::LowPtGsfElectronSeedValueMapsProducer( const edm::ParameterSet& conf ) : - gsfTracks_(consumes(conf.getParameter("gsfTracks"))), - preIdsValueMap_(consumes< edm::ValueMap >(conf.getParameter("preIdsValueMap"))), - names_(conf.getParameter< std::vector >("ModelNames")) -{ - for ( const auto& name : names_ ) { produces< edm::ValueMap >(name); } +LowPtGsfElectronSeedValueMapsProducer::LowPtGsfElectronSeedValueMapsProducer(const edm::ParameterSet& conf) + : gsfTracks_(consumes(conf.getParameter("gsfTracks"))), + preIdsValueMap_(consumes >(conf.getParameter("preIdsValueMap"))), + names_(conf.getParameter >("ModelNames")) { + for (const auto& name : names_) { + produces >(name); + } } //////////////////////////////////////////////////////////////////////////////// @@ -26,60 +27,59 @@ LowPtGsfElectronSeedValueMapsProducer::~LowPtGsfElectronSeedValueMapsProducer() //////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSeedValueMapsProducer::produce( edm::Event& event, const edm::EventSetup& setup ) { - +void LowPtGsfElectronSeedValueMapsProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // Retrieve GsfTracks from Event edm::Handle gsfTracks; - event.getByToken(gsfTracks_,gsfTracks); - if ( !gsfTracks.isValid() ) { edm::LogError("Problem with gsfTracks handle"); } + event.getByToken(gsfTracks_, gsfTracks); + if (!gsfTracks.isValid()) { + edm::LogError("Problem with gsfTracks handle"); + } // Retrieve PreIds from Event - edm::Handle< edm::ValueMap > preIdsValueMap; - event.getByToken(preIdsValueMap_,preIdsValueMap); - if ( !preIdsValueMap.isValid() ) { edm::LogError("Problem with preIdsValueMap handle"); } - + edm::Handle > preIdsValueMap; + event.getByToken(preIdsValueMap_, preIdsValueMap); + if (!preIdsValueMap.isValid()) { + edm::LogError("Problem with preIdsValueMap handle"); + } + // Iterate through GsfTracks, extract BDT output, and store result in ValueMap for each model - std::vector< std::vector > output; - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - output.push_back( std::vector(gsfTracks->size(),-999.) ); + std::vector > output; + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + output.push_back(std::vector(gsfTracks->size(), -999.)); } - for ( unsigned int igsf = 0; igsf < gsfTracks->size(); igsf++ ) { - reco::GsfTrackRef gsf(gsfTracks,igsf); - if ( gsf.isNonnull() && - gsf->extra().isNonnull() && - gsf->extra()->seedRef().isNonnull() ) { + for (unsigned int igsf = 0; igsf < gsfTracks->size(); igsf++) { + reco::GsfTrackRef gsf(gsfTracks, igsf); + if (gsf.isNonnull() && gsf->extra().isNonnull() && gsf->extra()->seedRef().isNonnull()) { reco::ElectronSeedRef seed = gsf->extra()->seedRef().castTo(); - if ( seed.isNonnull() && seed->ctfTrack().isNonnull() ) { - const reco::PreIdRef preid = (*preIdsValueMap)[seed->ctfTrack()]; - if ( preid.isNonnull() ) { - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - output[iname][igsf] = preid->mva(iname); - } - } + if (seed.isNonnull() && seed->ctfTrack().isNonnull()) { + const reco::PreIdRef preid = (*preIdsValueMap)[seed->ctfTrack()]; + if (preid.isNonnull()) { + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + output[iname][igsf] = preid->mva(iname); + } + } } } } - + // Create and put ValueMap in Event - for ( unsigned int iname = 0; iname < names_.size(); ++iname ) { - auto ptr = std::make_unique< edm::ValueMap >( edm::ValueMap() ); + for (unsigned int iname = 0; iname < names_.size(); ++iname) { + auto ptr = std::make_unique >(edm::ValueMap()); edm::ValueMap::Filler filler(*ptr); filler.insert(gsfTracks, output[iname].begin(), output[iname].end()); filler.fill(); - event.put(std::move(ptr),names_[iname]); + event.put(std::move(ptr), names_[iname]); } - } ////////////////////////////////////////////////////////////////////////////////////////// // -void LowPtGsfElectronSeedValueMapsProducer::fillDescriptions( edm::ConfigurationDescriptions& descriptions ) -{ +void LowPtGsfElectronSeedValueMapsProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - desc.add("gsfTracks",edm::InputTag("lowPtGsfEleGsfTracks")); - desc.add("preIdsValueMap",edm::InputTag("lowPtGsfElectronSeeds")); - desc.add< std::vector >("ModelNames",std::vector()); - descriptions.add("defaultLowPtGsfElectronSeedValueMaps",desc); + desc.add("gsfTracks", edm::InputTag("lowPtGsfEleGsfTracks")); + desc.add("preIdsValueMap", edm::InputTag("lowPtGsfElectronSeeds")); + desc.add >("ModelNames", std::vector()); + descriptions.add("defaultLowPtGsfElectronSeedValueMaps", desc); } ////////////////////////////////////////////////////////////////////////////////////////// diff --git a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.h index 28f70374e5510..66bb92ed1e22b 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/LowPtGsfElectronSeedValueMapsProducer.h @@ -11,23 +11,19 @@ #include class LowPtGsfElectronSeedValueMapsProducer : public edm::stream::EDProducer<> { - - public: - - explicit LowPtGsfElectronSeedValueMapsProducer( const edm::ParameterSet& ); - +public: + explicit LowPtGsfElectronSeedValueMapsProducer(const edm::ParameterSet&); + ~LowPtGsfElectronSeedValueMapsProducer() override; - - void produce( edm::Event&, const edm::EventSetup& ) override; - - static void fillDescriptions( edm::ConfigurationDescriptions& ); - private: - + void produce(edm::Event&, const edm::EventSetup&) override; + + static void fillDescriptions(edm::ConfigurationDescriptions&); + +private: const edm::EDGetTokenT gsfTracks_; - const edm::EDGetTokenT< edm::ValueMap > preIdsValueMap_; + const edm::EDGetTokenT > preIdsValueMap_; const std::vector names_; - }; -#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedValueMapsProducer_h +#endif // RecoEgamma_EgammaElectronProducers_LowPtGsfElectronSeedValueMapsProducer_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.cc b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.cc index be2d969e053ef..a0779b2530020 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.cc @@ -2,7 +2,7 @@ // // Package: SiStripElectronAssociator // Class: SiStripElectronAssociator -// +// /**\class SiStripElectronAssociator SiStripElectronAssociator.cc RecoEgamma/SiStripElectronAssociator/src/SiStripElectronAssociator.cc Description: @@ -16,7 +16,6 @@ // // - #include #include @@ -47,158 +46,156 @@ // // constructors and destructor // -SiStripElectronAssociator::SiStripElectronAssociator(const edm::ParameterSet& iConfig) -{ - //register your products +SiStripElectronAssociator::SiStripElectronAssociator(const edm::ParameterSet& iConfig) { + //register your products electronsLabel_ = iConfig.getParameter("electronsLabel"); produces(electronsLabel_.label()); - //now do what ever other initialization is needed - siStripElectronCollection_ = consumes(iConfig.getParameter("siStripElectronCollection")); + //now do what ever other initialization is needed + siStripElectronCollection_ = + consumes(iConfig.getParameter("siStripElectronCollection")); trackCollection_ = consumes(iConfig.getParameter("trackCollection")); } +SiStripElectronAssociator::~SiStripElectronAssociator() {} -SiStripElectronAssociator::~SiStripElectronAssociator() -{} +void SiStripElectronAssociator::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + // position tolerance for equality of 2 hits set to 10 microns + static const double positionTol = 1e-3; + + edm::Handle siStripElectrons; + iEvent.getByToken(siStripElectronCollection_, siStripElectrons); + + edm::Handle tracks; + iEvent.getByToken(trackCollection_, tracks); + + std::map alreadySeen; + for (reco::SiStripElectronCollection::const_iterator strippyIter = siStripElectrons->begin(); + strippyIter != siStripElectrons->end(); + ++strippyIter) { + alreadySeen[&(*strippyIter)] = false; + } + + // Output the high-level Electrons + auto output = std::make_unique(); + + LogDebug("SiStripElectronAssociator") << " About to loop over tracks " << std::endl; + LogDebug("SiStripElectronAssociator") << " Number of tracks in Associator " << tracks.product()->size(); + LogDebug("SiStripElectronAssociator") << " Number of SiStripElectron Candidates " << siStripElectrons->size(); + + // The reco::Track's hits are a (improper?) subset of the reco::SiStripElectron's + // countSiElFit counts electron candidates that return w/ a good track fit + int countSiElFit = 0; + for (unsigned int i = 0; i < tracks.product()->size(); i++) { + const reco::Track* trackPtr = &(*reco::TrackRef(tracks, i)); + + // If the reco::Track and the reco::SiStripElectron share even + // one hit in common, they belong to each other. (Disjoint sets + // of hits are assigned to electrons.) So let's look at one hit. + + // But first, make sure the track's hit list is not empty. + if (trackPtr->recHits().empty()) { + continue; + } + + // Detector id is not enough to completely specify a hit + uint32_t id = (*trackPtr->recHits().begin())->geographicalId().rawId(); + LocalPoint pos = (*trackPtr->recHits().begin())->localPosition(); + + LogDebug("SiStripElectronAssociator") << " New Track Candidate " << i << " DetId " << id << " pos " << pos << "\n"; + + // Find the electron with that hit! + bool foundElectron = false; + for (reco::SiStripElectronCollection::const_iterator strippyIter = siStripElectrons->begin(); + strippyIter != siStripElectrons->end(); + ++strippyIter) { + if (!alreadySeen[&(*strippyIter)]) { + bool hitInCommon = false; + LogDebug("SiStripElectronAssociator") << " Looping over Mono hits " + << "\n"; + + for (std::vector::const_iterator hitIter = strippyIter->rphiRecHits().begin(); + hitIter != strippyIter->rphiRecHits().end(); + ++hitIter) { + LogDebug("SiStripElectronAssociator") + << " SiStripCand " + << " DetId " << hitIter->geographicalId().rawId() << " localPos " << hitIter->localPosition() + << " deltasPos " << (hitIter->localPosition() - pos).mag(); + + if (hitIter->geographicalId().rawId() == id && (hitIter->localPosition() - pos).mag() < positionTol) { + hitInCommon = true; + LogDebug("SiStripElectronAssociator") << " hitInCommon True " + << "\n"; + break; + } else { + LogDebug("SiStripElectronAssociator") << " hitInCommon False " + << "\n"; + } + } // end loop over rphi hits + if (!hitInCommon) { + LogDebug("SiStripElectronAssociator") << " Looping over Stereo hits " + << "\n"; -void -SiStripElectronAssociator::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ + for (std::vector::const_iterator hitIter = strippyIter->stereoRecHits().begin(); + hitIter != strippyIter->stereoRecHits().end(); + ++hitIter) { + LogDebug("SiStripElectronAssociator") + << " SiStripCand " + << " DetId " << hitIter->geographicalId().rawId() << " localPos " << hitIter->localPosition() + << " deltasPos " << (hitIter->localPosition() - pos).mag(); - // position tolerance for equality of 2 hits set to 10 microns - static const double positionTol = 1e-3 ; - - edm::Handle siStripElectrons; - iEvent.getByToken(siStripElectronCollection_, siStripElectrons); - - edm::Handle tracks; - iEvent.getByToken(trackCollection_, tracks); - - std::map alreadySeen; - for (reco::SiStripElectronCollection::const_iterator strippyIter = siStripElectrons->begin(); strippyIter != siStripElectrons->end(); ++strippyIter) { - alreadySeen[&(*strippyIter)] = false; - } - - // Output the high-level Electrons - auto output = std::make_unique(); - - LogDebug("SiStripElectronAssociator") << " About to loop over tracks " << std::endl ; - LogDebug("SiStripElectronAssociator") << " Number of tracks in Associator " << tracks.product()->size() ; - LogDebug("SiStripElectronAssociator") << " Number of SiStripElectron Candidates " << siStripElectrons->size(); - - // The reco::Track's hits are a (improper?) subset of the reco::SiStripElectron's - // countSiElFit counts electron candidates that return w/ a good track fit - int countSiElFit = 0 ; - for (unsigned int i = 0; i < tracks.product()->size(); i++) { - const reco::Track* trackPtr = &(*reco::TrackRef(tracks, i)); - - // If the reco::Track and the reco::SiStripElectron share even - // one hit in common, they belong to each other. (Disjoint sets - // of hits are assigned to electrons.) So let's look at one hit. - - // But first, make sure the track's hit list is not empty. - if (trackPtr->recHits().empty()) { continue; } - - // Detector id is not enough to completely specify a hit - uint32_t id = (*trackPtr->recHits().begin())->geographicalId().rawId(); - LocalPoint pos = (*trackPtr->recHits().begin())->localPosition(); - - LogDebug("SiStripElectronAssociator") << " New Track Candidate " << i - << " DetId " << id - << " pos " << pos << "\n"; - - // Find the electron with that hit! - bool foundElectron = false; - for (reco::SiStripElectronCollection::const_iterator strippyIter = siStripElectrons->begin(); strippyIter != siStripElectrons->end(); ++strippyIter) { - if (!alreadySeen[&(*strippyIter)]) { - - bool hitInCommon = false; - LogDebug("SiStripElectronAssociator") << " Looping over Mono hits " << "\n" ; - - for (std::vector::const_iterator hitIter = strippyIter->rphiRecHits().begin(); hitIter != strippyIter->rphiRecHits().end(); ++hitIter) { - - LogDebug("SiStripElectronAssociator") << " SiStripCand " - << " DetId " << hitIter->geographicalId().rawId() - << " localPos " << hitIter->localPosition() - << " deltasPos " << (hitIter->localPosition() - pos).mag() ; - - if (hitIter->geographicalId().rawId() == id && - (hitIter->localPosition() - pos).mag() < positionTol ) { + if (hitIter->geographicalId().rawId() == id && (hitIter->localPosition() - pos).mag() < positionTol) { hitInCommon = true; - LogDebug("SiStripElectronAssociator") << " hitInCommon True " << "\n" ; + LogDebug("SiStripElectronAssociator") << " hitInCommon True " + << "\n"; break; } else { - LogDebug("SiStripElectronAssociator") << " hitInCommon False " << "\n" ; + LogDebug("SiStripElectronAssociator") << " hitInCommon False " + << "\n"; } - } // end loop over rphi hits - - if(!hitInCommon) { - LogDebug("SiStripElectronAssociator") << " Looping over Stereo hits " << "\n" ; - - for (std::vector::const_iterator hitIter = strippyIter->stereoRecHits().begin(); hitIter != strippyIter->stereoRecHits().end(); ++hitIter) { - - LogDebug("SiStripElectronAssociator") << " SiStripCand " - << " DetId " << hitIter->geographicalId().rawId() - << " localPos " << hitIter->localPosition() - << " deltasPos " << (hitIter->localPosition() - pos).mag() ; - - if (hitIter->geographicalId().rawId() == id && - (hitIter->localPosition() - pos).mag() < positionTol) { - hitInCommon = true; - LogDebug("SiStripElectronAssociator") << " hitInCommon True " << "\n" ; - break; - } else { - LogDebug("SiStripElectronAssociator") << " hitInCommon False " << "\n" ; - } - - } // end loop over stereo hits - } // end of hitInCommon check for loop over stereo hits - - if (hitInCommon) { - LogDebug("SiStripElectronAssociator") << " Hit in Common Found \n" ; - ++countSiElFit ; - foundElectron = true; - alreadySeen[&(*strippyIter)] = true; - - reco::Electron electron((trackPtr->charge() > 0 ? 1 : -1), - math::XYZTLorentzVector(trackPtr->px(), - trackPtr->py(), - trackPtr->pz(), - trackPtr->p()), - math::XYZPoint(trackPtr->vx(), - trackPtr->vy(), - trackPtr->vz())); - electron.setSuperCluster(strippyIter->superCluster()); - electron.setTrack(reco::TrackRef(tracks, i)); - - output->push_back(electron); - break ; // no need to check other SiStripElectrons if this one is good - - } else { - LogDebug("SiStripElectronAssociator") << "Hit in Common NOT found \n" ; - } - // endif this electron belongs to this track - - - } // endif we haven't seen this electron before - LogDebug("SiStripElectronAssociator") << "Done with this electron " << "\n\n\n"; - } // end loop over electrons - - LogDebug("SiStripElectronAssociator") << "Testing if foundElectron " << foundElectron << std::endl; - - if (!foundElectron) { - throw cms::Exception("Configuration") - << " Inconsistent track collection!"; - } - - LogDebug("SiStripElectronAssociator") << "At end of track loop \n" << std::endl; - - } // end loop over tracks - - - LogDebug("SiStripElectronAssociator") << " Number of SiStripElectrons returned with a good fit " - << countSiElFit << "\n"<< std::endl ; - iEvent.put(std::move(output), electronsLabel_.label()); + + } // end loop over stereo hits + } // end of hitInCommon check for loop over stereo hits + + if (hitInCommon) { + LogDebug("SiStripElectronAssociator") << " Hit in Common Found \n"; + ++countSiElFit; + foundElectron = true; + alreadySeen[&(*strippyIter)] = true; + + reco::Electron electron( + (trackPtr->charge() > 0 ? 1 : -1), + math::XYZTLorentzVector(trackPtr->px(), trackPtr->py(), trackPtr->pz(), trackPtr->p()), + math::XYZPoint(trackPtr->vx(), trackPtr->vy(), trackPtr->vz())); + electron.setSuperCluster(strippyIter->superCluster()); + electron.setTrack(reco::TrackRef(tracks, i)); + + output->push_back(electron); + break; // no need to check other SiStripElectrons if this one is good + + } else { + LogDebug("SiStripElectronAssociator") << "Hit in Common NOT found \n"; + } + // endif this electron belongs to this track + + } // endif we haven't seen this electron before + LogDebug("SiStripElectronAssociator") << "Done with this electron " + << "\n\n\n"; + } // end loop over electrons + + LogDebug("SiStripElectronAssociator") << "Testing if foundElectron " << foundElectron << std::endl; + + if (!foundElectron) { + throw cms::Exception("Configuration") << " Inconsistent track collection!"; + } + + LogDebug("SiStripElectronAssociator") << "At end of track loop \n" << std::endl; + + } // end loop over tracks + + LogDebug("SiStripElectronAssociator") << " Number of SiStripElectrons returned with a good fit " << countSiElFit + << "\n" + << std::endl; + iEvent.put(std::move(output), electronsLabel_.label()); } diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.h b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.h index 7828e8fb770e4..b221e844bff74 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronAssociator.h @@ -4,7 +4,7 @@ // // Package: EgammaElectronProducers // Class : SiStripElectronAssociator -// +// /**\class SiStripElectronAssociator SiStripElectronAssociator.h RecoEgamma/EgammaElectronProducers/interface/SiStripElectronAssociator.h Description: @@ -40,18 +40,18 @@ // class SiStripElectronAssociator : public edm::stream::EDProducer<> { - public: +public: explicit SiStripElectronAssociator(const edm::ParameterSet&); ~SiStripElectronAssociator() override; - - + void produce(edm::Event&, const edm::EventSetup&) override; - private: + +private: // ----------member data --------------------------- edm::EDGetTokenT siStripElectronCollection_; edm::EDGetTokenT trackCollection_; - + edm::InputTag electronsLabel_; }; -#endif // EgammaElectronProducers_SiStripElectronAssociator_h +#endif // EgammaElectronProducers_SiStripElectronAssociator_h diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.cc index 158af6e5a7f39..0c7d86c8d0cdd 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.cc @@ -2,11 +2,11 @@ // // Package: EgammaElectronProducers // Class : SiStripElectronProducer -// +// // Implementation: // // -// Original Author: +// Original Author: // Created: Fri May 26 16:11:30 EDT 2006 // @@ -30,7 +30,7 @@ #include "DataFormats/TrackerRecHit2D/interface/SiStripMatchedRecHit2DCollection.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" #include "MagneticField/Engine/interface/MagneticField.h" -#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" +#include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" // // constants, enums and typedefs @@ -43,55 +43,48 @@ // // constructors and destructor // -SiStripElectronProducer::SiStripElectronProducer(const edm::ParameterSet& iConfig) -{ - // register your products - siStripElectronsLabel_ = iConfig.getParameter("siStripElectronsLabel"); - trackCandidatesLabel_ = iConfig.getParameter("trackCandidatesLabel"); - produces(siStripElectronsLabel_); - produces(trackCandidatesLabel_); - - // get parameters - siHitProducer_ = iConfig.getParameter("siHitProducer"); - siRphiHitCollection_ = iConfig.getParameter("siRphiHitCollection"); - siStereoHitCollection_ = iConfig.getParameter("siStereoHitCollection"); - siMatchedHitCollection_ = iConfig.getParameter("siMatchedHitCollection"); - - superClusterProducer_ = iConfig.getParameter("superClusterProducer"); - superClusterCollection_ = iConfig.getParameter("superClusterCollection"); - - rphi_sistrips2dtag_ = - consumes(edm::InputTag(siHitProducer_,siRphiHitCollection_)); - stereo_sistrips2dtag_ = - consumes(edm::InputTag(siHitProducer_,siStereoHitCollection_)); - matched_sistrips2dtag_ = - consumes(edm::InputTag(siHitProducer_,siMatchedHitCollection_)); - superClustertag_ = - consumes(edm::InputTag(superClusterProducer_,superClusterCollection_)); - - algo_p = new SiStripElectronAlgo( - iConfig.getParameter("maxHitsOnDetId"), - iConfig.getParameter("originUncertainty"), - iConfig.getParameter("phiBandWidth"), // this is in radians - iConfig.getParameter("maxNormResid"), - iConfig.getParameter("minHits"), - iConfig.getParameter("maxReducedChi2")); - - LogDebug("") << " Welcome to SiStripElectronProducer " ; - +SiStripElectronProducer::SiStripElectronProducer(const edm::ParameterSet& iConfig) { + // register your products + siStripElectronsLabel_ = iConfig.getParameter("siStripElectronsLabel"); + trackCandidatesLabel_ = iConfig.getParameter("trackCandidatesLabel"); + produces(siStripElectronsLabel_); + produces(trackCandidatesLabel_); + + // get parameters + siHitProducer_ = iConfig.getParameter("siHitProducer"); + siRphiHitCollection_ = iConfig.getParameter("siRphiHitCollection"); + siStereoHitCollection_ = iConfig.getParameter("siStereoHitCollection"); + siMatchedHitCollection_ = iConfig.getParameter("siMatchedHitCollection"); + + superClusterProducer_ = iConfig.getParameter("superClusterProducer"); + superClusterCollection_ = iConfig.getParameter("superClusterCollection"); + + rphi_sistrips2dtag_ = consumes(edm::InputTag(siHitProducer_, siRphiHitCollection_)); + stereo_sistrips2dtag_ = consumes(edm::InputTag(siHitProducer_, siStereoHitCollection_)); + matched_sistrips2dtag_ = + consumes(edm::InputTag(siHitProducer_, siMatchedHitCollection_)); + superClustertag_ = + consumes(edm::InputTag(superClusterProducer_, superClusterCollection_)); + + algo_p = new SiStripElectronAlgo(iConfig.getParameter("maxHitsOnDetId"), + iConfig.getParameter("originUncertainty"), + iConfig.getParameter("phiBandWidth"), // this is in radians + iConfig.getParameter("maxNormResid"), + iConfig.getParameter("minHits"), + iConfig.getParameter("maxReducedChi2")); + + LogDebug("") << " Welcome to SiStripElectronProducer "; } - // SiStripElectronProducer::SiStripElectronProducer(const SiStripElectronProducer& rhs) // { // // do actual copying here; // } -SiStripElectronProducer::~SiStripElectronProducer() -{ - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) - delete algo_p; +SiStripElectronProducer::~SiStripElectronProducer() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) + delete algo_p; } // @@ -111,71 +104,75 @@ SiStripElectronProducer::~SiStripElectronProducer() // // ------------ method called to produce the data ------------ -void -SiStripElectronProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - // Extract data from the event - edm::ESHandle trackerHandle; - iSetup.get().get(trackerHandle); - - edm::Handle rphiHitsHandle; - iEvent.getByToken(rphi_sistrips2dtag_, rphiHitsHandle); - - edm::Handle stereoHitsHandle; - iEvent.getByToken(stereo_sistrips2dtag_, stereoHitsHandle); - - edm::Handle matchedHitsHandle; - iEvent.getByToken(matched_sistrips2dtag_, matchedHitsHandle); - - edm::ESHandle magneticFieldHandle; - iSetup.get().get(magneticFieldHandle); - - edm::Handle superClusterHandle; - iEvent.getByToken(superClustertag_, superClusterHandle); - - // Set up SiStripElectronAlgo for this event - algo_p->prepareEvent(trackerHandle, rphiHitsHandle, stereoHitsHandle, matchedHitsHandle, magneticFieldHandle); - - // Prepare the output electron candidates and clouds to be filled - auto electronOut = std::make_unique(); - auto trackCandidateOut = std::make_unique(); - - //Retrieve tracker topology from geometry - edm::ESHandle tTopoHand; - iSetup.get().get(tTopoHand); - const TrackerTopology *tTopo=tTopoHand.product(); - - // counter for electron candidates - int siStripElectCands = 0 ; - - std::ostringstream str; - - - // Loop over clusters - str << "Starting loop over superclusters."<< "\n" << std::endl; - for (unsigned int i = 0; i < superClusterHandle.product()->size(); i++) { - const reco::SuperCluster* sc = &(*reco::SuperClusterRef(superClusterHandle, i)); - double energy = sc->energy(); - - if (algo_p->findElectron(*electronOut, *trackCandidateOut, reco::SuperClusterRef(superClusterHandle, i),tTopo)) { - str << "Supercluster energy: " << energy << ", FOUND an electron." << "\n" << std::endl; - ++siStripElectCands ; - } - else { - str << "Supercluster energy: " << energy << ", DID NOT FIND an electron."<< "\n" << std::endl; - } - } - str << "Ending loop over superclusters." << "\n" << std::endl; - - str << " Found " << siStripElectCands - << " SiStripElectron Candidates before track fit " - << "\n" << std::endl ; - - LogDebug("SiStripElectronProducer") << str.str(); - - // Put the electron candidates and the tracking trajectories into the event - iEvent.put(std::move(electronOut), siStripElectronsLabel_); - iEvent.put(std::move(trackCandidateOut), trackCandidatesLabel_); +void SiStripElectronProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + // Extract data from the event + edm::ESHandle trackerHandle; + iSetup.get().get(trackerHandle); + + edm::Handle rphiHitsHandle; + iEvent.getByToken(rphi_sistrips2dtag_, rphiHitsHandle); + + edm::Handle stereoHitsHandle; + iEvent.getByToken(stereo_sistrips2dtag_, stereoHitsHandle); + + edm::Handle matchedHitsHandle; + iEvent.getByToken(matched_sistrips2dtag_, matchedHitsHandle); + + edm::ESHandle magneticFieldHandle; + iSetup.get().get(magneticFieldHandle); + + edm::Handle superClusterHandle; + iEvent.getByToken(superClustertag_, superClusterHandle); + + // Set up SiStripElectronAlgo for this event + algo_p->prepareEvent(trackerHandle, rphiHitsHandle, stereoHitsHandle, matchedHitsHandle, magneticFieldHandle); + + // Prepare the output electron candidates and clouds to be filled + auto electronOut = std::make_unique(); + auto trackCandidateOut = std::make_unique(); + + //Retrieve tracker topology from geometry + edm::ESHandle tTopoHand; + iSetup.get().get(tTopoHand); + const TrackerTopology* tTopo = tTopoHand.product(); + + // counter for electron candidates + int siStripElectCands = 0; + + std::ostringstream str; + + // Loop over clusters + str << "Starting loop over superclusters." + << "\n" + << std::endl; + for (unsigned int i = 0; i < superClusterHandle.product()->size(); i++) { + const reco::SuperCluster* sc = &(*reco::SuperClusterRef(superClusterHandle, i)); + double energy = sc->energy(); + + if (algo_p->findElectron(*electronOut, *trackCandidateOut, reco::SuperClusterRef(superClusterHandle, i), tTopo)) { + str << "Supercluster energy: " << energy << ", FOUND an electron." + << "\n" + << std::endl; + ++siStripElectCands; + } else { + str << "Supercluster energy: " << energy << ", DID NOT FIND an electron." + << "\n" + << std::endl; + } + } + str << "Ending loop over superclusters." + << "\n" + << std::endl; + + str << " Found " << siStripElectCands << " SiStripElectron Candidates before track fit " + << "\n" + << std::endl; + + LogDebug("SiStripElectronProducer") << str.str(); + + // Put the electron candidates and the tracking trajectories into the event + iEvent.put(std::move(electronOut), siStripElectronsLabel_); + iEvent.put(std::move(trackCandidateOut), trackCandidatesLabel_); } // diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.h index e380cad66bfad..a3d87b559e92f 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronProducer.h @@ -4,7 +4,7 @@ // // Package: EgammaElectronProducers // Class : SiStripElectronProducer -// +// /**\class SiStripElectronProducer SiStripElectronProducer.h RecoEgamma/EgammaElectronProducers/interface/SiStripElectronProducer.h Description: @@ -33,31 +33,29 @@ // forward declarations class SiStripElectronProducer : public edm::stream::EDProducer<> { - public: - explicit SiStripElectronProducer(const edm::ParameterSet&); - ~SiStripElectronProducer() override; - - - void produce(edm::Event&, const edm::EventSetup&) override; - private: - // ----------member data --------------------------- - std::string siHitProducer_; - std::string siRphiHitCollection_; - std::string siStereoHitCollection_; - std::string siMatchedHitCollection_; - std::string superClusterProducer_; - std::string superClusterCollection_; - std::string siStripElectronsLabel_; - std::string trackCandidatesLabel_; - - edm::EDGetTokenT rphi_sistrips2dtag_; - edm::EDGetTokenT stereo_sistrips2dtag_; - edm::EDGetTokenT matched_sistrips2dtag_; - edm::EDGetTokenT superClustertag_; - - - - SiStripElectronAlgo* algo_p; +public: + explicit SiStripElectronProducer(const edm::ParameterSet&); + ~SiStripElectronProducer() override; + + void produce(edm::Event&, const edm::EventSetup&) override; + +private: + // ----------member data --------------------------- + std::string siHitProducer_; + std::string siRphiHitCollection_; + std::string siStereoHitCollection_; + std::string siMatchedHitCollection_; + std::string superClusterProducer_; + std::string superClusterCollection_; + std::string siStripElectronsLabel_; + std::string trackCandidatesLabel_; + + edm::EDGetTokenT rphi_sistrips2dtag_; + edm::EDGetTokenT stereo_sistrips2dtag_; + edm::EDGetTokenT matched_sistrips2dtag_; + edm::EDGetTokenT superClustertag_; + + SiStripElectronAlgo* algo_p; }; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.cc index 23bfeb805743a..e5ba4b92b6de5 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.cc @@ -18,85 +18,79 @@ using namespace reco; -SiStripElectronSeedProducer::SiStripElectronSeedProducer(const edm::ParameterSet& iConfig) -{ - if(iConfig.exists("SeedConfiguration")){ - conf_ = iConfig.getParameter("SeedConfiguration") ; - }else{ - conf_.addParameter("beamSpot",edm::InputTag("offlineBeamSpot")); - conf_.addParameter("tibOriginZCut",20.); - conf_.addParameter("tidOriginZCut",20.); - conf_.addParameter("tecOriginZCut",20.); - conf_.addParameter("monoOriginZCut",20.); - conf_.addParameter("tibDeltaPsiCut",0.1); - conf_.addParameter("tidDeltaPsiCut",0.1); - conf_.addParameter("tecDeltaPsiCut",0.1); - conf_.addParameter("monoDeltaPsiCut",0.1); - conf_.addParameter("tibPhiMissHit2Cut",0.006); - conf_.addParameter("tidPhiMissHit2Cut",0.006); - conf_.addParameter("tecPhiMissHit2Cut",0.007); - conf_.addParameter("monoPhiMissHit2Cut",0.02); - conf_.addParameter("tibZMissHit2Cut",0.35); - conf_.addParameter("tidRMissHit2Cut",0.3); - conf_.addParameter("tecRMissHit2Cut",0.3); +SiStripElectronSeedProducer::SiStripElectronSeedProducer(const edm::ParameterSet& iConfig) { + if (iConfig.exists("SeedConfiguration")) { + conf_ = iConfig.getParameter("SeedConfiguration"); + } else { + conf_.addParameter("beamSpot", edm::InputTag("offlineBeamSpot")); + conf_.addParameter("tibOriginZCut", 20.); + conf_.addParameter("tidOriginZCut", 20.); + conf_.addParameter("tecOriginZCut", 20.); + conf_.addParameter("monoOriginZCut", 20.); + conf_.addParameter("tibDeltaPsiCut", 0.1); + conf_.addParameter("tidDeltaPsiCut", 0.1); + conf_.addParameter("tecDeltaPsiCut", 0.1); + conf_.addParameter("monoDeltaPsiCut", 0.1); + conf_.addParameter("tibPhiMissHit2Cut", 0.006); + conf_.addParameter("tidPhiMissHit2Cut", 0.006); + conf_.addParameter("tecPhiMissHit2Cut", 0.007); + conf_.addParameter("monoPhiMissHit2Cut", 0.02); + conf_.addParameter("tibZMissHit2Cut", 0.35); + conf_.addParameter("tidRMissHit2Cut", 0.3); + conf_.addParameter("tecRMissHit2Cut", 0.3); conf_.addParameter("tidEtaUsage", 1.2); - conf_.addParameter("tidMaxHits",4); - conf_.addParameter("tecMaxHits",2); - conf_.addParameter("monoMaxHits",4); - conf_.addParameter("maxSeeds",5); + conf_.addParameter("tidMaxHits", 4); + conf_.addParameter("tecMaxHits", 2); + conf_.addParameter("monoMaxHits", 4); + conf_.addParameter("maxSeeds", 5); } SiStripElectronSeedGenerator::Tokens ssesg_tokens; ssesg_tokens.token_bs = consumes(iConfig.getParameter("beamSpot")); if (conf_.existsAs("measurementTrackerEvent")) { - ssesg_tokens.token_mte = consumes(conf_.getParameter("measurementTrackerEvent")); + ssesg_tokens.token_mte = + consumes(conf_.getParameter("measurementTrackerEvent")); } - matcher_ = new SiStripElectronSeedGenerator(conf_,ssesg_tokens); - - + matcher_ = new SiStripElectronSeedGenerator(conf_, ssesg_tokens); // get labels from config - superClusters_[0]=consumes(iConfig.getParameter("barrelSuperClusters")); - superClusters_[1]=consumes(iConfig.getParameter("endcapSuperClusters")); + superClusters_[0] = + consumes(iConfig.getParameter("barrelSuperClusters")); + superClusters_[1] = + consumes(iConfig.getParameter("endcapSuperClusters")); //register your products produces(); } -SiStripElectronSeedProducer::~SiStripElectronSeedProducer() -{ +SiStripElectronSeedProducer::~SiStripElectronSeedProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) delete matcher_; } -void SiStripElectronSeedProducer::produce(edm::Event& e, const edm::EventSetup& iSetup) -{ +void SiStripElectronSeedProducer::produce(edm::Event& e, const edm::EventSetup& iSetup) { using namespace edm; using namespace std; LogDebug("entering"); - LogDebug("") <<"[SiStripElectronSeedProducer::produce] entering " ; + LogDebug("") << "[SiStripElectronSeedProducer::produce] entering "; matcher_->setupES(iSetup); - ElectronSeedCollection *seeds = new ElectronSeedCollection; + ElectronSeedCollection* seeds = new ElectronSeedCollection; std::unique_ptr pSeeds; // do both barrel and endcap instances - for (unsigned int i=0; i<2; i++) { - + for (unsigned int i = 0; i < 2; i++) { // get the superclusters edm::Handle clusters; - if(e.getByToken(superClusters_[i],clusters)) { + if (e.getByToken(superClusters_[i], clusters)) { // run the seed generator and put the ElectronSeeds into a collection - matcher_->run(e,iSetup,clusters,*seeds); + matcher_->run(e, iSetup, clusters, *seeds); } - } pSeeds = std::unique_ptr(seeds); e.put(std::move(pSeeds)); - } - diff --git a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.h index c04aad390ac2a..e3dfcb0eefb49 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/SiStripElectronSeedProducer.h @@ -1,7 +1,6 @@ #ifndef SiStripElectronSeedProducer_h #define SiStripElectronSeedProducer_h - #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" @@ -12,20 +11,18 @@ class SiStripElectronSeedGenerator; -class SiStripElectronSeedProducer : public edm::stream::EDProducer<> -{ - public: - +class SiStripElectronSeedProducer : public edm::stream::EDProducer<> { +public: explicit SiStripElectronSeedProducer(const edm::ParameterSet& conf); ~SiStripElectronSeedProducer() override; void produce(edm::Event& e, const edm::EventSetup& c) override; - private: +private: edm::EDGetTokenT superClusters_[2]; edm::ParameterSet conf_; - SiStripElectronSeedGenerator *matcher_; - }; + SiStripElectronSeedGenerator* matcher_; +}; #endif diff --git a/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersEDProducer.cc b/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersEDProducer.cc index 3c1e0f9743b54..dabd9bc69ae66 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersEDProducer.cc +++ b/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersEDProducer.cc @@ -4,6 +4,8 @@ #include "RecoTracker/TkTrackingRegions/interface/TrackingRegionProducerFactory.h" #include "RecoTracker/TkTrackingRegions/interface/TrackingRegionEDProducerT.h" #include "RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersProducer.h" -DEFINE_EDM_PLUGIN(TrackingRegionProducerFactory, TrackingRegionsFromSuperClustersProducer, "TrackingRegionsFromSuperClustersProducer"); +DEFINE_EDM_PLUGIN(TrackingRegionProducerFactory, + TrackingRegionsFromSuperClustersProducer, + "TrackingRegionsFromSuperClustersProducer"); using TrackingRegionsFromSuperClustersEDProducer = TrackingRegionEDProducerT; DEFINE_FWK_MODULE(TrackingRegionsFromSuperClustersEDProducer); diff --git a/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersProducer.h b/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersProducer.h index 2c51e9cde666f..cf1eb5c078f93 100644 --- a/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersProducer.h +++ b/RecoEgamma/EgammaElectronProducers/plugins/TrackingRegionsFromSuperClustersProducer.h @@ -1,11 +1,11 @@ -#ifndef RecoTracker_TkTrackingRegions_TrackingRegionsFromSuperClustersProducer_H +#ifndef RecoTracker_TkTrackingRegions_TrackingRegionsFromSuperClustersProducer_H #define RecoTracker_TkTrackingRegions_TrackingRegionsFromSuperClustersProducer_H //****************************************************************************** // // Part of the refactorisation of of the E/gamma pixel matching pre-2017 -// This refactorisation converts the monolithic approach to a series of -// independent producer modules, with each modules performing a specific +// This refactorisation converts the monolithic approach to a series of +// independent producer modules, with each modules performing a specific // job as recommended by the 2017 tracker framework // // This module is called a Producer even though its not an ED producer @@ -41,7 +41,6 @@ #include "DataFormats/EgammaReco/interface/SuperClusterFwd.h" #include "DataFormats/EgammaReco/interface/SuperCluster.h" - #include "RecoTracker/TkTrackingRegions/interface/TrackingRegionProducer.h" #include "RecoTracker/TkTrackingRegions/interface/RectangularEtaPhiTrackingRegion.h" #include "RecoTracker/MeasurementDet/interface/MeasurementTrackerEvent.h" @@ -54,70 +53,73 @@ //stick this in common tools #include "TEnum.h" #include "TEnumConstant.h" -namespace{ - template MyEnum strToEnum(std::string const& enumConstName){ +namespace { + template + MyEnum strToEnum(std::string const& enumConstName) { TEnum* en = TEnum::GetEnum(typeid(MyEnum)); - if (en != nullptr){ - if (TEnumConstant const* enc = en->GetConstant(enumConstName.c_str())){ - return static_cast(enc->GetValue()); - }else{ - throw cms::Exception("Configuration") <GetConstant(enumConstName.c_str())) { + return static_cast(enc->GetValue()); + } else { + throw cms::Exception("Configuration") << enumConstName << " is not a valid member of " << typeid(MyEnum).name(); } } - throw cms::Exception("LogicError") < RectangularEtaPhiTrackingRegion::UseMeasurementTracker strToEnum(std::string const& enumConstName){ + template <> + RectangularEtaPhiTrackingRegion::UseMeasurementTracker strToEnum(std::string const& enumConstName) { using MyEnum = RectangularEtaPhiTrackingRegion::UseMeasurementTracker; - if(enumConstName=="kNever") return MyEnum::kNever; - else if(enumConstName=="kForSiStrips") return MyEnum::kForSiStrips; - else if(enumConstName=="kAlways") return MyEnum::kAlways; - else{ - throw cms::Exception("InvalidConfiguration") < > - regions (const edm::Event& iEvent, const edm::EventSetup& iSetup)const override; + std::vector> regions(const edm::Event& iEvent, + const edm::EventSetup& iSetup) const override; private: - GlobalPoint getVtxPos(const edm::Event& iEvent,double& deltaZVertex)const; - - std::unique_ptr - createTrackingRegion(const reco::SuperCluster& superCluster,const GlobalPoint& vtxPos, - const double deltaZVertex,const Charge charge, - const MeasurementTrackerEvent* measTrackerEvent, - const MagneticField& magField)const; - + GlobalPoint getVtxPos(const edm::Event& iEvent, double& deltaZVertex) const; + + std::unique_ptr createTrackingRegion(const reco::SuperCluster& superCluster, + const GlobalPoint& vtxPos, + const double deltaZVertex, + const Charge charge, + const MeasurementTrackerEvent* measTrackerEvent, + const MagneticField& magField) const; + private: - void validateConfigSettings()const; + void validateConfigSettings() const; private: //there are 3 modes in which to define the Z area of the tracking region //1) from first vertex in the passed vertices collection +/- originHalfLength in z (useZInVertex=true) //2) the beamspot +/- nrSigmaForBSDeltaZ* zSigma of beamspot (useZInBeamspot=true) - // the zSigma of the beamspot can have a minimum value specified + // the zSigma of the beamspot can have a minimum value specified // we do this because a common error is that beamspot has too small of a value //3) defaultZ_ +/- originHalfLength (if useZInVertex and useZInBeamspot are both false) - double ptMin_; - double originRadius_; + double ptMin_; + double originRadius_; double originHalfLength_; double deltaEtaRegion_; double deltaPhiRegion_; @@ -128,187 +130,185 @@ class TrackingRegionsFromSuperClustersProducer : public TrackingRegionProducer double minBSDeltaZ_; bool precise_; RectangularEtaPhiTrackingRegion::UseMeasurementTracker whereToUseMeasTracker_; - - edm::EDGetTokenT verticesToken_; - edm::EDGetTokenT beamSpotToken_; - edm::EDGetTokenT measTrackerEventToken_; - std::vector> > superClustersTokens_; + edm::EDGetTokenT verticesToken_; + edm::EDGetTokenT beamSpotToken_; + edm::EDGetTokenT measTrackerEventToken_; + std::vector>> superClustersTokens_; }; - - namespace { - template - edm::Handle getHandle(const edm::Event& event,const edm::EDGetTokenT & token){ + template + edm::Handle getHandle(const edm::Event& event, const edm::EDGetTokenT& token) { edm::Handle handle; - event.getByToken(token,handle); + event.getByToken(token, handle); return handle; } -} +} // namespace -TrackingRegionsFromSuperClustersProducer:: -TrackingRegionsFromSuperClustersProducer(const edm::ParameterSet& cfg, - edm::ConsumesCollector && iC) -{ +TrackingRegionsFromSuperClustersProducer::TrackingRegionsFromSuperClustersProducer(const edm::ParameterSet& cfg, + edm::ConsumesCollector&& iC) { edm::ParameterSet regionPSet = cfg.getParameter("RegionPSet"); - - ptMin_ = regionPSet.getParameter("ptMin"); - originRadius_ = regionPSet.getParameter("originRadius"); - originHalfLength_ = regionPSet.getParameter("originHalfLength"); - deltaPhiRegion_ = regionPSet.getParameter("deltaPhiRegion"); - deltaEtaRegion_ = regionPSet.getParameter("deltaEtaRegion"); - useZInVertex_ = regionPSet.getParameter("useZInVertex"); - useZInBeamspot_ = regionPSet.getParameter("useZInBeamspot"); - nrSigmaForBSDeltaZ_ = regionPSet.getParameter("nrSigmaForBSDeltaZ"); - defaultZ_ = regionPSet.getParameter("defaultZ"); - minBSDeltaZ_ = regionPSet.getParameter("minBSDeltaZ"); - precise_ = regionPSet.getParameter("precise"); - whereToUseMeasTracker_ = strToEnum(regionPSet.getParameter("whereToUseMeasTracker")); - + + ptMin_ = regionPSet.getParameter("ptMin"); + originRadius_ = regionPSet.getParameter("originRadius"); + originHalfLength_ = regionPSet.getParameter("originHalfLength"); + deltaPhiRegion_ = regionPSet.getParameter("deltaPhiRegion"); + deltaEtaRegion_ = regionPSet.getParameter("deltaEtaRegion"); + useZInVertex_ = regionPSet.getParameter("useZInVertex"); + useZInBeamspot_ = regionPSet.getParameter("useZInBeamspot"); + nrSigmaForBSDeltaZ_ = regionPSet.getParameter("nrSigmaForBSDeltaZ"); + defaultZ_ = regionPSet.getParameter("defaultZ"); + minBSDeltaZ_ = regionPSet.getParameter("minBSDeltaZ"); + precise_ = regionPSet.getParameter("precise"); + whereToUseMeasTracker_ = strToEnum( + regionPSet.getParameter("whereToUseMeasTracker")); + validateConfigSettings(); - auto verticesTag = regionPSet.getParameter("vertices"); - auto beamSpotTag = regionPSet.getParameter("beamSpot"); - auto superClustersTags = regionPSet.getParameter >("superClusters"); + auto verticesTag = regionPSet.getParameter("vertices"); + auto beamSpotTag = regionPSet.getParameter("beamSpot"); + auto superClustersTags = regionPSet.getParameter>("superClusters"); auto measTrackerEventTag = regionPSet.getParameter("measurementTrackerEvent"); - - if(useZInVertex_){ - verticesToken_ = iC.consumes(verticesTag); - }else{ - beamSpotToken_ = iC.consumes(beamSpotTag); + + if (useZInVertex_) { + verticesToken_ = iC.consumes(verticesTag); + } else { + beamSpotToken_ = iC.consumes(beamSpotTag); } - if(whereToUseMeasTracker_ != RectangularEtaPhiTrackingRegion::UseMeasurementTracker::kNever){ + if (whereToUseMeasTracker_ != RectangularEtaPhiTrackingRegion::UseMeasurementTracker::kNever) { measTrackerEventToken_ = iC.consumes(measTrackerEventTag); } - for(const auto& tag : superClustersTags){ + for (const auto& tag : superClustersTags) { superClustersTokens_.emplace_back(iC.consumes>(tag)); } -} - - +} -void TrackingRegionsFromSuperClustersProducer:: -fillDescriptions(edm::ConfigurationDescriptions& descriptions) -{ +void TrackingRegionsFromSuperClustersProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; - + desc.add("ptMin", 1.5); desc.add("originRadius", 0.2); - desc.add("originHalfLength", 15.0)->setComment("z range is +/- this value except when using the beamspot (useZInBeamspot=true)"); - desc.add("deltaPhiRegion",0.4); - desc.add("deltaEtaRegion",0.1); - desc.add("useZInVertex", false)->setComment("use the leading vertex position +/-orginHalfLength, mutually exclusive with useZInBeamspot"); - desc.add("useZInBeamspot", true)->setComment("use the beamspot position +/- nrSigmaForBSDeltaZ* sigmaZ_{bs}, mutually exclusive with useZInVertex"); - desc.add("nrSigmaForBSDeltaZ",3.0)->setComment("# of sigma to extend the z region when using the beamspot, only active if useZInBeamspot=true"); - desc.add("minBSDeltaZ",0.0)->setComment("a minimum value of the beamspot sigma z to use, only active if useZInBeamspot=true"); - desc.add("defaultZ",0.)->setComment("the default z position, only used if useZInVertex and useZInBeamspot are both false"); + desc.add("originHalfLength", 15.0) + ->setComment("z range is +/- this value except when using the beamspot (useZInBeamspot=true)"); + desc.add("deltaPhiRegion", 0.4); + desc.add("deltaEtaRegion", 0.1); + desc.add("useZInVertex", false) + ->setComment("use the leading vertex position +/-orginHalfLength, mutually exclusive with useZInBeamspot"); + desc.add("useZInBeamspot", true) + ->setComment( + "use the beamspot position +/- nrSigmaForBSDeltaZ* sigmaZ_{bs}, mutually exclusive with useZInVertex"); + desc.add("nrSigmaForBSDeltaZ", 3.0) + ->setComment("# of sigma to extend the z region when using the beamspot, only active if useZInBeamspot=true"); + desc.add("minBSDeltaZ", 0.0) + ->setComment("a minimum value of the beamspot sigma z to use, only active if useZInBeamspot=true"); + desc.add("defaultZ", 0.) + ->setComment("the default z position, only used if useZInVertex and useZInBeamspot are both false"); desc.add("precise", true); - desc.add("whereToUseMeasTracker","kNever"); - desc.add("beamSpot", edm::InputTag("hltOnlineBeamSpot"))->setComment("only used if useZInBeamspot is true"); + desc.add("whereToUseMeasTracker", "kNever"); + desc.add("beamSpot", edm::InputTag("hltOnlineBeamSpot")) + ->setComment("only used if useZInBeamspot is true"); desc.add("vertices", edm::InputTag())->setComment("only used if useZInVertex is true"); - desc.add >("superClusters", std::vector{edm::InputTag{"hltEgammaSuperClustersToPixelMatch"}}); - desc.add("measurementTrackerEvent",edm::InputTag()); - + desc.add>("superClusters", + std::vector{edm::InputTag{"hltEgammaSuperClustersToPixelMatch"}}); + desc.add("measurementTrackerEvent", edm::InputTag()); + edm::ParameterSetDescription descRegion; descRegion.add("RegionPSet", desc); descriptions.add("trackingRegionsFromSuperClusters", descRegion); } +std::vector> TrackingRegionsFromSuperClustersProducer::regions( + const edm::Event& iEvent, const edm::EventSetup& iSetup) const { + std::vector> trackingRegions; + double deltaZVertex = 0; + GlobalPoint vtxPos = getVtxPos(iEvent, deltaZVertex); -std::vector > -TrackingRegionsFromSuperClustersProducer:: -regions(const edm::Event& iEvent, const edm::EventSetup& iSetup)const -{ - std::vector > trackingRegions; - - double deltaZVertex=0; - GlobalPoint vtxPos = getVtxPos(iEvent,deltaZVertex); - - const MeasurementTrackerEvent *measTrackerEvent = nullptr; - if(!measTrackerEventToken_.isUninitialized()){ - measTrackerEvent = getHandle(iEvent,measTrackerEventToken_).product(); + const MeasurementTrackerEvent* measTrackerEvent = nullptr; + if (!measTrackerEventToken_.isUninitialized()) { + measTrackerEvent = getHandle(iEvent, measTrackerEventToken_).product(); } edm::ESHandle magFieldHandle; iSetup.get().get(magFieldHandle); - - for(auto& superClustersToken : superClustersTokens_){ - auto superClustersHandle = getHandle(iEvent,superClustersToken); - for(auto& superClusterRef : *superClustersHandle){ - //do both charge hypothesises - trackingRegions.emplace_back(createTrackingRegion(*superClusterRef,vtxPos,deltaZVertex,Charge::POS,measTrackerEvent,*magFieldHandle)); - trackingRegions.emplace_back(createTrackingRegion(*superClusterRef,vtxPos,deltaZVertex,Charge::NEG,measTrackerEvent,*magFieldHandle)); + + for (auto& superClustersToken : superClustersTokens_) { + auto superClustersHandle = getHandle(iEvent, superClustersToken); + for (auto& superClusterRef : *superClustersHandle) { + //do both charge hypothesises + trackingRegions.emplace_back( + createTrackingRegion(*superClusterRef, vtxPos, deltaZVertex, Charge::POS, measTrackerEvent, *magFieldHandle)); + trackingRegions.emplace_back( + createTrackingRegion(*superClusterRef, vtxPos, deltaZVertex, Charge::NEG, measTrackerEvent, *magFieldHandle)); } } return trackingRegions; } -GlobalPoint TrackingRegionsFromSuperClustersProducer:: -getVtxPos(const edm::Event& iEvent,double& deltaZVertex)const -{ - if(useZInVertex_){ - auto verticesHandle = getHandle(iEvent,verticesToken_); - //we throw if the vertices are not there but if no vertex is +GlobalPoint TrackingRegionsFromSuperClustersProducer::getVtxPos(const edm::Event& iEvent, double& deltaZVertex) const { + if (useZInVertex_) { + auto verticesHandle = getHandle(iEvent, verticesToken_); + //we throw if the vertices are not there but if no vertex is //recoed in the event, we default to 0,0,defaultZ as the vertex - if(!verticesHandle->empty()){ + if (!verticesHandle->empty()) { deltaZVertex = originHalfLength_; const auto& pv = verticesHandle->front(); - return GlobalPoint(pv.x(),pv.y(),pv.z()); - }else{ + return GlobalPoint(pv.x(), pv.y(), pv.z()); + } else { deltaZVertex = originHalfLength_; - return GlobalPoint(0,0,defaultZ_); + return GlobalPoint(0, 0, defaultZ_); } - }else{ - - auto beamSpotHandle = getHandle(iEvent,beamSpotToken_); + } else { + auto beamSpotHandle = getHandle(iEvent, beamSpotToken_); const reco::BeamSpot::Point& bsPos = beamSpotHandle->position(); - - if(useZInBeamspot_){ + + if (useZInBeamspot_) { //as this is what has been done traditionally for e/gamma, others just use sigmaZ - const double bsSigmaZ = std::sqrt(beamSpotHandle->sigmaZ()*beamSpotHandle->sigmaZ() + - beamSpotHandle->sigmaZ0Error()*beamSpotHandle->sigmaZ0Error()); - const double sigmaZ = std::max(bsSigmaZ,minBSDeltaZ_); - deltaZVertex = nrSigmaForBSDeltaZ_*sigmaZ; - - return GlobalPoint(bsPos.x(),bsPos.y(),bsPos.z()); - }else{ + const double bsSigmaZ = std::sqrt(beamSpotHandle->sigmaZ() * beamSpotHandle->sigmaZ() + + beamSpotHandle->sigmaZ0Error() * beamSpotHandle->sigmaZ0Error()); + const double sigmaZ = std::max(bsSigmaZ, minBSDeltaZ_); + deltaZVertex = nrSigmaForBSDeltaZ_ * sigmaZ; + + return GlobalPoint(bsPos.x(), bsPos.y(), bsPos.z()); + } else { deltaZVertex = originHalfLength_; - return GlobalPoint(bsPos.x(),bsPos.y(),defaultZ_); + return GlobalPoint(bsPos.x(), bsPos.y(), defaultZ_); } } - } -std::unique_ptr -TrackingRegionsFromSuperClustersProducer:: -createTrackingRegion(const reco::SuperCluster& superCluster,const GlobalPoint& vtxPos, - const double deltaZVertex,const Charge charge, - const MeasurementTrackerEvent* measTrackerEvent, - const MagneticField& magField)const -{ +std::unique_ptr TrackingRegionsFromSuperClustersProducer::createTrackingRegion( + const reco::SuperCluster& superCluster, + const GlobalPoint& vtxPos, + const double deltaZVertex, + const Charge charge, + const MeasurementTrackerEvent* measTrackerEvent, + const MagneticField& magField) const { const GlobalPoint clusterPos(superCluster.position().x(), superCluster.position().y(), superCluster.position().z()); const double energy = superCluster.energy(); - - FreeTrajectoryState freeTrajState = FTSFromVertexToPointFactory::get(magField, clusterPos, vtxPos, energy, static_cast(charge)); + + FreeTrajectoryState freeTrajState = + FTSFromVertexToPointFactory::get(magField, clusterPos, vtxPos, energy, static_cast(charge)); return std::make_unique(freeTrajState.momentum(), - vtxPos, - ptMin_, - originRadius_, - deltaZVertex, - deltaEtaRegion_, - deltaPhiRegion_, - whereToUseMeasTracker_, - precise_, - measTrackerEvent); + vtxPos, + ptMin_, + originRadius_, + deltaZVertex, + deltaEtaRegion_, + deltaPhiRegion_, + whereToUseMeasTracker_, + precise_, + measTrackerEvent); } -void TrackingRegionsFromSuperClustersProducer::validateConfigSettings()const -{ - if(useZInVertex_ && useZInBeamspot_){ - throw cms::Exception("InvalidConfiguration") <<" when constructing TrackingRegionsFromSuperClustersProducer both useZInVertex ("< Features::get() { - std::vector output = { - rho_, - ele_pt_, - sc_eta_, - shape_full5x5_sigmaIetaIeta_, - shape_full5x5_sigmaIphiIphi_, - shape_full5x5_circularity_, - shape_full5x5_r9_, - sc_etaWidth_, - sc_phiWidth_, - shape_full5x5_HoverE_, - trk_nhits_, - trk_chi2red_, - gsf_chi2red_, - brem_frac_, - gsf_nhits_, - match_SC_EoverP_, - match_eclu_EoverP_, - match_SC_dEta_, - match_SC_dPhi_, - match_seed_dEta_, - sc_E_, - trk_p_, + std::vector output = { + rho_, + ele_pt_, + sc_eta_, + shape_full5x5_sigmaIetaIeta_, + shape_full5x5_sigmaIphiIphi_, + shape_full5x5_circularity_, + shape_full5x5_r9_, + sc_etaWidth_, + sc_phiWidth_, + shape_full5x5_HoverE_, + trk_nhits_, + trk_chi2red_, + gsf_chi2red_, + brem_frac_, + gsf_nhits_, + match_SC_EoverP_, + match_eclu_EoverP_, + match_SC_dEta_, + match_SC_dPhi_, + match_seed_dEta_, + sc_E_, + trk_p_, }; return output; } - + //////////////////////////////////////////////////////////////////////////////// // - void Features::set( const reco::GsfElectronRef& ele, double rho ) { - + void Features::set(const reco::GsfElectronRef& ele, double rho) { // KF tracks - if ( ele->core().isNonnull() ) { - reco::TrackRef trk = ele->core()->ctfTrack(); //@@ is this what we want?! - if ( trk.isNonnull() ) { - trk_p_ = float(trk->p()); - trk_nhits_ = float(trk->found()); - trk_chi2red_ = float(trk->normalizedChi2()); + if (ele->core().isNonnull()) { + reco::TrackRef trk = ele->core()->ctfTrack(); //@@ is this what we want?! + if (trk.isNonnull()) { + trk_p_ = float(trk->p()); + trk_nhits_ = float(trk->found()); + trk_chi2red_ = float(trk->normalizedChi2()); } } // GSF tracks - if ( ele->core().isNonnull() ) { + if (ele->core().isNonnull()) { reco::GsfTrackRef gsf = ele->core()->gsfTrack(); - if ( gsf.isNonnull() ) { - gsf_nhits_ = gsf->found(); - gsf_chi2red_ = gsf->normalizedChi2(); + if (gsf.isNonnull()) { + gsf_nhits_ = gsf->found(); + gsf_chi2red_ = gsf->normalizedChi2(); } } // Super clusters - if ( ele->core().isNonnull() ) { + if (ele->core().isNonnull()) { reco::SuperClusterRef sc = ele->core()->superCluster(); - if ( sc.isNonnull() ) { - sc_E_ = sc->energy(); - sc_eta_ = sc->eta(); - sc_etaWidth_ = sc->etaWidth(); - sc_phiWidth_ = sc->phiWidth(); + if (sc.isNonnull()) { + sc_E_ = sc->energy(); + sc_eta_ = sc->eta(); + sc_etaWidth_ = sc->etaWidth(); + sc_phiWidth_ = sc->phiWidth(); } } // Track-cluster matching - if ( ele.isNonnull() ) { + if (ele.isNonnull()) { match_seed_dEta_ = ele->deltaEtaSeedClusterTrackAtCalo(); - match_eclu_EoverP_ = (1./ele->ecalEnergy()) - (1./ele->p()); + match_eclu_EoverP_ = (1. / ele->ecalEnergy()) - (1. / ele->p()); match_SC_EoverP_ = ele->eSuperClusterOverP(); match_SC_dEta_ = ele->deltaEtaSuperClusterTrackAtVtx(); match_SC_dPhi_ = ele->deltaPhiSuperClusterTrackAtVtx(); - } + } // Shower shape vars - if ( ele.isNonnull() ) { + if (ele.isNonnull()) { shape_full5x5_sigmaIetaIeta_ = ele->full5x5_sigmaIetaIeta(); shape_full5x5_sigmaIphiIphi_ = ele->full5x5_sigmaIphiIphi(); - shape_full5x5_HoverE_ = ele->full5x5_hcalOverEcal(); + shape_full5x5_HoverE_ = ele->full5x5_hcalOverEcal(); shape_full5x5_r9_ = ele->full5x5_r9(); - shape_full5x5_circularity_ = 1. - ele->full5x5_e1x5() / ele->full5x5_e5x5(); + shape_full5x5_circularity_ = 1. - ele->full5x5_e1x5() / ele->full5x5_e5x5(); } // Misc rho_ = rho; - if ( ele.isNonnull() ) { + if (ele.isNonnull()) { brem_frac_ = ele->fbrem(); ele_pt_ = ele->pt(); } - }; //////////////////////////////////////////////////////////////////////////////// // - HeavyObjectCache::HeavyObjectCache( const edm::ParameterSet& conf ) { - for ( auto& name : conf.getParameter< std::vector >("ModelNames") ) - { - names_.push_back(name); - } - for ( auto& weights : conf.getParameter< std::vector >("ModelWeights") ) - { - models_.push_back(createGBRForest(edm::FileInPath(weights))); - } - for ( auto& thresh : conf.getParameter< std::vector >("ModelThresholds") ) - { - thresholds_.push_back(thresh); - } - if ( names_.size() != models_.size() ) { + HeavyObjectCache::HeavyObjectCache(const edm::ParameterSet& conf) { + for (auto& name : conf.getParameter >("ModelNames")) { + names_.push_back(name); + } + for (auto& weights : conf.getParameter >("ModelWeights")) { + models_.push_back(createGBRForest(edm::FileInPath(weights))); + } + for (auto& thresh : conf.getParameter >("ModelThresholds")) { + thresholds_.push_back(thresh); + } + if (names_.size() != models_.size()) { throw cms::Exception("Incorrect configuration") - << "'ModelNames' size (" << names_.size() - << ") != 'ModelWeights' size (" << models_.size() - << ").\n"; + << "'ModelNames' size (" << names_.size() << ") != 'ModelWeights' size (" << models_.size() << ").\n"; } - if ( models_.size() != thresholds_.size() ) { + if (models_.size() != thresholds_.size()) { throw cms::Exception("Incorrect configuration") - << "'ModelWeights' size (" << models_.size() - << ") != 'ModelThresholds' size (" << thresholds_.size() - << ").\n"; + << "'ModelWeights' size (" << models_.size() << ") != 'ModelThresholds' size (" << thresholds_.size() + << ").\n"; } - } //////////////////////////////////////////////////////////////////////////////// // - double HeavyObjectCache::eval( const std::string& name, - const reco::GsfElectronRef& ele, - double rho ) const - { - std::vector::const_iterator iter = std::find( names_.begin(), - names_.end(), - name ); - if ( iter != names_.end() ) { - int index = std::distance(names_.begin(),iter); + double HeavyObjectCache::eval(const std::string& name, const reco::GsfElectronRef& ele, double rho) const { + std::vector::const_iterator iter = std::find(names_.begin(), names_.end(), name); + if (iter != names_.end()) { + int index = std::distance(names_.begin(), iter); Features features; - features.set(ele,rho); + features.set(ele, rho); std::vector inputs = features.get(); - return models_.at(index)->GetResponse( inputs.data() ); + return models_.at(index)->GetResponse(inputs.data()); } else { throw cms::Exception("Unknown model name") - << "'Name given: '" << name - << "'. Check against configuration file.\n"; + << "'Name given: '" << name << "'. Check against configuration file.\n"; } return 0.; } -} // namespace lowptgsfeleid +} // namespace lowptgsfeleid diff --git a/RecoEgamma/EgammaElectronProducers/src/LowPtGsfElectronSeedHeavyObjectCache.cc b/RecoEgamma/EgammaElectronProducers/src/LowPtGsfElectronSeedHeavyObjectCache.cc index 180c282d77ea9..24021cf865089 100644 --- a/RecoEgamma/EgammaElectronProducers/src/LowPtGsfElectronSeedHeavyObjectCache.cc +++ b/RecoEgamma/EgammaElectronProducers/src/LowPtGsfElectronSeedHeavyObjectCache.cc @@ -15,47 +15,44 @@ namespace lowptgsfeleseed { //////////////////////////////////////////////////////////////////////////////// // std::vector Features::get() { - std::vector output = { - trk_pt_, - trk_eta_, - trk_phi_, - trk_p_, - trk_nhits_, - trk_high_quality_, - trk_chi2red_, - rho_, - ktf_ecal_cluster_e_, - ktf_ecal_cluster_deta_, - ktf_ecal_cluster_dphi_, - ktf_ecal_cluster_e3x3_, - ktf_ecal_cluster_e5x5_, - ktf_ecal_cluster_covEtaEta_, - ktf_ecal_cluster_covEtaPhi_, - ktf_ecal_cluster_covPhiPhi_, - ktf_ecal_cluster_r9_, - ktf_ecal_cluster_circularity_, - ktf_hcal_cluster_e_, - ktf_hcal_cluster_deta_, - ktf_hcal_cluster_dphi_, - preid_gsf_dpt_, - preid_trk_gsf_chiratio_, - preid_gsf_chi2red_, - trk_dxy_sig_ - }; + std::vector output = {trk_pt_, + trk_eta_, + trk_phi_, + trk_p_, + trk_nhits_, + trk_high_quality_, + trk_chi2red_, + rho_, + ktf_ecal_cluster_e_, + ktf_ecal_cluster_deta_, + ktf_ecal_cluster_dphi_, + ktf_ecal_cluster_e3x3_, + ktf_ecal_cluster_e5x5_, + ktf_ecal_cluster_covEtaEta_, + ktf_ecal_cluster_covEtaPhi_, + ktf_ecal_cluster_covPhiPhi_, + ktf_ecal_cluster_r9_, + ktf_ecal_cluster_circularity_, + ktf_hcal_cluster_e_, + ktf_hcal_cluster_deta_, + ktf_hcal_cluster_dphi_, + preid_gsf_dpt_, + preid_trk_gsf_chiratio_, + preid_gsf_chi2red_, + trk_dxy_sig_}; return output; } - + //////////////////////////////////////////////////////////////////////////////// // - void Features::set( const reco::PreId& ecal, - const reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& tools ) { - + void Features::set(const reco::PreId& ecal, + const reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& tools) { // Tracks reco::TrackRef trk = ecal.trackRef(); - if ( trk.isNonnull() ) { + if (trk.isNonnull()) { trk_pt_ = trk->pt(); trk_eta_ = trk->eta(); trk_phi_ = trk->phi(); @@ -63,18 +60,18 @@ namespace lowptgsfeleseed { trk_nhits_ = static_cast(trk->found()); trk_high_quality_ = static_cast(trk->quality(reco::TrackBase::qualityByName("highPurity"))); trk_chi2red_ = trk->normalizedChi2(); - if ( trk->dxy(spot) > 0. ) { - trk_dxy_sig_ = trk->dxyError() / trk->dxy(spot); //@@ to be consistent with the training based on 94X MC + if (trk->dxy(spot) > 0.) { + trk_dxy_sig_ = trk->dxyError() / trk->dxy(spot); //@@ to be consistent with the training based on 94X MC } - ktf_ecal_cluster_dphi_ *= trk->charge(); //@@ to be consistent with the training based on 94X MC + ktf_ecal_cluster_dphi_ *= trk->charge(); //@@ to be consistent with the training based on 94X MC } - + // Rho rho_ = static_cast(rho); - + // ECAL clusters reco::PFClusterRef ecal_clu = ecal.clusterRef(); - if ( ecal_clu.isNonnull() ) { + if (ecal_clu.isNonnull()) { ktf_ecal_cluster_e_ = ecal_clu->energy(); ktf_ecal_cluster_deta_ = ecal.geomMatching()[0]; ktf_ecal_cluster_dphi_ = ecal.geomMatching()[1]; @@ -84,19 +81,19 @@ namespace lowptgsfeleseed { ktf_ecal_cluster_covEtaEta_ = covs[0]; ktf_ecal_cluster_covEtaPhi_ = covs[1]; ktf_ecal_cluster_covPhiPhi_ = covs[2]; - if ( ktf_ecal_cluster_e_ > 0. ) { - ktf_ecal_cluster_r9_ = ktf_ecal_cluster_e3x3_ / ktf_ecal_cluster_e_; + if (ktf_ecal_cluster_e_ > 0.) { + ktf_ecal_cluster_r9_ = ktf_ecal_cluster_e3x3_ / ktf_ecal_cluster_e_; } - if ( ktf_ecal_cluster_e5x5_ > 0. ) { - ktf_ecal_cluster_circularity_ = 1. - tools.e1x5(*ecal_clu) / ktf_ecal_cluster_e5x5_; + if (ktf_ecal_cluster_e5x5_ > 0.) { + ktf_ecal_cluster_circularity_ = 1. - tools.e1x5(*ecal_clu) / ktf_ecal_cluster_e5x5_; } else { - ktf_ecal_cluster_circularity_ = -0.1; + ktf_ecal_cluster_circularity_ = -0.1; } } - + // HCAL clusters reco::PFClusterRef hcal_clu = hcal.clusterRef(); - if ( hcal_clu.isNonnull() ) { + if (hcal_clu.isNonnull()) { ktf_hcal_cluster_e_ = hcal_clu->energy(); ktf_hcal_cluster_deta_ = hcal.geomMatching()[0]; ktf_hcal_cluster_dphi_ = hcal.geomMatching()[1]; @@ -106,65 +103,53 @@ namespace lowptgsfeleseed { preid_gsf_dpt_ = ecal.dpt(); preid_trk_gsf_chiratio_ = ecal.chi2Ratio(); preid_gsf_chi2red_ = ecal.gsfChi2(); - }; //////////////////////////////////////////////////////////////////////////////// // - HeavyObjectCache::HeavyObjectCache( const edm::ParameterSet& conf ) { - for ( auto& name : conf.getParameter< std::vector >("ModelNames") ) - { - names_.push_back(name); - } - for ( auto& weights : conf.getParameter< std::vector >("ModelWeights") ) - { - models_.push_back(createGBRForest(edm::FileInPath(weights))); - } - for ( auto& thresh : conf.getParameter< std::vector >("ModelThresholds") ) - { - thresholds_.push_back(thresh); - } - if ( names_.size() != models_.size() ) { + HeavyObjectCache::HeavyObjectCache(const edm::ParameterSet& conf) { + for (auto& name : conf.getParameter >("ModelNames")) { + names_.push_back(name); + } + for (auto& weights : conf.getParameter >("ModelWeights")) { + models_.push_back(createGBRForest(edm::FileInPath(weights))); + } + for (auto& thresh : conf.getParameter >("ModelThresholds")) { + thresholds_.push_back(thresh); + } + if (names_.size() != models_.size()) { throw cms::Exception("Incorrect configuration") - << "'ModelNames' size (" << names_.size() - << ") != 'ModelWeights' size (" << models_.size() - << ").\n"; + << "'ModelNames' size (" << names_.size() << ") != 'ModelWeights' size (" << models_.size() << ").\n"; } - if ( models_.size() != thresholds_.size() ) { + if (models_.size() != thresholds_.size()) { throw cms::Exception("Incorrect configuration") - << "'ModelWeights' size (" << models_.size() - << ") != 'ModelThresholds' size (" << thresholds_.size() - << ").\n"; + << "'ModelWeights' size (" << models_.size() << ") != 'ModelThresholds' size (" << thresholds_.size() + << ").\n"; } - } //////////////////////////////////////////////////////////////////////////////// // - bool HeavyObjectCache::eval( const std::string& name, - reco::PreId& ecal, - reco::PreId& hcal, - double rho, - const reco::BeamSpot& spot, - noZS::EcalClusterLazyTools& ecalTools ) const - { - std::vector::const_iterator iter = std::find( names_.begin(), - names_.end(), - name ); - if ( iter != names_.end() ) { - int index = std::distance(names_.begin(),iter); + bool HeavyObjectCache::eval(const std::string& name, + reco::PreId& ecal, + reco::PreId& hcal, + double rho, + const reco::BeamSpot& spot, + noZS::EcalClusterLazyTools& ecalTools) const { + std::vector::const_iterator iter = std::find(names_.begin(), names_.end(), name); + if (iter != names_.end()) { + int index = std::distance(names_.begin(), iter); Features features; - features.set(ecal,hcal,rho,spot,ecalTools); + features.set(ecal, hcal, rho, spot, ecalTools); std::vector inputs = features.get(); - float output = models_.at(index)->GetResponse( inputs.data() ); + float output = models_.at(index)->GetResponse(inputs.data()); bool pass = output > thresholds_.at(index); - ecal.setMVA(pass,output,index); + ecal.setMVA(pass, output, index); return pass; } else { throw cms::Exception("Unknown model name") - << "'Name given: '" << name - << "'. Check against configuration file.\n"; + << "'Name given: '" << name << "'. Check against configuration file.\n"; } } -} // namespace lowptgsfeleseed +} // namespace lowptgsfeleseed diff --git a/RecoEgamma/EgammaElectronProducers/test/GEDValueMapAnalyzer.cc b/RecoEgamma/EgammaElectronProducers/test/GEDValueMapAnalyzer.cc index 8a944bff80f48..23527a8f65c96 100644 --- a/RecoEgamma/EgammaElectronProducers/test/GEDValueMapAnalyzer.cc +++ b/RecoEgamma/EgammaElectronProducers/test/GEDValueMapAnalyzer.cc @@ -10,68 +10,63 @@ #include -class GEDValueMapAnalyzer : public edm::EDAnalyzer -{ -public: +class GEDValueMapAnalyzer : public edm::EDAnalyzer { +public: GEDValueMapAnalyzer(const edm::ParameterSet&); ~GEDValueMapAnalyzer(); virtual void beginRun(edm::Run const&, edm::EventSetup const&); - virtual void analyze(const edm::Event & iEvent,const edm::EventSetup & c); + virtual void analyze(const edm::Event& iEvent, const edm::EventSetup& c); private: edm::InputTag inputTagValueMapElectrons_; edm::InputTag inputTagPFCandidates_; - }; GEDValueMapAnalyzer::GEDValueMapAnalyzer(const edm::ParameterSet& iConfig) { inputTagPFCandidates_ = iConfig.getParameter("PFCandidates"); - inputTagValueMapElectrons_ = iConfig.getParameter("ElectronValueMap"); + inputTagValueMapElectrons_ = iConfig.getParameter("ElectronValueMap"); } -GEDValueMapAnalyzer::~GEDValueMapAnalyzer() {;} +GEDValueMapAnalyzer::~GEDValueMapAnalyzer() { ; } -void GEDValueMapAnalyzer::beginRun(edm::Run const&, edm::EventSetup const& ){;} +void GEDValueMapAnalyzer::beginRun(edm::Run const&, edm::EventSetup const&) { ; } - -void GEDValueMapAnalyzer::analyze(const edm::Event & iEvent,const edm::EventSetup & c) { +void GEDValueMapAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& c) { edm::Handle pfCandidatesH; - bool found=iEvent.getByLabel(inputTagPFCandidates_,pfCandidatesH); - if(!found ) { + bool found = iEvent.getByLabel(inputTagPFCandidates_, pfCandidatesH); + if (!found) { std::ostringstream err; - err<<" cannot get PFCandidates: " - < > electronValMapH; - found = iEvent.getByLabel(inputTagValueMapElectrons_,electronValMapH); - const edm::ValueMap & myElectronValMap(*electronValMapH); - - std::cout << " Read Electron Value Map " << myElectronValMap.size() << std::endl; + found = iEvent.getByLabel(inputTagValueMapElectrons_, electronValMapH); + const edm::ValueMap& myElectronValMap(*electronValMapH); + std::cout << " Read Electron Value Map " << myElectronValMap.size() << std::endl; - unsigned ncandidates=pfCandidatesH->size(); - for(unsigned ic=0 ; ic < ncandidates ; ++ic) { + unsigned ncandidates = pfCandidatesH->size(); + for (unsigned ic = 0; ic < ncandidates; ++ic) { // check if it has a GsfTrack - const reco::PFCandidate & cand((*pfCandidatesH)[ic]); - if(!cand.gsfTrackRef().isNonnull()) continue; - - reco::PFCandidateRef pfRef(pfCandidatesH,ic); + const reco::PFCandidate& cand((*pfCandidatesH)[ic]); + if (!cand.gsfTrackRef().isNonnull()) + continue; + + reco::PFCandidateRef pfRef(pfCandidatesH, ic); // get the GsfElectronRef from the ValueMap - reco::GsfElectronRef gsfRef=myElectronValMap[pfRef]; - + reco::GsfElectronRef gsfRef = myElectronValMap[pfRef]; + //basic check - std::cout << " Comparing GsfTrackRef from GsfElectron and PFCandidate " ; - if(gsfRef->gsfTrack()==cand.gsfTrackRef()) std::cout << " OK " << std::endl; + std::cout << " Comparing GsfTrackRef from GsfElectron and PFCandidate "; + if (gsfRef->gsfTrack() == cand.gsfTrackRef()) + std::cout << " OK " << std::endl; else std::cout << " Problem different Ref" << std::endl; } - } - DEFINE_FWK_MODULE(GEDValueMapAnalyzer); diff --git a/RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h b/RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h index d5eb698820316..8868a01b849ac 100644 --- a/RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h +++ b/RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h @@ -5,7 +5,6 @@ #include "SimDataFormats/Vertex/interface/SimVertex.h" #include "SimDataFormats/Vertex/interface/SimVertexContainer.h" - #include #include #include @@ -17,32 +16,19 @@ * */ - class PhotonMCTruth; class PhotonMCTruthFinder { public: + PhotonMCTruthFinder(); + virtual ~PhotonMCTruthFinder() {} - PhotonMCTruthFinder(); - virtual ~PhotonMCTruthFinder() { } - - - std::vector find( const std::vector& simTracks, const std::vector& simVertices); - - void clear() {geantToIndex_.clear();} - - - private: + std::vector find(const std::vector& simTracks, const std::vector& simVertices); + void clear() { geantToIndex_.clear(); } - - void fill( const std::vector& theSimTracks, const std::vector& theSimVertices); - std::map geantToIndex_; - - - - +private: + void fill(const std::vector& theSimTracks, const std::vector& theSimVertices); + std::map geantToIndex_; }; - #endif - diff --git a/RecoEgamma/EgammaMCTools/interface/PizeroMCTruth.h b/RecoEgamma/EgammaMCTools/interface/PizeroMCTruth.h index 21e888188b4b9..882d3b288e11c 100644 --- a/RecoEgamma/EgammaMCTools/interface/PizeroMCTruth.h +++ b/RecoEgamma/EgammaMCTools/interface/PizeroMCTruth.h @@ -8,8 +8,6 @@ #include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruth.h" #include - - /** \class PizeroMCTruth * * This class stores all the MC truth information needed about the @@ -19,29 +17,20 @@ */ class PizeroMCTruth { - - public: - PizeroMCTruth(); - PizeroMCTruth( const CLHEP::HepLorentzVector& pizMom, - std::vector& photons, - const CLHEP::HepLorentzVector& pV); - - - - CLHEP::HepLorentzVector fourMomentum() const {return thePizero_;} - CLHEP::HepLorentzVector primaryVertex() const {return thePrimaryVertex_;} - std::vector photons() const { return thePhotons_;} - - - - private: - CLHEP::HepLorentzVector thePizero_; - std::vector thePhotons_; - CLHEP::HepLorentzVector thePrimaryVertex_; - - - - +public: + PizeroMCTruth(); + PizeroMCTruth(const CLHEP::HepLorentzVector& pizMom, + std::vector& photons, + const CLHEP::HepLorentzVector& pV); + + CLHEP::HepLorentzVector fourMomentum() const { return thePizero_; } + CLHEP::HepLorentzVector primaryVertex() const { return thePrimaryVertex_; } + std::vector photons() const { return thePhotons_; } + +private: + CLHEP::HepLorentzVector thePizero_; + std::vector thePhotons_; + CLHEP::HepLorentzVector thePrimaryVertex_; }; #endif diff --git a/RecoEgamma/EgammaMCTools/interface/PizeroMCTruthFinder.h b/RecoEgamma/EgammaMCTools/interface/PizeroMCTruthFinder.h index 0d4e6df94119d..f04a89227f133 100644 --- a/RecoEgamma/EgammaMCTools/interface/PizeroMCTruthFinder.h +++ b/RecoEgamma/EgammaMCTools/interface/PizeroMCTruthFinder.h @@ -1,36 +1,31 @@ #ifndef PizeroMCTruthFinder_h #define PizeroMCTruthFinder_h -#include "SimDataFormats/Track/interface/SimTrack.h" -#include "SimDataFormats/Track/interface/SimTrackContainer.h" -#include "SimDataFormats/Vertex/interface/SimVertex.h" -#include "SimDataFormats/Vertex/interface/SimVertexContainer.h" +#include "SimDataFormats/Track/interface/SimTrack.h" +#include "SimDataFormats/Track/interface/SimTrackContainer.h" +#include "SimDataFormats/Vertex/interface/SimVertex.h" +#include "SimDataFormats/Vertex/interface/SimVertexContainer.h" #include "RecoEgamma/EgammaMCTools/interface/PizeroMCTruth.h" #include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruth.h" #include "RecoEgamma/EgammaMCTools/interface/ElectronMCTruth.h" - class PhotonMCTruthFinder; class ElectronMCTruthFinder; class PizeroMCTruthFinder { +public: + PizeroMCTruthFinder(); - public: - - PizeroMCTruthFinder(); - - virtual ~PizeroMCTruthFinder(); - - std::vector find(const std::vector& simTracks, const std::vector& simVertices); - - private: + virtual ~PizeroMCTruthFinder(); - void fill(const std::vector& theSimTracks, const std::vector& theSimVertices); + std::vector find(const std::vector& simTracks, const std::vector& simVertices); - std::map geantToIndex_; - PhotonMCTruthFinder* thePhotonMCTruthFinder_; - ElectronMCTruthFinder* theElectronMCTruthFinder_; +private: + void fill(const std::vector& theSimTracks, const std::vector& theSimVertices); + std::map geantToIndex_; + PhotonMCTruthFinder* thePhotonMCTruthFinder_; + ElectronMCTruthFinder* theElectronMCTruthFinder_; }; #endif diff --git a/RecoEgamma/EgammaMCTools/plugins/PFClusterMatchedToPhotonsSelector.cc b/RecoEgamma/EgammaMCTools/plugins/PFClusterMatchedToPhotonsSelector.cc index 9affb178b6460..62d0e8b0ccacb 100644 --- a/RecoEgamma/EgammaMCTools/plugins/PFClusterMatchedToPhotonsSelector.cc +++ b/RecoEgamma/EgammaMCTools/plugins/PFClusterMatchedToPhotonsSelector.cc @@ -2,7 +2,7 @@ // // Package: CommonTools/RecoAlgos // Class: PFClusterMatchedToPhotonsSelector -// +// /**\class PFClusterMatchedToPhotonsSelector PFClusterMatchedToPhotonsSelector.cc CommonTools/RecoAlgos/plugins/PFClusterMatchedToPhotonsSelector.cc Description: Matches ECAL PF clusters to photons that do not convert @@ -16,7 +16,6 @@ // // - // system include files #include #include @@ -39,19 +38,17 @@ #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h" typedef reco::PFCluster::EEtoPSAssociation::value_type EEPSPair; -bool sortByKey(const EEPSPair& a, const EEPSPair& b) { - return a.first < b.first; -} +bool sortByKey(const EEPSPair& a, const EEPSPair& b) { return a.first < b.first; } class PFClusterMatchedToPhotonsSelector : public edm::stream::EDProducer<> { public: PFClusterMatchedToPhotonsSelector(const edm::ParameterSet&); static void fillDescriptions(edm::ConfigurationDescriptions&); - + private: void produce(edm::Event&, const edm::EventSetup&) override; - edm::EDGetTokenT genParticleToken_; // genParticles + edm::EDGetTokenT genParticleToken_; // genParticles edm::EDGetTokenT particleFlowClusterECALToken_; edm::EDGetTokenT associationToken_; edm::EDGetTokenT trackingParticleToken_; @@ -65,57 +62,58 @@ class PFClusterMatchedToPhotonsSelector : public edm::stream::EDProducer<> { PFClusterMatchedToPhotonsSelector::PFClusterMatchedToPhotonsSelector(const edm::ParameterSet& iConfig) { //now do what ever initialization is needed - particleFlowClusterECALToken_ = consumes(iConfig.getParameter("pfClustersTag")); - associationToken_ = consumes(iConfig.getParameter("pfClustersTag")); - trackingParticleToken_ = consumes(iConfig.getParameter("trackingParticleTag")); + particleFlowClusterECALToken_ = + consumes(iConfig.getParameter("pfClustersTag")); + associationToken_ = + consumes(iConfig.getParameter("pfClustersTag")); + trackingParticleToken_ = + consumes(iConfig.getParameter("trackingParticleTag")); genParticleToken_ = consumes(iConfig.getParameter("genParticleTag")); - matchMaxDR2_ = iConfig.getParameter("maxDR2"); - matchMaxDEDR2_ = iConfig.getParameter("maxDEDR2"); - volumeZ_EB_ = iConfig.getParameter("volumeZ_EB"); + matchMaxDR2_ = iConfig.getParameter("maxDR2"); + matchMaxDEDR2_ = iConfig.getParameter("maxDEDR2"); + volumeZ_EB_ = iConfig.getParameter("volumeZ_EB"); volumeRadius_EB_ = iConfig.getParameter("volumeRadius_EB"); - volumeZ_EE_ = iConfig.getParameter("volumeZ_EE"); + volumeZ_EE_ = iConfig.getParameter("volumeZ_EE"); produces(); produces(); produces >(); } - void PFClusterMatchedToPhotonsSelector::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add("pfClustersTag", edm::InputTag("particleFlowClusterECAL")); desc.add("trackingParticleTag", edm::InputTag("mix", "MergedTrackTruth")); desc.add("genParticleTag", edm::InputTag("genParticles")); - desc.add("maxDR2", 0.1*0.1); - desc.add("maxDEDR2", 0.5*0.5); + desc.add("maxDR2", 0.1 * 0.1); + desc.add("maxDEDR2", 0.5 * 0.5); desc.add("volumeZ_EB", 304.5); desc.add("volumeRadius_EB", 123.8); desc.add("volumeZ_EE", 317.0); descriptions.add("pfClusterMatchedToPhotonsSelector", desc); - } void PFClusterMatchedToPhotonsSelector::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { - edm::Handle particleFlowClusterECALHandle_; edm::Handle associationHandle_; edm::Handle trackingParticleHandle_; edm::Handle genParticleHandle_; iEvent.getByToken(particleFlowClusterECALToken_, particleFlowClusterECALHandle_); - iEvent.getByToken(trackingParticleToken_, trackingParticleHandle_); - iEvent.getByToken(genParticleToken_, genParticleHandle_); - iEvent.getByToken(associationToken_, associationHandle_); + iEvent.getByToken(trackingParticleToken_, trackingParticleHandle_); + iEvent.getByToken(genParticleToken_, genParticleHandle_); + iEvent.getByToken(associationToken_, associationHandle_); - std::unique_ptr out = std::make_unique(); - std::unique_ptr association_out = std::make_unique(); - std::unique_ptr > genmatching_out = std::make_unique >(); + std::unique_ptr out = std::make_unique(); + std::unique_ptr association_out = + std::make_unique(); + std::unique_ptr > genmatching_out = + std::make_unique >(); std::vector genmatching; - size_t iN(0); + size_t iN(0); for (size_t iP = 0; iP < particleFlowClusterECALHandle_->size(); iP++) { - auto&& pfCluster = particleFlowClusterECALHandle_->at(iP); bool isMatched = false; reco::GenParticleRef::key_type matchedKey; @@ -126,44 +124,53 @@ void PFClusterMatchedToPhotonsSelector::produce(edm::Event& iEvent, const edm::E } for (auto&& trackingParticle : *trackingParticleHandle_) { - if (trackingParticle.pdgId() != 22) continue; - if (trackingParticle.status() != 1) continue; + if (trackingParticle.pdgId() != 22) + continue; + if (trackingParticle.status() != 1) + continue; matchedKey = trackingParticle.genParticles().at(0).key(); float dR2 = reco::deltaR2(trackingParticle, pfCluster.position()); - if (dR2 > matchMaxDR2_) continue; - float dE = 1. - trackingParticle.genParticles().at(0)->energy()/pfCluster.energy(); - if ((dR2 + dE*dE) > matchMaxDEDR2_) continue; + if (dR2 > matchMaxDR2_) + continue; + float dE = 1. - trackingParticle.genParticles().at(0)->energy() / pfCluster.energy(); + if ((dR2 + dE * dE) > matchMaxDEDR2_) + continue; bool isConversion = false; for (auto&& vertRef : trackingParticle.decayVertices()) { - if (vertRef->position().rho() > volumeRadius_EB_ && std::abs(vertRef->position().z()) < volumeZ_EB_) continue; - if (std::abs(vertRef->position().z()) > volumeZ_EE_) continue; - - for(auto&& tpRef: vertRef->daughterTracks()) { - if(std::abs(tpRef->pdgId()) == 11) isConversion = true; - break; - } - if (isConversion) break; - } - if (isConversion) continue; - - isMatched = true; + if (vertRef->position().rho() > volumeRadius_EB_ && std::abs(vertRef->position().z()) < volumeZ_EB_) + continue; + if (std::abs(vertRef->position().z()) > volumeZ_EE_) + continue; + + for (auto&& tpRef : vertRef->daughterTracks()) { + if (std::abs(tpRef->pdgId()) == 11) + isConversion = true; + break; + } + if (isConversion) + break; + } + if (isConversion) + continue; + + isMatched = true; break; } if (isMatched) { out->push_back(pfCluster); - for (size_t i=0; isize(); i++) { - if (associationHandle_.product()->at(i).first == iP) { - association_out->push_back(std::make_pair(iN, associationHandle_.product()->at(i).second)); - } + for (size_t i = 0; i < associationHandle_.product()->size(); i++) { + if (associationHandle_.product()->at(i).first == iP) { + association_out->push_back(std::make_pair(iN, associationHandle_.product()->at(i).second)); + } } - genmatching.push_back(edm::Ref(genParticleHandle_,matchedKey)); + genmatching.push_back(edm::Ref(genParticleHandle_, matchedKey)); } } - std::sort(association_out->begin(),association_out->end(),sortByKey); - edm::OrphanHandle pfClusterHandle= iEvent.put(std::move(out)); + std::sort(association_out->begin(), association_out->end(), sortByKey); + edm::OrphanHandle pfClusterHandle = iEvent.put(std::move(out)); iEvent.put(std::move(association_out)); edm::ValueMap::Filler mapFiller(*genmatching_out); @@ -171,6 +178,6 @@ void PFClusterMatchedToPhotonsSelector::produce(edm::Event& iEvent, const edm::E mapFiller.fill(); iEvent.put(std::move(genmatching_out)); } - + //define this as a plug-in DEFINE_FWK_MODULE(PFClusterMatchedToPhotonsSelector); diff --git a/RecoEgamma/EgammaMCTools/src/PhotonMCTruth.cc b/RecoEgamma/EgammaMCTools/src/PhotonMCTruth.cc index eb442d56f1624..a71df4d0773f6 100644 --- a/RecoEgamma/EgammaMCTools/src/PhotonMCTruth.cc +++ b/RecoEgamma/EgammaMCTools/src/PhotonMCTruth.cc @@ -4,31 +4,23 @@ #include - PhotonMCTruth::PhotonMCTruth(int isAConversion, - CLHEP::HepLorentzVector phoMom, - int vertIndex, + CLHEP::HepLorentzVector phoMom, + int vertIndex, int trackId, int motherId, - CLHEP::HepLorentzVector mothMom, - CLHEP::HepLorentzVector mothVtx, - CLHEP::HepLorentzVector convVertex, - CLHEP::HepLorentzVector pV, - std::vector& electrons ) : - isAConversion_(isAConversion), - thePhoton_(phoMom), - theVertexIndex_(vertIndex), - theTrackId_(trackId), - theMotherId_(motherId), - theMotherMom_(mothMom), - theMotherVtx_(mothVtx), - theConvVertex_(convVertex), - thePrimaryVertex_(pV), - theElectrons_(electrons) { - - -} - - - - + CLHEP::HepLorentzVector mothMom, + CLHEP::HepLorentzVector mothVtx, + CLHEP::HepLorentzVector convVertex, + CLHEP::HepLorentzVector pV, + std::vector& electrons) + : isAConversion_(isAConversion), + thePhoton_(phoMom), + theVertexIndex_(vertIndex), + theTrackId_(trackId), + theMotherId_(motherId), + theMotherMom_(mothMom), + theMotherVtx_(mothVtx), + theConvVertex_(convVertex), + thePrimaryVertex_(pV), + theElectrons_(electrons) {} diff --git a/RecoEgamma/EgammaMCTools/src/PizeroMCTruth.cc b/RecoEgamma/EgammaMCTools/src/PizeroMCTruth.cc index f490956010fe4..e42a737dce8b0 100644 --- a/RecoEgamma/EgammaMCTools/src/PizeroMCTruth.cc +++ b/RecoEgamma/EgammaMCTools/src/PizeroMCTruth.cc @@ -2,21 +2,15 @@ #include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruth.h" #include "RecoEgamma/EgammaMCTools/interface/ElectronMCTruth.h" - #include -PizeroMCTruth::PizeroMCTruth() { - -} - - -PizeroMCTruth::PizeroMCTruth( const CLHEP::HepLorentzVector& pizeroFourMomentum, - std::vector& photons, - const CLHEP::HepLorentzVector& pV): - - thePizero_(pizeroFourMomentum), thePhotons_(photons), thePrimaryVertex_(pV) {} - - +PizeroMCTruth::PizeroMCTruth() {} +PizeroMCTruth::PizeroMCTruth(const CLHEP::HepLorentzVector& pizeroFourMomentum, + std::vector& photons, + const CLHEP::HepLorentzVector& pV) + : - + thePizero_(pizeroFourMomentum), + thePhotons_(photons), + thePrimaryVertex_(pV) {} diff --git a/RecoEgamma/EgammaMCTools/src/PizeroMCTruthFinder.cc b/RecoEgamma/EgammaMCTools/src/PizeroMCTruthFinder.cc index 771eecc2bee66..7199c233a66dd 100644 --- a/RecoEgamma/EgammaMCTools/src/PizeroMCTruthFinder.cc +++ b/RecoEgamma/EgammaMCTools/src/PizeroMCTruthFinder.cc @@ -2,119 +2,107 @@ #include "RecoEgamma/EgammaMCTools/interface/PhotonMCTruthFinder.h" #include "RecoEgamma/EgammaMCTools/interface/ElectronMCTruthFinder.h" - -#include +#include PizeroMCTruthFinder::PizeroMCTruthFinder() { - thePhotonMCTruthFinder_ = new PhotonMCTruthFinder(); theElectronMCTruthFinder_ = new ElectronMCTruthFinder(); - - } -PizeroMCTruthFinder::~PizeroMCTruthFinder() -{ - +PizeroMCTruthFinder::~PizeroMCTruthFinder() { delete thePhotonMCTruthFinder_; delete theElectronMCTruthFinder_; std::cout << "~PizeroMCTruthFinder" << std::endl; } -std::vector PizeroMCTruthFinder::find(const std::vector& theSimTracks, const std::vector& theSimVertices ) { +std::vector PizeroMCTruthFinder::find(const std::vector& theSimTracks, + const std::vector& theSimVertices) { std::cout << " PizeroMCTruthFinder::find " << std::endl; - - std::vector mcPhotons=thePhotonMCTruthFinder_->find (theSimTracks, theSimVertices); + std::vector mcPhotons = thePhotonMCTruthFinder_->find(theSimTracks, theSimVertices); std::vector result; std::vector photonsFromPizero; std::vector electronsFromPizero; - // Local variables + // Local variables //const int SINGLE=1; //const int DOUBLE=2; //const int PYTHIA=3; //const int ELECTRON_FLAV=1; //const int PIZERO_FLAV=2; //const int PHOTON_FLAV=3; - + //int ievtype=0; //int ievflav=0; - + std::vector pizeroTracks; - SimVertex primVtx; - - - fill(theSimTracks, theSimVertices); - - int iPV=-1; + SimVertex primVtx; + + fill(theSimTracks, theSimVertices); + + int iPV = -1; //int partType1=0; //int partType2=0; std::vector::const_iterator iFirstSimTk = theSimTracks.begin(); - if ( !(*iFirstSimTk).noVertex() ) { - iPV = (*iFirstSimTk).vertIndex(); - - int vtxId = (*iFirstSimTk).vertIndex(); + if (!(*iFirstSimTk).noVertex()) { + iPV = (*iFirstSimTk).vertIndex(); + + int vtxId = (*iFirstSimTk).vertIndex(); primVtx = theSimVertices[vtxId]; - + //partType1 = (*iFirstSimTk).type(); - std::cout << " Primary vertex id " << iPV << " first track type " << (*iFirstSimTk).type() << std::endl; + std::cout << " Primary vertex id " << iPV << " first track type " << (*iFirstSimTk).type() << std::endl; } else { std::cout << " First track has no vertex " << std::endl; } - - // CLHEP::HepLorentzVector primVtxPos= primVtx.position(); - math::XYZTLorentzVectorD primVtxPos(primVtx.position().x(), - primVtx.position().y(), - primVtx.position().z(), - primVtx.position().e()); + + // CLHEP::HepLorentzVector primVtxPos= primVtx.position(); + math::XYZTLorentzVectorD primVtxPos( + primVtx.position().x(), primVtx.position().y(), primVtx.position().z(), primVtx.position().e()); // Look at a second track iFirstSimTk++; - if ( iFirstSimTk!= theSimTracks.end() ) { - - if ( (*iFirstSimTk).vertIndex() == iPV) { - //partType2 = (*iFirstSimTk).type(); - std::cout << " second track type " << (*iFirstSimTk).type() << " vertex " << (*iFirstSimTk).vertIndex() << std::endl; - + if (iFirstSimTk != theSimTracks.end()) { + if ((*iFirstSimTk).vertIndex() == iPV) { + //partType2 = (*iFirstSimTk).type(); + std::cout << " second track type " << (*iFirstSimTk).type() << " vertex " << (*iFirstSimTk).vertIndex() + << std::endl; + } else { std::cout << " Only one kine track from Primary Vertex " << std::endl; } } - - int npv=0; - - for (std::vector::const_iterator iSimTk = theSimTracks.begin(); iSimTk != theSimTracks.end(); ++iSimTk){ - if ( (*iSimTk).noVertex() ) continue; + + int npv = 0; + + for (std::vector::const_iterator iSimTk = theSimTracks.begin(); iSimTk != theSimTracks.end(); ++iSimTk) { + if ((*iSimTk).noVertex()) + continue; int vertexId = (*iSimTk).vertIndex(); SimVertex vertex = theSimVertices[vertexId]; - - std::cout << " Particle type " << (*iSimTk).type() << " Sim Track ID " << (*iSimTk).trackId() << " momentum " << (*iSimTk).momentum() << " vertex position " << vertex.position() << std::endl; - if ( (*iSimTk).vertIndex() == iPV ) { - npv++; - if ( std::abs((*iSimTk).type() ) == 111) { + std::cout << " Particle type " << (*iSimTk).type() << " Sim Track ID " << (*iSimTk).trackId() << " momentum " + << (*iSimTk).momentum() << " vertex position " << vertex.position() << std::endl; - std::cout << " Found a primary pizero with ID " << (*iSimTk).trackId() << " momentum " << (*iSimTk).momentum() << std::endl; - - pizeroTracks.push_back( *iSimTk ); - - // CLHEP::HepLorentzVector momentum = (*iSimTk).momentum(); - math::XYZTLorentzVectorD momentum((*iSimTk).momentum().x(), - (*iSimTk).momentum().y(), - (*iSimTk).momentum().z(), - (*iSimTk).momentum().e()); + if ((*iSimTk).vertIndex() == iPV) { + npv++; + if (std::abs((*iSimTk).type()) == 111) { + std::cout << " Found a primary pizero with ID " << (*iSimTk).trackId() << " momentum " << (*iSimTk).momentum() + << std::endl; + pizeroTracks.push_back(*iSimTk); - } + // CLHEP::HepLorentzVector momentum = (*iSimTk).momentum(); + math::XYZTLorentzVectorD momentum( + (*iSimTk).momentum().x(), (*iSimTk).momentum().y(), (*iSimTk).momentum().z(), (*iSimTk).momentum().e()); + } } } - - + std::cout << " There are " << npv << " particles originating in the PV " << std::endl; - + //if(npv > 4) { // ievtype = PYTHIA; //} else if(npv == 1) { @@ -135,64 +123,53 @@ std::vector PizeroMCTruthFinder::find(const std::vector // } //} + for (std::vector::iterator iPizTk = pizeroTracks.begin(); iPizTk != pizeroTracks.end(); ++iPizTk) { + std::cout << " Looping on the primary pizero pt " << sqrt((*iPizTk).momentum().perp2()) << " pizero track ID " + << (*iPizTk).trackId() << std::endl; - - for (std::vector::iterator iPizTk = pizeroTracks.begin(); iPizTk != pizeroTracks.end(); ++iPizTk){ - std::cout << " Looping on the primary pizero pt " << sqrt((*iPizTk).momentum().perp2()) << " pizero track ID " << (*iPizTk).trackId() << std::endl; - photonsFromPizero.clear(); std::cout << " mcPhotons.size " << mcPhotons.size() << std::endl; - for ( std::vector::iterator iPho=mcPhotons.begin(); iPho !=mcPhotons.end(); ++iPho ){ + for (std::vector::iterator iPho = mcPhotons.begin(); iPho != mcPhotons.end(); ++iPho) { int phoVtxIndex = (*iPho).vertexInd(); SimVertex phoVtx = theSimVertices[phoVtxIndex]; - unsigned int phoParentInd= phoVtx.parentIndex(); + unsigned int phoParentInd = phoVtx.parentIndex(); std::cout << " photon parent vertex index " << phoParentInd << std::endl; - - if (phoParentInd == (*iPizTk).trackId()) { - std::cout << "Matched Photon ID " << (*iPho).trackId() << " vtx " << phoParentInd << " with pizero " << (*iPizTk).trackId() << std::endl; - photonsFromPizero.push_back( *iPho); - + + if (phoParentInd == (*iPizTk).trackId()) { + std::cout << "Matched Photon ID " << (*iPho).trackId() << " vtx " << phoParentInd << " with pizero " + << (*iPizTk).trackId() << std::endl; + photonsFromPizero.push_back(*iPho); } } - std::cout << " Photon matching the pizero vertex " << photonsFromPizero.size() <& simTracks, - const std::vector& simVertices ) { - + } // end loop over primary pizeros -unsigned nVtx = simVertices.size(); -unsigned nTks = simTracks.size(); + std::cout << " Pizero size " << result.size() << std::endl; -// Empty event, do nothin' -if ( nVtx == 0 ) return; + return result; +} -// create a map associating geant particle id and position in the -// event SimTrack vector -for( unsigned it=0; it& simTracks, const std::vector& simVertices) { + unsigned nVtx = simVertices.size(); + unsigned nTks = simTracks.size(); + // Empty event, do nothin' + if (nVtx == 0) + return; + // create a map associating geant particle id and position in the + // event SimTrack vector + for (unsigned it = 0; it < nTks; ++it) { + geantToIndex_[simTracks[it].trackId()] = it; + std::cout << " PizeroMCTruthFinder::fill it " << it << " simTracks[it].trackId() " << simTracks[it].trackId() + << std::endl; + } } diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ConversionProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/ConversionProducer.h index 2592497811788..b8d6bd5fc1b81 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ConversionProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ConversionProducer.h @@ -42,13 +42,11 @@ #include "RecoVertex/KinematicFitPrimitives/interface/TransientTrackKinematicParticle.h" #include "RecoVertex/KinematicFit/interface/KinematicParticleVertexFitter.h" - //Tracker tracks #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/TrackReco/interface/Track.h" #include "TrackingTools/TransientTrack/interface/TransientTrack.h" - //photon data format #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" @@ -64,148 +62,135 @@ class TransientTrackBuilder; class ConversionVertexFinder; class ConversionProducer : public edm::stream::EDProducer<> { - public: - explicit ConversionProducer(const edm::ParameterSet&); - ~ConversionProducer() override; - - - - - private: - - void produce(edm::Event&, const edm::EventSetup&) override; - - void buildSuperAndBasicClusterGeoMap(const edm::Event&, - std::multimap& basicClusterPtrs, - std::multimap& superClusterPtrs); - - - // ----------member data --------------------------- - std::string algoName_; - - typedef math::XYZPointF Point; - typedef std::vector PointCollection; - - edm::EDGetTokenT > src_; - - edm::EDGetTokenT > scBarrelProducer_; - edm::EDGetTokenT > scEndcapProducer_; - edm::EDGetTokenT > bcBarrelCollection_; - edm::EDGetTokenT > bcEndcapCollection_; - std::string ConvertedPhotonCollection_; - - bool allowD0_, allowDeltaPhi_, allowTrackBC_, allowDeltaCot_, allowMinApproach_, allowOppCharge_, allowVertex_; - - bool bypassPreselGsf_, bypassPreselEcal_, bypassPreselEcalEcal_; - - bool usePvtx_;//if use primary vertices - edm::EDGetTokenT vertexProducer_; - ConversionVertexFinder* theVertexFinder_; - - const TransientTrackBuilder *thettbuilder_; - - double deltaEta_; - - double halfWayEta_, halfWayPhi_;//halfway open angle to search in basic clusters - unsigned int maxNumOfTrackInPU_; - double maxTrackZ_; - double maxTrackRho_; - double minSCEt_; - double dEtacutForSCmatching_; - double dPhicutForSCmatching_; - double energyBC_;//1.5GeV for track BC selection - double energyTotalBC_;//5GeV for track pair BC selection - double d0Cut_;//0 for d0*charge cut - double dzCut_;//innerposition of z diff cut - double dEtaTkBC_, dPhiTkBC_;//0.06 0.6 for track and BC matching - - double maxChi2Left_, maxChi2Right_;//5. 5. for track chi2 quality - double minHitsLeft_, minHitsRight_;//5 2 for track hits quality - - double deltaCotTheta_, deltaPhi_, minApproachLow_, minApproachHigh_;//0.02 0.2 for track pair open angle and > -0.1 cm - - - double r_cut;//cross_r cut - double vtxChi2_;//vertex chi2 probablity cut - - bool allowSingleLeg_;//if single track conversion ? - bool rightBC_;//if right leg requires matching BC? - - - void buildCollection( edm::Event& iEvent, const edm::EventSetup& iSetup, - const std::multimap >& allTracks, - const std::multimap& superClusterPtrs, - const std::multimap& basicClusterPtrs, - const reco::Vertex& the_pvtx, - reco::ConversionCollection & outputConvPhotonCollection); - - - //track quality cut, returns pass or no - inline bool trackQualityFilter(const edm::RefToBase& ref, bool isLeft); - inline bool trackD0Cut(const edm::RefToBase& ref); - inline bool trackD0Cut(const edm::RefToBase& ref, const reco::Vertex& the_pvtx); - - //track impact point at ECAL wall, returns validity to access position ew - bool getTrackImpactPosition(const reco::Track* tk_ref, - const TrackerGeometry* trackerGeom, const MagneticField* magField, - math::XYZPointF& ew); - - //distance at min approaching point, returns distance - // double getMinApproach(const edm::RefToBase& ll, const edm::RefToBase& rr, - // const MagneticField* magField); - - bool preselectTrackPair(const reco::TransientTrack &ttk_l, const reco::TransientTrack &ttk_r, - double& appDist); - - //cut-based selection, TODO remove global cut variables - bool checkTrackPair(const std::pair, reco::CaloClusterPtr>& ll, - const std::pair, reco::CaloClusterPtr>& rr); - - //kinematic vertex fitting, return true for valid vertex - bool checkVertex(const reco::TransientTrack &ttk_l, const reco::TransientTrack &ttk_r, - const MagneticField* magField, - reco::Vertex& the_vertex); - bool checkPhi(const edm::RefToBase& tk_l, const edm::RefToBase& tk_r, - const TrackerGeometry* trackerGeom, const MagneticField* magField, - const reco::Vertex& the_vertex); - - //check the closest BC, returns true for found a BC - bool getMatchedBC(const std::multimap& bcMap, - const math::XYZPointF& trackImpactPosition, - reco::CaloClusterPtr& closestBC); - - // finds the super cluster matching with at least one track in the pair - bool matchingSC(const std::multimap& scMap, - reco::Conversion& conv, - reco::CaloClusterPtrVector& mSC); - - - - double etaTransformation( float EtaParticle , float Zvertex); - - - math::XYZPointF toFConverterP( const math::XYZPoint &val) { - return math::XYZPointF(val.x(),val.y(),val.z()); - } - - math::XYZVectorF toFConverterV( const math::XYZVector &val) { - return math::XYZVectorF(val.x(),val.y(),val.z()); - } - +public: + explicit ConversionProducer(const edm::ParameterSet&); + ~ConversionProducer() override; + +private: + void produce(edm::Event&, const edm::EventSetup&) override; + + void buildSuperAndBasicClusterGeoMap(const edm::Event&, + std::multimap& basicClusterPtrs, + std::multimap& superClusterPtrs); + + // ----------member data --------------------------- + std::string algoName_; + + typedef math::XYZPointF Point; + typedef std::vector PointCollection; + + edm::EDGetTokenT > src_; + + edm::EDGetTokenT > scBarrelProducer_; + edm::EDGetTokenT > scEndcapProducer_; + edm::EDGetTokenT > bcBarrelCollection_; + edm::EDGetTokenT > bcEndcapCollection_; + std::string ConvertedPhotonCollection_; + + bool allowD0_, allowDeltaPhi_, allowTrackBC_, allowDeltaCot_, allowMinApproach_, allowOppCharge_, allowVertex_; + + bool bypassPreselGsf_, bypassPreselEcal_, bypassPreselEcalEcal_; + + bool usePvtx_; //if use primary vertices + edm::EDGetTokenT vertexProducer_; + ConversionVertexFinder* theVertexFinder_; + + const TransientTrackBuilder* thettbuilder_; + + double deltaEta_; + + double halfWayEta_, halfWayPhi_; //halfway open angle to search in basic clusters + unsigned int maxNumOfTrackInPU_; + double maxTrackZ_; + double maxTrackRho_; + double minSCEt_; + double dEtacutForSCmatching_; + double dPhicutForSCmatching_; + double energyBC_; //1.5GeV for track BC selection + double energyTotalBC_; //5GeV for track pair BC selection + double d0Cut_; //0 for d0*charge cut + double dzCut_; //innerposition of z diff cut + double dEtaTkBC_, dPhiTkBC_; //0.06 0.6 for track and BC matching + + double maxChi2Left_, maxChi2Right_; //5. 5. for track chi2 quality + double minHitsLeft_, minHitsRight_; //5 2 for track hits quality + + double deltaCotTheta_, deltaPhi_, minApproachLow_, + minApproachHigh_; //0.02 0.2 for track pair open angle and > -0.1 cm + + double r_cut; //cross_r cut + double vtxChi2_; //vertex chi2 probablity cut + + bool allowSingleLeg_; //if single track conversion ? + bool rightBC_; //if right leg requires matching BC? + + void buildCollection(edm::Event& iEvent, + const edm::EventSetup& iSetup, + const std::multimap >& allTracks, + const std::multimap& superClusterPtrs, + const std::multimap& basicClusterPtrs, + const reco::Vertex& the_pvtx, + reco::ConversionCollection& outputConvPhotonCollection); + + //track quality cut, returns pass or no + inline bool trackQualityFilter(const edm::RefToBase& ref, bool isLeft); + inline bool trackD0Cut(const edm::RefToBase& ref); + inline bool trackD0Cut(const edm::RefToBase& ref, const reco::Vertex& the_pvtx); + + //track impact point at ECAL wall, returns validity to access position ew + bool getTrackImpactPosition(const reco::Track* tk_ref, + const TrackerGeometry* trackerGeom, + const MagneticField* magField, + math::XYZPointF& ew); + + //distance at min approaching point, returns distance + // double getMinApproach(const edm::RefToBase& ll, const edm::RefToBase& rr, + // const MagneticField* magField); + + bool preselectTrackPair(const reco::TransientTrack& ttk_l, const reco::TransientTrack& ttk_r, double& appDist); + + //cut-based selection, TODO remove global cut variables + bool checkTrackPair(const std::pair, reco::CaloClusterPtr>& ll, + const std::pair, reco::CaloClusterPtr>& rr); + + //kinematic vertex fitting, return true for valid vertex + bool checkVertex(const reco::TransientTrack& ttk_l, + const reco::TransientTrack& ttk_r, + const MagneticField* magField, + reco::Vertex& the_vertex); + bool checkPhi(const edm::RefToBase& tk_l, + const edm::RefToBase& tk_r, + const TrackerGeometry* trackerGeom, + const MagneticField* magField, + const reco::Vertex& the_vertex); + + //check the closest BC, returns true for found a BC + bool getMatchedBC(const std::multimap& bcMap, + const math::XYZPointF& trackImpactPosition, + reco::CaloClusterPtr& closestBC); + // finds the super cluster matching with at least one track in the pair + bool matchingSC(const std::multimap& scMap, + reco::Conversion& conv, + reco::CaloClusterPtrVector& mSC); + + double etaTransformation(float EtaParticle, float Zvertex); + + math::XYZPointF toFConverterP(const math::XYZPoint& val) { return math::XYZPointF(val.x(), val.y(), val.z()); } + + math::XYZVectorF toFConverterV(const math::XYZVector& val) { return math::XYZVectorF(val.x(), val.y(), val.z()); } }; - -inline const GeomDet * recHitDet( const TrackingRecHit & hit, const TrackingGeometry * geom ) { - return geom->idToDet( hit.geographicalId() ); +inline const GeomDet* recHitDet(const TrackingRecHit& hit, const TrackingGeometry* geom) { + return geom->idToDet(hit.geographicalId()); } -inline const BoundPlane & recHitSurface( const TrackingRecHit & hit, const TrackingGeometry * geom ) { - return recHitDet( hit, geom )->surface(); +inline const BoundPlane& recHitSurface(const TrackingRecHit& hit, const TrackingGeometry* geom) { + return recHitDet(hit, geom)->surface(); } -inline LocalVector toLocal( const reco::Track::Vector & v, const Surface & s ) { - return s.toLocal( GlobalVector( v.x(), v.y(), v.z() ) ); +inline LocalVector toLocal(const reco::Track::Vector& v, const Surface& s) { + return s.toLocal(GlobalVector(v.x(), v.y(), v.z())); } #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackCandidateProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackCandidateProducer.h index 724d5cb0d2219..ed2d0b683bf6c 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackCandidateProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackCandidateProducer.h @@ -36,29 +36,25 @@ class InOutConversionTrackFinder; // ConversionTrackCandidateProducer inherits from EDProducer, so it can be a module: class ConversionTrackCandidateProducer : public edm::stream::EDProducer<> { - - public: - - ConversionTrackCandidateProducer (const edm::ParameterSet& ps); +public: + ConversionTrackCandidateProducer(const edm::ParameterSet& ps); ~ConversionTrackCandidateProducer() override; - - void beginRun (edm::Run const&, edm::EventSetup const & es) final; - void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: + void beginRun(edm::Run const&, edm::EventSetup const& es) final; + void produce(edm::Event& evt, const edm::EventSetup& es) override; +private: int nEvt_; - - /// Initialize EventSetup objects at each event - void setEventSetup( const edm::EventSetup& es ) ; + + /// Initialize EventSetup objects at each event + void setEventSetup(const edm::EventSetup& es); std::string OutInTrackCandidateCollection_; std::string InOutTrackCandidateCollection_; - std::string OutInTrackSuperClusterAssociationCollection_; std::string InOutTrackSuperClusterAssociationCollection_; - + edm::EDGetTokenT > bcBarrelCollection_; edm::EDGetTokenT > bcEndcapCollection_; edm::EDGetTokenT > scHybridBarrelProducer_; @@ -67,17 +63,17 @@ class ConversionTrackCandidateProducer : public edm::stream::EDProducer<> { edm::EDGetTokenT barrelecalCollection_; edm::EDGetTokenT endcapecalCollection_; edm::EDGetTokenT measurementTrkEvtToken_; - + double hOverEConeSize_; double maxHOverE_; double minSCEt_; - double isoConeR_ ; - double isoInnerConeR_ ; - double isoEtaSlice_ ; - double isoEtMin_ ; - double isoEMin_ ; - bool vetoClusteredHits_ ; - bool useNumXtals_; + double isoConeR_; + double isoInnerConeR_; + double isoEtaSlice_; + double isoEtMin_; + double isoEMin_; + bool vetoClusteredHits_; + bool useNumXtals_; std::vector flagsexclEB_; std::vector flagsexclEE_; @@ -87,35 +83,32 @@ class ConversionTrackCandidateProducer : public edm::stream::EDProducer<> { double ecalIsoCut_offset_; double ecalIsoCut_slope_; - - edm::ESHandle theCaloGeom_; + edm::ESHandle theCaloGeom_; std::unique_ptr theTrajectoryBuilder_; - std::unique_ptr theOutInSeedFinder_; + std::unique_ptr theOutInSeedFinder_; std::unique_ptr theOutInTrackFinder_; - std::unique_ptr theInOutSeedFinder_; + std::unique_ptr theInOutSeedFinder_; std::unique_ptr theInOutTrackFinder_; - - std::vector > caloPtrVecOutIn_; - std::vector > caloPtrVecInOut_; - - std::vector > vecOfSCRefForOutIn; - std::vector > vecOfSCRefForInOut; - - void buildCollections(bool detector, - const edm::Handle > & scHandle, - const edm::Handle > & bcHandle, - edm::Handle ecalRecHitHandle, - const EcalRecHitCollection& ecalRecHits, - const EcalSeverityLevelAlgo* sevLev, - //edm::ESHandle chStatus, - const edm::Handle & hcalTowersHandle, - TrackCandidateCollection& outInTracks, - TrackCandidateCollection& inOutTracks, - std::vector >& vecRecOI, - std::vector >& vecRecIO); - + std::vector > caloPtrVecOutIn_; + std::vector > caloPtrVecInOut_; + + std::vector > vecOfSCRefForOutIn; + std::vector > vecOfSCRefForInOut; + + void buildCollections(bool detector, + const edm::Handle >& scHandle, + const edm::Handle >& bcHandle, + edm::Handle ecalRecHitHandle, + const EcalRecHitCollection& ecalRecHits, + const EcalSeverityLevelAlgo* sevLev, + //edm::ESHandle chStatus, + const edm::Handle& hcalTowersHandle, + TrackCandidateCollection& outInTracks, + TrackCandidateCollection& inOutTracks, + std::vector >& vecRecOI, + std::vector >& vecRecIO); }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackMerger.h b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackMerger.h index 1ff1fb09caf25..a5f0a2f328987 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackMerger.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackMerger.h @@ -4,7 +4,7 @@ // // Package: RecoTracker/FinalTrackSelectors // Class: ConversionTrackMerger -// +// // Description: Hit Dumper // // Original Author: Steve Wagner, stevew@pizero.colorado.edu @@ -17,7 +17,6 @@ #include "DataFormats/Common/interface/Handle.h" #include "FWCore/Framework/interface/EventSetup.h" - #include "DataFormats/EgammaTrackReco/interface/ConversionTrack.h" #include "DataFormats/EgammaTrackReco/interface/ConversionTrackFwd.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" @@ -27,24 +26,21 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" - class ConversionTrackMerger : public edm::stream::EDProducer<> - { - public: - - explicit ConversionTrackMerger(const edm::ParameterSet& conf); - - ~ConversionTrackMerger() override; +class ConversionTrackMerger : public edm::stream::EDProducer<> { +public: + explicit ConversionTrackMerger(const edm::ParameterSet& conf); - void produce(edm::Event& e, const edm::EventSetup& c) override; + ~ConversionTrackMerger() override; - private: - edm::ParameterSet conf_; + void produce(edm::Event& e, const edm::EventSetup& c) override; - edm::EDGetTokenT trackProducer1; - edm::EDGetTokenT trackProducer2; +private: + edm::ParameterSet conf_; - std::unique_ptr outputTrks; - }; + edm::EDGetTokenT trackProducer1; + edm::EDGetTokenT trackProducer2; + std::unique_ptr outputTrks; +}; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackProducer.h index 6f633bc4b9cea..c1787971e1687 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ConversionTrackProducer.h @@ -4,7 +4,7 @@ // // Package: RecoTracker/FinalTrackSelectors // Class: ConversionTrackProducer -// +// // Description: Hit Dumper // // Original Author: Steve Wagner, stevew@pizero.colorado.edu @@ -40,47 +40,42 @@ namespace reco { #include "RecoTracker/ConversionSeedGenerators/interface/IdealHelixParameters.h" //-------------------------------------------------- - class ConversionTrackProducer : public edm::stream::EDProducer<> - { - - typedef edm::AssociationMap, - reco::GsfTrackCollection,unsigned short> > +class ConversionTrackProducer : public edm::stream::EDProducer<> { + typedef edm::AssociationMap, reco::GsfTrackCollection, unsigned short> > TrajGsfTrackAssociationCollection; - public: - - explicit ConversionTrackProducer(const edm::ParameterSet& conf); - - ~ConversionTrackProducer() override; +public: + explicit ConversionTrackProducer(const edm::ParameterSet& conf); - void produce(edm::Event& e, const edm::EventSetup& c) override; + ~ConversionTrackProducer() override; - private: + void produce(edm::Event& e, const edm::EventSetup& c) override; - edm::ParameterSet conf_; +private: + edm::ParameterSet conf_; - std::string trackProducer; - edm::EDGetTokenT > genericTracks ; - edm::EDGetTokenT kfTrajectories; - edm::EDGetTokenT gsfTrajectories; - bool useTrajectory; - bool setTrackerOnly; - bool setIsGsfTrackOpen; - bool setArbitratedEcalSeeded; - bool setArbitratedMerged; - bool setArbitratedMergedEcalGeneral; + std::string trackProducer; + edm::EDGetTokenT > genericTracks; + edm::EDGetTokenT kfTrajectories; + edm::EDGetTokenT gsfTrajectories; + bool useTrajectory; + bool setTrackerOnly; + bool setIsGsfTrackOpen; + bool setArbitratedEcalSeeded; + bool setArbitratedMerged; + bool setArbitratedMergedEcalGeneral; - //-------------------------------------------------- - //Added by D. Giordano - // 2011/08/05 - // Reduction of the track sample based on geometric hypothesis for conversion tracks + //-------------------------------------------------- + //Added by D. Giordano + // 2011/08/05 + // Reduction of the track sample based on geometric hypothesis for conversion tracks - edm::EDGetTokenT beamSpotInputTag; - bool filterOnConvTrackHyp; - double minConvRadius; - IdealHelixParameters ConvTrackPreSelector; - //-------------------------------------------------- + edm::EDGetTokenT beamSpotInputTag; + bool filterOnConvTrackHyp; + double minConvRadius; + IdealHelixParameters ConvTrackPreSelector; + //-------------------------------------------------- - std::unique_ptr outputTrks; - }; + std::unique_ptr outputTrks; +}; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ConvertedPhotonProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/ConvertedPhotonProducer.h index 322569a8025ee..5a9468708575b 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ConvertedPhotonProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ConvertedPhotonProducer.h @@ -32,53 +32,43 @@ class ConversionTrackEcalImpactPoint; class ConversionTrackPairFinder; class ConversionVertexFinder; class ConvertedPhotonProducer : public edm::stream::EDProducer<> { - - public: - - ConvertedPhotonProducer (const edm::ParameterSet& ps); +public: + ConvertedPhotonProducer(const edm::ParameterSet& ps); ~ConvertedPhotonProducer() override; - void beginRun(edm::Run const&, const edm::EventSetup &es) final; + void beginRun(edm::Run const&, const edm::EventSetup& es) final; void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: - - - - - - - void buildCollections ( edm::EventSetup const & es, - const edm::Handle > & scHandle, - const edm::Handle > & bcHandle, - const edm::Handle & hcalTowersHandle, - const edm::Handle & trkHandle, - std::map, reco::CaloClusterPtr, CompareTwoTracksVectors>& allPairs, - reco::ConversionCollection & outputConvPhotonCollection); - void cleanCollections (const edm::Handle > & scHandle, - const edm::OrphanHandle & conversionHandle, - reco::ConversionCollection & outputCollection); - - std::vector solveAmbiguity( const edm::OrphanHandle & conversionHandle, reco::CaloClusterPtr const& sc); - - float calculateMinApproachDistance ( const reco::TrackRef& track1, const reco::TrackRef& track2); +private: + void buildCollections( + edm::EventSetup const& es, + const edm::Handle >& scHandle, + const edm::Handle >& bcHandle, + const edm::Handle& hcalTowersHandle, + const edm::Handle& trkHandle, + std::map, reco::CaloClusterPtr, CompareTwoTracksVectors>& allPairs, + reco::ConversionCollection& outputConvPhotonCollection); + void cleanCollections(const edm::Handle >& scHandle, + const edm::OrphanHandle& conversionHandle, + reco::ConversionCollection& outputCollection); + + std::vector solveAmbiguity(const edm::OrphanHandle& conversionHandle, + reco::CaloClusterPtr const& sc); + + float calculateMinApproachDistance(const reco::TrackRef& track1, const reco::TrackRef& track2); void getCircleCenter(const reco::TrackRef& tk, double r, double& x0, double& y0); - - + edm::EDGetTokenT conversionOITrackProducer_; edm::EDGetTokenT conversionIOTrackProducer_; - - edm::EDGetTokenT - outInTrackSCAssociationCollection_; - edm::EDGetTokenT - inOutTrackSCAssociationCollection_; + edm::EDGetTokenT outInTrackSCAssociationCollection_; + edm::EDGetTokenT inOutTrackSCAssociationCollection_; edm::EDGetTokenT generalTrackProducer_; - + std::string ConvertedPhotonCollection_; std::string CleanedConvertedPhotonCollection_; - + edm::EDGetTokenT > bcBarrelCollection_; edm::EDGetTokenT > bcEndcapCollection_; edm::EDGetTokenT > scHybridBarrelProducer_; @@ -90,36 +80,27 @@ class ConvertedPhotonProducer : public edm::stream::EDProducer<> { edm::ESHandle theMF_; edm::ESHandle theTransientTrackBuilder_; - ConversionTrackPairFinder* theTrackPairFinder_; - ConversionVertexFinder* theVertexFinder_; + ConversionTrackPairFinder* theTrackPairFinder_; + ConversionVertexFinder* theVertexFinder_; ConversionTrackEcalImpactPoint* theEcalImpactPositionFinder_; int nEvt_; std::string algoName_; - double hOverEConeSize_; double maxHOverE_; double minSCEt_; - bool recoverOneTrackCase_; + bool recoverOneTrackCase_; double dRForConversionRecovery_; double deltaCotCut_; double minApproachDisCut_; - int maxNumOfCandidates_; + int maxNumOfCandidates_; bool risolveAmbiguity_; - ConversionLikelihoodCalculator* theLikelihoodCalc_; std::string likelihoodWeights_; - math::XYZPointF toFConverterP( const math::XYZPoint &val) { - return math::XYZPointF(val.x(),val.y(),val.z()); - } - - math::XYZVectorF toFConverterV( const math::XYZVector &val) { - return math::XYZVectorF(val.x(),val.y(),val.z()); - } - - + math::XYZPointF toFConverterP(const math::XYZPoint& val) { return math::XYZPointF(val.x(), val.y(), val.z()); } + math::XYZVectorF toFConverterV(const math::XYZVector& val) { return math::XYZVectorF(val.x(), val.y(), val.z()); } }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonCoreProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonCoreProducer.h index 603864d217f82..afb90298f4c53 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonCoreProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonCoreProducer.h @@ -21,16 +21,13 @@ // GEDPhotonCoreProducer inherits from EDProducer, so it can be a module: class GEDPhotonCoreProducer : public edm::stream::EDProducer<> { - - public: - - GEDPhotonCoreProducer (const edm::ParameterSet& ps); +public: + GEDPhotonCoreProducer(const edm::ParameterSet& ps); ~GEDPhotonCoreProducer() override; void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: - +private: std::string GEDPhotonCoreCollection_; edm::EDGetTokenT pfEgammaCandidates_; edm::EDGetTokenT pixelSeedProducer_; @@ -39,6 +36,5 @@ class GEDPhotonCoreProducer : public edm::stream::EDProducer<> { bool validConversions_; edm::ParameterSet conf_; bool validPixelSeeds_; - }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonProducer.h index 17efb13a263ed..8a84bb4a16695 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonProducer.h @@ -30,99 +30,92 @@ #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoEgamma/PhotonIdentification/interface/PhotonMIPHaloTagger.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" -#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" +#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" #include "RecoEgamma/EgammaPhotonAlgos/interface/PhotonEnergyCorrector.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" - // GEDPhotonProducer inherits from EDProducer, so it can be a module: class GEDPhotonProducer : public edm::stream::EDProducer<> { - - public: - - GEDPhotonProducer (const edm::ParameterSet& ps); +public: + GEDPhotonProducer(const edm::ParameterSet& ps); ~GEDPhotonProducer() override; - void beginRun (edm::Run const& r, edm::EventSetup const & es) final; - void endRun(edm::Run const&, edm::EventSetup const&) final; + void beginRun(edm::Run const& r, edm::EventSetup const& es) final; + void endRun(edm::Run const&, edm::EventSetup const&) final; void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: +private: class RecoStepInfo { public: - enum FlagBits{kOOT=0x1,kFinal=0x2}; + enum FlagBits { kOOT = 0x1, kFinal = 0x2 }; explicit RecoStepInfo(const std::string& recoStep); - - bool isOOT()const{return flags_&kOOT;} - bool isFinal()const{return flags_&kFinal;} + + bool isOOT() const { return flags_ & kOOT; } + bool isFinal() const { return flags_ & kFinal; } + private: unsigned int flags_; }; - void fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonCoreHandle, - const CaloTopology *topology, - const EcalRecHitCollection* ecalBarrelHits, - const EcalRecHitCollection* ecalEndcapHits, + edm::EventSetup const& es, + const edm::Handle& photonCoreHandle, + const CaloTopology* topology, + const EcalRecHitCollection* ecalBarrelHits, + const EcalRecHitCollection* ecalEndcapHits, const EcalRecHitCollection* preshowerHits, - const edm::Handle & hcalTowersHandle, - const reco::VertexCollection& pvVertices, - reco::PhotonCollection & outputCollection, - int& iSC); - - - void fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonHandle, - const edm::Handle pfCandidateHandle, - const edm::Handle pfEGCandidateHandle, - edm::ValueMap pfEGCandToPhotonMap, - edm::Handle< reco::VertexCollection >& pvVertices, - reco::PhotonCollection & outputCollection, - int& iSC, - const edm::Handle>& chargedHadrons, - const edm::Handle>& neutralHadrons, - const edm::Handle>& photons, - const edm::Handle>& chargedHadronsWorstVtx, - const edm::Handle>& chargedHadronsWorstVtxGeomVeto, - const edm::Handle>& chargedHadronsPFPV, - const edm::Handle>& pfEcalClusters, - const edm::Handle>& pfHcalClusters); - - - - - // std::string PhotonCoreCollection_; - std::string photonCollection_; - edm::InputTag photonProducer_; - - edm::EDGetTokenT photonCoreProducerT_; - edm::EDGetTokenT photonProducerT_; - edm::EDGetTokenT barrelEcalHits_; - edm::EDGetTokenT endcapEcalHits_; - edm::EDGetTokenT preshowerHits_; - edm::EDGetTokenT pfEgammaCandidates_; - edm::EDGetTokenT pfCandidates_; - edm::EDGetTokenT hcalTowers_; - edm::EDGetTokenT vertexProducer_; - //for isolation with map-based veto - edm::EDGetTokenT > > particleBasedIsolationToken; + const edm::Handle& hcalTowersHandle, + const reco::VertexCollection& pvVertices, + reco::PhotonCollection& outputCollection, + int& iSC); + + void fillPhotonCollection(edm::Event& evt, + edm::EventSetup const& es, + const edm::Handle& photonHandle, + const edm::Handle pfCandidateHandle, + const edm::Handle pfEGCandidateHandle, + edm::ValueMap pfEGCandToPhotonMap, + edm::Handle& pvVertices, + reco::PhotonCollection& outputCollection, + int& iSC, + const edm::Handle>& chargedHadrons, + const edm::Handle>& neutralHadrons, + const edm::Handle>& photons, + const edm::Handle>& chargedHadronsWorstVtx, + const edm::Handle>& chargedHadronsWorstVtxGeomVeto, + const edm::Handle>& chargedHadronsPFPV, + const edm::Handle>& pfEcalClusters, + const edm::Handle>& pfHcalClusters); + + // std::string PhotonCoreCollection_; + std::string photonCollection_; + edm::InputTag photonProducer_; + + edm::EDGetTokenT photonCoreProducerT_; + edm::EDGetTokenT photonProducerT_; + edm::EDGetTokenT barrelEcalHits_; + edm::EDGetTokenT endcapEcalHits_; + edm::EDGetTokenT preshowerHits_; + edm::EDGetTokenT pfEgammaCandidates_; + edm::EDGetTokenT pfCandidates_; + edm::EDGetTokenT hcalTowers_; + edm::EDGetTokenT vertexProducer_; + //for isolation with map-based veto + edm::EDGetTokenT>> particleBasedIsolationToken; //photon isolation sums - edm::EDGetTokenT > phoChargedIsolationToken_; - edm::EDGetTokenT > phoNeutralHadronIsolationToken_; - edm::EDGetTokenT > phoPhotonIsolationToken_; - edm::EDGetTokenT > phoChargedWorstVtxIsoToken_; - edm::EDGetTokenT > phoChargedWorstVtxGeomVetoIsoToken_; - edm::EDGetTokenT > phoChargedPFPVIsoToken_; - - edm::EDGetTokenT > phoPFECALClusIsolationToken_; - edm::EDGetTokenT > phoPFHCALClusIsolationToken_; - + edm::EDGetTokenT> phoChargedIsolationToken_; + edm::EDGetTokenT> phoNeutralHadronIsolationToken_; + edm::EDGetTokenT> phoPhotonIsolationToken_; + edm::EDGetTokenT> phoChargedWorstVtxIsoToken_; + edm::EDGetTokenT> phoChargedWorstVtxGeomVetoIsoToken_; + edm::EDGetTokenT> phoChargedPFPVIsoToken_; + + edm::EDGetTokenT> phoPFECALClusIsolationToken_; + edm::EDGetTokenT> phoPFHCALClusIsolationToken_; + std::string conversionProducer_; std::string conversionCollection_; std::string valueMapPFCandPhoton_; @@ -131,20 +124,19 @@ class GEDPhotonProducer : public edm::stream::EDProducer<> { //AA //Flags and severities to be excluded from calculations - + std::vector flagsexclEB_; std::vector flagsexclEE_; std::vector severitiesexclEB_; std::vector severitiesexclEE_; - double hOverEConeSize_; double maxHOverE_; double minSCEt_; double highEt_; - double minR9Barrel_; - double minR9Endcap_; - bool runMIPTagger_; + double minR9Barrel_; + double minR9Endcap_; + bool runMIPTagger_; bool validConversions_; RecoStepInfo recoStep_; @@ -155,20 +147,19 @@ class GEDPhotonProducer : public edm::stream::EDProducer<> { edm::ESHandle theCaloGeom_; edm::ESHandle theCaloTopo_; - + bool validPixelSeeds_; //MIP PhotonMIPHaloTagger* thePhotonMIPHaloTagger_; - std::vector preselCutValuesBarrel_; - std::vector preselCutValuesEndcap_; + std::vector preselCutValuesBarrel_; + std::vector preselCutValuesEndcap_; EcalClusterFunctionBaseClass* energyCorrectionF; PhotonEnergyCorrector* thePhotonEnergyCorrector_; - std::string candidateP4type_; + std::string candidateP4type_; bool checkHcalStatus_; - }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/PhotonCoreProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/PhotonCoreProducer.h index 847fa56a9c1d3..547771b83bd38 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/PhotonCoreProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/PhotonCoreProducer.h @@ -28,27 +28,23 @@ // PhotonCoreProducer inherits from EDProducer, so it can be a module: class PhotonCoreProducer : public edm::stream::EDProducer<> { - - public: - - PhotonCoreProducer (const edm::ParameterSet& ps); +public: + PhotonCoreProducer(const edm::ParameterSet& ps); ~PhotonCoreProducer() override; void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: - +private: void fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & scHandle, - const edm::Handle & conversionHandle, - const edm::Handle & pixelSeeds, - reco::PhotonCoreCollection & outputCollection, - int& iSC); - - reco::ConversionRef solveAmbiguity( const edm::Handle & conversionHandle, reco::SuperClusterRef& sc); - + edm::EventSetup const& es, + const edm::Handle& scHandle, + const edm::Handle& conversionHandle, + const edm::Handle& pixelSeeds, + reco::PhotonCoreCollection& outputCollection, + int& iSC); + reco::ConversionRef solveAmbiguity(const edm::Handle& conversionHandle, + reco::SuperClusterRef& sc); std::string PhotonCoreCollection_; edm::EDGetTokenT scHybridBarrelProducer_; @@ -61,6 +57,5 @@ class PhotonCoreProducer : public edm::stream::EDProducer<> { edm::ParameterSet conf_; bool validPixelSeeds_; bool risolveAmbiguity_; - }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/PhotonProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/PhotonProducer.h index d2352d479b2bc..eac9cd676e534 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/PhotonProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/PhotonProducer.h @@ -29,34 +29,31 @@ #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoEgamma/PhotonIdentification/interface/PhotonMIPHaloTagger.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" -#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" +#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" #include "RecoEgamma/EgammaPhotonAlgos/interface/PhotonEnergyCorrector.h" // PhotonProducer inherits from EDProducer, so it can be a module: class PhotonProducer : public edm::stream::EDProducer<> { - - public: - - PhotonProducer (const edm::ParameterSet& ps); +public: + PhotonProducer(const edm::ParameterSet& ps); ~PhotonProducer() override; void produce(edm::Event& evt, const edm::EventSetup& es) override; - private: - +private: void fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonCoreHandle, - const CaloTopology *topology, - const EcalRecHitCollection* ecalBarrelHits, - const EcalRecHitCollection* ecalEndcapHits, - const edm::Handle & hcalTowersHandle, - //math::XYZPoint & vtx, - reco::VertexCollection& pvVertices, - reco::PhotonCollection & outputCollection, - int& iSC, - const EcalSeverityLevelAlgo * sevLv); + edm::EventSetup const& es, + const edm::Handle& photonCoreHandle, + const CaloTopology* topology, + const EcalRecHitCollection* ecalBarrelHits, + const EcalRecHitCollection* ecalEndcapHits, + const edm::Handle& hcalTowersHandle, + //math::XYZPoint & vtx, + reco::VertexCollection& pvVertices, + reco::PhotonCollection& outputCollection, + int& iSC, + const EcalSeverityLevelAlgo* sevLv); // std::string PhotonCoreCollection_; std::string PhotonCollection_; @@ -71,24 +68,23 @@ class PhotonProducer : public edm::stream::EDProducer<> { //AA //Flags and severities to be excluded from calculations - + std::vector flagsexclEB_; std::vector flagsexclEE_; std::vector severitiesexclEB_; std::vector severitiesexclEE_; - double hOverEConeSize_; double maxHOverE_; double minSCEt_; double highEt_; - double minR9Barrel_; - double minR9Endcap_; - bool runMIPTagger_; + double minR9Barrel_; + double minR9Endcap_; + bool runMIPTagger_; bool validConversions_; std::string pixelSeedProducer_; - + bool usePrimaryVertex_; edm::ParameterSet conf_; @@ -96,19 +92,18 @@ class PhotonProducer : public edm::stream::EDProducer<> { edm::ESHandle theCaloGeom_; edm::ESHandle theCaloTopo_; - + bool validPixelSeeds_; PhotonIsolationCalculator* thePhotonIsolationCalculator_; //MIP PhotonMIPHaloTagger* thePhotonMIPHaloTagger_; - std::vector preselCutValuesBarrel_; - std::vector preselCutValuesEndcap_; + std::vector preselCutValuesBarrel_; + std::vector preselCutValuesEndcap_; EcalClusterFunctionBaseClass* energyCorrectionF; PhotonEnergyCorrector* thePhotonEnergyCorrector_; - std::string candidateP4type_; - + std::string candidateP4type_; }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/interface/ReducedEGProducer.h b/RecoEgamma/EgammaPhotonProducers/interface/ReducedEGProducer.h index 1e7b58bb46c63..9635c38c0e27f 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/ReducedEGProducer.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/ReducedEGProducer.h @@ -33,8 +33,8 @@ #include "RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h" #include "RecoEgamma/PhotonIdentification/interface/PhotonMIPHaloTagger.h" #include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" -#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" +#include "CondFormats/EcalObjects/interface/EcalFunctionParameters.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EGHcalRecHitSelector.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" @@ -42,187 +42,179 @@ #include "CommonTools/UtilAlgos/interface/StringCutObjectSelector.h" - // ReducedEGProducer inherits from EDProducer, so it can be a module: class ReducedEGProducer : public edm::stream::EDProducer<> { - - public: - - ReducedEGProducer (const edm::ParameterSet& ps); +public: + ReducedEGProducer(const edm::ParameterSet& ps); ~ReducedEGProducer() override; - void beginRun (edm::Run const&, const edm::EventSetup&) final; + void beginRun(edm::Run const&, const edm::EventSetup&) final; void produce(edm::Event& evt, const edm::EventSetup& es) final; - private: - +private: template void linkCore(const T& core, U& cores, std::map& coreMap); - - void linkSuperCluster(const reco::SuperClusterRef& superCluster, - std::map& superClusterMap, - reco::SuperClusterCollection& superClusters, - const bool relink, - std::unordered_set& superClusterFullRelinkMap); + + void linkSuperCluster(const reco::SuperClusterRef& superCluster, + std::map& superClusterMap, + reco::SuperClusterCollection& superClusters, + const bool relink, + std::unordered_set& superClusterFullRelinkMap); void linkConversions(const reco::ConversionRefVector& convrefs, - reco::ConversionCollection& conversions, - std::map& conversionMap); - + reco::ConversionCollection& conversions, + std::map& conversionMap); + void linkConversionsByTrackRef(const edm::Handle& conversionHandle, - const reco::GsfElectron& gsfElectron, - reco::ConversionCollection& conversions, - std::map& conversionMap); + const reco::GsfElectron& gsfElectron, + reco::ConversionCollection& conversions, + std::map& conversionMap); void linkConversionsByTrackRef(const edm::Handle& conversionHandle, - const reco::SuperCluster& superCluster, - reco::ConversionCollection& conversions, - std::map& conversionMap); - + const reco::SuperCluster& superCluster, + reco::ConversionCollection& conversions, + std::map& conversionMap); + void linkConversion(const reco::ConversionRef& convref, - reco::ConversionCollection& conversions, - std::map& conversionMap); + reco::ConversionCollection& conversions, + std::map& conversionMap); void linkCaloCluster(const reco::CaloClusterPtr& caloCluster, - reco::CaloClusterCollection& caloClusters, - std::map& caloClusterMap); - - void linkCaloClusters(const reco::SuperCluster& superCluster, - reco::CaloClusterCollection& ebeeClusters, - std::map& ebeeClusterMap, - std::unordered_set& rechitMap, - const edm::Handle& barrelHitHandle, - const edm::Handle& endcapHitHandle, - const CaloTopology *caloTopology, - reco::CaloClusterCollection& esClusters, - std::map& esClusterMap); - - void linkHcalHits(const reco::SuperCluster& superClus,const HBHERecHitCollection& recHits, - std::unordered_set& hcalDetIds); - - void relinkCaloClusters(reco::SuperCluster& superCluster, - const std::map& ebeeClusterMap, - const std::map& esClusterMap, - const edm::OrphanHandle& outEBEEClusterHandle, - const edm::OrphanHandle& outESClusterHandle); - - template + reco::CaloClusterCollection& caloClusters, + std::map& caloClusterMap); + + void linkCaloClusters(const reco::SuperCluster& superCluster, + reco::CaloClusterCollection& ebeeClusters, + std::map& ebeeClusterMap, + std::unordered_set& rechitMap, + const edm::Handle& barrelHitHandle, + const edm::Handle& endcapHitHandle, + const CaloTopology* caloTopology, + reco::CaloClusterCollection& esClusters, + std::map& esClusterMap); + + void linkHcalHits(const reco::SuperCluster& superClus, + const HBHERecHitCollection& recHits, + std::unordered_set& hcalDetIds); + + void relinkCaloClusters(reco::SuperCluster& superCluster, + const std::map& ebeeClusterMap, + const std::map& esClusterMap, + const edm::OrphanHandle& outEBEEClusterHandle, + const edm::OrphanHandle& outESClusterHandle); + + template void relinkSuperCluster(T& core, - const std::map& superClusterMap, - const edm::OrphanHandle& outSuperClusterHandle); + const std::map& superClusterMap, + const edm::OrphanHandle& outSuperClusterHandle); void relinkGsfTrack(reco::GsfElectronCore& electroncore, - const std::map& gsfTrackMap, - const edm::OrphanHandle& outGsfTrackHandle); - - void relinkConversions(reco::PhotonCore& photonCore, - const reco::ConversionRefVector& convrefs, - const std::map& conversionMap, - const edm::OrphanHandle &outConversionHandle); - - void relinkPhotonCore(reco::Photon& photon, - const std::map& photonCoreMap, - const edm::OrphanHandle& outPhotonCoreHandle); - - void relinkGsfElectronCore(reco::GsfElectron& gsfElectron, - const std::map& gsfElectronCoreMap, - const edm::OrphanHandle& outGsfElectronCoreHandle); - - static void calibratePhoton(reco::Photon& photon, - const reco::PhotonRef& oldPhoRef, - const edm::ValueMap& energyMap, - const edm::ValueMap& energyErrMap); - - static void calibrateElectron(reco::GsfElectron& gsfElectron, - const reco::GsfElectronRef& oldEleRef, - const edm::ValueMap& energyMap, - const edm::ValueMap& energyErrMap, - const edm::ValueMap& ecalEnergyMap, - const edm::ValueMap& ecalEnergyErrMap); + const std::map& gsfTrackMap, + const edm::OrphanHandle& outGsfTrackHandle); + void relinkConversions(reco::PhotonCore& photonCore, + const reco::ConversionRefVector& convrefs, + const std::map& conversionMap, + const edm::OrphanHandle& outConversionHandle); + + void relinkPhotonCore(reco::Photon& photon, + const std::map& photonCoreMap, + const edm::OrphanHandle& outPhotonCoreHandle); + + void relinkGsfElectronCore(reco::GsfElectron& gsfElectron, + const std::map& gsfElectronCoreMap, + const edm::OrphanHandle& outGsfElectronCoreHandle); + + static void calibratePhoton(reco::Photon& photon, + const reco::PhotonRef& oldPhoRef, + const edm::ValueMap& energyMap, + const edm::ValueMap& energyErrMap); + + static void calibrateElectron(reco::GsfElectron& gsfElectron, + const reco::GsfElectronRef& oldEleRef, + const edm::ValueMap& energyMap, + const edm::ValueMap& energyErrMap, + const edm::ValueMap& ecalEnergyMap, + const edm::ValueMap& ecalEnergyErrMap); template - void setToken(edm::EDGetTokenT& token,const edm::ParameterSet& config,const std::string& name){ + void setToken(edm::EDGetTokenT& token, const edm::ParameterSet& config, const std::string& name) { token = consumes(config.getParameter(name)); } - - //tokens for input collections - const edm::EDGetTokenT photonT_; - edm::EDGetTokenT ootPhotonT_; - const edm::EDGetTokenT gsfElectronT_; - const edm::EDGetTokenT gsfTrackT_; - const edm::EDGetTokenT conversionT_; - const edm::EDGetTokenT singleConversionT_; - - const edm::EDGetTokenT barrelEcalHits_; - const edm::EDGetTokenT endcapEcalHits_; - const bool doPreshowerEcalHits_; - const edm::EDGetTokenT preshowerEcalHits_; - const edm::EDGetTokenT hbheHits_; - - const edm::EDGetTokenT > > photonPfCandMapT_; - const edm::EDGetTokenT > > gsfElectronPfCandMapT_; - - std::vector > > photonIdTs_; - std::vector > > gsfElectronIdTs_; - - std::vector > > photonFloatValueMapTs_; - std::vector > > ootPhotonFloatValueMapTs_; - std::vector > > gsfElectronFloatValueMapTs_; - - const bool applyPhotonCalibOnData_; - const bool applyPhotonCalibOnMC_; - const bool applyGsfElectronCalibOnData_; - const bool applyGsfElectronCalibOnMC_; - edm::EDGetTokenT > photonCalibEnergyT_; - edm::EDGetTokenT > photonCalibEnergyErrT_; - edm::EDGetTokenT > gsfElectronCalibEnergyT_; - edm::EDGetTokenT > gsfElectronCalibEnergyErrT_; - edm::EDGetTokenT > gsfElectronCalibEcalEnergyT_; - edm::EDGetTokenT > gsfElectronCalibEcalEnergyErrT_; - - //names for output collections - const std::string outPhotons_; - const std::string outPhotonCores_; - const std::string outOOTPhotons_; - const std::string outOOTPhotonCores_; - const std::string outGsfElectrons_; - const std::string outGsfElectronCores_; - const std::string outGsfTracks_; - const std::string outConversions_; - const std::string outSingleConversions_; - const std::string outSuperClusters_; - const std::string outEBEEClusters_; - const std::string outESClusters_; - const std::string outOOTSuperClusters_; - const std::string outOOTEBEEClusters_; - const std::string outOOTESClusters_; - const std::string outEBRecHits_; - const std::string outEERecHits_; - const std::string outESRecHits_; - const std::string outHBHERecHits_; - const std::string outPhotonPfCandMap_; - const std::string outGsfElectronPfCandMap_; - const std::vector outPhotonIds_; - const std::vector outGsfElectronIds_; - const std::vector outPhotonFloatValueMaps_; - const std::vector outOOTPhotonFloatValueMaps_; - const std::vector outGsfElectronFloatValueMaps_; - - const StringCutObjectSelector keepPhotonSel_; - const StringCutObjectSelector slimRelinkPhotonSel_; - const StringCutObjectSelector relinkPhotonSel_; - const StringCutObjectSelector keepOOTPhotonSel_; - const StringCutObjectSelector slimRelinkOOTPhotonSel_; - const StringCutObjectSelector relinkOOTPhotonSel_; - const StringCutObjectSelector keepGsfElectronSel_; - const StringCutObjectSelector slimRelinkGsfElectronSel_; - const StringCutObjectSelector relinkGsfElectronSel_; - - EGHcalRecHitSelector hcalHitSel_; - + //tokens for input collections + const edm::EDGetTokenT photonT_; + edm::EDGetTokenT ootPhotonT_; + const edm::EDGetTokenT gsfElectronT_; + const edm::EDGetTokenT gsfTrackT_; + const edm::EDGetTokenT conversionT_; + const edm::EDGetTokenT singleConversionT_; + + const edm::EDGetTokenT barrelEcalHits_; + const edm::EDGetTokenT endcapEcalHits_; + const bool doPreshowerEcalHits_; + const edm::EDGetTokenT preshowerEcalHits_; + const edm::EDGetTokenT hbheHits_; + + const edm::EDGetTokenT > > photonPfCandMapT_; + const edm::EDGetTokenT > > gsfElectronPfCandMapT_; + + std::vector > > photonIdTs_; + std::vector > > gsfElectronIdTs_; + + std::vector > > photonFloatValueMapTs_; + std::vector > > ootPhotonFloatValueMapTs_; + std::vector > > gsfElectronFloatValueMapTs_; + + const bool applyPhotonCalibOnData_; + const bool applyPhotonCalibOnMC_; + const bool applyGsfElectronCalibOnData_; + const bool applyGsfElectronCalibOnMC_; + edm::EDGetTokenT > photonCalibEnergyT_; + edm::EDGetTokenT > photonCalibEnergyErrT_; + edm::EDGetTokenT > gsfElectronCalibEnergyT_; + edm::EDGetTokenT > gsfElectronCalibEnergyErrT_; + edm::EDGetTokenT > gsfElectronCalibEcalEnergyT_; + edm::EDGetTokenT > gsfElectronCalibEcalEnergyErrT_; + + //names for output collections + const std::string outPhotons_; + const std::string outPhotonCores_; + const std::string outOOTPhotons_; + const std::string outOOTPhotonCores_; + const std::string outGsfElectrons_; + const std::string outGsfElectronCores_; + const std::string outGsfTracks_; + const std::string outConversions_; + const std::string outSingleConversions_; + const std::string outSuperClusters_; + const std::string outEBEEClusters_; + const std::string outESClusters_; + const std::string outOOTSuperClusters_; + const std::string outOOTEBEEClusters_; + const std::string outOOTESClusters_; + const std::string outEBRecHits_; + const std::string outEERecHits_; + const std::string outESRecHits_; + const std::string outHBHERecHits_; + const std::string outPhotonPfCandMap_; + const std::string outGsfElectronPfCandMap_; + const std::vector outPhotonIds_; + const std::vector outGsfElectronIds_; + const std::vector outPhotonFloatValueMaps_; + const std::vector outOOTPhotonFloatValueMaps_; + const std::vector outGsfElectronFloatValueMaps_; + + const StringCutObjectSelector keepPhotonSel_; + const StringCutObjectSelector slimRelinkPhotonSel_; + const StringCutObjectSelector relinkPhotonSel_; + const StringCutObjectSelector keepOOTPhotonSel_; + const StringCutObjectSelector slimRelinkOOTPhotonSel_; + const StringCutObjectSelector relinkOOTPhotonSel_; + const StringCutObjectSelector keepGsfElectronSel_; + const StringCutObjectSelector slimRelinkGsfElectronSel_; + const StringCutObjectSelector relinkGsfElectronSel_; + + EGHcalRecHitSelector hcalHitSel_; }; #endif - - diff --git a/RecoEgamma/EgammaPhotonProducers/interface/TrackProducerWithSCAssociation.h b/RecoEgamma/EgammaPhotonProducers/interface/TrackProducerWithSCAssociation.h index 60b03eb264601..b69872cceebfd 100644 --- a/RecoEgamma/EgammaPhotonProducers/interface/TrackProducerWithSCAssociation.h +++ b/RecoEgamma/EgammaPhotonProducers/interface/TrackProducerWithSCAssociation.h @@ -18,38 +18,36 @@ class TrackProducerWithSCAssociation : public TrackProducerBase, public edm::stream::EDProducer<> { public: - explicit TrackProducerWithSCAssociation(const edm::ParameterSet& iConfig); - void produce(edm::Event&, const edm::EventSetup&) override; std::vector getTransient(edm::Event&, const edm::EventSetup&); private: - std::string myname_; + std::string myname_; TrackProducerAlgorithm theAlgo; std::string conversionTrackCandidateProducer_; std::string trackCSuperClusterAssociationCollection_; std::string trackSuperClusterAssociationCollection_; edm::EDGetTokenT assoc_token; - edm::OrphanHandle rTracks_; + edm::OrphanHandle rTracks_; edm::EDGetTokenT measurementTrkToken_; bool myTrajectoryInEvent_; bool validTrackCandidateSCAssociationInput_; - //Same recipe as Ursula's for electrons. Copy this from TrackProducerBase to get the OrphanHandle //ugly temporary solution!! I agree ! void putInEvt(edm::Event& evt, - const Propagator* thePropagator, - const MeasurementTracker* theMeasTk, - std::unique_ptr selHits, - std::unique_ptr selTracks, - std::unique_ptr selTrackExtras, - std::unique_ptr> selTrajectories, - AlgoProductCollection& algoResults, TransientTrackingRecHitBuilder const * hitBuilder, - const TrackerTopology *ttopo); + const Propagator* thePropagator, + const MeasurementTracker* theMeasTk, + std::unique_ptr selHits, + std::unique_ptr selTracks, + std::unique_ptr selTrackExtras, + std::unique_ptr> selTrajectories, + AlgoProductCollection& algoResults, + TransientTrackingRecHitBuilder const* hitBuilder, + const TrackerTopology* ttopo); }; #endif diff --git a/RecoEgamma/EgammaPhotonProducers/src/ConversionProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/ConversionProducer.cc index 5687f2fa6dc1e..7350fec85d301 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ConversionProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ConversionProducer.cc @@ -16,12 +16,10 @@ Description: Produces converted photon objects using default track collections // // - // system include files #include #include - #include "RecoEgamma/EgammaPhotonProducers/interface/ConversionProducer.h" #include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" @@ -36,7 +34,6 @@ Description: Produces converted photon objects using default track collections #include "TrackingTools/TransientTrack/interface/TrackTransientTrack.h" #include "DataFormats/EgammaTrackReco/interface/ConversionTrack.h" - #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/GsfTrackReco/interface/GsfTrack.h" @@ -56,7 +53,6 @@ Description: Produces converted photon objects using default track collections #include "RecoEgamma/EgammaPhotonAlgos/interface/TangentApproachInRPhi.h" #include "RecoEgamma/EgammaPhotonAlgos/interface/ConversionHitChecker.h" - //Kinematic constraint vertex fitter #include "RecoVertex/KinematicFitPrimitives/interface/ParticleMass.h" #include "RecoVertex/KinematicFitPrimitives/interface/MultiTrackKinematicConstraint.h" @@ -68,16 +64,13 @@ Description: Produces converted photon objects using default track collections #include "RecoVertex/KinematicFit/interface/MassKinematicConstraint.h" #include "RecoVertex/KinematicFit/interface/ColinearityKinematicConstraint.h" - - -ConversionProducer::ConversionProducer(const edm::ParameterSet& iConfig): - theVertexFinder_(nullptr) +ConversionProducer::ConversionProducer(const edm::ParameterSet& iConfig) + : theVertexFinder_(nullptr) { - algoName_ = iConfig.getParameter( "AlgorithmName" ); + algoName_ = iConfig.getParameter("AlgorithmName"); - src_ = - consumes >(iConfig.getParameter("src")); + src_ = consumes >(iConfig.getParameter("src")); maxNumOfTrackInPU_ = iConfig.getParameter("maxNumOfTrackInPU"); maxTrackRho_ = iConfig.getParameter("maxTrackRho"); @@ -95,47 +88,42 @@ ConversionProducer::ConversionProducer(const edm::ParameterSet& iConfig): bypassPreselGsf_ = iConfig.getParameter("bypassPreselGsf"); bypassPreselEcal_ = iConfig.getParameter("bypassPreselEcal"); bypassPreselEcalEcal_ = iConfig.getParameter("bypassPreselEcalEcal"); - + deltaEta_ = iConfig.getParameter("deltaEta"); - - halfWayEta_ = iConfig.getParameter("HalfwayEta");//open angle to search track matches with BC + + halfWayEta_ = iConfig.getParameter("HalfwayEta"); //open angle to search track matches with BC d0Cut_ = iConfig.getParameter("d0"); - - usePvtx_ = iConfig.getParameter("UsePvtx");//if use primary vertices - vertexProducer_ = - consumes(iConfig.getParameter("primaryVertexProducer")); - + usePvtx_ = iConfig.getParameter("UsePvtx"); //if use primary vertices + + vertexProducer_ = consumes(iConfig.getParameter("primaryVertexProducer")); //Track-cluster matching eta and phi cuts - dEtaTkBC_ = iConfig.getParameter("dEtaTrackBC");//TODO research on cut endcap/barrel + dEtaTkBC_ = iConfig.getParameter("dEtaTrackBC"); //TODO research on cut endcap/barrel dPhiTkBC_ = iConfig.getParameter("dPhiTrackBC"); - - bcBarrelCollection_ = - consumes >(iConfig.getParameter("bcBarrelCollection")); - bcEndcapCollection_ = - consumes >(iConfig.getParameter("bcEndcapCollection")); - - scBarrelProducer_ = - consumes >(iConfig.getParameter("scBarrelProducer")); - scEndcapProducer_ = - consumes >(iConfig.getParameter("scEndcapProducer")); - - energyBC_ = iConfig.getParameter("EnergyBC");//BC energy threshold - energyTotalBC_ = iConfig.getParameter("EnergyTotalBC");//BC energy threshold - minSCEt_ = iConfig.getParameter("minSCEt");//super cluster energy threshold - dEtacutForSCmatching_ = iConfig.getParameter("dEtacutForSCmatching");// dEta between conversion momentum direction and SC position - dPhicutForSCmatching_ = iConfig.getParameter("dPhicutForSCmatching");// dPhi between conversion momentum direction and SC position - - - + + bcBarrelCollection_ = + consumes >(iConfig.getParameter("bcBarrelCollection")); + bcEndcapCollection_ = + consumes >(iConfig.getParameter("bcEndcapCollection")); + + scBarrelProducer_ = consumes >(iConfig.getParameter("scBarrelProducer")); + scEndcapProducer_ = consumes >(iConfig.getParameter("scEndcapProducer")); + + energyBC_ = iConfig.getParameter("EnergyBC"); //BC energy threshold + energyTotalBC_ = iConfig.getParameter("EnergyTotalBC"); //BC energy threshold + minSCEt_ = iConfig.getParameter("minSCEt"); //super cluster energy threshold + dEtacutForSCmatching_ = iConfig.getParameter( + "dEtacutForSCmatching"); // dEta between conversion momentum direction and SC position + dPhicutForSCmatching_ = iConfig.getParameter( + "dPhicutForSCmatching"); // dPhi between conversion momentum direction and SC position //Track cuts on left right track: at least one leg reaches ECAL //Left track: must exist, must reach Ecal and match BC, so loose cut on Chi2 and tight on hits //Right track: not necessary to exist (if allowSingleLeg_), not necessary to reach ECAL or match BC, so tight cut on Chi2 and loose on hits - maxChi2Left_ = iConfig.getParameter("MaxChi2Left"); - maxChi2Right_ = iConfig.getParameter("MaxChi2Right"); + maxChi2Left_ = iConfig.getParameter("MaxChi2Left"); + maxChi2Right_ = iConfig.getParameter("MaxChi2Right"); minHitsLeft_ = iConfig.getParameter("MinHitsLeft"); minHitsRight_ = iConfig.getParameter("MinHitsRight"); @@ -144,7 +132,6 @@ ConversionProducer::ConversionProducer(const edm::ParameterSet& iConfig): deltaPhi_ = iConfig.getParameter("DeltaPhi"); minApproachLow_ = iConfig.getParameter("MinApproachLow"); minApproachHigh_ = iConfig.getParameter("MinApproachHigh"); - // if allow single track collection, by default False allowSingleLeg_ = iConfig.getParameter("AllowSingleLeg"); @@ -156,32 +143,24 @@ ConversionProducer::ConversionProducer(const edm::ParameterSet& iConfig): r_cut = iConfig.getParameter("rCut"); vtxChi2_ = iConfig.getParameter("vtxChi2"); - - theVertexFinder_ = new ConversionVertexFinder ( iConfig ); + theVertexFinder_ = new ConversionVertexFinder(iConfig); thettbuilder_ = nullptr; //output - ConvertedPhotonCollection_ = iConfig.getParameter("convertedPhotonCollection"); - - produces< reco::ConversionCollection >(ConvertedPhotonCollection_); + ConvertedPhotonCollection_ = iConfig.getParameter("convertedPhotonCollection"); + produces(ConvertedPhotonCollection_); } - -ConversionProducer::~ConversionProducer() -{ - +ConversionProducer::~ConversionProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) delete theVertexFinder_; } - // ------------ method called to produce the data ------------ -void -ConversionProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void ConversionProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; reco::ConversionCollection outputConvPhotonCollection; @@ -191,175 +170,170 @@ ConversionProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) //Read multiple track input collections edm::Handle > trackCollectionHandle; - iEvent.getByToken(src_,trackCollectionHandle); + iEvent.getByToken(src_, trackCollectionHandle); //build map of ConversionTracks ordered in eta std::multimap > convTrackMap; - for(auto const& t : trackCollectionHandle->ptrs()) convTrackMap.emplace(t->track()->eta(),t); + for (auto const& t : trackCollectionHandle->ptrs()) + convTrackMap.emplace(t->track()->eta(), t); edm::Handle vertexHandle; reco::VertexCollection vertexCollection; - if (usePvtx_){ + if (usePvtx_) { iEvent.getByToken(vertexProducer_, vertexHandle); if (!vertexHandle.isValid()) { - edm::LogError("ConversionProducer") - << "Error! Can't get the product primary Vertex Collection "<< "\n"; + edm::LogError("ConversionProducer") << "Error! Can't get the product primary Vertex Collection " + << "\n"; usePvtx_ = false; } if (usePvtx_) vertexCollection = *(vertexHandle.product()); } - + edm::ESHandle hTransientTrackBuilder; - iSetup.get().get("TransientTrackBuilder",hTransientTrackBuilder); + iSetup.get().get("TransientTrackBuilder", hTransientTrackBuilder); thettbuilder_ = hTransientTrackBuilder.product(); - + reco::Vertex the_pvtx; //because the priamry vertex is sorted by quality, the first one is the best if (!vertexCollection.empty()) the_pvtx = *(vertexCollection.begin()); - - if (trackCollectionHandle->size()> maxNumOfTrackInPU_){ + + if (trackCollectionHandle->size() > maxNumOfTrackInPU_) { iEvent.put(std::move(outputConvPhotonCollection_p), ConvertedPhotonCollection_); return; } - - + // build Super and Basic cluster geometry map to search in eta bounds for clusters std::multimap basicClusterPtrs; std::multimap superClusterPtrs; - - buildSuperAndBasicClusterGeoMap(iEvent,basicClusterPtrs,superClusterPtrs); - - buildCollection( iEvent, iSetup, convTrackMap, superClusterPtrs, basicClusterPtrs, the_pvtx, outputConvPhotonCollection);//allow empty basicClusterPtrs - + buildSuperAndBasicClusterGeoMap(iEvent, basicClusterPtrs, superClusterPtrs); + + buildCollection(iEvent, + iSetup, + convTrackMap, + superClusterPtrs, + basicClusterPtrs, + the_pvtx, + outputConvPhotonCollection); //allow empty basicClusterPtrs + outputConvPhotonCollection_p->assign(outputConvPhotonCollection.begin(), outputConvPhotonCollection.end()); iEvent.put(std::move(outputConvPhotonCollection_p), ConvertedPhotonCollection_); - } - -void ConversionProducer::buildSuperAndBasicClusterGeoMap(const edm::Event& iEvent, - std::multimap& basicClusterPtrs, - std::multimap& superClusterPtrs){ - +void ConversionProducer::buildSuperAndBasicClusterGeoMap(const edm::Event& iEvent, + std::multimap& basicClusterPtrs, + std::multimap& superClusterPtrs) { // Get the Super Cluster collection in the Barrel edm::Handle > scBarrelHandle; - iEvent.getByToken(scBarrelProducer_,scBarrelHandle); + iEvent.getByToken(scBarrelProducer_, scBarrelHandle); if (!scBarrelHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the barrel superclusters!"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the barrel superclusters!"; } - + // Get the Super Cluster collection in the Endcap edm::Handle > scEndcapHandle; - iEvent.getByToken(scEndcapProducer_,scEndcapHandle); + iEvent.getByToken(scEndcapProducer_, scEndcapHandle); if (!scEndcapHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the endcap superclusters!"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the endcap superclusters!"; } - - + edm::Handle > bcBarrelHandle; - edm::Handle > bcEndcapHandle;//TODO check cluster type if BasicCluster or PFCluster + edm::Handle > bcEndcapHandle; //TODO check cluster type if BasicCluster or PFCluster - iEvent.getByToken( bcBarrelCollection_, bcBarrelHandle); + iEvent.getByToken(bcBarrelCollection_, bcBarrelHandle); if (!bcBarrelHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the barrel basic clusters!"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the barrel basic clusters!"; } - iEvent.getByToken( bcEndcapCollection_, bcEndcapHandle); - if (! bcEndcapHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the endcap basic clusters!"; + iEvent.getByToken(bcEndcapCollection_, bcEndcapHandle); + if (!bcEndcapHandle.isValid()) { + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the endcap basic clusters!"; } - if( bcBarrelHandle.isValid() ) { - for(auto const& handle : {bcBarrelHandle, bcEndcapHandle} ) { - for(auto const& bc : handle->ptrs()) { - if(bc->energy() > energyBC_) basicClusterPtrs.emplace(bc->position().eta(), bc); + if (bcBarrelHandle.isValid()) { + for (auto const& handle : {bcBarrelHandle, bcEndcapHandle}) { + for (auto const& bc : handle->ptrs()) { + if (bc->energy() > energyBC_) + basicClusterPtrs.emplace(bc->position().eta(), bc); } } } - if( scBarrelHandle.isValid() ) { - for(auto const& handle : {scBarrelHandle, scEndcapHandle} ) { - for(auto const& sc : handle->ptrs()) { - if(sc->energy() > minSCEt_) superClusterPtrs.emplace(sc->position().eta(), sc); + if (scBarrelHandle.isValid()) { + for (auto const& handle : {scBarrelHandle, scEndcapHandle}) { + for (auto const& sc : handle->ptrs()) { + if (sc->energy() > minSCEt_) + superClusterPtrs.emplace(sc->position().eta(), sc); } - } + } } - } - -void ConversionProducer::buildCollection(edm::Event& iEvent, const edm::EventSetup& iSetup, +void ConversionProducer::buildCollection(edm::Event& iEvent, + const edm::EventSetup& iSetup, const std::multimap >& allTracks, const std::multimap& superClusterPtrs, const std::multimap& basicClusterPtrs, const reco::Vertex& the_pvtx, - reco::ConversionCollection & outputConvPhotonCollection){ - - + reco::ConversionCollection& outputConvPhotonCollection) { edm::ESHandle trackerGeomHandle; edm::ESHandle magFieldHandle; - iSetup.get().get( trackerGeomHandle ); - iSetup.get().get( magFieldHandle ); - + iSetup.get().get(trackerGeomHandle); + iSetup.get().get(magFieldHandle); + const TrackerGeometry* trackerGeom = trackerGeomHandle.product(); const MagneticField* magField = magFieldHandle.product(); - -// std::vector trackImpactPosition; -// trackImpactPosition.reserve(allTracks.size());//track impact position at ECAL -// std::vector trackValidECAL;//Does this track reach ECAL basic cluster (reach ECAL && match with BC) -// trackValidECAL.assign(allTracks.size(), false); -// -// std::vector trackMatchedBC; -// reco::CaloClusterPtr empty_bc; -// trackMatchedBC.assign(allTracks.size(), empty_bc);//TODO find a better way to avoid copy constructor -// -// std::vector bcHandleId;//the associated BC handle id, -1 invalid, 0 barrel 1 endcap -// bcHandleId.assign(allTracks.size(), -1); - + + // std::vector trackImpactPosition; + // trackImpactPosition.reserve(allTracks.size());//track impact position at ECAL + // std::vector trackValidECAL;//Does this track reach ECAL basic cluster (reach ECAL && match with BC) + // trackValidECAL.assign(allTracks.size(), false); + // + // std::vector trackMatchedBC; + // reco::CaloClusterPtr empty_bc; + // trackMatchedBC.assign(allTracks.size(), empty_bc);//TODO find a better way to avoid copy constructor + // + // std::vector bcHandleId;//the associated BC handle id, -1 invalid, 0 barrel 1 endcap + // bcHandleId.assign(allTracks.size(), -1); + // not used std::multimap trackInnerEta;//Track innermost state Eta map to TrackRef index, to be used in track pair sorting - + std::map, math::XYZPointF> trackImpactPosition; std::map, reco::CaloClusterPtr> trackMatchedBC; - + ConversionHitChecker hitChecker; - - + //2 propagate all tracks into ECAL, record its eta and phi - - for (std::multimap >::const_iterator tk_ref = allTracks.begin(); tk_ref != allTracks.end(); ++tk_ref ){ - const reco::Track* tk = tk_ref->second->trackRef().get() ; - - + + for (std::multimap >::const_iterator tk_ref = allTracks.begin(); + tk_ref != allTracks.end(); + ++tk_ref) { + const reco::Track* tk = tk_ref->second->trackRef().get(); + //check impact position then match with BC math::XYZPointF ew; - if ( getTrackImpactPosition(tk, trackerGeom, magField, ew) ){ + if (getTrackImpactPosition(tk, trackerGeom, magField, ew)) { trackImpactPosition[tk_ref->second] = ew; - - reco::CaloClusterPtr closest_bc;//the closest matching BC to track - - if ( getMatchedBC(basicClusterPtrs, ew, closest_bc) ){ - trackMatchedBC[tk_ref->second] = closest_bc; + + reco::CaloClusterPtr closest_bc; //the closest matching BC to track + + if (getMatchedBC(basicClusterPtrs, ew, closest_bc)) { + trackMatchedBC[tk_ref->second] = closest_bc; } - } + } } - - - - //3. pair up tracks: + + //3. pair up tracks: //TODO it is k-Closest pair of point problem //std::cout << " allTracks.size() " << allTracks.size() << std::endl; - for(std::multimap >::const_iterator ll = allTracks.begin(); ll != allTracks.end(); ++ll ) { - bool track1HighPurity=true; + for (std::multimap >::const_iterator ll = allTracks.begin(); + ll != allTracks.end(); + ++ll) { + bool track1HighPurity = true; //std::cout << " Loop on allTracks " << std::endl; - const edm::RefToBase & left = ll->second->trackRef(); - + const edm::RefToBase& left = ll->second->trackRef(); //TODO: This is a workaround, should be fixed with a proper function in the TTBuilder //(Note that the TrackRef and GsfTrackRef versions of the constructor are needed @@ -367,98 +341,101 @@ void ConversionProducer::buildCollection(edm::Event& iEvent, const edm::EventSet reco::TransientTrack ttk_l; if (dynamic_cast(left.get())) { ttk_l = thettbuilder_->build(left.castTo()); - } - else { + } else { ttk_l = thettbuilder_->build(left.castTo()); } - - //// Remove BC matching from track selection + + //// Remove BC matching from track selection // if ((allowTrackBC_ && !trackValidECAL[ll-allTracks.begin()]) )//this Left leg should have valid BC // continue; - - - if (the_pvtx.isValid()){ - if (!(trackD0Cut(left, the_pvtx))) track1HighPurity=false; + + if (the_pvtx.isValid()) { + if (!(trackD0Cut(left, the_pvtx))) + track1HighPurity = false; } else { - if (!(trackD0Cut(left))) track1HighPurity=false; + if (!(trackD0Cut(left))) + track1HighPurity = false; } - - std::vector right_candidates;//store all right legs passed the cut (theta/approach and ref pair) + + std::vector right_candidates; //store all right legs passed the cut (theta/approach and ref pair) std::vector right_candidate_theta, right_candidate_approach; std::vector > vertex_candidates; - + //inner loop only over tracks between eta and eta + deltaEta of the first track float etasearch = ll->first + deltaEta_; std::multimap >::const_iterator rr = ll; - ++rr; - for (; rr != allTracks.lower_bound(etasearch); ++rr ) { + ++rr; + for (; rr != allTracks.lower_bound(etasearch); ++rr) { bool track2HighPurity = true; bool highPurityPair = true; - - const edm::RefToBase & right = rr->second->trackRef(); - - + + const edm::RefToBase& right = rr->second->trackRef(); + //TODO: This is a workaround, should be fixed with a proper function in the TTBuilder reco::TransientTrack ttk_r; if (dynamic_cast(right.get())) { ttk_r = thettbuilder_->build(right.castTo()); - } - else { + } else { ttk_r = thettbuilder_->build(right.castTo()); } //std::cout << " This track is " << right->algoName() << std::endl; - - + //all vertexing preselection should go here - + //check for opposite charge - if ( allowOppCharge_ && (left->charge()*right->charge() > 0) ) - continue; //same sign, reject pair - - //// Remove BC matching from track selection + if (allowOppCharge_ && (left->charge() * right->charge() > 0)) + continue; //same sign, reject pair + + //// Remove BC matching from track selection //if ( (allowTrackBC_ && !trackValidECAL[rr-allTracks.begin()] && rightBC_) )// if right track matches ECAL // continue; - - + double approachDist = -999.; //apply preselection to track pair, overriding preselection for gsf+X or ecalseeded+X pairs if so configured - bool preselected = preselectTrackPair(ttk_l,ttk_r, approachDist); - preselected = preselected || (bypassPreselGsf_ && (left->algo()==reco::TrackBase::gsf || right->algo()==reco::TrackBase::gsf)); - preselected = preselected || (bypassPreselEcal_ && (left->algo()==reco::TrackBase::outInEcalSeededConv || right->algo()==reco::TrackBase::outInEcalSeededConv || left->algo()==reco::TrackBase::inOutEcalSeededConv || right->algo()==reco::TrackBase::inOutEcalSeededConv)); - preselected = preselected || (bypassPreselEcalEcal_ && (left->algo()==reco::TrackBase::outInEcalSeededConv || left->algo()==reco::TrackBase::inOutEcalSeededConv) && (right->algo()==reco::TrackBase::outInEcalSeededConv || right->algo()==reco::TrackBase::inOutEcalSeededConv)); - + bool preselected = preselectTrackPair(ttk_l, ttk_r, approachDist); + preselected = preselected || (bypassPreselGsf_ && + (left->algo() == reco::TrackBase::gsf || right->algo() == reco::TrackBase::gsf)); + preselected = preselected || (bypassPreselEcal_ && (left->algo() == reco::TrackBase::outInEcalSeededConv || + right->algo() == reco::TrackBase::outInEcalSeededConv || + left->algo() == reco::TrackBase::inOutEcalSeededConv || + right->algo() == reco::TrackBase::inOutEcalSeededConv)); + preselected = preselected || (bypassPreselEcalEcal_ && + (left->algo() == reco::TrackBase::outInEcalSeededConv || + left->algo() == reco::TrackBase::inOutEcalSeededConv) && + (right->algo() == reco::TrackBase::outInEcalSeededConv || + right->algo() == reco::TrackBase::inOutEcalSeededConv)); + if (!preselected) { continue; } - + //do the actual vertex fit - reco::Vertex theConversionVertex;//by default it is invalid + reco::Vertex theConversionVertex; //by default it is invalid bool goodVertex = checkVertex(ttk_l, ttk_r, magField, theConversionVertex); - + //bail as early as possible in case the fit didn't return a good vertex if (!goodVertex) { continue; } - - //track pair pass the quality cut - if ( !( (trackQualityFilter(left, true) && trackQualityFilter(right, false)) - || (trackQualityFilter(left, false) && trackQualityFilter(right, true)) ) ) { - highPurityPair=false; + if (!((trackQualityFilter(left, true) && trackQualityFilter(right, false)) || + (trackQualityFilter(left, false) && trackQualityFilter(right, true)))) { + highPurityPair = false; } - if (the_pvtx.isValid()){ - if (!(trackD0Cut(right, the_pvtx))) track2HighPurity=false; + if (the_pvtx.isValid()) { + if (!(trackD0Cut(right, the_pvtx))) + track2HighPurity = false; } else { - if (!(trackD0Cut(right))) track2HighPurity=false; + if (!(trackD0Cut(right))) + track2HighPurity = false; } - //if all cuts passed, go ahead to make conversion candidates std::vector > trackPairRef; - trackPairRef.push_back(left);//left track - trackPairRef.push_back(right);//right track + trackPairRef.push_back(left); //left track + trackPairRef.push_back(right); //right track std::vector trackPin; std::vector trackPout; @@ -466,75 +443,75 @@ void ConversionProducer::buildCollection(edm::Event& iEvent, const edm::EventSet std::vector nHitsBeforeVtx; std::vector dlClosestHitToVtx; - if (left->extra().isNonnull() && right->extra().isNonnull()){//only available on TrackExtra - trackInnPos.push_back( toFConverterP(left->innerPosition())); - trackInnPos.push_back( toFConverterP(right->innerPosition())); + if (left->extra().isNonnull() && right->extra().isNonnull()) { //only available on TrackExtra + trackInnPos.push_back(toFConverterP(left->innerPosition())); + trackInnPos.push_back(toFConverterP(right->innerPosition())); trackPin.push_back(toFConverterV(left->innerMomentum())); trackPin.push_back(toFConverterV(right->innerMomentum())); trackPout.push_back(toFConverterV(left->outerMomentum())); - trackPout.push_back(toFConverterV(right->outerMomentum())); - auto leftWrongHits = hitChecker.nHitsBeforeVtx(*left->extra(),theConversionVertex); - auto rightWrongHits = hitChecker.nHitsBeforeVtx(*right->extra(),theConversionVertex); + trackPout.push_back(toFConverterV(right->outerMomentum())); + auto leftWrongHits = hitChecker.nHitsBeforeVtx(*left->extra(), theConversionVertex); + auto rightWrongHits = hitChecker.nHitsBeforeVtx(*right->extra(), theConversionVertex); nHitsBeforeVtx.push_back(leftWrongHits.first); nHitsBeforeVtx.push_back(rightWrongHits.first); dlClosestHitToVtx.push_back(leftWrongHits.second); - dlClosestHitToVtx.push_back(rightWrongHits.second); + dlClosestHitToVtx.push_back(rightWrongHits.second); } - - uint8_t nSharedHits = hitChecker.nSharedHits(*left.get(),*right.get()); + uint8_t nSharedHits = hitChecker.nSharedHits(*left.get(), *right.get()); //if using kinematic fit, check with chi2 post cut - if (theConversionVertex.isValid()){ + if (theConversionVertex.isValid()) { const float chi2Prob = ChiSquaredProbability(theConversionVertex.chi2(), theConversionVertex.ndof()); - if (chi2Prob trkPositionAtEcal; std::vector matchingBC; - if (allowTrackBC_){//TODO find out the BC ptrs if not doing matching, otherwise, leave it empty + if (allowTrackBC_) { //TODO find out the BC ptrs if not doing matching, otherwise, leave it empty //const int lbc_handle = bcHandleId[ll-allTracks.begin()], // rbc_handle = bcHandleId[rr-allTracks.begin()]; - std::map, math::XYZPointF>::const_iterator trackImpactPositionLeft = trackImpactPosition.find(ll->second); - std::map, math::XYZPointF>::const_iterator trackImpactPositionRight = trackImpactPosition.find(rr->second); - std::map, reco::CaloClusterPtr>::const_iterator trackMatchedBCLeft = trackMatchedBC.find(ll->second); - std::map, reco::CaloClusterPtr>::const_iterator trackMatchedBCRight = trackMatchedBC.find(rr->second); - - if (trackImpactPositionLeft!=trackImpactPosition.end()) { - trkPositionAtEcal.push_back(trackImpactPositionLeft->second);//left track - } - else { - trkPositionAtEcal.push_back(math::XYZPointF());//left track + std::map, math::XYZPointF>::const_iterator trackImpactPositionLeft = + trackImpactPosition.find(ll->second); + std::map, math::XYZPointF>::const_iterator trackImpactPositionRight = + trackImpactPosition.find(rr->second); + std::map, reco::CaloClusterPtr>::const_iterator trackMatchedBCLeft = + trackMatchedBC.find(ll->second); + std::map, reco::CaloClusterPtr>::const_iterator trackMatchedBCRight = + trackMatchedBC.find(rr->second); + + if (trackImpactPositionLeft != trackImpactPosition.end()) { + trkPositionAtEcal.push_back(trackImpactPositionLeft->second); //left track + } else { + trkPositionAtEcal.push_back(math::XYZPointF()); //left track } - if (trackImpactPositionRight!=trackImpactPosition.end()) {//second track ECAL position may be invalid + if (trackImpactPositionRight != trackImpactPosition.end()) { //second track ECAL position may be invalid trkPositionAtEcal.push_back(trackImpactPositionRight->second); } double total_e_bc = 0.; - if (trackMatchedBCLeft!=trackMatchedBC.end()) { - matchingBC.push_back(trackMatchedBCLeft->second);//left track + if (trackMatchedBCLeft != trackMatchedBC.end()) { + matchingBC.push_back(trackMatchedBCLeft->second); //left track total_e_bc += trackMatchedBCLeft->second->energy(); + } else { + matchingBC.push_back(reco::CaloClusterPtr()); //left track } - else { - matchingBC.push_back( reco::CaloClusterPtr() );//left track - } - if (trackMatchedBCRight!=trackMatchedBC.end()) {//second track ECAL position may be invalid + if (trackMatchedBCRight != trackMatchedBC.end()) { //second track ECAL position may be invalid matchingBC.push_back(trackMatchedBCRight->second); total_e_bc += trackMatchedBCRight->second->energy(); } - - if (total_e_bcsecond->isTrackerOnly() && rr->second->isTrackerOnly() && !dynamic_cast(ll->second->trackRef().get()) && !dynamic_cast(rr->second->trackRef().get()); + if (matchingSC(superClusterPtrs, newCandidate, scPtrVec)) + newCandidate.setMatchingSuperCluster(scPtrVec); + + newCandidate.setQuality(reco::Conversion::highPurity, highPurityPair); + bool generalTracksOnly = ll->second->isTrackerOnly() && rr->second->isTrackerOnly() && + !dynamic_cast(ll->second->trackRef().get()) && + !dynamic_cast(rr->second->trackRef().get()); bool gsfTracksOpenOnly = ll->second->isGsfTrackOpen() && rr->second->isGsfTrackOpen(); bool arbitratedEcalSeeded = ll->second->isArbitratedEcalSeeded() && rr->second->isArbitratedEcalSeeded(); bool arbitratedMerged = ll->second->isArbitratedMerged() && rr->second->isArbitratedMerged(); - bool arbitratedMergedEcalGeneral = ll->second->isArbitratedMergedEcalGeneral() && rr->second->isArbitratedMergedEcalGeneral(); - - newCandidate.setQuality(reco::Conversion::generalTracksOnly, generalTracksOnly); - newCandidate.setQuality(reco::Conversion::gsfTracksOpenOnly, gsfTracksOpenOnly); - newCandidate.setQuality(reco::Conversion::arbitratedEcalSeeded, arbitratedEcalSeeded); - newCandidate.setQuality(reco::Conversion::arbitratedMerged, arbitratedMerged); - newCandidate.setQuality(reco::Conversion::arbitratedMergedEcalGeneral, arbitratedMergedEcalGeneral); - - outputConvPhotonCollection.push_back(newCandidate); + bool arbitratedMergedEcalGeneral = + ll->second->isArbitratedMergedEcalGeneral() && rr->second->isArbitratedMergedEcalGeneral(); + + newCandidate.setQuality(reco::Conversion::generalTracksOnly, generalTracksOnly); + newCandidate.setQuality(reco::Conversion::gsfTracksOpenOnly, gsfTracksOpenOnly); + newCandidate.setQuality(reco::Conversion::arbitratedEcalSeeded, arbitratedEcalSeeded); + newCandidate.setQuality(reco::Conversion::arbitratedMerged, arbitratedMerged); + newCandidate.setQuality(reco::Conversion::arbitratedMergedEcalGeneral, arbitratedMergedEcalGeneral); + outputConvPhotonCollection.push_back(newCandidate); } - } - - - - - - } - - - - // // member functions // -inline bool ConversionProducer::trackQualityFilter(const edm::RefToBase& ref, bool isLeft){ +inline bool ConversionProducer::trackQualityFilter(const edm::RefToBase& ref, bool isLeft) { bool pass = true; - if (isLeft){ + if (isLeft) { pass = (ref->normalizedChi2() < maxChi2Left_ && ref->found() >= minHitsLeft_); } else { pass = (ref->normalizedChi2() < maxChi2Right_ && ref->found() >= minHitsRight_); @@ -602,169 +582,166 @@ inline bool ConversionProducer::trackQualityFilter(const edm::RefToBase& ref){ +inline bool ConversionProducer::trackD0Cut(const edm::RefToBase& ref) { //NOTE if not allow d0 cut, always true - return ((!allowD0_) || !(ref->d0()*ref->charge()/ref->d0Error()d0() * ref->charge() / ref->d0Error() < d0Cut_)); } -inline bool ConversionProducer::trackD0Cut(const edm::RefToBase& ref, const reco::Vertex& the_pvtx){ +inline bool ConversionProducer::trackD0Cut(const edm::RefToBase& ref, const reco::Vertex& the_pvtx) { // - return ((!allowD0_) || !(-ref->dxy(the_pvtx.position())*ref->charge()/ref->dxyError()dxy(the_pvtx.position()) * ref->charge() / ref->dxyError() < d0Cut_)); } - bool ConversionProducer::getTrackImpactPosition(const reco::Track* tk_ref, - const TrackerGeometry* trackerGeom, const MagneticField* magField, - math::XYZPointF& ew){ - - PropagatorWithMaterial propag( alongMomentum, 0.000511, magField ); - - ReferenceCountingPointer ecalWall( - new BoundCylinder(129.f, GlobalPoint(0.,0.,0.), TkRotation(), - new SimpleCylinderBounds( 129, 129, -320.5, 320.5 ) ) ); + const TrackerGeometry* trackerGeom, + const MagneticField* magField, + math::XYZPointF& ew) { + PropagatorWithMaterial propag(alongMomentum, 0.000511, magField); + + ReferenceCountingPointer ecalWall(new BoundCylinder( + 129.f, GlobalPoint(0., 0., 0.), TkRotation(), new SimpleCylinderBounds(129, 129, -320.5, 320.5))); const float epsilon = 0.001; - Surface::RotationType rot; // unit rotation matrix + Surface::RotationType rot; // unit rotation matrix const float barrelRadius = 129.f; const float barrelHalfLength = 270.9f; const float endcapRadius = 171.1f; const float endcapZ = 320.5f; - ReferenceCountingPointer theBarrel_(new BoundCylinder(barrelRadius, Surface::PositionType(0,0,0), rot, - new SimpleCylinderBounds( barrelRadius-epsilon, barrelRadius+epsilon, --barrelHalfLength, barrelHalfLength))); - ReferenceCountingPointer theNegativeEtaEndcap_( - new BoundDisk( Surface::PositionType( 0, 0, -endcapZ), rot, - new SimpleDiskBounds( 0, endcapRadius, -epsilon, epsilon))); - ReferenceCountingPointer thePositiveEtaEndcap_( - new BoundDisk( Surface::PositionType( 0, 0, endcapZ), rot, - new SimpleDiskBounds( 0, endcapRadius, -epsilon, epsilon))); + ReferenceCountingPointer theBarrel_(new BoundCylinder( + barrelRadius, + Surface::PositionType(0, 0, 0), + rot, + new SimpleCylinderBounds(barrelRadius - epsilon, barrelRadius + epsilon, -barrelHalfLength, barrelHalfLength))); + ReferenceCountingPointer theNegativeEtaEndcap_(new BoundDisk( + Surface::PositionType(0, 0, -endcapZ), rot, new SimpleDiskBounds(0, endcapRadius, -epsilon, epsilon))); + ReferenceCountingPointer thePositiveEtaEndcap_(new BoundDisk( + Surface::PositionType(0, 0, endcapZ), rot, new SimpleDiskBounds(0, endcapRadius, -epsilon, epsilon))); //const TrajectoryStateOnSurface myTSOS = trajectoryStateTransform::innerStateOnSurface(*(*ref), *trackerGeom, magField); - const TrajectoryStateOnSurface myTSOS = trajectoryStateTransform::outerStateOnSurface(*tk_ref, *trackerGeom, magField); - TrajectoryStateOnSurface stateAtECAL; + const TrajectoryStateOnSurface myTSOS = + trajectoryStateTransform::outerStateOnSurface(*tk_ref, *trackerGeom, magField); + TrajectoryStateOnSurface stateAtECAL; stateAtECAL = propag.propagate(myTSOS, *theBarrel_); - if (!stateAtECAL.isValid() || ( stateAtECAL.isValid() && fabs(stateAtECAL.globalPosition().eta() ) >1.479f ) ) { + if (!stateAtECAL.isValid() || (stateAtECAL.isValid() && fabs(stateAtECAL.globalPosition().eta()) > 1.479f)) { //endcap propagator if (myTSOS.globalPosition().z() > 0.) { - stateAtECAL = propag.propagate(myTSOS, *thePositiveEtaEndcap_); + stateAtECAL = propag.propagate(myTSOS, *thePositiveEtaEndcap_); } else { - stateAtECAL = propag.propagate(myTSOS, *theNegativeEtaEndcap_); + stateAtECAL = propag.propagate(myTSOS, *theNegativeEtaEndcap_); } - } - if (stateAtECAL.isValid()){ + } + if (stateAtECAL.isValid()) { ew = stateAtECAL.globalPosition(); return true; - } - else + } else return false; } - - - -bool ConversionProducer::matchingSC(const std::multimap& scMap, +bool ConversionProducer::matchingSC(const std::multimap& scMap, reco::Conversion& aConv, // reco::CaloClusterPtr& mSC){ reco::CaloClusterPtrVector& mSC) { - // double dRMin=999.; - double detaMin=999.; - double dphiMin=999.; + double detaMin = 999.; + double dphiMin = 999.; reco::CaloClusterPtr match; - for (std::multimap::const_iterator scItr = scMap.begin(); scItr != scMap.end(); scItr++) { - const reco::CaloClusterPtr& sc = scItr->second; - const double delta_phi = reco::deltaPhi( aConv.refittedPairMomentum().phi(), sc->phi()); + for (std::multimap::const_iterator scItr = scMap.begin(); scItr != scMap.end(); + scItr++) { + const reco::CaloClusterPtr& sc = scItr->second; + const double delta_phi = reco::deltaPhi(aConv.refittedPairMomentum().phi(), sc->phi()); double sceta = sc->eta(); - double conveta = etaTransformation(aConv.refittedPairMomentum().eta(), aConv.zOfPrimaryVertexFromTracks() ); + double conveta = etaTransformation(aConv.refittedPairMomentum().eta(), aConv.zOfPrimaryVertexFromTracks()); const double delta_eta = fabs(conveta - sceta); - if ( fabs(delta_eta) < fabs(detaMin) && fabs(delta_phi) < fabs(dphiMin) ) { - detaMin= fabs(delta_eta); - dphiMin= fabs(delta_phi); - match=sc; + if (fabs(delta_eta) < fabs(detaMin) && fabs(delta_phi) < fabs(dphiMin)) { + detaMin = fabs(delta_eta); + dphiMin = fabs(delta_phi); + match = sc; } } - - if ( fabs(detaMin) < dEtacutForSCmatching_ && fabs(dphiMin) < dPhicutForSCmatching_ ) { + + if (fabs(detaMin) < dEtacutForSCmatching_ && fabs(dphiMin) < dPhicutForSCmatching_) { mSC.push_back(match); return true; - } else + } else return false; } -bool ConversionProducer::getMatchedBC(const std::multimap& bcMap, +bool ConversionProducer::getMatchedBC(const std::multimap& bcMap, const math::XYZPointF& trackImpactPosition, - reco::CaloClusterPtr& closestBC){ + reco::CaloClusterPtr& closestBC) { const double track_eta = trackImpactPosition.eta(); const double track_phi = trackImpactPosition.phi(); double min_eta = 999., min_phi = 999.; reco::CaloClusterPtr closest_bc; for (std::multimap::const_iterator bc = bcMap.lower_bound(track_eta - halfWayEta_); - bc != bcMap.upper_bound(track_eta + halfWayEta_); ++bc){//use eta map to select possible BC collection then loop in + bc != bcMap.upper_bound(track_eta + halfWayEta_); + ++bc) { //use eta map to select possible BC collection then loop in const reco::CaloClusterPtr& ebc = bc->second; - const double delta_eta = track_eta-(ebc->position().eta()); + const double delta_eta = track_eta - (ebc->position().eta()); const double delta_phi = reco::deltaPhi(track_phi, (ebc->position().phi())); - if (fabs(delta_eta)fabs(delta_eta) && fabs(min_phi)>fabs(delta_phi)){//take the closest to track BC + if (fabs(delta_eta) < dEtaTkBC_ && fabs(delta_phi) < dPhiTkBC_) { + if (fabs(min_eta) > fabs(delta_eta) && fabs(min_phi) > fabs(delta_phi)) { //take the closest to track BC min_eta = delta_eta; min_phi = delta_phi; closest_bc = bc->second; //TODO check if min_eta>delta_eta but min_phi& tk_l, const edm::RefToBase& tk_r, - const TrackerGeometry* trackerGeom, const MagneticField* magField, - const reco::Vertex& vtx){ +bool ConversionProducer::checkPhi(const edm::RefToBase& tk_l, + const edm::RefToBase& tk_r, + const TrackerGeometry* trackerGeom, + const MagneticField* magField, + const reco::Vertex& vtx) { if (!allowDeltaPhi_) return true; //if track has innermost momentum, check with innermost phi //if track also has valid vertex, propagate to vertex then calculate phi there //if track has no innermost momentum, just return true, because track->phi() makes no sense - if (tk_l->extra().isNonnull() && tk_r->extra().isNonnull()){ + if (tk_l->extra().isNonnull() && tk_r->extra().isNonnull()) { double iphi1 = tk_l->innerMomentum().phi(), iphi2 = tk_r->innerMomentum().phi(); - if (vtx.isValid()){ - PropagatorWithMaterial propag( anyDirection, 0.000511, magField ); - - double recoPhoR = vtx.position().Rho(); - Surface::RotationType rot; - ReferenceCountingPointer theBarrel_(new BoundCylinder(recoPhoR, Surface::PositionType(0,0,0), rot, - new SimpleCylinderBounds( recoPhoR-0.001, recoPhoR+0.001, - -fabs(vtx.position().z()), fabs(vtx.position().z())))); - ReferenceCountingPointer theDisk_( - new BoundDisk( Surface::PositionType( 0, 0, vtx.position().z()), rot, - new SimpleDiskBounds( 0, recoPhoR, -0.001, 0.001))); - - const TrajectoryStateOnSurface myTSOS1 = trajectoryStateTransform::innerStateOnSurface(*tk_l, *trackerGeom, magField); - const TrajectoryStateOnSurface myTSOS2 = trajectoryStateTransform::innerStateOnSurface(*tk_r, *trackerGeom, magField); - TrajectoryStateOnSurface stateAtVtx1, stateAtVtx2; - stateAtVtx1 = propag.propagate(myTSOS1, *theBarrel_); - if (!stateAtVtx1.isValid() ) { + if (vtx.isValid()) { + PropagatorWithMaterial propag(anyDirection, 0.000511, magField); + + double recoPhoR = vtx.position().Rho(); + Surface::RotationType rot; + ReferenceCountingPointer theBarrel_(new BoundCylinder( + recoPhoR, + Surface::PositionType(0, 0, 0), + rot, + new SimpleCylinderBounds( + recoPhoR - 0.001, recoPhoR + 0.001, -fabs(vtx.position().z()), fabs(vtx.position().z())))); + ReferenceCountingPointer theDisk_(new BoundDisk( + Surface::PositionType(0, 0, vtx.position().z()), rot, new SimpleDiskBounds(0, recoPhoR, -0.001, 0.001))); + + const TrajectoryStateOnSurface myTSOS1 = + trajectoryStateTransform::innerStateOnSurface(*tk_l, *trackerGeom, magField); + const TrajectoryStateOnSurface myTSOS2 = + trajectoryStateTransform::innerStateOnSurface(*tk_r, *trackerGeom, magField); + TrajectoryStateOnSurface stateAtVtx1, stateAtVtx2; + stateAtVtx1 = propag.propagate(myTSOS1, *theBarrel_); + if (!stateAtVtx1.isValid()) { stateAtVtx1 = propag.propagate(myTSOS1, *theDisk_); - } - if (stateAtVtx1.isValid()){ + } + if (stateAtVtx1.isValid()) { iphi1 = stateAtVtx1.globalDirection().phi(); - } - stateAtVtx2 = propag.propagate(myTSOS2, *theBarrel_); - if (!stateAtVtx2.isValid() ) { + } + stateAtVtx2 = propag.propagate(myTSOS2, *theBarrel_); + if (!stateAtVtx2.isValid()) { stateAtVtx2 = propag.propagate(myTSOS2, *theDisk_); - } - if (stateAtVtx2.isValid()){ + } + if (stateAtVtx2.isValid()) { iphi2 = stateAtVtx2.globalDirection().phi(); - } + } } const double dPhi = reco::deltaPhi(iphi1, iphi2); return (fabs(dPhi) < deltaPhi_); @@ -773,139 +750,131 @@ bool ConversionProducer::checkPhi(const edm::RefToBase& tk_l, const } } -bool ConversionProducer::preselectTrackPair(const reco::TransientTrack &ttk_l, const reco::TransientTrack &ttk_r, +bool ConversionProducer::preselectTrackPair(const reco::TransientTrack& ttk_l, + const reco::TransientTrack& ttk_r, double& appDist) { - - - double dCotTheta = 1./tan(ttk_l.track().innerMomentum().theta()) - 1./tan(ttk_r.track().innerMomentum().theta()); + double dCotTheta = 1. / tan(ttk_l.track().innerMomentum().theta()) - 1. / tan(ttk_r.track().innerMomentum().theta()); if (allowDeltaCot_ && (std::abs(dCotTheta) > deltaCotTheta_)) { return false; } - + //non-conversion hypothesis, reject prompt track pairs ClosestApproachInRPhi closest; - closest.calculate(ttk_l.innermostMeasurementState(),ttk_r.innermostMeasurementState()); + closest.calculate(ttk_l.innermostMeasurementState(), ttk_r.innermostMeasurementState()); if (!closest.status()) { return false; } - + if (closest.crossingPoint().perp() < r_cut) { return false; } - //compute tangent point btw tracks (conversion hypothesis) TangentApproachInRPhi tangent; - tangent.calculate(ttk_l.innermostMeasurementState(),ttk_r.innermostMeasurementState()); + tangent.calculate(ttk_l.innermostMeasurementState(), ttk_r.innermostMeasurementState()); if (!tangent.status()) { return false; } - + GlobalPoint tangentPoint = tangent.crossingPoint(); double rho = tangentPoint.perp(); - + //reject candidates well outside of tracker bounds if (rho > maxTrackRho_) { return false; } - + if (std::abs(tangentPoint.z()) > maxTrackZ_) { return false; } - - std::pair trajs = tangent.trajectoryParameters(); - + + std::pair trajs = tangent.trajectoryParameters(); + //very large separation in z, no hope if (std::abs(trajs.first.position().z() - trajs.second.position().z()) > dzCut_) { return false; } - - + float minApproach = tangent.perpdist(); appDist = minApproach; - - if (allowMinApproach_ && (minApproach < minApproachLow_ || minApproach > minApproachHigh_) ) { + + if (allowMinApproach_ && (minApproach < minApproachLow_ || minApproach > minApproachHigh_)) { return false; } - + return true; - - } -bool ConversionProducer::checkTrackPair(const std::pair, reco::CaloClusterPtr>& ll, - const std::pair, reco::CaloClusterPtr>& rr){ - - const reco::CaloClusterPtr& bc_l = ll.second;//can be null, so check isNonnull() +bool ConversionProducer::checkTrackPair(const std::pair, reco::CaloClusterPtr>& ll, + const std::pair, reco::CaloClusterPtr>& rr) { + const reco::CaloClusterPtr& bc_l = ll.second; //can be null, so check isNonnull() const reco::CaloClusterPtr& bc_r = rr.second; - + //The cuts should be ordered by considering if takes time and if cuts off many fakes - if (allowTrackBC_){ + if (allowTrackBC_) { //check energy of BC double total_e_bc = 0; - if (bc_l.isNonnull()) total_e_bc += bc_l->energy(); - if (rightBC_) - if (bc_r.isNonnull()) + if (bc_l.isNonnull()) + total_e_bc += bc_l->energy(); + if (rightBC_) + if (bc_r.isNonnull()) total_e_bc += bc_r->energy(); - if (total_e_bc < energyTotalBC_) return false; + if (total_e_bc < energyTotalBC_) + return false; } return true; } - - //because reco::vertex uses track ref, so have to keep them -bool ConversionProducer::checkVertex(const reco::TransientTrack &ttk_l, const reco::TransientTrack &ttk_r, +bool ConversionProducer::checkVertex(const reco::TransientTrack& ttk_l, + const reco::TransientTrack& ttk_r, const MagneticField* magField, - reco::Vertex& the_vertex){ + reco::Vertex& the_vertex) { bool found = false; - std::vector pair; + std::vector pair; pair.push_back(ttk_l); pair.push_back(ttk_r); - - found = theVertexFinder_->run(pair, the_vertex); - + found = theVertexFinder_->run(pair, the_vertex); return found; } - - -double ConversionProducer::etaTransformation( float EtaParticle , float Zvertex) { - +double ConversionProducer::etaTransformation(float EtaParticle, float Zvertex) { //---Definitions - const float PI = 3.1415927; + const float PI = 3.1415927; //---Definitions for ECAL - const float R_ECAL = 136.5; - const float Z_Endcap = 328.0; - const float etaBarrelEndcap = 1.479; - + const float R_ECAL = 136.5; + const float Z_Endcap = 328.0; + const float etaBarrelEndcap = 1.479; + //---ETA correction - float Theta = 0.0 ; - float ZEcal = R_ECAL*sinh(EtaParticle)+Zvertex; - - if(ZEcal != 0.0) Theta = atan(R_ECAL/ZEcal); - if(Theta<0.0) Theta = Theta+PI ; - double ETA = - log(tan(0.5*Theta)); - - if( fabs(ETA) > etaBarrelEndcap ) - { - float Zend = Z_Endcap ; - if(EtaParticle<0.0 ) Zend = -Zend ; - float Zlen = Zend - Zvertex ; - float RR = Zlen/sinh(EtaParticle); - Theta = atan(RR/Zend); - if(Theta<0.0) Theta = Theta+PI ; - ETA = - log(tan(0.5*Theta)); - } + float Theta = 0.0; + float ZEcal = R_ECAL * sinh(EtaParticle) + Zvertex; + + if (ZEcal != 0.0) + Theta = atan(R_ECAL / ZEcal); + if (Theta < 0.0) + Theta = Theta + PI; + double ETA = -log(tan(0.5 * Theta)); + + if (fabs(ETA) > etaBarrelEndcap) { + float Zend = Z_Endcap; + if (EtaParticle < 0.0) + Zend = -Zend; + float Zlen = Zend - Zvertex; + float RR = Zlen / sinh(EtaParticle); + Theta = atan(RR / Zend); + if (Theta < 0.0) + Theta = Theta + PI; + ETA = -log(tan(0.5 * Theta)); + } //---Return the result return ETA; //---end } - diff --git a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackCandidateProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackCandidateProducer.cc index 4ef26c94e183d..b83e95d08fd2b 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackCandidateProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackCandidateProducer.cc @@ -50,133 +50,116 @@ namespace { auto createBaseCkfTrajectoryBuilder(const edm::ParameterSet& pset, edm::ConsumesCollector&& iC) { return BaseCkfTrajectoryBuilderFactory::get()->create(pset.getParameter("ComponentType"), pset, iC); } -} - -ConversionTrackCandidateProducer::ConversionTrackCandidateProducer(const edm::ParameterSet& config) : - theTrajectoryBuilder_(createBaseCkfTrajectoryBuilder(config.getParameter("TrajectoryBuilderPSet"), consumesCollector())), - theOutInSeedFinder_(new OutInConversionSeedFinder(config,consumesCollector())), - theOutInTrackFinder_(new OutInConversionTrackFinder(config, theTrajectoryBuilder_.get())), - theInOutSeedFinder_(new InOutConversionSeedFinder(config,consumesCollector())), - theInOutTrackFinder_(new InOutConversionTrackFinder(config, theTrajectoryBuilder_.get())) -{ +} // namespace + +ConversionTrackCandidateProducer::ConversionTrackCandidateProducer(const edm::ParameterSet& config) + : theTrajectoryBuilder_(createBaseCkfTrajectoryBuilder( + config.getParameter("TrajectoryBuilderPSet"), consumesCollector())), + theOutInSeedFinder_(new OutInConversionSeedFinder(config, consumesCollector())), + theOutInTrackFinder_(new OutInConversionTrackFinder(config, theTrajectoryBuilder_.get())), + theInOutSeedFinder_(new InOutConversionSeedFinder(config, consumesCollector())), + theInOutTrackFinder_(new InOutConversionTrackFinder(config, theTrajectoryBuilder_.get())) { //std::cout << "ConversionTrackCandidateProducer CTOR " << "\n"; - nEvt_=0; - + nEvt_ = 0; + // use onfiguration file to setup input/output collection names - - - bcBarrelCollection_ = - consumes >(config.getParameter("bcBarrelCollection")); - bcEndcapCollection_ = - consumes >(config.getParameter("bcEndcapCollection")); - - scHybridBarrelProducer_ = - consumes >(config.getParameter("scHybridBarrelProducer")); - scIslandEndcapProducer_ = - consumes >(config.getParameter("scIslandEndcapProducer")); - + + bcBarrelCollection_ = + consumes >(config.getParameter("bcBarrelCollection")); + bcEndcapCollection_ = + consumes >(config.getParameter("bcEndcapCollection")); + + scHybridBarrelProducer_ = + consumes >(config.getParameter("scHybridBarrelProducer")); + scIslandEndcapProducer_ = + consumes >(config.getParameter("scIslandEndcapProducer")); + OutInTrackCandidateCollection_ = config.getParameter("outInTrackCandidateCollection"); InOutTrackCandidateCollection_ = config.getParameter("inOutTrackCandidateCollection"); - - OutInTrackSuperClusterAssociationCollection_ = config.getParameter("outInTrackCandidateSCAssociationCollection"); - InOutTrackSuperClusterAssociationCollection_ = config.getParameter("inOutTrackCandidateSCAssociationCollection"); - - barrelecalCollection_ = - consumes(config.getParameter("barrelEcalRecHitCollection")); - endcapecalCollection_ = - consumes(config.getParameter("endcapEcalRecHitCollection")); - hcalTowers_ = - consumes(config.getParameter("hcalTowers")); - measurementTrkEvtToken_ = - consumes(edm::InputTag("MeasurementTrackerEvent")); - hOverEConeSize_ = config.getParameter("hOverEConeSize"); - maxHOverE_ = config.getParameter("maxHOverE"); - minSCEt_ = config.getParameter("minSCEt"); - isoConeR_ = config.getParameter("isoConeR"); - isoInnerConeR_ = config.getParameter("isoInnerConeR"); - isoEtaSlice_ = config.getParameter("isoEtaSlice"); - isoEtMin_ = config.getParameter("isoEtMin"); - isoEMin_ = config.getParameter("isoEMin"); + OutInTrackSuperClusterAssociationCollection_ = + config.getParameter("outInTrackCandidateSCAssociationCollection"); + InOutTrackSuperClusterAssociationCollection_ = + config.getParameter("inOutTrackCandidateSCAssociationCollection"); + + barrelecalCollection_ = + consumes(config.getParameter("barrelEcalRecHitCollection")); + endcapecalCollection_ = + consumes(config.getParameter("endcapEcalRecHitCollection")); + hcalTowers_ = consumes(config.getParameter("hcalTowers")); + measurementTrkEvtToken_ = consumes(edm::InputTag("MeasurementTrackerEvent")); + hOverEConeSize_ = config.getParameter("hOverEConeSize"); + maxHOverE_ = config.getParameter("maxHOverE"); + minSCEt_ = config.getParameter("minSCEt"); + isoConeR_ = config.getParameter("isoConeR"); + isoInnerConeR_ = config.getParameter("isoInnerConeR"); + isoEtaSlice_ = config.getParameter("isoEtaSlice"); + isoEtMin_ = config.getParameter("isoEtMin"); + isoEMin_ = config.getParameter("isoEMin"); vetoClusteredHits_ = config.getParameter("vetoClusteredHits"); - useNumXtals_ = config.getParameter("useNumXstals"); - ecalIsoCut_offset_ = config.getParameter("ecalIsoCut_offset"); - ecalIsoCut_slope_ = config.getParameter("ecalIsoCut_slope"); + useNumXtals_ = config.getParameter("useNumXstals"); + ecalIsoCut_offset_ = config.getParameter("ecalIsoCut_offset"); + ecalIsoCut_slope_ = config.getParameter("ecalIsoCut_slope"); //Flags and Severities to be excluded from photon calculations - const std::vector flagnamesEB = - config.getParameter >("RecHitFlagToBeExcludedEB"); + const std::vector flagnamesEB = + config.getParameter >("RecHitFlagToBeExcludedEB"); const std::vector flagnamesEE = - config.getParameter >("RecHitFlagToBeExcludedEE"); + config.getParameter >("RecHitFlagToBeExcludedEE"); - flagsexclEB_= - StringToEnumValue(flagnamesEB); + flagsexclEB_ = StringToEnumValue(flagnamesEB); - flagsexclEE_= - StringToEnumValue(flagnamesEE); + flagsexclEE_ = StringToEnumValue(flagnamesEE); - const std::vector severitynamesEB = - config.getParameter >("RecHitSeverityToBeExcludedEB"); + const std::vector severitynamesEB = + config.getParameter >("RecHitSeverityToBeExcludedEB"); - severitiesexclEB_= - StringToEnumValue(severitynamesEB); + severitiesexclEB_ = StringToEnumValue(severitynamesEB); - const std::vector severitynamesEE = - config.getParameter >("RecHitSeverityToBeExcludedEE"); + const std::vector severitynamesEE = + config.getParameter >("RecHitSeverityToBeExcludedEE"); - severitiesexclEE_= - StringToEnumValue(severitynamesEE); + severitiesexclEE_ = StringToEnumValue(severitynamesEE); // Register the product - produces< TrackCandidateCollection > (OutInTrackCandidateCollection_); - produces< TrackCandidateCollection > (InOutTrackCandidateCollection_); - - produces< reco::TrackCandidateCaloClusterPtrAssociation > ( OutInTrackSuperClusterAssociationCollection_); - produces< reco::TrackCandidateCaloClusterPtrAssociation > ( InOutTrackSuperClusterAssociationCollection_); - + produces(OutInTrackCandidateCollection_); + produces(InOutTrackCandidateCollection_); + produces(OutInTrackSuperClusterAssociationCollection_); + produces(InOutTrackSuperClusterAssociationCollection_); } -ConversionTrackCandidateProducer::~ConversionTrackCandidateProducer(){} +ConversionTrackCandidateProducer::~ConversionTrackCandidateProducer() {} -void ConversionTrackCandidateProducer::setEventSetup (const edm::EventSetup & theEventSetup) { +void ConversionTrackCandidateProducer::setEventSetup(const edm::EventSetup& theEventSetup) { theOutInSeedFinder_->setEventSetup(theEventSetup); theInOutSeedFinder_->setEventSetup(theEventSetup); theOutInTrackFinder_->setEventSetup(theEventSetup); theInOutTrackFinder_->setEventSetup(theEventSetup); } - -void ConversionTrackCandidateProducer::beginRun (edm::Run const& r , edm::EventSetup const & theEventSetup) { - +void ConversionTrackCandidateProducer::beginRun(edm::Run const& r, edm::EventSetup const& theEventSetup) { edm::ESHandle nav; theEventSetup.get().get("SimpleNavigationSchool", nav); - const NavigationSchool *navigation = nav.product(); + const NavigationSchool* navigation = nav.product(); theTrajectoryBuilder_->setNavigationSchool(navigation); theOutInSeedFinder_->setNavigationSchool(navigation); theInOutSeedFinder_->setNavigationSchool(navigation); } - void ConversionTrackCandidateProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { - using namespace edm; nEvt_++; // std::cout << "ConversionTrackCandidateProducer Analyzing event number " << theEvent.id() << " Global Counter " << nEvt_ << "\n"; - - // get the trajectory builder and initialize it with the data edm::Handle data; - theEvent.getByToken( measurementTrkEvtToken_, data); + theEvent.getByToken(measurementTrkEvtToken_, data); theTrajectoryBuilder_->setEvent(theEvent, theEventSetup, &*data); - // this need to be done after the initialization of the TrajectoryBuilder! - setEventSetup( theEventSetup ); - - + setEventSetup(theEventSetup); theOutInSeedFinder_->setEvent(theEvent); theInOutSeedFinder_->setEvent(theEvent); @@ -185,62 +168,53 @@ void ConversionTrackCandidateProducer::produce(edm::Event& theEvent, const edm:: // create empty output collections // // Out In Track Candidates - auto outInTrackCandidate_p = std::make_unique(); + auto outInTrackCandidate_p = std::make_unique(); // In Out Track Candidates - auto inOutTrackCandidate_p = std::make_unique(); + auto inOutTrackCandidate_p = std::make_unique(); // Track Candidate calo Cluster Association auto outInAssoc_p = std::make_unique(); auto inOutAssoc_p = std::make_unique(); - - // Get the basic cluster collection in the Barrel - bool validBarrelBCHandle=true; + + // Get the basic cluster collection in the Barrel + bool validBarrelBCHandle = true; edm::Handle > bcBarrelHandle; theEvent.getByToken(bcBarrelCollection_, bcBarrelHandle); if (!bcBarrelHandle.isValid()) { - edm::LogError("ConversionTrackCandidateProducer") - << "Error! Can't get the Barrel Basic Clusters!"; - validBarrelBCHandle=false; + edm::LogError("ConversionTrackCandidateProducer") << "Error! Can't get the Barrel Basic Clusters!"; + validBarrelBCHandle = false; } - - - // Get the basic cluster collection in the Endcap - bool validEndcapBCHandle=true; + + // Get the basic cluster collection in the Endcap + bool validEndcapBCHandle = true; edm::Handle > bcEndcapHandle; theEvent.getByToken(bcEndcapCollection_, bcEndcapHandle); if (!bcEndcapHandle.isValid()) { - edm::LogError("CoonversionTrackCandidateProducer") - << "Error! Can't get the Endcap Basic Clusters"; - validEndcapBCHandle=false; + edm::LogError("CoonversionTrackCandidateProducer") << "Error! Can't get the Endcap Basic Clusters"; + validEndcapBCHandle = false; } - - // Get the Super Cluster collection in the Barrel - bool validBarrelSCHandle=true; + bool validBarrelSCHandle = true; edm::Handle > scBarrelHandle; - theEvent.getByToken(scHybridBarrelProducer_,scBarrelHandle); + theEvent.getByToken(scHybridBarrelProducer_, scBarrelHandle); if (!scBarrelHandle.isValid()) { - edm::LogError("CoonversionTrackCandidateProducer") - << "Error! Can't get the barrel superclusters!"; - validBarrelSCHandle=false; + edm::LogError("CoonversionTrackCandidateProducer") << "Error! Can't get the barrel superclusters!"; + validBarrelSCHandle = false; } - // Get the Super Cluster collection in the Endcap - bool validEndcapSCHandle=true; + bool validEndcapSCHandle = true; edm::Handle > scEndcapHandle; - theEvent.getByToken(scIslandEndcapProducer_,scEndcapHandle); + theEvent.getByToken(scIslandEndcapProducer_, scEndcapHandle); if (!scEndcapHandle.isValid()) { - edm::LogError("CoonversionTrackCandidateProducer") - << "Error! Can't get the endcap superclusters!"; - validEndcapSCHandle=false; + edm::LogError("CoonversionTrackCandidateProducer") << "Error! Can't get the endcap superclusters!"; + validEndcapSCHandle = false; } - // get the geometry from the event setup: theEventSetup.get().get(theCaloGeom_); - // get Hcal towers collection + // get Hcal towers collection Handle hcalTowersHandle; theEvent.getByToken(hcalTowers_, hcalTowersHandle); @@ -257,100 +231,106 @@ void ConversionTrackCandidateProducer::produce(edm::Event& theEvent, const edm:: caloPtrVecOutIn_.clear(); caloPtrVecInOut_.clear(); - bool isBarrel=true; - if ( validBarrelBCHandle && validBarrelSCHandle ) - buildCollections(isBarrel, scBarrelHandle, bcBarrelHandle, ecalhitsCollEB, *ecalhitsCollEB, sevLevel, hcalTowersHandle, *outInTrackCandidate_p, *inOutTrackCandidate_p, caloPtrVecOutIn_, caloPtrVecInOut_); - - if ( validEndcapBCHandle && validEndcapSCHandle ) { - isBarrel=false; - buildCollections(isBarrel, scEndcapHandle, bcEndcapHandle, ecalhitsCollEE, *ecalhitsCollEE, sevLevel, hcalTowersHandle, *outInTrackCandidate_p, *inOutTrackCandidate_p, caloPtrVecOutIn_, caloPtrVecInOut_); + bool isBarrel = true; + if (validBarrelBCHandle && validBarrelSCHandle) + buildCollections(isBarrel, + scBarrelHandle, + bcBarrelHandle, + ecalhitsCollEB, + *ecalhitsCollEB, + sevLevel, + hcalTowersHandle, + *outInTrackCandidate_p, + *inOutTrackCandidate_p, + caloPtrVecOutIn_, + caloPtrVecInOut_); + + if (validEndcapBCHandle && validEndcapSCHandle) { + isBarrel = false; + buildCollections(isBarrel, + scEndcapHandle, + bcEndcapHandle, + ecalhitsCollEE, + *ecalhitsCollEE, + sevLevel, + hcalTowersHandle, + *outInTrackCandidate_p, + *inOutTrackCandidate_p, + caloPtrVecOutIn_, + caloPtrVecInOut_); } - - // std::cout << " ConversionTrackCandidateProducer caloPtrVecOutIn_ size " << caloPtrVecOutIn_.size() << " caloPtrVecInOut_ size " << caloPtrVecInOut_.size() << "\n"; - - + // std::cout << " ConversionTrackCandidateProducer caloPtrVecOutIn_ size " << caloPtrVecOutIn_.size() << " caloPtrVecInOut_ size " << caloPtrVecInOut_.size() << "\n"; // put all products in the event - // Barrel - //std::cout << "ConversionTrackCandidateProducer Putting in the event " << (*outInTrackCandidate_p).size() << " Out In track Candidates " << "\n"; - const edm::OrphanHandle refprodOutInTrackC = theEvent.put(std::move(outInTrackCandidate_p), OutInTrackCandidateCollection_ ); - //std::cout << "ConversionTrackCandidateProducer refprodOutInTrackC size " << (*(refprodOutInTrackC.product())).size() << "\n"; - // - //std::cout << "ConversionTrackCandidateProducer Putting in the event " << (*inOutTrackCandidate_p).size() << " In Out track Candidates " << "\n"; - const edm::OrphanHandle refprodInOutTrackC = theEvent.put(std::move(inOutTrackCandidate_p), InOutTrackCandidateCollection_ ); - //std::cout << "ConversionTrackCandidateProducer refprodInOutTrackC size " << (*(refprodInOutTrackC.product())).size() << "\n"; - - - edm::ValueMap::Filler fillerOI(*outInAssoc_p); - fillerOI.insert(refprodOutInTrackC, caloPtrVecOutIn_.begin(), caloPtrVecOutIn_.end()); - fillerOI.fill(); - edm::ValueMap::Filler fillerIO(*inOutAssoc_p); - fillerIO.insert(refprodInOutTrackC, caloPtrVecInOut_.begin(), caloPtrVecInOut_.end()); - fillerIO.fill(); - - - - // std::cout << "ConversionTrackCandidateProducer Putting in the event OutIn track - SC association: size " << (*outInAssoc_p).size() << "\n"; - theEvent.put(std::move(outInAssoc_p), OutInTrackSuperClusterAssociationCollection_); - - // std::cout << "ConversionTrackCandidateProducer Putting in the event InOut track - SC association: size " << (*inOutAssoc_p).size() << "\n"; - theEvent.put(std::move(inOutAssoc_p), InOutTrackSuperClusterAssociationCollection_); - - theOutInSeedFinder_->clear(); - theInOutSeedFinder_->clear(); - - - + // Barrel + //std::cout << "ConversionTrackCandidateProducer Putting in the event " << (*outInTrackCandidate_p).size() << " Out In track Candidates " << "\n"; + const edm::OrphanHandle refprodOutInTrackC = + theEvent.put(std::move(outInTrackCandidate_p), OutInTrackCandidateCollection_); + //std::cout << "ConversionTrackCandidateProducer refprodOutInTrackC size " << (*(refprodOutInTrackC.product())).size() << "\n"; + // + //std::cout << "ConversionTrackCandidateProducer Putting in the event " << (*inOutTrackCandidate_p).size() << " In Out track Candidates " << "\n"; + const edm::OrphanHandle refprodInOutTrackC = + theEvent.put(std::move(inOutTrackCandidate_p), InOutTrackCandidateCollection_); + //std::cout << "ConversionTrackCandidateProducer refprodInOutTrackC size " << (*(refprodInOutTrackC.product())).size() << "\n"; + + edm::ValueMap::Filler fillerOI(*outInAssoc_p); + fillerOI.insert(refprodOutInTrackC, caloPtrVecOutIn_.begin(), caloPtrVecOutIn_.end()); + fillerOI.fill(); + edm::ValueMap::Filler fillerIO(*inOutAssoc_p); + fillerIO.insert(refprodInOutTrackC, caloPtrVecInOut_.begin(), caloPtrVecInOut_.end()); + fillerIO.fill(); + + // std::cout << "ConversionTrackCandidateProducer Putting in the event OutIn track - SC association: size " << (*outInAssoc_p).size() << "\n"; + theEvent.put(std::move(outInAssoc_p), OutInTrackSuperClusterAssociationCollection_); + + // std::cout << "ConversionTrackCandidateProducer Putting in the event InOut track - SC association: size " << (*inOutAssoc_p).size() << "\n"; + theEvent.put(std::move(inOutAssoc_p), InOutTrackSuperClusterAssociationCollection_); + + theOutInSeedFinder_->clear(); + theInOutSeedFinder_->clear(); } - -void ConversionTrackCandidateProducer::buildCollections(bool isBarrel, - const edm::Handle > & scHandle, - const edm::Handle > & bcHandle, - edm::Handle ecalRecHitHandle, - const EcalRecHitCollection& ecalRecHits, - const EcalSeverityLevelAlgo* sevLevel, - //edm::ESHandle chStatus, - //const EcalChannelStatus* chStatus, - const edm::Handle & hcalTowersHandle, - TrackCandidateCollection& outInTrackCandidates, - TrackCandidateCollection& inOutTrackCandidates, - std::vector >& vecRecOI, - std::vector >& vecRecIO ) +void ConversionTrackCandidateProducer::buildCollections(bool isBarrel, + const edm::Handle >& scHandle, + const edm::Handle >& bcHandle, + edm::Handle ecalRecHitHandle, + const EcalRecHitCollection& ecalRecHits, + const EcalSeverityLevelAlgo* sevLevel, + //edm::ESHandle chStatus, + //const EcalChannelStatus* chStatus, + const edm::Handle& hcalTowersHandle, + TrackCandidateCollection& outInTrackCandidates, + TrackCandidateCollection& inOutTrackCandidates, + std::vector >& vecRecOI, + std::vector >& vecRecIO) { - //std::cout << "ConversionTrackCandidateProducer is barrel " << isBarrel << "\n"; //std::cout << "ConversionTrackCandidateProducer builcollections sc size " << scHandle->size() << "\n"; //std::cout << "ConversionTrackCandidateProducer builcollections bc size " << bcHandle->size() << "\n"; //const CaloGeometry* geometry = theCaloGeom_.product(); // Loop over SC in the barrel and reconstruct converted photons - for(auto const& aClus : scHandle->ptrs()) - { - // preselection based in Et and H/E cut. - if (aClus->energy()/cosh(aClus->eta()) <= minSCEt_) continue; - if (aClus->eta() > 1.479 && aClus->eta() < 1.556 ) continue; - - const reco::CaloCluster* pClus=&(*aClus); - const reco::SuperCluster* sc=dynamic_cast(pClus); - double scEt = sc->energy()/cosh(sc->eta()); + for (auto const& aClus : scHandle->ptrs()) { + // preselection based in Et and H/E cut. + if (aClus->energy() / cosh(aClus->eta()) <= minSCEt_) + continue; + if (aClus->eta() > 1.479 && aClus->eta() < 1.556) + continue; + + const reco::CaloCluster* pClus = &(*aClus); + const reco::SuperCluster* sc = dynamic_cast(pClus); + double scEt = sc->energy() / cosh(sc->eta()); const CaloTowerCollection* hcalTowersColl = hcalTowersHandle.product(); - EgammaTowerIsolation towerIso(hOverEConeSize_,0.,0.,-1,hcalTowersColl) ; - double HoE = towerIso.getTowerESum(sc)/sc->energy(); - if (HoE >= maxHOverE_) continue; + EgammaTowerIsolation towerIso(hOverEConeSize_, 0., 0., -1, hcalTowersColl); + double HoE = towerIso.getTowerESum(sc) / sc->energy(); + if (HoE >= maxHOverE_) + continue; //// Apply also ecal isolation - EgammaRecHitIsolation ecalIso(isoConeR_, - isoInnerConeR_, - isoEtaSlice_, - isoEtMin_, - isoEMin_, - theCaloGeom_, - ecalRecHits, - sevLevel, - DetId::Ecal); + EgammaRecHitIsolation ecalIso( + isoConeR_, isoInnerConeR_, isoEtaSlice_, isoEtMin_, isoEMin_, theCaloGeom_, ecalRecHits, sevLevel, DetId::Ecal); ecalIso.setVetoClustered(vetoClusteredHits_); ecalIso.setUseNumCrystals(useNumXtals_); @@ -363,34 +343,37 @@ void ConversionTrackCandidateProducer::buildCollections(bool isBarrel, } double ecalIsolation = ecalIso.getEtSum(sc); - if ( ecalIsolation > ecalIsoCut_offset_ + ecalIsoCut_slope_*scEt ) continue; + if (ecalIsolation > ecalIsoCut_offset_ + ecalIsoCut_slope_ * scEt) + continue; // Now launch the seed finding - theOutInSeedFinder_->setCandidate(pClus->energy(), GlobalPoint(pClus->position().x(),pClus->position().y(),pClus->position().z() ) ); - theOutInSeedFinder_->makeSeeds( bcHandle ); + theOutInSeedFinder_->setCandidate(pClus->energy(), + GlobalPoint(pClus->position().x(), pClus->position().y(), pClus->position().z())); + theOutInSeedFinder_->makeSeeds(bcHandle); - std::vector theOutInTracks= theOutInTrackFinder_->tracks(theOutInSeedFinder_->seeds(), outInTrackCandidates); + std::vector theOutInTracks = + theOutInTrackFinder_->tracks(theOutInSeedFinder_->seeds(), outInTrackCandidates); - theInOutSeedFinder_->setCandidate(pClus->energy(), GlobalPoint(pClus->position().x(),pClus->position().y(),pClus->position().z() ) ); - theInOutSeedFinder_->setTracks( theOutInTracks ); - theInOutSeedFinder_->makeSeeds( bcHandle); - - std::vector theInOutTracks= theInOutTrackFinder_->tracks(theInOutSeedFinder_->seeds(), inOutTrackCandidates); + theInOutSeedFinder_->setCandidate(pClus->energy(), + GlobalPoint(pClus->position().x(), pClus->position().y(), pClus->position().z())); + theInOutSeedFinder_->setTracks(theOutInTracks); + theInOutSeedFinder_->makeSeeds(bcHandle); + + std::vector theInOutTracks = + theInOutTrackFinder_->tracks(theInOutSeedFinder_->seeds(), inOutTrackCandidates); // Debug // std::cout << "ConversionTrackCandidateProducer theOutInTracks.size() " << theOutInTracks.size() << " theInOutTracks.size() " << theInOutTracks.size() << " Event pointer to out in track size barrel " << outInTrackCandidates.size() << " in out track size " << inOutTrackCandidates.size() << "\n"; - - //////////// Fill vectors of Ref to SC to be used for the Track-SC association - for (std::vector::const_iterator it = theOutInTracks.begin(); it != theOutInTracks.end(); ++it) { + //////////// Fill vectors of Ref to SC to be used for the Track-SC association + for (std::vector::const_iterator it = theOutInTracks.begin(); it != theOutInTracks.end(); ++it) { caloPtrVecOutIn_.push_back(aClus); - // std::cout << "ConversionTrackCandidateProducer Barrel OutIn Tracks Number of hits " << (*it).foundHits() << "\n"; + // std::cout << "ConversionTrackCandidateProducer Barrel OutIn Tracks Number of hits " << (*it).foundHits() << "\n"; } - for (std::vector::const_iterator it = theInOutTracks.begin(); it != theInOutTracks.end(); ++it) { + for (std::vector::const_iterator it = theInOutTracks.begin(); it != theInOutTracks.end(); ++it) { caloPtrVecInOut_.push_back(aClus); - // std::cout << "ConversionTrackCandidateProducer Barrel InOut Tracks Number of hits " << (*it).foundHits() << "\n"; + // std::cout << "ConversionTrackCandidateProducer Barrel InOut Tracks Number of hits " << (*it).foundHits() << "\n"; } } } - diff --git a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackMerger.cc b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackMerger.cc index af3f3e14ff2cb..aee70d72a9039 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackMerger.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackMerger.cc @@ -1,7 +1,7 @@ // // Package: RecoTracker/FinalTrackSelectors // Class: ConversionTrackMerger -// +// // Description: Merger for ConversionTracks, adapted from SimpleTrackListMerger // // Original Author: J.Bendavid @@ -34,218 +34,240 @@ #include "CommonTools/Statistics/interface/ChiSquaredProbability.h" - - ConversionTrackMerger::ConversionTrackMerger(edm::ParameterSet const& conf) : - conf_(conf) - { - // retrieve producer name of input TrackCollection(s) - trackProducer1 = consumes(conf_.getParameter("TrackProducer1")); - trackProducer2 = consumes(conf_.getParameter("TrackProducer2")); +ConversionTrackMerger::ConversionTrackMerger(edm::ParameterSet const& conf) : conf_(conf) { + // retrieve producer name of input TrackCollection(s) + trackProducer1 = consumes(conf_.getParameter("TrackProducer1")); + trackProducer2 = consumes(conf_.getParameter("TrackProducer2")); + + produces(); +} + +// Virtual destructor needed. +ConversionTrackMerger::~ConversionTrackMerger() {} + +// Functions that gets called by framework every event +void ConversionTrackMerger::produce(edm::Event& e, const edm::EventSetup& es) { + double shareFrac = conf_.getParameter("ShareFrac"); + bool allowFirstHitShare = conf_.getParameter("allowFirstHitShare"); + bool checkCharge = conf_.getParameter("checkCharge"); + double minProb = conf_.getParameter("minProb"); + + int outputPreferCollection = conf_.getParameter("outputPreferCollection"); + int trackerOnlyPreferCollection = conf_.getParameter("trackerOnlyPreferCollection"); + int arbitratedEcalSeededPreferCollection = conf_.getParameter("arbitratedEcalSeededPreferCollection"); + int arbitratedMergedPreferCollection = conf_.getParameter("arbitratedMergedPreferCollection"); + int arbitratedMergedEcalGeneralPreferCollection = + conf_.getParameter("arbitratedMergedEcalGeneralPreferCollection"); + + // get Inputs + // if 1 input list doesn't exist, make an empty list, issue a warning, and continue + // this allows ConversionTrackMerger to be used as a cleaner only if handed just one list + // if both input lists don't exist, will issue 2 warnings and generate an empty output collection + // + const reco::ConversionTrackCollection* TC1 = nullptr; + static const reco::ConversionTrackCollection s_empty1, s_empty2; + edm::Handle trackCollection1; + e.getByToken(trackProducer1, trackCollection1); + if (trackCollection1.isValid()) { + TC1 = trackCollection1.product(); + //std::cout << "1st collection " << trackProducer1 << " has "<< TC1->size() << " tracks" << std::endl ; + } else { + TC1 = &s_empty1; + edm::LogWarning("ConversionTrackMerger") << "1st TrackCollection not found;" + << " will only clean 2nd TrackCollection "; + } + reco::ConversionTrackCollection tC1 = *TC1; - produces(); - + const reco::ConversionTrackCollection* TC2 = nullptr; + edm::Handle trackCollection2; + e.getByToken(trackProducer2, trackCollection2); + if (trackCollection2.isValid()) { + TC2 = trackCollection2.product(); + //std::cout << "2nd collection " << trackProducer2 << " has "<< TC2->size() << " tracks" << std::endl ; + } else { + TC2 = &s_empty2; + edm::LogWarning("ConversionTrackMerger") << "2nd TrackCollection not found;" + << " will only clean 1st TrackCollection "; } + reco::ConversionTrackCollection tC2 = *TC2; + + // Step B: create empty output collection + outputTrks = std::make_unique(); + int i; + std::vector selected1; + for (unsigned int i = 0; i < tC1.size(); ++i) { + selected1.push_back(1); + } + std::vector selected2; + for (unsigned int i = 0; i < tC2.size(); ++i) { + selected2.push_back(1); + } - // Virtual destructor needed. - ConversionTrackMerger::~ConversionTrackMerger() { } - - // Functions that gets called by framework every event - void ConversionTrackMerger::produce(edm::Event& e, const edm::EventSetup& es) - { - - - double shareFrac = conf_.getParameter("ShareFrac"); - bool allowFirstHitShare = conf_.getParameter("allowFirstHitShare"); - bool checkCharge = conf_.getParameter("checkCharge"); - double minProb = conf_.getParameter("minProb"); - - int outputPreferCollection = conf_.getParameter("outputPreferCollection"); - int trackerOnlyPreferCollection = conf_.getParameter("trackerOnlyPreferCollection"); - int arbitratedEcalSeededPreferCollection = conf_.getParameter("arbitratedEcalSeededPreferCollection"); - int arbitratedMergedPreferCollection = conf_.getParameter("arbitratedMergedPreferCollection"); - int arbitratedMergedEcalGeneralPreferCollection = conf_.getParameter("arbitratedMergedEcalGeneralPreferCollection"); - - // get Inputs - // if 1 input list doesn't exist, make an empty list, issue a warning, and continue - // this allows ConversionTrackMerger to be used as a cleaner only if handed just one list - // if both input lists don't exist, will issue 2 warnings and generate an empty output collection - // - const reco::ConversionTrackCollection *TC1 = nullptr; - static const reco::ConversionTrackCollection s_empty1, s_empty2; - edm::Handle trackCollection1; - e.getByToken(trackProducer1, trackCollection1); - if (trackCollection1.isValid()) { - TC1 = trackCollection1.product(); - //std::cout << "1st collection " << trackProducer1 << " has "<< TC1->size() << " tracks" << std::endl ; - } else { - TC1 = &s_empty1; - edm::LogWarning("ConversionTrackMerger") - << "1st TrackCollection not found;" - << " will only clean 2nd TrackCollection "; + std::map > rh1; + std::map > rh2; + for (reco::ConversionTrackCollection::const_iterator track = tC1.begin(); track != tC1.end(); ++track) { + trackingRecHit_iterator itB = track->track()->recHitsBegin(); + trackingRecHit_iterator itE = track->track()->recHitsEnd(); + for (trackingRecHit_iterator it = itB; it != itE; ++it) { + const TrackingRecHit* hit = &(**it); + rh1[track].push_back(hit); } - reco::ConversionTrackCollection tC1 = *TC1; - - const reco::ConversionTrackCollection *TC2 = nullptr; - edm::Handle trackCollection2; - e.getByToken(trackProducer2, trackCollection2); - if (trackCollection2.isValid()) { - TC2 = trackCollection2.product(); - //std::cout << "2nd collection " << trackProducer2 << " has "<< TC2->size() << " tracks" << std::endl ; - } else { - TC2 = &s_empty2; - edm::LogWarning("ConversionTrackMerger") - << "2nd TrackCollection not found;" - <<" will only clean 1st TrackCollection "; + } + for (reco::ConversionTrackCollection::const_iterator track = tC2.begin(); track != tC2.end(); ++track) { + trackingRecHit_iterator jtB = track->track()->recHitsBegin(); + trackingRecHit_iterator jtE = track->track()->recHitsEnd(); + for (trackingRecHit_iterator jt = jtB; jt != jtE; ++jt) { + const TrackingRecHit* hit = &(**jt); + rh2[track].push_back(hit); } - reco::ConversionTrackCollection tC2 = *TC2; - - // Step B: create empty output collection - outputTrks = std::make_unique(); - int i; - - std::vector selected1; for (unsigned int i=0; i selected2; for (unsigned int i=0; i > rh1; - std::map > rh2; - for (reco::ConversionTrackCollection::const_iterator track=tC1.begin(); track!=tC1.end(); ++track){ - trackingRecHit_iterator itB = track->track()->recHitsBegin(); - trackingRecHit_iterator itE = track->track()->recHitsEnd(); - for (trackingRecHit_iterator it = itB; it != itE; ++it) { - const TrackingRecHit* hit = &(**it); - rh1[track].push_back(hit); - } - } - for (reco::ConversionTrackCollection::const_iterator track=tC2.begin(); track!=tC2.end(); ++track){ - trackingRecHit_iterator jtB = track->track()->recHitsBegin(); - trackingRecHit_iterator jtE = track->track()->recHitsEnd(); - for (trackingRecHit_iterator jt = jtB; jt != jtE; ++jt) { - const TrackingRecHit* hit = &(**jt); - rh2[track].push_back(hit); - } - } - - if ( (!tC1.empty())&&(!tC2.empty()) ){ - i=-1; - for (reco::ConversionTrackCollection::iterator track=tC1.begin(); track!=tC1.end(); ++track){ - i++; - + } + + if ((!tC1.empty()) && (!tC2.empty())) { + i = -1; + for (reco::ConversionTrackCollection::iterator track = tC1.begin(); track != tC1.end(); ++track) { + i++; + //clear flags if preferCollection was set to 0 - selected1[i] = selected1[i] && outputPreferCollection!=0; - track->setIsTrackerOnly ( track->isTrackerOnly() && trackerOnlyPreferCollection!=0 ); - track->setIsArbitratedEcalSeeded( track->isArbitratedEcalSeeded() && arbitratedEcalSeededPreferCollection!=0 ); - track->setIsArbitratedMerged( track->isArbitratedMerged() && arbitratedMergedPreferCollection!=0 ); - track->setIsArbitratedMergedEcalGeneral( track->isArbitratedMergedEcalGeneral() && arbitratedMergedEcalGeneralPreferCollection!=0 ); - - - std::vector& iHits = rh1[track]; + selected1[i] = selected1[i] && outputPreferCollection != 0; + track->setIsTrackerOnly(track->isTrackerOnly() && trackerOnlyPreferCollection != 0); + track->setIsArbitratedEcalSeeded(track->isArbitratedEcalSeeded() && arbitratedEcalSeededPreferCollection != 0); + track->setIsArbitratedMerged(track->isArbitratedMerged() && arbitratedMergedPreferCollection != 0); + track->setIsArbitratedMergedEcalGeneral(track->isArbitratedMergedEcalGeneral() && + arbitratedMergedEcalGeneralPreferCollection != 0); + + std::vector& iHits = rh1[track]; unsigned nh1 = iHits.size(); - int j=-1; - for (reco::ConversionTrackCollection::iterator track2=tC2.begin(); track2!=tC2.end(); ++track2){ + int j = -1; + for (reco::ConversionTrackCollection::iterator track2 = tC2.begin(); track2 != tC2.end(); ++track2) { j++; //clear flags if preferCollection was set to 0 - selected2[j] = selected2[j] && outputPreferCollection!=0; - track2->setIsTrackerOnly ( track2->isTrackerOnly() && trackerOnlyPreferCollection!=0 ); - track2->setIsArbitratedEcalSeeded( track2->isArbitratedEcalSeeded() && arbitratedEcalSeededPreferCollection!=0 ); - track2->setIsArbitratedMerged( track2->isArbitratedMerged() && arbitratedMergedPreferCollection!=0 ); - track2->setIsArbitratedMergedEcalGeneral( track2->isArbitratedMergedEcalGeneral() && arbitratedMergedEcalGeneralPreferCollection!=0 ); - - std::vector& jHits = rh2[track2]; - unsigned nh2 = jHits.size(); - int noverlap=0; - int firstoverlap=0; - for ( unsigned ih=0; ihisValid()){ - int jj=-1; - for ( unsigned jh=0; jhsetIsTrackerOnly(track2->isTrackerOnly() && trackerOnlyPreferCollection != 0); + track2->setIsArbitratedEcalSeeded(track2->isArbitratedEcalSeeded() && + arbitratedEcalSeededPreferCollection != 0); + track2->setIsArbitratedMerged(track2->isArbitratedMerged() && arbitratedMergedPreferCollection != 0); + track2->setIsArbitratedMergedEcalGeneral(track2->isArbitratedMergedEcalGeneral() && + arbitratedMergedEcalGeneralPreferCollection != 0); + + std::vector& jHits = rh2[track2]; + unsigned nh2 = jHits.size(); + int noverlap = 0; + int firstoverlap = 0; + for (unsigned ih = 0; ih < nh1; ++ih) { + const TrackingRecHit* it = iHits[ih]; + if (it->isValid()) { + int jj = -1; + for (unsigned jh = 0; jh < nh2; ++jh) { + const TrackingRecHit* jt = jHits[jh]; jj++; - if (jt->isValid()){ - if ( it->sharesInput(jt,TrackingRecHit::some) ) { - noverlap++; - if ( allowFirstHitShare && ( ih == 0 ) && ( jh == 0 ) ) firstoverlap=1; - } - } + if (jt->isValid()) { + if (it->sharesInput(jt, TrackingRecHit::some)) { + noverlap++; + if (allowFirstHitShare && (ih == 0) && (jh == 0)) + firstoverlap = 1; + } + } } } } - int nhit1 = track->track()->numberOfValidHits(); - int nhit2 = track2->track()->numberOfValidHits(); + int nhit1 = track->track()->numberOfValidHits(); + int nhit2 = track2->track()->numberOfValidHits(); //if (noverlap>0) printf("noverlap = %i, firstoverlap = %i, nhit1 = %i, nhit2 = %i, algo1 = %i, algo2 = %i, q1 = %i, q2 = %i\n",noverlap,firstoverlap,nhit1,nhit2,track->track()->algo(),track2->track()->algo(),track->track()->charge(),track2->track()->charge()); - //std::cout << " trk1 trk2 nhits1 nhits2 nover " << i << " " << j << " " << track->numberOfValidHits() << " " << track2->numberOfValidHits() << " " << noverlap << " " << fi << " " << fj < (std::min(nhit1,nhit2)-firstoverlap)*shareFrac && (!checkCharge || track->track()->charge()*track2->track()->charge()>0) ) { + //std::cout << " trk1 trk2 nhits1 nhits2 nover " << i << " " << j << " " << track->numberOfValidHits() << " " << track2->numberOfValidHits() << " " << noverlap << " " << fi << " " << fj < (std::min(nhit1, nhit2) - firstoverlap) * shareFrac && + (!checkCharge || track->track()->charge() * track2->track()->charge() > 0)) { //printf("overlapping tracks\n"); - //printf ("ndof1 = %5f, chisq1 = %5f, ndof2 = %5f, chisq2 = %5f\n",track->track()->ndof(),track->track()->chi2(),track2->track()->ndof(),track2->track()->chi2()); - + //printf ("ndof1 = %5f, chisq1 = %5f, ndof2 = %5f, chisq2 = %5f\n",track->track()->ndof(),track->track()->chi2(),track2->track()->ndof(),track2->track()->chi2()); + double probFirst = ChiSquaredProbability(track->track()->chi2(), track->track()->ndof()); double probSecond = ChiSquaredProbability(track2->track()->chi2(), track2->track()->ndof()); //arbitrate by number of hits and reduced chisq - bool keepFirst = ( nhit1>nhit2 || (nhit1==nhit2 && track->track()->normalizedChi2()track()->normalizedChi2()) ); + bool keepFirst = (nhit1 > nhit2 || + (nhit1 == nhit2 && track->track()->normalizedChi2() < track2->track()->normalizedChi2())); //override decision in case one track is radically worse quality than the other - keepFirst |= (probFirst>minProb && probSecond<=minProb); - keepFirst &= !(probFirst<=minProb && probSecond>minProb); + keepFirst |= (probFirst > minProb && probSecond <= minProb); + keepFirst &= !(probFirst <= minProb && probSecond > minProb); bool keepSecond = !keepFirst; - + //set flags based on arbitration decision and precedence settings - selected1[i] = selected1[i] && ( (keepFirst && outputPreferCollection==3) || outputPreferCollection==-1 || outputPreferCollection==1 ); - track->setIsTrackerOnly ( track->isTrackerOnly() && ( (keepFirst && trackerOnlyPreferCollection==3) || trackerOnlyPreferCollection==-1 || trackerOnlyPreferCollection==1 ) ); - track->setIsArbitratedEcalSeeded( track->isArbitratedEcalSeeded() && ( (keepFirst && arbitratedEcalSeededPreferCollection==3) || arbitratedEcalSeededPreferCollection==-1 || arbitratedEcalSeededPreferCollection==1 ) ); - track->setIsArbitratedMerged( track->isArbitratedMerged() && ( (keepFirst && arbitratedMergedPreferCollection==3) || arbitratedMergedPreferCollection==-1 || arbitratedMergedPreferCollection==1 ) ); - track->setIsArbitratedMergedEcalGeneral( track->isArbitratedMergedEcalGeneral() && ( (keepFirst && arbitratedMergedEcalGeneralPreferCollection==3) || arbitratedMergedEcalGeneralPreferCollection==-1 || arbitratedMergedEcalGeneralPreferCollection==1 ) ); - - selected2[j] = selected2[j] && ( (keepSecond && outputPreferCollection==3) || outputPreferCollection==-1 || outputPreferCollection==2 ); - track2->setIsTrackerOnly ( track2->isTrackerOnly() && ( (keepSecond && trackerOnlyPreferCollection==3) || trackerOnlyPreferCollection==-1 || trackerOnlyPreferCollection==2 ) ); - track2->setIsArbitratedEcalSeeded( track2->isArbitratedEcalSeeded() && ( (keepSecond && arbitratedEcalSeededPreferCollection==3) || arbitratedEcalSeededPreferCollection==-1 || arbitratedEcalSeededPreferCollection==2 ) ); - track2->setIsArbitratedMerged( track2->isArbitratedMerged() && ( (keepSecond && arbitratedMergedPreferCollection==3) || arbitratedMergedPreferCollection==-1 || arbitratedMergedPreferCollection==2 ) ); - track2->setIsArbitratedMergedEcalGeneral( track2->isArbitratedMergedEcalGeneral() && ( (keepSecond && arbitratedMergedEcalGeneralPreferCollection==3) || arbitratedMergedEcalGeneralPreferCollection==-1 || arbitratedMergedEcalGeneralPreferCollection==2 ) ); - - }//end got a duplicate - }//end track2 loop - }//end track loop - }//end more than 1 track + selected1[i] = selected1[i] && ((keepFirst && outputPreferCollection == 3) || outputPreferCollection == -1 || + outputPreferCollection == 1); + track->setIsTrackerOnly(track->isTrackerOnly() && + ((keepFirst && trackerOnlyPreferCollection == 3) || + trackerOnlyPreferCollection == -1 || trackerOnlyPreferCollection == 1)); + track->setIsArbitratedEcalSeeded(track->isArbitratedEcalSeeded() && + ((keepFirst && arbitratedEcalSeededPreferCollection == 3) || + arbitratedEcalSeededPreferCollection == -1 || + arbitratedEcalSeededPreferCollection == 1)); + track->setIsArbitratedMerged(track->isArbitratedMerged() && + ((keepFirst && arbitratedMergedPreferCollection == 3) || + arbitratedMergedPreferCollection == -1 || + arbitratedMergedPreferCollection == 1)); + track->setIsArbitratedMergedEcalGeneral(track->isArbitratedMergedEcalGeneral() && + ((keepFirst && arbitratedMergedEcalGeneralPreferCollection == 3) || + arbitratedMergedEcalGeneralPreferCollection == -1 || + arbitratedMergedEcalGeneralPreferCollection == 1)); + + selected2[j] = selected2[j] && ((keepSecond && outputPreferCollection == 3) || outputPreferCollection == -1 || + outputPreferCollection == 2); + track2->setIsTrackerOnly(track2->isTrackerOnly() && + ((keepSecond && trackerOnlyPreferCollection == 3) || + trackerOnlyPreferCollection == -1 || trackerOnlyPreferCollection == 2)); + track2->setIsArbitratedEcalSeeded(track2->isArbitratedEcalSeeded() && + ((keepSecond && arbitratedEcalSeededPreferCollection == 3) || + arbitratedEcalSeededPreferCollection == -1 || + arbitratedEcalSeededPreferCollection == 2)); + track2->setIsArbitratedMerged(track2->isArbitratedMerged() && + ((keepSecond && arbitratedMergedPreferCollection == 3) || + arbitratedMergedPreferCollection == -1 || + arbitratedMergedPreferCollection == 2)); + track2->setIsArbitratedMergedEcalGeneral(track2->isArbitratedMergedEcalGeneral() && + ((keepSecond && arbitratedMergedEcalGeneralPreferCollection == 3) || + arbitratedMergedEcalGeneralPreferCollection == -1 || + arbitratedMergedEcalGeneralPreferCollection == 2)); + + } //end got a duplicate + } //end track2 loop + } //end track loop + } //end more than 1 track // // output selected tracks - if any // - - if ( !tC1.empty() ){ - i=0; - for (reco::ConversionTrackCollection::const_iterator track=tC1.begin(); track!=tC1.end(); - ++track, ++i){ + + if (!tC1.empty()) { + i = 0; + for (reco::ConversionTrackCollection::const_iterator track = tC1.begin(); track != tC1.end(); ++track, ++i) { //don't store tracks rejected as duplicates - if (!selected1[i]){ - continue; + if (!selected1[i]) { + continue; } //fill the TrackCollection - outputTrks->push_back(*track); - }//end faux loop over tracks - }//end more than 0 track - - //Fill the trajectories, etc. for 1st collection - - - if ( !tC2.empty() ){ - i=0; - for (reco::ConversionTrackCollection::const_iterator track=tC2.begin(); track!=tC2.end(); - ++track, ++i){ + outputTrks->push_back(*track); + } //end faux loop over tracks + } //end more than 0 track + + //Fill the trajectories, etc. for 1st collection + + if (!tC2.empty()) { + i = 0; + for (reco::ConversionTrackCollection::const_iterator track = tC2.begin(); track != tC2.end(); ++track, ++i) { //don't store tracks rejected as duplicates - if (!selected2[i]){ + if (!selected2[i]) { continue; } //fill the TrackCollection outputTrks->push_back(*track); - }//end faux loop over tracks - }//end more than 0 track - - e.put(std::move(outputTrks)); - return; + } //end faux loop over tracks + } //end more than 0 track + + e.put(std::move(outputTrks)); + return; - }//end produce +} //end produce diff --git a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackProducer.cc index d7c61a48af121..e85d6046f3ec8 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ConversionTrackProducer.cc @@ -1,7 +1,7 @@ // // Package: RecoTracker/FinalTrackSelectors // Class: ConversionTrackProducer -// +// // Description: Trivial producer of ConversionTrack collection from an edm::View of a track collection // (ConversionTrack is a simple wrappper class containing a TrackBaseRef and some additional flags) // @@ -32,139 +32,118 @@ #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" - -ConversionTrackProducer::ConversionTrackProducer(edm::ParameterSet const& conf) : - conf_(conf), - trackProducer ( conf.getParameter("TrackProducer") ), - useTrajectory ( conf.getParameter("useTrajectory") ), - setTrackerOnly ( conf.getParameter("setTrackerOnly") ), - setIsGsfTrackOpen ( conf.getParameter("setIsGsfTrackOpen") ), - setArbitratedEcalSeeded ( conf.getParameter("setArbitratedEcalSeeded") ), - setArbitratedMerged ( conf.getParameter("setArbitratedMerged") ), - setArbitratedMergedEcalGeneral ( conf.getParameter("setArbitratedMergedEcalGeneral") ), - beamSpotInputTag ( consumes(conf.getParameter("beamSpotInputTag")) ), - filterOnConvTrackHyp( conf.getParameter("filterOnConvTrackHyp") ), - minConvRadius( conf.getParameter("minConvRadius") ) -{ +ConversionTrackProducer::ConversionTrackProducer(edm::ParameterSet const& conf) + : conf_(conf), + trackProducer(conf.getParameter("TrackProducer")), + useTrajectory(conf.getParameter("useTrajectory")), + setTrackerOnly(conf.getParameter("setTrackerOnly")), + setIsGsfTrackOpen(conf.getParameter("setIsGsfTrackOpen")), + setArbitratedEcalSeeded(conf.getParameter("setArbitratedEcalSeeded")), + setArbitratedMerged(conf.getParameter("setArbitratedMerged")), + setArbitratedMergedEcalGeneral(conf.getParameter("setArbitratedMergedEcalGeneral")), + beamSpotInputTag(consumes(conf.getParameter("beamSpotInputTag"))), + filterOnConvTrackHyp(conf.getParameter("filterOnConvTrackHyp")), + minConvRadius(conf.getParameter("minConvRadius")) { edm::InputTag thetp(trackProducer); - genericTracks = - consumes >(thetp); - kfTrajectories = - consumes(thetp); - gsfTrajectories = - consumes(thetp); + genericTracks = consumes >(thetp); + kfTrajectories = consumes(thetp); + gsfTrajectories = consumes(thetp); produces(); - } - - // Virtual destructor needed. - ConversionTrackProducer::~ConversionTrackProducer() { } - - // Functions that gets called by framework every event - void ConversionTrackProducer::produce(edm::Event& e, const edm::EventSetup& es) - { - //get input collection (through edm::View) - edm::Handle > hTrks; - e.getByToken(genericTracks, hTrks); - - //get association maps between trajectories and tracks and build temporary maps - edm::Handle< TrajTrackAssociationCollection > hTTAss; - edm::Handle< TrajGsfTrackAssociationCollection > hTTAssGsf; - - std::map > > tracktrajmap; - std::map > > gsftracktrajmap; - - if (useTrajectory) { - if (!hTrks->empty()) { - if (dynamic_cast(&hTrks->at(0))) { - //fill map for gsf tracks - e.getByToken(gsfTrajectories, hTTAssGsf); - for ( TrajGsfTrackAssociationCollection::const_iterator iPair = - hTTAssGsf->begin(); - iPair != hTTAssGsf->end(); ++iPair) { - - gsftracktrajmap[iPair->val] = iPair->key; - - } - +// Virtual destructor needed. +ConversionTrackProducer::~ConversionTrackProducer() {} + +// Functions that gets called by framework every event +void ConversionTrackProducer::produce(edm::Event& e, const edm::EventSetup& es) { + //get input collection (through edm::View) + edm::Handle > hTrks; + e.getByToken(genericTracks, hTrks); + + //get association maps between trajectories and tracks and build temporary maps + edm::Handle hTTAss; + edm::Handle hTTAssGsf; + + std::map > > tracktrajmap; + std::map > > gsftracktrajmap; + + if (useTrajectory) { + if (!hTrks->empty()) { + if (dynamic_cast(&hTrks->at(0))) { + //fill map for gsf tracks + e.getByToken(gsfTrajectories, hTTAssGsf); + for (TrajGsfTrackAssociationCollection::const_iterator iPair = hTTAssGsf->begin(); iPair != hTTAssGsf->end(); + ++iPair) { + gsftracktrajmap[iPair->val] = iPair->key; } - else { - //fill map for standard tracks - e.getByToken(kfTrajectories, hTTAss); - for ( TrajTrackAssociationCollection::const_iterator iPair = hTTAss->begin(); - iPair != hTTAss->end(); - ++iPair) { - - tracktrajmap[iPair->val] = iPair->key; - - } + + } else { + //fill map for standard tracks + e.getByToken(kfTrajectories, hTTAss); + for (TrajTrackAssociationCollection::const_iterator iPair = hTTAss->begin(); iPair != hTTAss->end(); ++iPair) { + tracktrajmap[iPair->val] = iPair->key; } } } + } + + // Step B: create empty output collection + outputTrks = std::make_unique(); + + //-------------------------------------------------- + //Added by D. Giordano + // 2011/08/05 + // Reduction of the track sample based on geometric hypothesis for conversion tracks + + edm::Handle beamSpotHandle; + e.getByToken(beamSpotInputTag, beamSpotHandle); + + edm::ESHandle magFieldHandle; + es.get().get(magFieldHandle); - // Step B: create empty output collection - outputTrks = std::make_unique(); + if (filterOnConvTrackHyp && !beamSpotHandle.isValid()) { + edm::LogError("Invalid Collection") << "invalid collection for the BeamSpot"; + throw; + } + ConvTrackPreSelector.setMagnField(magFieldHandle.product()); + + //---------------------------------------------------------- + + // Simple conversion of tracks to conversion tracks, setting appropriate flags from configuration + for (size_t i = 0; i < hTrks->size(); ++i) { //-------------------------------------------------- //Added by D. Giordano // 2011/08/05 // Reduction of the track sample based on geometric hypothesis for conversion tracks - - edm::Handle beamSpotHandle; - e.getByToken(beamSpotInputTag,beamSpotHandle); - - edm::ESHandle magFieldHandle; - es.get().get( magFieldHandle ); - - - if(filterOnConvTrackHyp && !beamSpotHandle.isValid()) { - edm::LogError("Invalid Collection") - << "invalid collection for the BeamSpot"; - throw; - } - ConvTrackPreSelector.setMagnField(magFieldHandle.product()); - - //---------------------------------------------------------- - - - // Simple conversion of tracks to conversion tracks, setting appropriate flags from configuration - for (size_t i = 0; i < hTrks->size(); ++i) { - - //-------------------------------------------------- - //Added by D. Giordano - // 2011/08/05 - // Reduction of the track sample based on geometric hypothesis for conversion tracks - - math::XYZVector beamSpot= math::XYZVector(beamSpotHandle->position()); - edm::RefToBase trackBaseRef = hTrks->refAt(i); - if( filterOnConvTrackHyp && ConvTrackPreSelector.isTangentPointDistanceLessThan( minConvRadius, trackBaseRef.get(), beamSpot ) ) - continue; - //-------------------------------------------------- - - reco::ConversionTrack convTrack(trackBaseRef); - convTrack.setIsTrackerOnly(setTrackerOnly); - convTrack.setIsGsfTrackOpen(setIsGsfTrackOpen); - convTrack.setIsArbitratedEcalSeeded(setArbitratedEcalSeeded); - convTrack.setIsArbitratedMerged(setArbitratedMerged); - convTrack.setIsArbitratedMergedEcalGeneral(setArbitratedMergedEcalGeneral); - - //fill trajectory association if configured, using correct map depending on track type - if (useTrajectory) { - if (!gsftracktrajmap.empty()) { - convTrack.setTrajRef(gsftracktrajmap.find(trackBaseRef.castTo())->second); - } - else { - convTrack.setTrajRef(tracktrajmap.find(trackBaseRef.castTo())->second); - } + math::XYZVector beamSpot = math::XYZVector(beamSpotHandle->position()); + edm::RefToBase trackBaseRef = hTrks->refAt(i); + if (filterOnConvTrackHyp && + ConvTrackPreSelector.isTangentPointDistanceLessThan(minConvRadius, trackBaseRef.get(), beamSpot)) + continue; + //-------------------------------------------------- + + reco::ConversionTrack convTrack(trackBaseRef); + convTrack.setIsTrackerOnly(setTrackerOnly); + convTrack.setIsGsfTrackOpen(setIsGsfTrackOpen); + convTrack.setIsArbitratedEcalSeeded(setArbitratedEcalSeeded); + convTrack.setIsArbitratedMerged(setArbitratedMerged); + convTrack.setIsArbitratedMergedEcalGeneral(setArbitratedMergedEcalGeneral); + + //fill trajectory association if configured, using correct map depending on track type + if (useTrajectory) { + if (!gsftracktrajmap.empty()) { + convTrack.setTrajRef(gsftracktrajmap.find(trackBaseRef.castTo())->second); + } else { + convTrack.setTrajRef(tracktrajmap.find(trackBaseRef.castTo())->second); } - - outputTrks->push_back(convTrack); } - - e.put(std::move(outputTrks)); - return; - }//end produce + outputTrks->push_back(convTrack); + } + + e.put(std::move(outputTrks)); + return; +} //end produce diff --git a/RecoEgamma/EgammaPhotonProducers/src/ConvertedPhotonProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/ConvertedPhotonProducer.cc index 434f21ce1834c..8acc51eab0f08 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ConvertedPhotonProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ConvertedPhotonProducer.cc @@ -43,91 +43,70 @@ #include "TrackingTools/Records/interface/TransientTrackRecord.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaTowerIsolation.h" -ConvertedPhotonProducer::ConvertedPhotonProducer(const edm::ParameterSet& config) : - conf_(config), - theTrackPairFinder_(nullptr), - theVertexFinder_(nullptr), - theLikelihoodCalc_(nullptr) -{ - - - +ConvertedPhotonProducer::ConvertedPhotonProducer(const edm::ParameterSet& config) + : conf_(config), theTrackPairFinder_(nullptr), theVertexFinder_(nullptr), theLikelihoodCalc_(nullptr) { //cout<< " ConvertedPhotonProducer CTOR " << "\n"; - - - + // use onfiguration file to setup input collection names - bcBarrelCollection_ = - consumes >(conf_.getParameter("bcBarrelCollection")); - bcEndcapCollection_ = - consumes >(conf_.getParameter("bcEndcapCollection")); - - scHybridBarrelProducer_ = - consumes >(conf_.getParameter("scHybridBarrelProducer")); - scIslandEndcapProducer_ = - consumes >(conf_.getParameter("scIslandEndcapProducer")); - - std::string oitrackprod = - conf_.getParameter("conversionOITrackProducer"); - std::string iotrackprod = - conf_.getParameter("conversionIOTrackProducer"); - - std::string oitrackassoc = - conf_.getParameter("outInTrackSCAssociation"); - std::string iotrackassoc = - conf_.getParameter("inOutTrackSCAssociation"); - - edm::InputTag oitracks(oitrackprod),oitracksassoc(oitrackprod,oitrackassoc), - iotracks(iotrackprod), iotracksassoc(iotrackprod,iotrackassoc); + bcBarrelCollection_ = + consumes >(conf_.getParameter("bcBarrelCollection")); + bcEndcapCollection_ = + consumes >(conf_.getParameter("bcEndcapCollection")); + + scHybridBarrelProducer_ = + consumes >(conf_.getParameter("scHybridBarrelProducer")); + scIslandEndcapProducer_ = + consumes >(conf_.getParameter("scIslandEndcapProducer")); + + std::string oitrackprod = conf_.getParameter("conversionOITrackProducer"); + std::string iotrackprod = conf_.getParameter("conversionIOTrackProducer"); + + std::string oitrackassoc = conf_.getParameter("outInTrackSCAssociation"); + std::string iotrackassoc = conf_.getParameter("inOutTrackSCAssociation"); + + edm::InputTag oitracks(oitrackprod), oitracksassoc(oitrackprod, oitrackassoc), iotracks(iotrackprod), + iotracksassoc(iotrackprod, iotrackassoc); conversionOITrackProducer_ = consumes(oitracks); - outInTrackSCAssociationCollection_ = - consumes(oitracksassoc); - conversionIOTrackProducer_ = consumes(iotracks); - inOutTrackSCAssociationCollection_ = - consumes(iotracksassoc); - - generalTrackProducer_ = - consumes(conf_.getParameter("generalTracksSrc")); - - algoName_ = conf_.getParameter( "AlgorithmName" ); - - hcalTowers_ = - consumes(conf_.getParameter("hcalTowers")); - hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); - maxHOverE_ = conf_.getParameter("maxHOverE"); - minSCEt_ = conf_.getParameter("minSCEt"); - recoverOneTrackCase_ = conf_.getParameter( "recoverOneTrackCase" ); + outInTrackSCAssociationCollection_ = consumes(oitracksassoc); + conversionIOTrackProducer_ = consumes(iotracks); + inOutTrackSCAssociationCollection_ = consumes(iotracksassoc); + + generalTrackProducer_ = consumes(conf_.getParameter("generalTracksSrc")); + + algoName_ = conf_.getParameter("AlgorithmName"); + + hcalTowers_ = consumes(conf_.getParameter("hcalTowers")); + hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); + maxHOverE_ = conf_.getParameter("maxHOverE"); + minSCEt_ = conf_.getParameter("minSCEt"); + recoverOneTrackCase_ = conf_.getParameter("recoverOneTrackCase"); dRForConversionRecovery_ = conf_.getParameter("dRForConversionRecovery"); deltaCotCut_ = conf_.getParameter("deltaCotCut"); minApproachDisCut_ = conf_.getParameter("minApproachDisCut"); - maxNumOfCandidates_ = conf_.getParameter("maxNumOfCandidates"); - risolveAmbiguity_ = conf_.getParameter("risolveConversionAmbiguity"); - likelihoodWeights_= conf_.getParameter("MVA_weights_location"); - - + maxNumOfCandidates_ = conf_.getParameter("maxNumOfCandidates"); + risolveAmbiguity_ = conf_.getParameter("risolveConversionAmbiguity"); + likelihoodWeights_ = conf_.getParameter("MVA_weights_location"); + // use configuration file to setup output collection names ConvertedPhotonCollection_ = conf_.getParameter("convertedPhotonCollection"); CleanedConvertedPhotonCollection_ = conf_.getParameter("cleanedConvertedPhotonCollection"); - - + // Register the product - produces< reco::ConversionCollection >(ConvertedPhotonCollection_); - produces< reco::ConversionCollection >(CleanedConvertedPhotonCollection_); - + produces(ConvertedPhotonCollection_); + produces(CleanedConvertedPhotonCollection_); + // instantiate the Track Pair Finder algorithm - theTrackPairFinder_ = new ConversionTrackPairFinder (); - edm::FileInPath path_mvaWeightFile(likelihoodWeights_.c_str() ); + theTrackPairFinder_ = new ConversionTrackPairFinder(); + edm::FileInPath path_mvaWeightFile(likelihoodWeights_.c_str()); theLikelihoodCalc_ = new ConversionLikelihoodCalculator(); theLikelihoodCalc_->setWeightsFile(path_mvaWeightFile.fullPath().c_str()); // instantiate the Vertex Finder algorithm - theVertexFinder_ = new ConversionVertexFinder ( conf_); - + theVertexFinder_ = new ConversionVertexFinder(conf_); // Inizilize my global event counter - nEvt_=0; - + nEvt_ = 0; } ConvertedPhotonProducer::~ConvertedPhotonProducer() { @@ -136,32 +115,22 @@ ConvertedPhotonProducer::~ConvertedPhotonProducer() { delete theVertexFinder_; } - - -void ConvertedPhotonProducer::beginRun (edm::Run const& r, edm::EventSetup const & theEventSetup) { - - - //get magnetic field +void ConvertedPhotonProducer::beginRun(edm::Run const& r, edm::EventSetup const& theEventSetup) { + //get magnetic field //edm::LogInfo("ConvertedPhotonProducer") << " get magnetic field" << "\n"; - theEventSetup.get().get(theMF_); + theEventSetup.get().get(theMF_); // Transform Track into TransientTrack (needed by the Vertex fitter) - theEventSetup.get().get("TransientTrackBuilder",theTransientTrackBuilder_); - - + theEventSetup.get().get("TransientTrackBuilder", theTransientTrackBuilder_); } - - void ConvertedPhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { - using namespace edm; - nEvt_++; - + nEvt_++; // LogDebug("ConvertedPhotonProducer") << "ConvertedPhotonProduce::produce event number " << theEvent.id() << " Global counter " << nEvt_ << "\n"; // std::cout << "ConvertedPhotonProduce::produce event number " << theEvent.id() << " Global counter " << nEvt_ << "\n"; - + // // create empty output collections // @@ -172,524 +141,485 @@ void ConvertedPhotonProducer::produce(edm::Event& theEvent, const edm::EventSetu reco::ConversionCollection cleanedConversionCollection; auto cleanedConversionCollection_p = std::make_unique(); - // Get the Super Cluster collection in the Barrel - bool validBarrelSCHandle=true; + bool validBarrelSCHandle = true; edm::Handle > scBarrelHandle; - theEvent.getByToken(scHybridBarrelProducer_,scBarrelHandle); + theEvent.getByToken(scHybridBarrelProducer_, scBarrelHandle); if (!scBarrelHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the scHybridBarrelProducer"; - validBarrelSCHandle=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the scHybridBarrelProducer"; + validBarrelSCHandle = false; } - + // Get the Super Cluster collection in the Endcap - bool validEndcapSCHandle=true; + bool validEndcapSCHandle = true; edm::Handle > scEndcapHandle; - theEvent.getByToken(scIslandEndcapProducer_,scEndcapHandle); + theEvent.getByToken(scIslandEndcapProducer_, scEndcapHandle); if (!scEndcapHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the scIslandEndcapProducer"; - validEndcapSCHandle=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the scIslandEndcapProducer"; + validEndcapSCHandle = false; } - - - //// Get the Out In CKF tracks from conversions - bool validTrackInputs=true; + + //// Get the Out In CKF tracks from conversions + bool validTrackInputs = true; Handle outInTrkHandle; - theEvent.getByToken(conversionOITrackProducer_, outInTrkHandle); + theEvent.getByToken(conversionOITrackProducer_, outInTrkHandle); if (!outInTrkHandle.isValid()) { //std::cout << "Error! Can't get the conversionOITrack " << "\n"; - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the conversionOITrack " << "\n"; - validTrackInputs=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the conversionOITrack " + << "\n"; + validTrackInputs = false; } // LogDebug("ConvertedPhotonProducer")<< "ConvertedPhotonProducer outInTrack collection size " << (*outInTrkHandle).size() << "\n"; - - + //// Get the association map between CKF Out In tracks and the SC where they originated Handle outInTrkSCAssocHandle; - theEvent.getByToken( outInTrackSCAssociationCollection_, outInTrkSCAssocHandle); + theEvent.getByToken(outInTrackSCAssociationCollection_, outInTrkSCAssocHandle); if (!outInTrkSCAssocHandle.isValid()) { // std::cout << "Error! Can't get the product " << outInTrackSCAssociationCollection_.c_str() <<"\n"; - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the outInTrackSCAssociationCollection)"; - validTrackInputs=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the outInTrackSCAssociationCollection)"; + validTrackInputs = false; } - //// Get the In Out CKF tracks from conversions + //// Get the In Out CKF tracks from conversions Handle inOutTrkHandle; theEvent.getByToken(conversionIOTrackProducer_, inOutTrkHandle); if (!inOutTrkHandle.isValid()) { // std::cout << "Error! Can't get the conversionIOTrack " << "\n"; - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the conversionIOTrack " << "\n"; - validTrackInputs=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the conversionIOTrack " + << "\n"; + validTrackInputs = false; } // LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer inOutTrack collection size " << (*inOutTrkHandle).size() << "\n"; - //// Get the generalTracks if the recovery of one track cases is switched on Handle generalTrkHandle; - if ( recoverOneTrackCase_ ) { + if (recoverOneTrackCase_) { theEvent.getByToken(generalTrackProducer_, generalTrkHandle); if (!generalTrkHandle.isValid()) { //std::cout << "Error! Can't get the genralTracks " << "\n"; - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the genralTracks " << "\n"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the genralTracks " + << "\n"; } - } - + } + //// Get the association map between CKF in out tracks and the SC where they originated Handle inOutTrkSCAssocHandle; - theEvent.getByToken( inOutTrackSCAssociationCollection_, inOutTrkSCAssocHandle); + theEvent.getByToken(inOutTrackSCAssociationCollection_, inOutTrkSCAssocHandle); if (!inOutTrkSCAssocHandle.isValid()) { //std::cout << "Error! Can't get the product " << inOutTrackSCAssociationCollection_.c_str() <<"\n"; - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the inOutTrackSCAssociationCollection_.c_str()"; - validTrackInputs=false; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the inOutTrackSCAssociationCollection_.c_str()"; + validTrackInputs = false; } - - - - // Get the basic cluster collection in the Barrel + // Get the basic cluster collection in the Barrel edm::Handle > bcBarrelHandle; - theEvent.getByToken( bcBarrelCollection_, bcBarrelHandle); + theEvent.getByToken(bcBarrelCollection_, bcBarrelHandle); if (!bcBarrelHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the bcBarrelCollection"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the bcBarrelCollection"; } - - // Get the basic cluster collection in the Endcap + // Get the basic cluster collection in the Endcap edm::Handle > bcEndcapHandle; - theEvent.getByToken( bcEndcapCollection_, bcEndcapHandle); + theEvent.getByToken(bcEndcapCollection_, bcEndcapHandle); if (!bcEndcapHandle.isValid()) { - edm::LogError("ConvertedPhotonProducer") - << "Error! Can't get the bcEndcapCollection"; + edm::LogError("ConvertedPhotonProducer") << "Error! Can't get the bcEndcapCollection"; } - -// get Hcal towers collection + // get Hcal towers collection Handle hcalTowersHandle; theEvent.getByToken(hcalTowers_, hcalTowersHandle); // get the geometry from the event setup: theEventSetup.get().get(theCaloGeom_); - - if ( validTrackInputs ) { + if (validTrackInputs) { //do the conversion: - std::vector t_outInTrk = ( *theTransientTrackBuilder_ ).build(outInTrkHandle ); - std::vector t_inOutTrk = ( *theTransientTrackBuilder_ ).build(inOutTrkHandle ); - - + std::vector t_outInTrk = (*theTransientTrackBuilder_).build(outInTrkHandle); + std::vector t_inOutTrk = (*theTransientTrackBuilder_).build(inOutTrkHandle); + ///// Find the +/- pairs std::map, reco::CaloClusterPtr, CompareTwoTracksVectors> allPairs; - allPairs = theTrackPairFinder_->run(t_outInTrk, outInTrkHandle, outInTrkSCAssocHandle, t_inOutTrk, inOutTrkHandle, inOutTrkSCAssocHandle ); - //LogDebug("ConvertedPhotonProducer") << "ConvertedPhotonProducer allPairs.size " << allPairs.size() << "\n"; - - buildCollections(theEventSetup, scBarrelHandle, bcBarrelHandle, hcalTowersHandle, generalTrkHandle, allPairs, outputConvPhotonCollection); - buildCollections(theEventSetup, scEndcapHandle, bcEndcapHandle, hcalTowersHandle, generalTrkHandle, allPairs, outputConvPhotonCollection); + allPairs = theTrackPairFinder_->run( + t_outInTrk, outInTrkHandle, outInTrkSCAssocHandle, t_inOutTrk, inOutTrkHandle, inOutTrkSCAssocHandle); + //LogDebug("ConvertedPhotonProducer") << "ConvertedPhotonProducer allPairs.size " << allPairs.size() << "\n"; + + buildCollections(theEventSetup, + scBarrelHandle, + bcBarrelHandle, + hcalTowersHandle, + generalTrkHandle, + allPairs, + outputConvPhotonCollection); + buildCollections(theEventSetup, + scEndcapHandle, + bcEndcapHandle, + hcalTowersHandle, + generalTrkHandle, + allPairs, + outputConvPhotonCollection); } - - // put the product in the event - outputConvPhotonCollection_p->assign(outputConvPhotonCollection.begin(),outputConvPhotonCollection.end()); - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Putting in the event converted photon candidates " << (*outputConvPhotonCollection_p).size() << "\n"; - const edm::OrphanHandle conversionHandle= theEvent.put(std::move(outputConvPhotonCollection_p), ConvertedPhotonCollection_); + // put the product in the event + outputConvPhotonCollection_p->assign(outputConvPhotonCollection.begin(), outputConvPhotonCollection.end()); + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Putting in the event converted photon candidates " << (*outputConvPhotonCollection_p).size() << "\n"; + const edm::OrphanHandle conversionHandle = + theEvent.put(std::move(outputConvPhotonCollection_p), ConvertedPhotonCollection_); // Loop over barrel and endcap SC collections and fill the photon collection - if ( validBarrelSCHandle) cleanCollections(scBarrelHandle, - conversionHandle, - cleanedConversionCollection); - if ( validEndcapSCHandle) cleanCollections(scEndcapHandle, - conversionHandle, - cleanedConversionCollection); - - - cleanedConversionCollection_p->assign(cleanedConversionCollection.begin(),cleanedConversionCollection.end()); - theEvent.put(std::move(cleanedConversionCollection_p), CleanedConvertedPhotonCollection_); + if (validBarrelSCHandle) + cleanCollections(scBarrelHandle, conversionHandle, cleanedConversionCollection); + if (validEndcapSCHandle) + cleanCollections(scEndcapHandle, conversionHandle, cleanedConversionCollection); - + cleanedConversionCollection_p->assign(cleanedConversionCollection.begin(), cleanedConversionCollection.end()); + theEvent.put(std::move(cleanedConversionCollection_p), CleanedConvertedPhotonCollection_); } - -void ConvertedPhotonProducer::buildCollections ( edm::EventSetup const & es, - const edm::Handle > & scHandle, - const edm::Handle > & bcHandle, - const edm::Handle & hcalTowersHandle, - const edm::Handle & generalTrkHandle, - std::map, reco::CaloClusterPtr, CompareTwoTracksVectors>& allPairs, - reco::ConversionCollection & outputConvPhotonCollection) +void ConvertedPhotonProducer::buildCollections( + edm::EventSetup const& es, + const edm::Handle >& scHandle, + const edm::Handle >& bcHandle, + const edm::Handle& hcalTowersHandle, + const edm::Handle& generalTrkHandle, + std::map, reco::CaloClusterPtr, CompareTwoTracksVectors>& allPairs, + reco::ConversionCollection& outputConvPhotonCollection) { - - // instantiate the algorithm for finding the position of the track extrapolation at the Ecal front face - ConversionTrackEcalImpactPoint theEcalImpactPositionFinder( &(*theMF_) ); - + // instantiate the algorithm for finding the position of the track extrapolation at the Ecal front face + ConversionTrackEcalImpactPoint theEcalImpactPositionFinder(&(*theMF_)); reco::Conversion::ConversionAlgorithm algo = reco::Conversion::algoByName(algoName_); - + std::vector t_generalTrk; - if ( recoverOneTrackCase_ ) t_generalTrk = ( *theTransientTrackBuilder_ ).build(generalTrkHandle ); - //const CaloGeometry* geometry = theCaloGeom_.product(); + if (recoverOneTrackCase_) + t_generalTrk = (*theTransientTrackBuilder_).build(generalTrkHandle); + //const CaloGeometry* geometry = theCaloGeom_.product(); // Loop over SC in the barrel and reconstruct converted photons - int myCands=0; + int myCands = 0; reco::CaloClusterPtrVector scPtrVec; - for(auto const& aClus : scHandle->ptrs()) - { + for (auto const& aClus : scHandle->ptrs()) { // preselection based in Et and H/E cut - if (aClus->energy()/cosh(aClus->eta()) <= minSCEt_) continue; - const reco::CaloCluster* pClus=&(*aClus); - const reco::SuperCluster* sc=dynamic_cast(pClus); + if (aClus->energy() / cosh(aClus->eta()) <= minSCEt_) + continue; + const reco::CaloCluster* pClus = &(*aClus); + const reco::SuperCluster* sc = dynamic_cast(pClus); const CaloTowerCollection* hcalTowersColl = hcalTowersHandle.product(); - EgammaTowerIsolation towerIso(hOverEConeSize_,0.,0.,-1,hcalTowersColl) ; - double HoE=towerIso.getTowerESum(sc)/sc->energy(); - if (HoE>=maxHOverE_) continue; + EgammaTowerIsolation towerIso(hOverEConeSize_, 0., 0., -1, hcalTowersColl); + double HoE = towerIso.getTowerESum(sc) / sc->energy(); + if (HoE >= maxHOverE_) + continue; ///// - std::vector > trackPairRef; std::vector trackInnPos; std::vector trackPin; std::vector trackPout; - float minAppDist=-99; + float minAppDist = -99; //LogDebug("ConvertedPhotonProducer") << "ConvertedPhotonProducer SC energy " << aClus->energy() << " eta " << aClus->eta() << " phi " << aClus->phi() << "\n"; - //// Set here first quantities for the converted photon - const reco::Particle::Point vtx( 0, 0, 0 ); + const reco::Particle::Point vtx(0, 0, 0); - - math::XYZVector direction =aClus->position() - vtx; + math::XYZVector direction = aClus->position() - vtx; math::XYZVector momentum = direction.unit() * aClus->energy(); - const reco::Particle::LorentzVector p4(momentum.x(), momentum.y(), momentum.z(), aClus->energy() ); - - int nFound=0; - if ( !allPairs.empty() ) { - - nFound=0; - - - for ( std::map, reco::CaloClusterPtr>::const_iterator iPair= allPairs.begin(); iPair!= allPairs.end(); ++iPair ) { - scPtrVec.clear(); - - reco::Vertex theConversionVertex; - reco::CaloClusterPtr caloPtr=iPair->second; - if ( !( aClus == caloPtr ) ) continue; - - scPtrVec.push_back(aClus); - nFound++; - - std::vector trkPositionAtEcal = theEcalImpactPositionFinder.find( iPair->first, bcHandle ); - std::vector matchingBC = theEcalImpactPositionFinder.matchingBC(); - - - minAppDist=-99; - const std::string metname = "ConvertedPhotons|ConvertedPhotonProducer"; - if ( (iPair->first).size() > 1 ) { - try{ - - theVertexFinder_->run(iPair->first, theConversionVertex ); - - - } - catch ( cms::Exception& e ) { - //std::cout << " cms::Exception caught in ConvertedPhotonProducer::produce" << "\n" ; - edm::LogWarning(metname) << "cms::Exception caught in ConvertedPhotonProducer::produce\n" - << e.explainSelf(); - - } - - // Old TwoTrackMinimumDistance md; - // Old md.calculate ( (iPair->first)[0].initialFreeState(), (iPair->first)[1].initialFreeState() ); - // Old minAppDist = md.distance(); - - - - - - - - /* - for ( unsigned int i=0; i< matchingBC.size(); ++i) { - if ( matchingBC[i].isNull() ) std::cout << " This ref to BC is null: skipping " << "\n"; - else - std::cout << " BC energy " << matchingBC[i]->energy() << "\n"; - } - */ - + const reco::Particle::LorentzVector p4(momentum.x(), momentum.y(), momentum.z(), aClus->energy()); - //// loop over tracks in the pair for creating a reference - trackPairRef.clear(); - trackInnPos.clear(); - trackPin.clear(); - trackPout.clear(); - - - for ( std::vector::const_iterator iTk=(iPair->first).begin(); iTk!= (iPair->first).end(); ++iTk) { - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Transient Tracks in the pair charge " << iTk->charge() << " Num of RecHits " << iTk->recHitsSize() << " inner momentum " << iTk->track().innerMomentum() << "\n"; - - const reco::TrackTransientTrack* ttt = dynamic_cast(iTk->basicTransientTrack()); - reco::TrackRef myTkRef= ttt->persistentTrackRef(); - - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Ref to Rec Tracks in the pair charge " << myTkRef->charge() << " Num of RecHits " << myTkRef->recHitsSize() << " inner momentum " << myTkRef->innerMomentum() << "\n"; - if ( myTkRef->extra().isNonnull() ) { - trackInnPos.push_back( toFConverterP(myTkRef->innerPosition())); - trackPin.push_back( toFConverterV( myTkRef->innerMomentum())); - trackPout.push_back( toFConverterV(myTkRef->outerMomentum())); - } - trackPairRef.push_back(myTkRef); - - } - - // std::cout << " ConvertedPhotonProducer trackPin size " << trackPin.size() << std::endl; - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer SC energy " << aClus->energy() << "\n"; - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer photon p4 " << p4 << "\n"; - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer vtx " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; - if( theConversionVertex.isValid() ) { - - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer theConversionVertex " << theConversionVertex.position().x() << " " << theConversionVertex.position().y() << " " << theConversionVertex.position().z() << "\n"; - - } - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer trackPairRef " << trackPairRef.size() << "\n"; - - - minAppDist=calculateMinApproachDistance( trackPairRef[0], trackPairRef[1]); - - double like = -999.; - reco::Conversion newCandidate(scPtrVec, trackPairRef, trkPositionAtEcal, theConversionVertex, matchingBC, minAppDist, trackInnPos, trackPin, trackPout, like, algo); -// like = theLikelihoodCalc_->calculateLikelihood(newCandidate, es ); - like = theLikelihoodCalc_->calculateLikelihood( newCandidate ); -// std::cout << "like = " << like << std::endl; - newCandidate.setMVAout(like); - outputConvPhotonCollection.push_back(newCandidate); - - - myCands++; - //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Put the ConvertedPhotonCollection a candidate in the Barrel " << "\n"; - - } else { - - - // std::cout << " ConvertedPhotonProducer case with only one track found " << "\n"; - - //std::cout << " ConvertedPhotonProducer recovering one track " << "\n"; - trackPairRef.clear(); - trackInnPos.clear(); - trackPin.clear(); - trackPout.clear(); - std::vector::const_iterator iTk=(iPair->first).begin(); - //std::cout << " ConvertedPhotonProducer Transient Tracks in the pair charge " << iTk->charge() << " Num of RecHits " << iTk->recHitsSize() << " inner momentum " << iTk->track().innerMomentum() << " pt " << sqrt(iTk->track().innerMomentum().perp2()) << "\n"; - const reco::TrackTransientTrack* ttt = dynamic_cast(iTk->basicTransientTrack()); - reco::TrackRef myTk= ttt->persistentTrackRef(); - if ( myTk->extra().isNonnull() ) { - trackInnPos.push_back( toFConverterP(myTk->innerPosition())); - trackPin.push_back( toFConverterV(myTk->innerMomentum())); - trackPout.push_back( toFConverterV(myTk->outerMomentum())); - } - trackPairRef.push_back(myTk); - //std::cout << " Provenance " << myTk->algoName() << std::endl; - - if ( recoverOneTrackCase_ ) { - float theta1 = myTk->innerMomentum().Theta(); - float dCot=999.; - float dCotTheta=-999.; - reco::TrackRef goodRef; - std::vector::const_iterator iGoodGenTran; - for ( std::vector::const_iterator iTran= t_generalTrk.begin(); iTran != t_generalTrk.end(); ++iTran) { - const reco::TrackTransientTrack* ttt = dynamic_cast(iTran->basicTransientTrack()); - reco::TrackRef trRef= ttt->persistentTrackRef(); - if ( trRef->charge()*myTk->charge() > 0 ) continue; - float dEta = trRef->eta() - myTk->eta(); - float dPhi = trRef->phi() - myTk->phi(); - if ( sqrt (dEta*dEta + dPhi*dPhi) > dRForConversionRecovery_ ) continue; - float theta2 = trRef->innerMomentum().Theta(); - dCotTheta = 1./tan(theta1) - 1./tan(theta2) ; - // std::cout << " ConvertedPhotonProducer recovering general transient track charge " << trRef->charge() << " momentum " << trRef->innerMomentum() << " dcotTheta " << fabs(dCotTheta) << std::endl; - if ( fabs(dCotTheta) < dCot ) { - dCot = fabs(dCotTheta); - goodRef = trRef; - iGoodGenTran=iTran; - } - } - - if ( goodRef.isNonnull() ) { - - minAppDist=calculateMinApproachDistance( myTk, goodRef); - - // std::cout << " ConvertedPhotonProducer chosen dCotTheta " << fabs(dCotTheta) << std::endl; - if ( fabs(dCotTheta) < deltaCotCut_ && minAppDist > minApproachDisCut_ ) { - trackInnPos.push_back( toFConverterP(goodRef->innerPosition())); - trackPin.push_back( toFConverterV(goodRef->innerMomentum())); - trackPout.push_back( toFConverterV(goodRef->outerMomentum())); - trackPairRef.push_back( goodRef ); - // std::cout << " ConvertedPhotonProducer adding opposite charge track from generalTrackCollection charge " << goodRef ->charge() << " pt " << sqrt(goodRef->innerMomentum().perp2()) << " trackPairRef size " << trackPairRef.size() << std::endl; - //std::cout << " Track Provenenance " << goodRef->algoName() << std::endl; - std::vector mypair; - mypair.push_back(*iTk); - mypair.push_back(*iGoodGenTran); - - try{ - theVertexFinder_->run(iPair->first, theConversionVertex ); - - } - catch ( cms::Exception& e ) { - //std::cout << " cms::Exception caught in ConvertedPhotonProducer::produce" << "\n" ; - edm::LogWarning(metname) << "cms::Exception caught in ConvertedPhotonProducer::produce\n" - << e.explainSelf(); - - } - } - - } - - } // bool On/Off one track case recovery using generalTracks - double like = -999.; - reco::Conversion newCandidate(scPtrVec, trackPairRef, trkPositionAtEcal, theConversionVertex, matchingBC, minAppDist, trackInnPos, trackPin, trackPout, like, algo); - like = theLikelihoodCalc_->calculateLikelihood(newCandidate); - newCandidate.setMVAout(like); - outputConvPhotonCollection.push_back(newCandidate); - - - - - } // case with only on track: looking in general tracks - - - - - } - - } - + int nFound = 0; + if (!allPairs.empty()) { + nFound = 0; + for (std::map, reco::CaloClusterPtr>::const_iterator iPair = allPairs.begin(); + iPair != allPairs.end(); + ++iPair) { + scPtrVec.clear(); - - } - + reco::Vertex theConversionVertex; + reco::CaloClusterPtr caloPtr = iPair->second; + if (!(aClus == caloPtr)) + continue; + scPtrVec.push_back(aClus); + nFound++; + std::vector trkPositionAtEcal = theEcalImpactPositionFinder.find(iPair->first, bcHandle); + std::vector matchingBC = theEcalImpactPositionFinder.matchingBC(); + minAppDist = -99; + const std::string metname = "ConvertedPhotons|ConvertedPhotonProducer"; + if ((iPair->first).size() > 1) { + try { + theVertexFinder_->run(iPair->first, theConversionVertex); -} + } catch (cms::Exception& e) { + //std::cout << " cms::Exception caught in ConvertedPhotonProducer::produce" << "\n" ; + edm::LogWarning(metname) << "cms::Exception caught in ConvertedPhotonProducer::produce\n" + << e.explainSelf(); + } + // Old TwoTrackMinimumDistance md; + // Old md.calculate ( (iPair->first)[0].initialFreeState(), (iPair->first)[1].initialFreeState() ); + // Old minAppDist = md.distance(); -void ConvertedPhotonProducer::cleanCollections(const edm::Handle > & scHandle, - const edm::OrphanHandle & conversionHandle, - reco::ConversionCollection & outputConversionCollection) { + /* + for ( unsigned int i=0; i< matchingBC.size(); ++i) { + if ( matchingBC[i].isNull() ) std::cout << " This ref to BC is null: skipping " << "\n"; + else + std::cout << " BC energy " << matchingBC[i]->energy() << "\n"; + } + */ + //// loop over tracks in the pair for creating a reference + trackPairRef.clear(); + trackInnPos.clear(); + trackPin.clear(); + trackPout.clear(); + + for (std::vector::const_iterator iTk = (iPair->first).begin(); + iTk != (iPair->first).end(); + ++iTk) { + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Transient Tracks in the pair charge " << iTk->charge() << " Num of RecHits " << iTk->recHitsSize() << " inner momentum " << iTk->track().innerMomentum() << "\n"; + + const reco::TrackTransientTrack* ttt = + dynamic_cast(iTk->basicTransientTrack()); + reco::TrackRef myTkRef = ttt->persistentTrackRef(); + + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Ref to Rec Tracks in the pair charge " << myTkRef->charge() << " Num of RecHits " << myTkRef->recHitsSize() << " inner momentum " << myTkRef->innerMomentum() << "\n"; + if (myTkRef->extra().isNonnull()) { + trackInnPos.push_back(toFConverterP(myTkRef->innerPosition())); + trackPin.push_back(toFConverterV(myTkRef->innerMomentum())); + trackPout.push_back(toFConverterV(myTkRef->outerMomentum())); + } + trackPairRef.push_back(myTkRef); + } + + // std::cout << " ConvertedPhotonProducer trackPin size " << trackPin.size() << std::endl; + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer SC energy " << aClus->energy() << "\n"; + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer photon p4 " << p4 << "\n"; + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer vtx " << vtx.x() << " " << vtx.y() << " " << vtx.z() << "\n"; + if (theConversionVertex.isValid()) { + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer theConversionVertex " << theConversionVertex.position().x() << " " << theConversionVertex.position().y() << " " << theConversionVertex.position().z() << "\n"; + } + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer trackPairRef " << trackPairRef.size() << "\n"; + + minAppDist = calculateMinApproachDistance(trackPairRef[0], trackPairRef[1]); + + double like = -999.; + reco::Conversion newCandidate(scPtrVec, + trackPairRef, + trkPositionAtEcal, + theConversionVertex, + matchingBC, + minAppDist, + trackInnPos, + trackPin, + trackPout, + like, + algo); + // like = theLikelihoodCalc_->calculateLikelihood(newCandidate, es ); + like = theLikelihoodCalc_->calculateLikelihood(newCandidate); + // std::cout << "like = " << like << std::endl; + newCandidate.setMVAout(like); + outputConvPhotonCollection.push_back(newCandidate); + + myCands++; + //LogDebug("ConvertedPhotonProducer") << " ConvertedPhotonProducer Put the ConvertedPhotonCollection a candidate in the Barrel " << "\n"; + + } else { + // std::cout << " ConvertedPhotonProducer case with only one track found " << "\n"; + + //std::cout << " ConvertedPhotonProducer recovering one track " << "\n"; + trackPairRef.clear(); + trackInnPos.clear(); + trackPin.clear(); + trackPout.clear(); + std::vector::const_iterator iTk = (iPair->first).begin(); + //std::cout << " ConvertedPhotonProducer Transient Tracks in the pair charge " << iTk->charge() << " Num of RecHits " << iTk->recHitsSize() << " inner momentum " << iTk->track().innerMomentum() << " pt " << sqrt(iTk->track().innerMomentum().perp2()) << "\n"; + const reco::TrackTransientTrack* ttt = + dynamic_cast(iTk->basicTransientTrack()); + reco::TrackRef myTk = ttt->persistentTrackRef(); + if (myTk->extra().isNonnull()) { + trackInnPos.push_back(toFConverterP(myTk->innerPosition())); + trackPin.push_back(toFConverterV(myTk->innerMomentum())); + trackPout.push_back(toFConverterV(myTk->outerMomentum())); + } + trackPairRef.push_back(myTk); + //std::cout << " Provenance " << myTk->algoName() << std::endl; + + if (recoverOneTrackCase_) { + float theta1 = myTk->innerMomentum().Theta(); + float dCot = 999.; + float dCotTheta = -999.; + reco::TrackRef goodRef; + std::vector::const_iterator iGoodGenTran; + for (std::vector::const_iterator iTran = t_generalTrk.begin(); + iTran != t_generalTrk.end(); + ++iTran) { + const reco::TrackTransientTrack* ttt = + dynamic_cast(iTran->basicTransientTrack()); + reco::TrackRef trRef = ttt->persistentTrackRef(); + if (trRef->charge() * myTk->charge() > 0) + continue; + float dEta = trRef->eta() - myTk->eta(); + float dPhi = trRef->phi() - myTk->phi(); + if (sqrt(dEta * dEta + dPhi * dPhi) > dRForConversionRecovery_) + continue; + float theta2 = trRef->innerMomentum().Theta(); + dCotTheta = 1. / tan(theta1) - 1. / tan(theta2); + // std::cout << " ConvertedPhotonProducer recovering general transient track charge " << trRef->charge() << " momentum " << trRef->innerMomentum() << " dcotTheta " << fabs(dCotTheta) << std::endl; + if (fabs(dCotTheta) < dCot) { + dCot = fabs(dCotTheta); + goodRef = trRef; + iGoodGenTran = iTran; + } + } + + if (goodRef.isNonnull()) { + minAppDist = calculateMinApproachDistance(myTk, goodRef); + + // std::cout << " ConvertedPhotonProducer chosen dCotTheta " << fabs(dCotTheta) << std::endl; + if (fabs(dCotTheta) < deltaCotCut_ && minAppDist > minApproachDisCut_) { + trackInnPos.push_back(toFConverterP(goodRef->innerPosition())); + trackPin.push_back(toFConverterV(goodRef->innerMomentum())); + trackPout.push_back(toFConverterV(goodRef->outerMomentum())); + trackPairRef.push_back(goodRef); + // std::cout << " ConvertedPhotonProducer adding opposite charge track from generalTrackCollection charge " << goodRef ->charge() << " pt " << sqrt(goodRef->innerMomentum().perp2()) << " trackPairRef size " << trackPairRef.size() << std::endl; + //std::cout << " Track Provenenance " << goodRef->algoName() << std::endl; + std::vector mypair; + mypair.push_back(*iTk); + mypair.push_back(*iGoodGenTran); + + try { + theVertexFinder_->run(iPair->first, theConversionVertex); + + } catch (cms::Exception& e) { + //std::cout << " cms::Exception caught in ConvertedPhotonProducer::produce" << "\n" ; + edm::LogWarning(metname) << "cms::Exception caught in ConvertedPhotonProducer::produce\n" + << e.explainSelf(); + } + } + } + + } // bool On/Off one track case recovery using generalTracks + double like = -999.; + reco::Conversion newCandidate(scPtrVec, + trackPairRef, + trkPositionAtEcal, + theConversionVertex, + matchingBC, + minAppDist, + trackInnPos, + trackPin, + trackPout, + like, + algo); + like = theLikelihoodCalc_->calculateLikelihood(newCandidate); + newCandidate.setMVAout(like); + outputConvPhotonCollection.push_back(newCandidate); + + } // case with only on track: looking in general tracks + } + } + } +} - reco::Conversion* newCandidate=nullptr; - for(auto const& aClus : scHandle->ptrs()) - { +void ConvertedPhotonProducer::cleanCollections(const edm::Handle >& scHandle, + const edm::OrphanHandle& conversionHandle, + reco::ConversionCollection& outputConversionCollection) { + reco::Conversion* newCandidate = nullptr; + for (auto const& aClus : scHandle->ptrs()) { // SC energy preselection - if (aClus->energy()/cosh(aClus->eta()) <= minSCEt_) continue; - + if (aClus->energy() / cosh(aClus->eta()) <= minSCEt_) + continue; - if ( conversionHandle.isValid() ) { + if (conversionHandle.isValid()) { + if (risolveAmbiguity_) { + std::vector bestRef = solveAmbiguity(conversionHandle, aClus); - if ( risolveAmbiguity_ ) { - std::vector bestRef=solveAmbiguity( conversionHandle , aClus); - - for ( std::vector::iterator iRef=bestRef.begin(); iRef!=bestRef.end(); iRef++ ) { - if ( iRef->isNonnull() ) { - newCandidate= (*iRef)->clone(); - outputConversionCollection.push_back(*newCandidate); + for (std::vector::iterator iRef = bestRef.begin(); iRef != bestRef.end(); iRef++) { + if (iRef->isNonnull()) { + newCandidate = (*iRef)->clone(); + outputConversionCollection.push_back(*newCandidate); delete newCandidate; - } - } - + } + } + } else { - - - for( unsigned int icp = 0; icp < conversionHandle->size(); icp++) { - reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle,icp)); - if (!( aClus.id() == cpRef->caloCluster()[0].id() && aClus.key() == cpRef->caloCluster()[0].key() )) continue; - if ( !cpRef->isConverted() ) continue; - if ( cpRef->nTracks() <2 ) continue; - newCandidate= (&(*cpRef))->clone(); - outputConversionCollection.push_back(*newCandidate); - delete newCandidate; - - } - - } // solve or not the ambiguity of many conversion candidates - - } - - - } + for (unsigned int icp = 0; icp < conversionHandle->size(); icp++) { + reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle, icp)); + if (!(aClus.id() == cpRef->caloCluster()[0].id() && aClus.key() == cpRef->caloCluster()[0].key())) + continue; + if (!cpRef->isConverted()) + continue; + if (cpRef->nTracks() < 2) + continue; + newCandidate = (&(*cpRef))->clone(); + outputConversionCollection.push_back(*newCandidate); + delete newCandidate; + } + + } // solve or not the ambiguity of many conversion candidates + } + } } +std::vector ConvertedPhotonProducer::solveAmbiguity( + const edm::OrphanHandle& conversionHandle, reco::CaloClusterPtr const& scRef) { + std::multimap > convMap; + for (unsigned int icp = 0; icp < conversionHandle->size(); icp++) { + reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle, icp)); - -std::vector ConvertedPhotonProducer::solveAmbiguity(const edm::OrphanHandle & conversionHandle, reco::CaloClusterPtr const& scRef) { - std::multimap > convMap; - - for ( unsigned int icp=0; icp< conversionHandle->size(); icp++) { - reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle,icp)); - - //std::cout << " cpRef " << cpRef->nTracks() << " " << cpRef ->caloCluster()[0]->energy() << std::endl; - if (!( scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key() )) continue; - if ( !cpRef->isConverted() ) continue; + //std::cout << " cpRef " << cpRef->nTracks() << " " << cpRef ->caloCluster()[0]->energy() << std::endl; + if (!(scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key())) + continue; + if (!cpRef->isConverted()) + continue; double like = cpRef->MVAout(); - if ( cpRef->nTracks() <2 ) continue; + if (cpRef->nTracks() < 2) + continue; // std::cout << " Like " << like << std::endl; - convMap.insert ( std::make_pair(like,cpRef) ); - - } - + convMap.insert(std::make_pair(like, cpRef)); + } + // std::cout << " convMap size " << convMap.size() << std::endl; - std::multimap::iterator iMap; + std::multimap::iterator iMap; std::vector bestRefs; - for (iMap=convMap.begin(); iMap!=convMap.end(); iMap++) { + for (iMap = convMap.begin(); iMap != convMap.end(); iMap++) { // std::cout << " Like list in the map " << iMap->first << " " << (iMap->second)->EoverP() << std::endl; - bestRefs.push_back( iMap->second ); - if ( int(bestRefs.size()) == maxNumOfCandidates_ ) break; + bestRefs.push_back(iMap->second); + if (int(bestRefs.size()) == maxNumOfCandidates_) + break; } + return bestRefs; +} - return bestRefs; - - -} - - - - - -float ConvertedPhotonProducer::calculateMinApproachDistance ( const reco::TrackRef& track1, const reco::TrackRef& track2) { - float dist=9999.; +float ConvertedPhotonProducer::calculateMinApproachDistance(const reco::TrackRef& track1, + const reco::TrackRef& track2) { + float dist = 9999.; double x1, x2, y1, y2; double xx_1 = track1->innerPosition().x(), yy_1 = track1->innerPosition().y(), zz_1 = track1->innerPosition().z(); double xx_2 = track2->innerPosition().x(), yy_2 = track2->innerPosition().y(), zz_2 = track2->innerPosition().z(); - double radius1 = track1->innerMomentum().Rho()/(.3*(theMF_->inTesla(GlobalPoint(xx_1, yy_1, zz_1)).z()))*100; - double radius2 = track2->innerMomentum().Rho()/(.3*(theMF_->inTesla(GlobalPoint(xx_2, yy_2, zz_2)).z()))*100; + double radius1 = track1->innerMomentum().Rho() / (.3 * (theMF_->inTesla(GlobalPoint(xx_1, yy_1, zz_1)).z())) * 100; + double radius2 = track2->innerMomentum().Rho() / (.3 * (theMF_->inTesla(GlobalPoint(xx_2, yy_2, zz_2)).z())) * 100; getCircleCenter(track1, radius1, x1, y1); getCircleCenter(track2, radius2, x2, y2); - dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) - radius1 - radius2; - - return dist; - -} + dist = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) - radius1 - radius2; + return dist; +} -void ConvertedPhotonProducer::getCircleCenter(const reco::TrackRef& tk, double r, double& x0, double& y0){ +void ConvertedPhotonProducer::getCircleCenter(const reco::TrackRef& tk, double r, double& x0, double& y0) { double x1, y1, phi; - x1 = tk->innerPosition().x();//inner position and inner momentum need track Extra! + x1 = tk->innerPosition().x(); //inner position and inner momentum need track Extra! y1 = tk->innerPosition().y(); phi = tk->innerMomentum().phi(); const int charge = tk->charge(); - x0 = x1 + r*sin(phi)*charge; - y0 = y1 - r*cos(phi)*charge; - + x0 = x1 + r * sin(phi) * charge; + y0 = y1 - r * cos(phi) * charge; } diff --git a/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonCoreProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonCoreProducer.cc index 32c18446ecdaf..982d96d315abd 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonCoreProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonCoreProducer.cc @@ -33,34 +33,23 @@ #include "TLorentzVector.h" #include "TMath.h" -GEDPhotonCoreProducer::GEDPhotonCoreProducer(const edm::ParameterSet& config) : - conf_(config) +GEDPhotonCoreProducer::GEDPhotonCoreProducer(const edm::ParameterSet& config) + : conf_(config) { - // use onfiguration file to setup input/output collection names - pfEgammaCandidates_ = - consumes(conf_.getParameter("pfEgammaCandidates")); - pixelSeedProducer_ = - consumes(conf_.getParameter("pixelSeedProducer")); + pfEgammaCandidates_ = consumes(conf_.getParameter("pfEgammaCandidates")); + pixelSeedProducer_ = consumes(conf_.getParameter("pixelSeedProducer")); GEDPhotonCoreCollection_ = conf_.getParameter("gedPhotonCoreCollection"); - - // Register the product produces(GEDPhotonCoreCollection_); - } GEDPhotonCoreProducer::~GEDPhotonCoreProducer() {} - - - -void GEDPhotonCoreProducer::produce(edm::Event &theEvent, const edm::EventSetup& theEventSetup) { - - +void GEDPhotonCoreProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { using namespace edm; // nEvt_++; @@ -69,38 +58,33 @@ void GEDPhotonCoreProducer::produce(edm::Event &theEvent, const edm::EventSetup& // Get the PF refined cluster collection Handle pfCandidateHandle; - theEvent.getByToken(pfEgammaCandidates_,pfCandidateHandle); + theEvent.getByToken(pfEgammaCandidates_, pfCandidateHandle); if (!pfCandidateHandle.isValid()) { - edm::LogError("GEDPhotonCoreProducer") - << "Error! Can't get the pfEgammaCandidates"; + edm::LogError("GEDPhotonCoreProducer") << "Error! Can't get the pfEgammaCandidates"; } - - // Get ElectronPixelSeeds - validPixelSeeds_=true; + // Get ElectronPixelSeeds + validPixelSeeds_ = true; Handle pixelSeedHandle; reco::ElectronSeedCollection pixelSeeds; theEvent.getByToken(pixelSeedProducer_, pixelSeedHandle); if (!pixelSeedHandle.isValid()) { - validPixelSeeds_=false; + validPixelSeeds_ = false; } - - // std::cout << " GEDPhotonCoreProducer::produce input PFcandidate size " << pfCandidateHandle->size() << std::endl; - // Loop over PF candidates and get only photons - for(unsigned int lCand=0; lCand < pfCandidateHandle->size(); lCand++) { - reco::PFCandidateRef candRef (reco::PFCandidateRef(pfCandidateHandle,lCand)); + for (unsigned int lCand = 0; lCand < pfCandidateHandle->size(); lCand++) { + reco::PFCandidateRef candRef(reco::PFCandidateRef(pfCandidateHandle, lCand)); // Retrieve stuff from the pfPhoton - reco::PFCandidateEGammaExtraRef pfPhoRef = candRef->egammaExtraRef(); - reco::SuperClusterRef refinedSC= pfPhoRef->superClusterRef(); - reco::SuperClusterRef boxSC= pfPhoRef->superClusterPFECALRef(); - const reco::ConversionRefVector & doubleLegConv = pfPhoRef->conversionRef(); - const reco::ConversionRefVector & singleLegConv = pfPhoRef->singleLegConversionRef(); - reco::CaloClusterPtr refinedSCPtr= edm::refToPtr(refinedSC); + reco::PFCandidateEGammaExtraRef pfPhoRef = candRef->egammaExtraRef(); + reco::SuperClusterRef refinedSC = pfPhoRef->superClusterRef(); + reco::SuperClusterRef boxSC = pfPhoRef->superClusterPFECALRef(); + const reco::ConversionRefVector& doubleLegConv = pfPhoRef->conversionRef(); + const reco::ConversionRefVector& singleLegConv = pfPhoRef->singleLegConversionRef(); + reco::CaloClusterPtr refinedSCPtr = edm::refToPtr(refinedSC); // std::cout << "newCandidate doubleLegConv="<assign(outputPhotonCoreCollection.begin(),outputPhotonCoreCollection.end()); + outputPhotonCoreCollection_p->assign(outputPhotonCoreCollection.begin(), outputPhotonCoreCollection.end()); theEvent.put(std::move(outputPhotonCoreCollection_p), GEDPhotonCoreCollection_); - - - - -} +} diff --git a/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonProducer.cc index e9bada750e359..2c58588bbd964 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/GEDPhotonProducer.cc @@ -14,7 +14,6 @@ #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" - #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/EgammaReco/interface/ClusterShape.h" @@ -38,51 +37,47 @@ #include "RecoEgamma/EgammaPhotonProducers/interface/GEDPhotonProducer.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaTowerIsolation.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" #include "RecoEcal/EgammaCoreTools/plugins/EcalClusterCrackCorrection.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaHadTower.h" #include "RecoEcal/EgammaCoreTools/interface/EcalTools.h" namespace { - inline double ptFast( const double energy, - const math::XYZPoint& position, - const math::XYZPoint& origin ) { + inline double ptFast(const double energy, const math::XYZPoint& position, const math::XYZPoint& origin) { const auto v = position - origin; - return energy*std::sqrt(v.perp2()/v.mag2()); + return energy * std::sqrt(v.perp2() / v.mag2()); } -} - -GEDPhotonProducer::RecoStepInfo::RecoStepInfo(const std::string& step): - flags_(0) -{ - if(step=="final") flags_ = kFinal; - else if(step=="oot") flags_ = kOOT; - else if(step=="ootfinal") flags_ = (kOOT|kFinal); - else if(step=="tmp") flags_ = 0; - else{ - throw cms::Exception("InvalidConfig") <<" reconstructStep "<("reconstructionStep")), - conf_(config) -{ - +GEDPhotonProducer::GEDPhotonProducer(const edm::ParameterSet& config) + : recoStep_(config.getParameter("reconstructionStep")), conf_(config) { // use configuration file to setup input/output collection names // - photonProducer_ = conf_.getParameter("photonProducer"); - - if ( recoStep_.isFinal() ) { - photonProducerT_ = - consumes(photonProducer_); - pfCandidates_ = - consumes(conf_.getParameter("pfCandidates")); + photonProducer_ = conf_.getParameter("photonProducer"); + + if (recoStep_.isFinal()) { + photonProducerT_ = consumes(photonProducer_); + pfCandidates_ = consumes(conf_.getParameter("pfCandidates")); const edm::ParameterSet& pfIsolCfg = conf_.getParameter("pfIsolCfg"); - auto getVMToken = [&pfIsolCfg,this](const std::string& name){ - return consumes >(pfIsolCfg.getParameter(name)); + auto getVMToken = [&pfIsolCfg, this](const std::string& name) { + return consumes>(pfIsolCfg.getParameter(name)); }; phoChargedIsolationToken_ = getVMToken("chargedHadronIso"); phoNeutralHadronIsolationToken_ = getVMToken("neutralHadronIso"); @@ -93,85 +88,68 @@ GEDPhotonProducer::GEDPhotonProducer(const edm::ParameterSet& config) : //OOT photons in legacy 80X re-miniAOD do not have PF cluster embeded into the reco object //to preserve 80X behaviour - if(conf_.exists("pfECALClusIsolation")){ - phoPFECALClusIsolationToken_ = - consumes>(conf_.getParameter("pfECALClusIsolation")); + if (conf_.exists("pfECALClusIsolation")) { + phoPFECALClusIsolationToken_ = + consumes>(conf_.getParameter("pfECALClusIsolation")); } - if(conf_.exists("pfHCALClusIsolation")){ - phoPFHCALClusIsolationToken_ = - consumes>(conf_.getParameter("pfHCALClusIsolation")); + if (conf_.exists("pfHCALClusIsolation")) { + phoPFHCALClusIsolationToken_ = + consumes>(conf_.getParameter("pfHCALClusIsolation")); } } else { - - photonCoreProducerT_ = - consumes(photonProducer_); - + photonCoreProducerT_ = consumes(photonProducer_); } auto pfEg = conf_.getParameter("pfEgammaCandidates"); if (not pfEg.label().empty()) - pfEgammaCandidates_ = - consumes(pfEg); - barrelEcalHits_ = - consumes(conf_.getParameter("barrelEcalHits")); - endcapEcalHits_ = - consumes(conf_.getParameter("endcapEcalHits")); - preshowerHits_ = - consumes(conf_.getParameter("preshowerHits")); - vertexProducer_ = - consumes(conf_.getParameter("primaryVertexProducer")); + pfEgammaCandidates_ = consumes(pfEg); + barrelEcalHits_ = consumes(conf_.getParameter("barrelEcalHits")); + endcapEcalHits_ = consumes(conf_.getParameter("endcapEcalHits")); + preshowerHits_ = consumes(conf_.getParameter("preshowerHits")); + vertexProducer_ = consumes(conf_.getParameter("primaryVertexProducer")); auto hcTow = conf_.getParameter("hcalTowers"); if (not hcTow.label().empty()) - hcalTowers_ = - consumes(hcTow); + hcalTowers_ = consumes(hcTow); // - photonCollection_ = conf_.getParameter("outputPhotonCollection"); - hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); - highEt_ = conf_.getParameter("highEt"); + photonCollection_ = conf_.getParameter("outputPhotonCollection"); + hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); + highEt_ = conf_.getParameter("highEt"); // R9 value to decide converted/unconverted - minR9Barrel_ = conf_.getParameter("minR9Barrel"); - minR9Endcap_ = conf_.getParameter("minR9Endcap"); - usePrimaryVertex_ = conf_.getParameter("usePrimaryVertex"); - runMIPTagger_ = conf_.getParameter("runMIPTagger"); + minR9Barrel_ = conf_.getParameter("minR9Barrel"); + minR9Endcap_ = conf_.getParameter("minR9Endcap"); + usePrimaryVertex_ = conf_.getParameter("usePrimaryVertex"); + runMIPTagger_ = conf_.getParameter("runMIPTagger"); - candidateP4type_ = config.getParameter("candidateP4type") ; + candidateP4type_ = config.getParameter("candidateP4type"); valueMapPFCandPhoton_ = config.getParameter("valueMapPhotons"); - - edm::ParameterSet posCalcParameters = - config.getParameter("posCalcParameters"); + edm::ParameterSet posCalcParameters = config.getParameter("posCalcParameters"); posCalculator_ = PositionCalc(posCalcParameters); - //AA //Flags and Severities to be excluded from photon calculations - const std::vector flagnamesEB = - config.getParameter >("RecHitFlagToBeExcludedEB"); + const std::vector flagnamesEB = + config.getParameter>("RecHitFlagToBeExcludedEB"); const std::vector flagnamesEE = - config.getParameter >("RecHitFlagToBeExcludedEE"); + config.getParameter>("RecHitFlagToBeExcludedEE"); - flagsexclEB_= - StringToEnumValue(flagnamesEB); + flagsexclEB_ = StringToEnumValue(flagnamesEB); - flagsexclEE_= - StringToEnumValue(flagnamesEE); + flagsexclEE_ = StringToEnumValue(flagnamesEE); - const std::vector severitynamesEB = - config.getParameter >("RecHitSeverityToBeExcludedEB"); + const std::vector severitynamesEB = + config.getParameter>("RecHitSeverityToBeExcludedEB"); - severitiesexclEB_= - StringToEnumValue(severitynamesEB); + severitiesexclEB_ = StringToEnumValue(severitynamesEB); - const std::vector severitynamesEE = - config.getParameter >("RecHitSeverityToBeExcludedEE"); + const std::vector severitynamesEE = + config.getParameter>("RecHitSeverityToBeExcludedEE"); - severitiesexclEE_= - StringToEnumValue(severitynamesEE); + severitiesexclEE_ = StringToEnumValue(severitynamesEE); - thePhotonEnergyCorrector_ = - new PhotonEnergyCorrector(conf_, consumesCollector()); + thePhotonEnergyCorrector_ = new PhotonEnergyCorrector(conf_, consumesCollector()); //AA @@ -187,190 +165,177 @@ GEDPhotonProducer::GEDPhotonProducer(const edm::ParameterSet& config) : //providedParameters.insert(std::make_pair("X0",conf_.getParameter("posCalc_x0"))); //posCalculator_ = PositionCalc(providedParameters); // cut values for pre-selection - preselCutValuesBarrel_.push_back(conf_.getParameter("minSCEtBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("maxHoverEBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("ecalRecHitSumEtOffsetBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("ecalRecHitSumEtSlopeBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("minSCEtBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("maxHoverEBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("ecalRecHitSumEtOffsetBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("ecalRecHitSumEtSlopeBarrel")); preselCutValuesBarrel_.push_back(conf_.getParameter("hcalTowerSumEtOffsetBarrel")); preselCutValuesBarrel_.push_back(conf_.getParameter("hcalTowerSumEtSlopeBarrel")); preselCutValuesBarrel_.push_back(conf_.getParameter("nTrackSolidConeBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("nTrackHollowConeBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("trackPtSumSolidConeBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("trackPtSumHollowConeBarrel")); - preselCutValuesBarrel_.push_back(conf_.getParameter("sigmaIetaIetaCutBarrel")); - // - preselCutValuesEndcap_.push_back(conf_.getParameter("minSCEtEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("maxHoverEEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("ecalRecHitSumEtOffsetEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("ecalRecHitSumEtSlopeEndcap")); + preselCutValuesBarrel_.push_back(conf_.getParameter("nTrackHollowConeBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("trackPtSumSolidConeBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("trackPtSumHollowConeBarrel")); + preselCutValuesBarrel_.push_back(conf_.getParameter("sigmaIetaIetaCutBarrel")); + // + preselCutValuesEndcap_.push_back(conf_.getParameter("minSCEtEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("maxHoverEEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("ecalRecHitSumEtOffsetEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("ecalRecHitSumEtSlopeEndcap")); preselCutValuesEndcap_.push_back(conf_.getParameter("hcalTowerSumEtOffsetEndcap")); preselCutValuesEndcap_.push_back(conf_.getParameter("hcalTowerSumEtSlopeEndcap")); preselCutValuesEndcap_.push_back(conf_.getParameter("nTrackSolidConeEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("nTrackHollowConeEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("trackPtSumSolidConeEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("trackPtSumHollowConeEndcap")); - preselCutValuesEndcap_.push_back(conf_.getParameter("sigmaIetaIetaCutEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("nTrackHollowConeEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("trackPtSumSolidConeEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("trackPtSumHollowConeEndcap")); + preselCutValuesEndcap_.push_back(conf_.getParameter("sigmaIetaIetaCutEndcap")); // //moved from beginRun to here, I dont see how this could cause harm as its just reading in the exactly same parameters each run - if ( !recoStep_.isFinal()){ + if (!recoStep_.isFinal()) { thePhotonIsolationCalculator_ = new PhotonIsolationCalculator(); - edm::ParameterSet isolationSumsCalculatorSet = conf_.getParameter("isolationSumsCalculatorSet"); - thePhotonIsolationCalculator_->setup(isolationSumsCalculatorSet, flagsexclEB_, flagsexclEE_, severitiesexclEB_, severitiesexclEE_,consumesCollector()); + edm::ParameterSet isolationSumsCalculatorSet = conf_.getParameter("isolationSumsCalculatorSet"); + thePhotonIsolationCalculator_->setup(isolationSumsCalculatorSet, + flagsexclEB_, + flagsexclEE_, + severitiesexclEB_, + severitiesexclEE_, + consumesCollector()); thePhotonMIPHaloTagger_ = new PhotonMIPHaloTagger(); - edm::ParameterSet mipVariableSet = conf_.getParameter("mipVariableSet"); - thePhotonMIPHaloTagger_->setup(mipVariableSet,consumesCollector()); - - }else{ - thePhotonIsolationCalculator_=nullptr; - thePhotonMIPHaloTagger_=nullptr; + edm::ParameterSet mipVariableSet = conf_.getParameter("mipVariableSet"); + thePhotonMIPHaloTagger_->setup(mipVariableSet, consumesCollector()); + + } else { + thePhotonIsolationCalculator_ = nullptr; + thePhotonMIPHaloTagger_ = nullptr; } checkHcalStatus_ = conf_.getParameter("checkHcalStatus"); // Register the product - produces< reco::PhotonCollection >(photonCollection_); + produces(photonCollection_); if (not pfEgammaCandidates_.isUninitialized()) - produces< edm::ValueMap > (valueMapPFCandPhoton_); - - + produces>(valueMapPFCandPhoton_); } -GEDPhotonProducer::~GEDPhotonProducer() -{ +GEDPhotonProducer::~GEDPhotonProducer() { delete thePhotonEnergyCorrector_; delete thePhotonIsolationCalculator_; delete thePhotonMIPHaloTagger_; - //delete energyCorrectionF; + //delete energyCorrectionF; } - - -void GEDPhotonProducer::beginRun (edm::Run const& r, edm::EventSetup const & theEventSetup) { - - if ( !recoStep_.isFinal() ) { - thePhotonEnergyCorrector_ -> init(theEventSetup); +void GEDPhotonProducer::beginRun(edm::Run const& r, edm::EventSetup const& theEventSetup) { + if (!recoStep_.isFinal()) { + thePhotonEnergyCorrector_->init(theEventSetup); } - -} - -void GEDPhotonProducer::endRun (edm::Run const& r, edm::EventSetup const & theEventSetup) { } +void GEDPhotonProducer::endRun(edm::Run const& r, edm::EventSetup const& theEventSetup) {} void GEDPhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { - using namespace edm; // nEvt_++; - + reco::PhotonCollection outputPhotonCollection; auto outputPhotonCollection_p = std::make_unique(); edm::ValueMap pfEGCandToPhotonMap; - // Get the PhotonCore collection - bool validPhotonCoreHandle=false; + bool validPhotonCoreHandle = false; Handle photonCoreHandle; - bool validPhotonHandle= false; + bool validPhotonHandle = false; Handle photonHandle; //value maps for isolation - edm::Handle > phoChargedIsolationMap; - edm::Handle > phoNeutralHadronIsolationMap; - edm::Handle > phoPhotonIsolationMap; - edm::Handle > phoChargedWorstVtxIsoMap; - edm::Handle > phoChargedWorstVtxGeomVetoIsoMap; - edm::Handle > phoChargedPFPVIsoMap; - - edm::Handle > phoPFECALClusIsolationMap; - edm::Handle > phoPFHCALClusIsolationMap; - - if ( recoStep_.isFinal() ) { - theEvent.getByToken(photonProducerT_,photonHandle); + edm::Handle> phoChargedIsolationMap; + edm::Handle> phoNeutralHadronIsolationMap; + edm::Handle> phoPhotonIsolationMap; + edm::Handle> phoChargedWorstVtxIsoMap; + edm::Handle> phoChargedWorstVtxGeomVetoIsoMap; + edm::Handle> phoChargedPFPVIsoMap; + + edm::Handle> phoPFECALClusIsolationMap; + edm::Handle> phoPFHCALClusIsolationMap; + + if (recoStep_.isFinal()) { + theEvent.getByToken(photonProducerT_, photonHandle); //get isolation objects - theEvent.getByToken(phoChargedIsolationToken_,phoChargedIsolationMap); - theEvent.getByToken(phoNeutralHadronIsolationToken_,phoNeutralHadronIsolationMap); - theEvent.getByToken(phoPhotonIsolationToken_,phoPhotonIsolationMap); - theEvent.getByToken(phoChargedWorstVtxIsoToken_,phoChargedWorstVtxIsoMap); - theEvent.getByToken(phoChargedWorstVtxGeomVetoIsoToken_,phoChargedWorstVtxGeomVetoIsoMap); - theEvent.getByToken(phoChargedPFPVIsoToken_,phoChargedPFPVIsoMap); + theEvent.getByToken(phoChargedIsolationToken_, phoChargedIsolationMap); + theEvent.getByToken(phoNeutralHadronIsolationToken_, phoNeutralHadronIsolationMap); + theEvent.getByToken(phoPhotonIsolationToken_, phoPhotonIsolationMap); + theEvent.getByToken(phoChargedWorstVtxIsoToken_, phoChargedWorstVtxIsoMap); + theEvent.getByToken(phoChargedWorstVtxGeomVetoIsoToken_, phoChargedWorstVtxGeomVetoIsoMap); + theEvent.getByToken(phoChargedPFPVIsoToken_, phoChargedPFPVIsoMap); //OOT photons in legacy 80X re-miniAOD workflow dont have cluster isolation embed in them - if(!phoPFECALClusIsolationToken_.isUninitialized()) { - theEvent.getByToken(phoPFECALClusIsolationToken_,phoPFECALClusIsolationMap); + if (!phoPFECALClusIsolationToken_.isUninitialized()) { + theEvent.getByToken(phoPFECALClusIsolationToken_, phoPFECALClusIsolationMap); } - if(!phoPFHCALClusIsolationToken_.isUninitialized()){ - theEvent.getByToken(phoPFHCALClusIsolationToken_,phoPFHCALClusIsolationMap); + if (!phoPFHCALClusIsolationToken_.isUninitialized()) { + theEvent.getByToken(phoPFHCALClusIsolationToken_, phoPFHCALClusIsolationMap); } - - if ( photonHandle.isValid()) { - validPhotonHandle=true; + + if (photonHandle.isValid()) { + validPhotonHandle = true; } else { - throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the product " << photonProducer_.label() << "\n"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the product " << photonProducer_.label() << "\n"; } } else { - - theEvent.getByToken(photonCoreProducerT_,photonCoreHandle); + theEvent.getByToken(photonCoreProducerT_, photonCoreHandle); if (photonCoreHandle.isValid()) { - validPhotonCoreHandle=true; + validPhotonCoreHandle = true; } else { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the photonCoreProducer " << photonProducer_.label() << "\n"; - } + throw cms::Exception("GEDPhotonProducer") + << "Error! Can't get the photonCoreProducer " << photonProducer_.label() << "\n"; + } } // Get EcalRecHits - bool validEcalRecHits=true; + bool validEcalRecHits = true; Handle barrelHitHandle; const EcalRecHitCollection dummyEB; theEvent.getByToken(barrelEcalHits_, barrelHitHandle); if (!barrelHitHandle.isValid()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the barrelEcalHits"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the barrelEcalHits"; } const EcalRecHitCollection& barrelRecHits(validEcalRecHits ? *(barrelHitHandle.product()) : dummyEB); - + Handle endcapHitHandle; theEvent.getByToken(endcapEcalHits_, endcapHitHandle); const EcalRecHitCollection dummyEE; if (!endcapHitHandle.isValid()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the endcapEcalHits"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the endcapEcalHits"; } const EcalRecHitCollection& endcapRecHits(validEcalRecHits ? *(endcapHitHandle.product()) : dummyEE); - bool validPreshowerRecHits=true; + bool validPreshowerRecHits = true; Handle preshowerHitHandle; theEvent.getByToken(preshowerHits_, preshowerHitHandle); EcalRecHitCollection preshowerRecHits; if (!preshowerHitHandle.isValid()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the preshowerEcalHits"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the preshowerEcalHits"; } - if( validPreshowerRecHits ) preshowerRecHits = *(preshowerHitHandle.product()); - - + if (validPreshowerRecHits) + preshowerRecHits = *(preshowerHitHandle.product()); Handle pfEGCandidateHandle; // Get the PF refined cluster collection - if (not pfEgammaCandidates_.isUninitialized()){ - theEvent.getByToken(pfEgammaCandidates_,pfEGCandidateHandle); + if (not pfEgammaCandidates_.isUninitialized()) { + theEvent.getByToken(pfEgammaCandidates_, pfEGCandidateHandle); if (!pfEGCandidateHandle.isValid()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the pfEgammaCandidates"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the pfEgammaCandidates"; } } Handle pfCandidateHandle; - if ( recoStep_.isFinal() ) { + if (recoStep_.isFinal()) { // Get the PF candidates collection - theEvent.getByToken(pfCandidates_,pfCandidateHandle); + theEvent.getByToken(pfCandidates_, pfCandidateHandle); //OOT photons have no PF candidates so its not an error in this case if (!pfCandidateHandle.isValid() && !recoStep_.isOOT()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the pfCandidates"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the pfCandidates"; } - } + } //AA //Get the severity level object @@ -378,10 +343,9 @@ void GEDPhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& the theEventSetup.get().get(sevLv); // - -// get Hcal towers collection + // get Hcal towers collection Handle hcalTowersHandle; - if (not hcalTowers_.isUninitialized()){ + if (not hcalTowers_.isUninitialized()) { theEvent.getByToken(hcalTowers_, hcalTowersHandle); } @@ -390,241 +354,237 @@ void GEDPhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& the // // update energy correction function - // energyCorrectionF->init(theEventSetup); + // energyCorrectionF->init(theEventSetup); edm::ESHandle pTopology; theEventSetup.get().get(theCaloTopo_); - const CaloTopology *topology = theCaloTopo_.product(); + const CaloTopology* topology = theCaloTopo_.product(); // Get the primary event vertex Handle vertexHandle; const reco::VertexCollection dummyVC; - bool validVertex=true; - if ( usePrimaryVertex_ ) { + bool validVertex = true; + if (usePrimaryVertex_) { theEvent.getByToken(vertexProducer_, vertexHandle); if (!vertexHandle.isValid()) { - throw cms::Exception("GEDPhotonProducer") - << "Error! Can't get the product primary Vertex Collection"; + throw cms::Exception("GEDPhotonProducer") << "Error! Can't get the product primary Vertex Collection"; } } - const reco::VertexCollection& vertexCollection(usePrimaryVertex_ && validVertex ? *(vertexHandle.product()) : dummyVC); + const reco::VertexCollection& vertexCollection(usePrimaryVertex_ && validVertex ? *(vertexHandle.product()) + : dummyVC); // math::XYZPoint vtx(0.,0.,0.); //if (vertexCollection.size()>0) vtx = vertexCollection.begin()->position(); // get the regression calculator ready thePhotonEnergyCorrector_->init(theEventSetup); - if( thePhotonEnergyCorrector_->gedRegression() ) { + if (thePhotonEnergyCorrector_->gedRegression()) { thePhotonEnergyCorrector_->gedRegression()->setEvent(theEvent); thePhotonEnergyCorrector_->gedRegression()->setEventContent(theEventSetup); } - - int iSC=0; // index in photon collection + int iSC = 0; // index in photon collection // Loop over barrel and endcap SC collections and fill the photon collection - if ( validPhotonCoreHandle) + if (validPhotonCoreHandle) fillPhotonCollection(theEvent, - theEventSetup, - photonCoreHandle, - topology, - &barrelRecHits, - &endcapRecHits, + theEventSetup, + photonCoreHandle, + topology, + &barrelRecHits, + &endcapRecHits, &preshowerRecHits, - hcalTowersHandle, - //vtx, - vertexCollection, - outputPhotonCollection, - iSC); - - iSC=0; - if ( validPhotonHandle && recoStep_.isFinal() ) + hcalTowersHandle, + //vtx, + vertexCollection, + outputPhotonCollection, + iSC); + + iSC = 0; + if (validPhotonHandle && recoStep_.isFinal()) fillPhotonCollection(theEvent, - theEventSetup, - photonHandle, - pfCandidateHandle, - pfEGCandidateHandle, - pfEGCandToPhotonMap, - vertexHandle, - outputPhotonCollection, - iSC, - phoChargedIsolationMap, - phoNeutralHadronIsolationMap, - phoPhotonIsolationMap, - phoChargedWorstVtxIsoMap, - phoChargedWorstVtxGeomVetoIsoMap, - phoChargedPFPVIsoMap, - phoPFECALClusIsolationMap, - phoPFHCALClusIsolationMap); - - + theEventSetup, + photonHandle, + pfCandidateHandle, + pfEGCandidateHandle, + pfEGCandToPhotonMap, + vertexHandle, + outputPhotonCollection, + iSC, + phoChargedIsolationMap, + phoNeutralHadronIsolationMap, + phoPhotonIsolationMap, + phoChargedWorstVtxIsoMap, + phoChargedWorstVtxGeomVetoIsoMap, + phoChargedPFPVIsoMap, + phoPFECALClusIsolationMap, + phoPFHCALClusIsolationMap); // put the product in the event edm::LogInfo("GEDPhotonProducer") << " Put in the event " << iSC << " Photon Candidates \n"; - outputPhotonCollection_p->assign(outputPhotonCollection.begin(),outputPhotonCollection.end()); - const edm::OrphanHandle photonOrphHandle = theEvent.put(std::move(outputPhotonCollection_p), photonCollection_); - + outputPhotonCollection_p->assign(outputPhotonCollection.begin(), outputPhotonCollection.end()); + const edm::OrphanHandle photonOrphHandle = + theEvent.put(std::move(outputPhotonCollection_p), photonCollection_); - if ( !recoStep_.isFinal() && not pfEgammaCandidates_.isUninitialized()) { - //// Define the value map which associate to each Egamma-unbiassaed candidate (key-ref) the corresponding PhotonRef + if (!recoStep_.isFinal() && not pfEgammaCandidates_.isUninitialized()) { + //// Define the value map which associate to each Egamma-unbiassaed candidate (key-ref) the corresponding PhotonRef auto pfEGCandToPhotonMap_p = std::make_unique>(); edm::ValueMap::Filler filler(*pfEGCandToPhotonMap_p); unsigned nObj = pfEGCandidateHandle->size(); std::vector values(nObj); - //// Fill the value map which associate to each Photon (key) the corresponding Egamma-unbiassaed candidate (value-ref) - for(unsigned int lCand=0; lCand < nObj; lCand++) { - reco::PFCandidateRef pfCandRef (reco::PFCandidateRef(pfEGCandidateHandle,lCand)); - reco::SuperClusterRef pfScRef = pfCandRef -> superClusterRef(); - - for(unsigned int lSC=0; lSC < photonOrphHandle->size(); lSC++) { - reco::PhotonRef photonRef(reco::PhotonRef(photonOrphHandle, lSC)); - reco::SuperClusterRef scRef=photonRef->superCluster(); - if ( pfScRef != scRef ) continue; - values[lCand] = photonRef; + //// Fill the value map which associate to each Photon (key) the corresponding Egamma-unbiassaed candidate (value-ref) + for (unsigned int lCand = 0; lCand < nObj; lCand++) { + reco::PFCandidateRef pfCandRef(reco::PFCandidateRef(pfEGCandidateHandle, lCand)); + reco::SuperClusterRef pfScRef = pfCandRef->superClusterRef(); + + for (unsigned int lSC = 0; lSC < photonOrphHandle->size(); lSC++) { + reco::PhotonRef photonRef(reco::PhotonRef(photonOrphHandle, lSC)); + reco::SuperClusterRef scRef = photonRef->superCluster(); + if (pfScRef != scRef) + continue; + values[lCand] = photonRef; } } - - - filler.insert(pfEGCandidateHandle,values.begin(),values.end()); - filler.fill(); - theEvent.put(std::move(pfEGCandToPhotonMap_p),valueMapPFCandPhoton_); - + filler.insert(pfEGCandidateHandle, values.begin(), values.end()); + filler.fill(); + theEvent.put(std::move(pfEGCandToPhotonMap_p), valueMapPFCandPhoton_); } - - - - - - } void GEDPhotonProducer::fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonCoreHandle, - const CaloTopology* topology, - const EcalRecHitCollection* ecalBarrelHits, - const EcalRecHitCollection* ecalEndcapHits, + edm::EventSetup const& es, + const edm::Handle& photonCoreHandle, + const CaloTopology* topology, + const EcalRecHitCollection* ecalBarrelHits, + const EcalRecHitCollection* ecalEndcapHits, const EcalRecHitCollection* preshowerHits, - const edm::Handle & hcalTowersHandle, - const reco::VertexCollection & vertexCollection, - reco::PhotonCollection & outputPhotonCollection, int& iSC) { - - + const edm::Handle& hcalTowersHandle, + const reco::VertexCollection& vertexCollection, + reco::PhotonCollection& outputPhotonCollection, + int& iSC) { const CaloGeometry* geometry = theCaloGeom_.product(); - const EcalRecHitCollection* hits = nullptr ; + const EcalRecHitCollection* hits = nullptr; std::vector preselCutValues; std::vector flags_, severitiesexcl_; - for(unsigned int lSC=0; lSC < photonCoreHandle->size(); lSC++) { - + for (unsigned int lSC = 0; lSC < photonCoreHandle->size(); lSC++) { reco::PhotonCoreRef coreRef(reco::PhotonCoreRef(photonCoreHandle, lSC)); reco::SuperClusterRef parentSCRef = coreRef->parentSuperCluster(); - reco::SuperClusterRef scRef=coreRef->superCluster(); + reco::SuperClusterRef scRef = coreRef->superCluster(); - - // const reco::SuperCluster* pClus=&(*scRef); iSC++; - + DetId::Detector thedet = scRef->seed()->hitsAndFractions()[0].first.det(); int subdet = scRef->seed()->hitsAndFractions()[0].first.subdetId(); - if (subdet==EcalBarrel) { + if (subdet == EcalBarrel) { preselCutValues = preselCutValuesBarrel_; hits = ecalBarrelHits; flags_ = flagsexclEB_; severitiesexcl_ = severitiesexclEB_; - } else if (subdet==EcalEndcap) { + } else if (subdet == EcalEndcap) { preselCutValues = preselCutValuesEndcap_; hits = ecalEndcapHits; flags_ = flagsexclEE_; severitiesexcl_ = severitiesexclEE_; - } else if ( EcalTools::isHGCalDet(thedet) ) { + } else if (EcalTools::isHGCalDet(thedet)) { preselCutValues = preselCutValuesEndcap_; hits = nullptr; flags_ = flagsexclEE_; severitiesexcl_ = severitiesexclEE_; } else { - edm::LogWarning("")<<"GEDPhotonProducer: do not know if it is a barrel or endcap SuperCluster: " << thedet << ' ' << subdet; + edm::LogWarning("") << "GEDPhotonProducer: do not know if it is a barrel or endcap SuperCluster: " << thedet + << ' ' << subdet; } - - - // SC energy preselection if (parentSCRef.isNonnull() && - ptFast(parentSCRef->energy(),parentSCRef->position(),math::XYZPoint(0,0,0)) <= preselCutValues[0] ) continue; - // calculate HoE + ptFast(parentSCRef->energy(), parentSCRef->position(), math::XYZPoint(0, 0, 0)) <= preselCutValues[0]) + continue; + // calculate HoE - double HoE1,HoE2; - HoE1=HoE2=0.; + double HoE1, HoE2; + HoE1 = HoE2 = 0.; std::vector TowersBehindClus; - float hcalDepth1OverEcalBc,hcalDepth2OverEcalBc; - hcalDepth1OverEcalBc=hcalDepth2OverEcalBc=0.f; + float hcalDepth1OverEcalBc, hcalDepth2OverEcalBc; + hcalDepth1OverEcalBc = hcalDepth2OverEcalBc = 0.f; bool invalidHcal = false; if (not hcalTowers_.isUninitialized()) { const CaloTowerCollection* hcalTowersColl = hcalTowersHandle.product(); - EgammaTowerIsolation towerIso1(hOverEConeSize_,0.,0.,1,hcalTowersColl) ; - EgammaTowerIsolation towerIso2(hOverEConeSize_,0.,0.,2,hcalTowersColl) ; - HoE1=towerIso1.getTowerESum(&(*scRef))/scRef->energy(); - HoE2=towerIso2.getTowerESum(&(*scRef))/scRef->energy(); + EgammaTowerIsolation towerIso1(hOverEConeSize_, 0., 0., 1, hcalTowersColl); + EgammaTowerIsolation towerIso2(hOverEConeSize_, 0., 0., 2, hcalTowersColl); + HoE1 = towerIso1.getTowerESum(&(*scRef)) / scRef->energy(); + HoE2 = towerIso2.getTowerESum(&(*scRef)) / scRef->energy(); - EgammaHadTower towerIsoBehindClus(es); + EgammaHadTower towerIsoBehindClus(es); towerIsoBehindClus.setTowerCollection(hcalTowersHandle.product()); TowersBehindClus = towerIsoBehindClus.towersOf(*scRef); - hcalDepth1OverEcalBc = towerIsoBehindClus.getDepth1HcalESum(TowersBehindClus)/scRef->energy(); - hcalDepth2OverEcalBc = towerIsoBehindClus.getDepth2HcalESum(TowersBehindClus)/scRef->energy(); + hcalDepth1OverEcalBc = towerIsoBehindClus.getDepth1HcalESum(TowersBehindClus) / scRef->energy(); + hcalDepth2OverEcalBc = towerIsoBehindClus.getDepth2HcalESum(TowersBehindClus) / scRef->energy(); if (checkHcalStatus_ && hcalDepth1OverEcalBc == 0 && hcalDepth2OverEcalBc == 0) { - invalidHcal = !towerIsoBehindClus.hasActiveHcal(TowersBehindClus); + invalidHcal = !towerIsoBehindClus.hasActiveHcal(TowersBehindClus); } } // std::cout << " GEDPhotonProducer calculation of HoE with towers in a cone " << HoE1 << " " << HoE2 << std::endl; //std::cout << " GEDPhotonProducer calcualtion of HoE with towers behind the BCs " << hcalDepth1OverEcalBc << " " << hcalDepth2OverEcalBc << std::endl; - float maxXtal = ( hits != nullptr ? EcalClusterTools::eMax( *(scRef->seed()), &(*hits) ) : 0.f ); + float maxXtal = (hits != nullptr ? EcalClusterTools::eMax(*(scRef->seed()), &(*hits)) : 0.f); //AA //Change these to consider severity level of hits - float e1x5 = ( hits != nullptr ? EcalClusterTools::e1x5( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float e2x5 = ( hits != nullptr ? EcalClusterTools::e2x5Max( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float e3x3 = ( hits != nullptr ? EcalClusterTools::e3x3( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float e5x5 = ( hits != nullptr ? EcalClusterTools::e5x5( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - std::vector cov = ( hits != nullptr ? EcalClusterTools::covariances( *(scRef->seed()), &(*hits), &(*topology), geometry) : std::vector( {0.f,0.f,0.f} ) ); - std::vector locCov = ( hits != nullptr ? EcalClusterTools::localCovariances( *(scRef->seed()), &(*hits), &(*topology)) : std::vector( {0.f,0.f,0.f} ) ); - + float e1x5 = (hits != nullptr ? EcalClusterTools::e1x5(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float e2x5 = (hits != nullptr ? EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float e3x3 = (hits != nullptr ? EcalClusterTools::e3x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float e5x5 = (hits != nullptr ? EcalClusterTools::e5x5(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + std::vector cov = + (hits != nullptr ? EcalClusterTools::covariances(*(scRef->seed()), &(*hits), &(*topology), geometry) + : std::vector({0.f, 0.f, 0.f})); + std::vector locCov = + (hits != nullptr ? EcalClusterTools::localCovariances(*(scRef->seed()), &(*hits), &(*topology)) + : std::vector({0.f, 0.f, 0.f})); + float sigmaEtaEta = sqrt(cov[0]); float sigmaIetaIeta = sqrt(locCov[0]); - - float full5x5_maxXtal = ( hits != nullptr ? noZS::EcalClusterTools::eMax( *(scRef->seed()), &(*hits) ) : 0.f ); + + float full5x5_maxXtal = (hits != nullptr ? noZS::EcalClusterTools::eMax(*(scRef->seed()), &(*hits)) : 0.f); //AA //Change these to consider severity level of hits - float full5x5_e1x5 = ( hits != nullptr ? noZS::EcalClusterTools::e1x5( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float full5x5_e2x5 = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Max( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float full5x5_e3x3 = ( hits != nullptr ? noZS::EcalClusterTools::e3x3( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - float full5x5_e5x5 = ( hits != nullptr ? noZS::EcalClusterTools::e5x5( *(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - std::vector full5x5_cov = ( hits != nullptr ? noZS::EcalClusterTools::covariances( *(scRef->seed()), &(*hits), &(*topology), geometry) : std::vector( {0.f,0.f,0.f} ) ); - std::vector full5x5_locCov = ( hits != nullptr ? noZS::EcalClusterTools::localCovariances( *(scRef->seed()), &(*hits), &(*topology)) : std::vector( {0.f,0.f,0.f} ) ); - + float full5x5_e1x5 = + (hits != nullptr ? noZS::EcalClusterTools::e1x5(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float full5x5_e2x5 = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float full5x5_e3x3 = + (hits != nullptr ? noZS::EcalClusterTools::e3x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + float full5x5_e5x5 = + (hits != nullptr ? noZS::EcalClusterTools::e5x5(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + std::vector full5x5_cov = + (hits != nullptr ? noZS::EcalClusterTools::covariances(*(scRef->seed()), &(*hits), &(*topology), geometry) + : std::vector({0.f, 0.f, 0.f})); + std::vector full5x5_locCov = + (hits != nullptr ? noZS::EcalClusterTools::localCovariances(*(scRef->seed()), &(*hits), &(*topology)) + : std::vector({0.f, 0.f, 0.f})); + float full5x5_sigmaEtaEta = sqrt(full5x5_cov[0]); - float full5x5_sigmaIetaIeta = sqrt(full5x5_locCov[0]); - + float full5x5_sigmaIetaIeta = sqrt(full5x5_locCov[0]); + // compute position of ECAL shower math::XYZPoint caloPosition = scRef->position(); - //// energy determination -- Default to create the candidate. Afterwards corrections are applied - double photonEnergy=1.; - math::XYZPoint vtx(0.,0.,0.); - if (!vertexCollection.empty()) vtx = vertexCollection.begin()->position(); + double photonEnergy = 1.; + math::XYZPoint vtx(0., 0., 0.); + if (!vertexCollection.empty()) + vtx = vertexCollection.begin()->position(); // compute momentum vector of photon from primary vertex and cluster position math::XYZVector direction = caloPosition - vtx; //math::XYZVector momentum = direction.unit() * photonEnergy ; - math::XYZVector momentum = direction.unit() ; + math::XYZVector momentum = direction.unit(); // Create dummy candidate with unit momentum and zero energy to allow setting of all variables. The energy is set for last. - math::XYZTLorentzVectorD p4(momentum.x(), momentum.y(), momentum.z(), photonEnergy ); + math::XYZTLorentzVectorD p4(momentum.x(), momentum.y(), momentum.z(), photonEnergy); reco::Photon newCandidate(p4, caloPosition, coreRef, vtx); //std::cout << " standard p4 before " << newCandidate.p4() << " energy " << newCandidate.energy() << std::endl; @@ -633,151 +593,159 @@ void GEDPhotonProducer::fillPhotonCollection(edm::Event& evt, // Calculate fiducial flags and isolation variable. Blocked are filled from the isolationCalculator reco::Photon::FiducialFlags fiducialFlags; reco::Photon::IsolationVariables isolVarR03, isolVarR04; - if( !EcalTools::isHGCalDet(thedet) ) { - thePhotonIsolationCalculator_->calculate( &newCandidate,evt,es,fiducialFlags,isolVarR04, isolVarR03); + if (!EcalTools::isHGCalDet(thedet)) { + thePhotonIsolationCalculator_->calculate(&newCandidate, evt, es, fiducialFlags, isolVarR04, isolVarR03); } - newCandidate.setFiducialVolumeFlags( fiducialFlags ); - newCandidate.setIsolationVariables(isolVarR04, isolVarR03 ); + newCandidate.setFiducialVolumeFlags(fiducialFlags); + newCandidate.setIsolationVariables(isolVarR04, isolVarR03); - /// fill shower shape block - reco::Photon::ShowerShape showerShape; - showerShape.e1x5= e1x5; - showerShape.e2x5= e2x5; - showerShape.e3x3= e3x3; - showerShape.e5x5= e5x5; - showerShape.maxEnergyXtal = maxXtal; - showerShape.sigmaEtaEta = sigmaEtaEta; - showerShape.sigmaIetaIeta = sigmaIetaIeta; + reco::Photon::ShowerShape showerShape; + showerShape.e1x5 = e1x5; + showerShape.e2x5 = e2x5; + showerShape.e3x3 = e3x3; + showerShape.e5x5 = e5x5; + showerShape.maxEnergyXtal = maxXtal; + showerShape.sigmaEtaEta = sigmaEtaEta; + showerShape.sigmaIetaIeta = sigmaIetaIeta; showerShape.hcalDepth1OverEcal = HoE1; showerShape.hcalDepth2OverEcal = HoE2; showerShape.hcalDepth1OverEcalBc = hcalDepth1OverEcalBc; showerShape.hcalDepth2OverEcalBc = hcalDepth2OverEcalBc; - showerShape.hcalTowersBehindClusters = TowersBehindClus; + showerShape.hcalTowersBehindClusters = TowersBehindClus; showerShape.invalidHcal = invalidHcal; /// fill extra shower shapes const float spp = (!edm::isFinite(locCov[2]) ? 0. : sqrt(locCov[2])); const float sep = locCov[1]; showerShape.sigmaIetaIphi = sep; showerShape.sigmaIphiIphi = spp; - showerShape.e2nd = ( hits != nullptr ? EcalClusterTools::e2nd(*(scRef->seed()),&(*hits)) : 0.f ); - showerShape.eTop = ( hits != nullptr ? EcalClusterTools::eTop(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.eLeft = ( hits != nullptr ? EcalClusterTools::eLeft(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.eRight = ( hits != nullptr ? EcalClusterTools::eRight(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.eBottom = ( hits != nullptr ? EcalClusterTools::eBottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e1x3 = ( hits != nullptr ? EcalClusterTools::e1x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x2 = ( hits != nullptr ? EcalClusterTools::e2x2(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x5Max = ( hits != nullptr ? EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x5Left = ( hits != nullptr ? EcalClusterTools::e2x5Left(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x5Right = ( hits != nullptr ? EcalClusterTools::e2x5Right(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x5Top = ( hits != nullptr ? EcalClusterTools::e2x5Top(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - showerShape.e2x5Bottom = ( hits != nullptr ? EcalClusterTools::e2x5Bottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - if(hits){ - Cluster2ndMoments clus2ndMoments = EcalClusterTools::cluster2ndMoments(*(scRef->seed()),*hits); + showerShape.e2nd = (hits != nullptr ? EcalClusterTools::e2nd(*(scRef->seed()), &(*hits)) : 0.f); + showerShape.eTop = (hits != nullptr ? EcalClusterTools::eTop(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.eLeft = (hits != nullptr ? EcalClusterTools::eLeft(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.eRight = (hits != nullptr ? EcalClusterTools::eRight(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.eBottom = (hits != nullptr ? EcalClusterTools::eBottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e1x3 = (hits != nullptr ? EcalClusterTools::e1x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x2 = (hits != nullptr ? EcalClusterTools::e2x2(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x5Max = (hits != nullptr ? EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x5Left = + (hits != nullptr ? EcalClusterTools::e2x5Left(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x5Right = + (hits != nullptr ? EcalClusterTools::e2x5Right(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x5Top = (hits != nullptr ? EcalClusterTools::e2x5Top(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + showerShape.e2x5Bottom = + (hits != nullptr ? EcalClusterTools::e2x5Bottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + if (hits) { + Cluster2ndMoments clus2ndMoments = EcalClusterTools::cluster2ndMoments(*(scRef->seed()), *hits); showerShape.smMajor = clus2ndMoments.sMaj; showerShape.smMinor = clus2ndMoments.sMin; showerShape.smAlpha = clus2ndMoments.alpha; - }else{ + } else { showerShape.smMajor = 0.f; showerShape.smMinor = 0.f; showerShape.smAlpha = 0.f; } - // fill preshower shapes EcalClusterLazyTools toolsforES(evt, es, barrelEcalHits_, endcapEcalHits_, preshowerHits_); - const float sigmaRR = toolsforES.eseffsirir( *scRef ); + const float sigmaRR = toolsforES.eseffsirir(*scRef); showerShape.effSigmaRR = sigmaRR; - newCandidate.setShowerShapeVariables ( showerShape ); + newCandidate.setShowerShapeVariables(showerShape); reco::Photon::SaturationInfo saturationInfo; - const reco::CaloCluster& seedCluster = *(scRef->seed()) ; + const reco::CaloCluster& seedCluster = *(scRef->seed()); DetId seedXtalId = seedCluster.seed(); int nSaturatedXtals = 0; bool isSeedSaturated = false; if (hits != nullptr) { const auto hitsAndFractions = scRef->hitsAndFractions(); - for (auto&& hitFractionPair : hitsAndFractions) { - auto&& ecalRecHit = hits->find(hitFractionPair.first); - if (ecalRecHit == hits->end()) continue; - if (ecalRecHit->checkFlag(EcalRecHit::Flags::kSaturated)) { - nSaturatedXtals++; - if (seedXtalId == ecalRecHit->detid()) - isSeedSaturated = true; - } + for (auto&& hitFractionPair : hitsAndFractions) { + auto&& ecalRecHit = hits->find(hitFractionPair.first); + if (ecalRecHit == hits->end()) + continue; + if (ecalRecHit->checkFlag(EcalRecHit::Flags::kSaturated)) { + nSaturatedXtals++; + if (seedXtalId == ecalRecHit->detid()) + isSeedSaturated = true; + } } } saturationInfo.nSaturatedXtals = nSaturatedXtals; saturationInfo.isSeedSaturated = isSeedSaturated; newCandidate.setSaturationInfo(saturationInfo); - + /// fill full5x5 shower shape block - reco::Photon::ShowerShape full5x5_showerShape; - full5x5_showerShape.e1x5= full5x5_e1x5; - full5x5_showerShape.e2x5= full5x5_e2x5; - full5x5_showerShape.e3x3= full5x5_e3x3; - full5x5_showerShape.e5x5= full5x5_e5x5; - full5x5_showerShape.maxEnergyXtal = full5x5_maxXtal; - full5x5_showerShape.sigmaEtaEta = full5x5_sigmaEtaEta; - full5x5_showerShape.sigmaIetaIeta = full5x5_sigmaIetaIeta; + reco::Photon::ShowerShape full5x5_showerShape; + full5x5_showerShape.e1x5 = full5x5_e1x5; + full5x5_showerShape.e2x5 = full5x5_e2x5; + full5x5_showerShape.e3x3 = full5x5_e3x3; + full5x5_showerShape.e5x5 = full5x5_e5x5; + full5x5_showerShape.maxEnergyXtal = full5x5_maxXtal; + full5x5_showerShape.sigmaEtaEta = full5x5_sigmaEtaEta; + full5x5_showerShape.sigmaIetaIeta = full5x5_sigmaIetaIeta; /// fill extra full5x5 shower shapes const float full5x5_spp = (!edm::isFinite(full5x5_locCov[2]) ? 0. : sqrt(full5x5_locCov[2])); const float full5x5_sep = full5x5_locCov[1]; full5x5_showerShape.sigmaIetaIphi = full5x5_sep; full5x5_showerShape.sigmaIphiIphi = full5x5_spp; - full5x5_showerShape.e2nd = ( hits != nullptr ? noZS::EcalClusterTools::e2nd(*(scRef->seed()),&(*hits)) : 0.f ); - full5x5_showerShape.eTop = ( hits != nullptr ? noZS::EcalClusterTools::eTop(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.eLeft = ( hits != nullptr ? noZS::EcalClusterTools::eLeft(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.eRight = ( hits != nullptr ? noZS::EcalClusterTools::eRight(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.eBottom = ( hits != nullptr ? noZS::EcalClusterTools::eBottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e1x3 = ( hits != nullptr ? noZS::EcalClusterTools::e1x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x2 = ( hits != nullptr ? noZS::EcalClusterTools::e2x2(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x5Max = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x5Left = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Left(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x5Right = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Right(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x5Top = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Top(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - full5x5_showerShape.e2x5Bottom = ( hits != nullptr ? noZS::EcalClusterTools::e2x5Bottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f ); - if(hits){ - Cluster2ndMoments clus2ndMoments = noZS::EcalClusterTools::cluster2ndMoments(*(scRef->seed()),*hits); + full5x5_showerShape.e2nd = (hits != nullptr ? noZS::EcalClusterTools::e2nd(*(scRef->seed()), &(*hits)) : 0.f); + full5x5_showerShape.eTop = + (hits != nullptr ? noZS::EcalClusterTools::eTop(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.eLeft = + (hits != nullptr ? noZS::EcalClusterTools::eLeft(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.eRight = + (hits != nullptr ? noZS::EcalClusterTools::eRight(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.eBottom = + (hits != nullptr ? noZS::EcalClusterTools::eBottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e1x3 = + (hits != nullptr ? noZS::EcalClusterTools::e1x3(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x2 = + (hits != nullptr ? noZS::EcalClusterTools::e2x2(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x5Max = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x5Left = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Left(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x5Right = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Right(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x5Top = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Top(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + full5x5_showerShape.e2x5Bottom = + (hits != nullptr ? noZS::EcalClusterTools::e2x5Bottom(*(scRef->seed()), &(*hits), &(*topology)) : 0.f); + if (hits) { + Cluster2ndMoments clus2ndMoments = noZS::EcalClusterTools::cluster2ndMoments(*(scRef->seed()), *hits); full5x5_showerShape.smMajor = clus2ndMoments.sMaj; full5x5_showerShape.smMinor = clus2ndMoments.sMin; full5x5_showerShape.smAlpha = clus2ndMoments.alpha; - }else{ + } else { full5x5_showerShape.smMajor = 0.f; full5x5_showerShape.smMinor = 0.f; full5x5_showerShape.smAlpha = 0.f; } - // fill preshower shapes + // fill preshower shapes full5x5_showerShape.effSigmaRR = sigmaRR; - newCandidate.full5x5_setShowerShapeVariables ( full5x5_showerShape ); - - + newCandidate.full5x5_setShowerShapeVariables(full5x5_showerShape); - /// get ecal photon specific corrected energy + /// get ecal photon specific corrected energy /// plus values from regressions and store them in the Photon - // Photon candidate takes by default (set in photons_cfi.py) - // a 4-momentum derived from the ecal photon-specific corrections. - if( !EcalTools::isHGCalDet(thedet) ) { + // Photon candidate takes by default (set in photons_cfi.py) + // a 4-momentum derived from the ecal photon-specific corrections. + if (!EcalTools::isHGCalDet(thedet)) { thePhotonEnergyCorrector_->calculate(evt, newCandidate, subdet, vertexCollection, es); - if ( candidateP4type_ == "fromEcalEnergy") { - newCandidate.setP4( newCandidate.p4(reco::Photon::ecal_photons) ); - newCandidate.setCandidateP4type(reco::Photon::ecal_photons); - } else if ( candidateP4type_ == "fromRegression1") { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression1) ); - newCandidate.setCandidateP4type(reco::Photon::regression1); - } else if ( candidateP4type_ == "fromRegression2") { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression2) ); - newCandidate.setCandidateP4type(reco::Photon::regression2); - } else if ( candidateP4type_ == "fromRefinedSCRegression" ) { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression2) ); - newCandidate.setCandidateP4type(reco::Photon::regression2); + if (candidateP4type_ == "fromEcalEnergy") { + newCandidate.setP4(newCandidate.p4(reco::Photon::ecal_photons)); + newCandidate.setCandidateP4type(reco::Photon::ecal_photons); + } else if (candidateP4type_ == "fromRegression1") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression1)); + newCandidate.setCandidateP4type(reco::Photon::regression1); + } else if (candidateP4type_ == "fromRegression2") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression2)); + newCandidate.setCandidateP4type(reco::Photon::regression2); + } else if (candidateP4type_ == "fromRefinedSCRegression") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression2)); + newCandidate.setCandidateP4type(reco::Photon::regression2); } } else { math::XYZVector gamma_momentum = direction.unit() * scRef->energy(); - math::XYZTLorentzVectorD p4(gamma_momentum.x(), - gamma_momentum.y(), - gamma_momentum.z(), - scRef->energy()); + math::XYZTLorentzVectorD p4(gamma_momentum.x(), gamma_momentum.y(), gamma_momentum.z(), scRef->energy()); newCandidate.setP4(p4); newCandidate.setCandidateP4type(reco::Photon::ecal_photons); // Make it an EE photon @@ -788,135 +756,128 @@ void GEDPhotonProducer::fillPhotonCollection(edm::Event& evt, // std::cout << " final p4 " << newCandidate.p4() << " energy " << newCandidate.energy() << std::endl; - // std::cout << " GEDPhotonProducer from candidate HoE with towers in a cone " << newCandidate.hadronicOverEm() << " " << newCandidate.hadronicDepth1OverEm() << " " << newCandidate.hadronicDepth2OverEm() << std::endl; // std::cout << " GEDPhotonProducer from candidate of HoE with towers behind the BCs " << newCandidate.hadTowOverEm() << " " << newCandidate.hadTowDepth1OverEm() << " " << newCandidate.hadTowDepth2OverEm() << std::endl; - - // fill MIP Vairables for Halo: Block for MIP are filled from PhotonMIPHaloTagger - reco::Photon::MIPVariables mipVar ; - if(subdet==EcalBarrel && runMIPTagger_ ) - { - - thePhotonMIPHaloTagger_-> MIPcalculate( &newCandidate,evt,es,mipVar); - newCandidate.setMIPVariables(mipVar); + // fill MIP Vairables for Halo: Block for MIP are filled from PhotonMIPHaloTagger + reco::Photon::MIPVariables mipVar; + if (subdet == EcalBarrel && runMIPTagger_) { + thePhotonMIPHaloTagger_->MIPcalculate(&newCandidate, evt, es, mipVar); + newCandidate.setMIPVariables(mipVar); } - - /// Pre-selection loose isolation cuts - bool isLooseEM=true; - if ( newCandidate.pt() < highEt_) { - if ( newCandidate.hadronicOverEm() >= preselCutValues[1] ) isLooseEM=false; - if ( newCandidate.ecalRecHitSumEtConeDR04() > preselCutValues[2]+ preselCutValues[3]*newCandidate.pt() ) isLooseEM=false; - if ( newCandidate.hcalTowerSumEtConeDR04() > preselCutValues[4]+ preselCutValues[5]*newCandidate.pt() ) isLooseEM=false; - if ( newCandidate.nTrkSolidConeDR04() > int(preselCutValues[6]) ) isLooseEM=false; - if ( newCandidate.nTrkHollowConeDR04() > int(preselCutValues[7]) ) isLooseEM=false; - if ( newCandidate.trkSumPtSolidConeDR04() > preselCutValues[8] ) isLooseEM=false; - if ( newCandidate.trkSumPtHollowConeDR04() > preselCutValues[9] ) isLooseEM=false; - if ( newCandidate.sigmaIetaIeta() > preselCutValues[10] ) isLooseEM=false; - } - - - - if ( isLooseEM) + bool isLooseEM = true; + if (newCandidate.pt() < highEt_) { + if (newCandidate.hadronicOverEm() >= preselCutValues[1]) + isLooseEM = false; + if (newCandidate.ecalRecHitSumEtConeDR04() > preselCutValues[2] + preselCutValues[3] * newCandidate.pt()) + isLooseEM = false; + if (newCandidate.hcalTowerSumEtConeDR04() > preselCutValues[4] + preselCutValues[5] * newCandidate.pt()) + isLooseEM = false; + if (newCandidate.nTrkSolidConeDR04() > int(preselCutValues[6])) + isLooseEM = false; + if (newCandidate.nTrkHollowConeDR04() > int(preselCutValues[7])) + isLooseEM = false; + if (newCandidate.trkSumPtSolidConeDR04() > preselCutValues[8]) + isLooseEM = false; + if (newCandidate.trkSumPtHollowConeDR04() > preselCutValues[9]) + isLooseEM = false; + if (newCandidate.sigmaIetaIeta() > preselCutValues[10]) + isLooseEM = false; + } + + if (isLooseEM) outputPhotonCollection.push_back(newCandidate); - - } } - - - void GEDPhotonProducer::fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonHandle, - const edm::Handle pfCandidateHandle, - const edm::Handle pfEGCandidateHandle, - edm::ValueMap pfEGCandToPhotonMap, - edm::Handle< reco::VertexCollection > & vertexHandle, - reco::PhotonCollection & outputPhotonCollection, int& iSC, - const edm::Handle>& chargedHadrons, - const edm::Handle>& neutralHadrons, - const edm::Handle>& photons, - const edm::Handle>& chargedHadronsWorstVtx, - const edm::Handle>& chargedHadronsWorstVtxGeomVeto, - const edm::Handle>& chargedHadronsPFPV, - const edm::Handle>& pfEcalClusters, - const edm::Handle>& pfHcalClusters){ - - - + edm::EventSetup const& es, + const edm::Handle& photonHandle, + const edm::Handle pfCandidateHandle, + const edm::Handle pfEGCandidateHandle, + edm::ValueMap pfEGCandToPhotonMap, + edm::Handle& vertexHandle, + reco::PhotonCollection& outputPhotonCollection, + int& iSC, + const edm::Handle>& chargedHadrons, + const edm::Handle>& neutralHadrons, + const edm::Handle>& photons, + const edm::Handle>& chargedHadronsWorstVtx, + const edm::Handle>& chargedHadronsWorstVtxGeomVeto, + const edm::Handle>& chargedHadronsPFPV, + const edm::Handle>& pfEcalClusters, + const edm::Handle>& pfHcalClusters) { std::vector preselCutValues; - - for(unsigned int lSC=0; lSC < photonHandle->size(); lSC++) { + for (unsigned int lSC = 0; lSC < photonHandle->size(); lSC++) { reco::PhotonRef phoRef(reco::PhotonRef(photonHandle, lSC)); reco::SuperClusterRef parentSCRef = phoRef->parentSuperCluster(); - reco::SuperClusterRef scRef=phoRef->superCluster(); + reco::SuperClusterRef scRef = phoRef->superCluster(); DetId::Detector thedet = scRef->seed()->hitsAndFractions()[0].first.det(); int subdet = scRef->seed()->hitsAndFractions()[0].first.subdetId(); - if (subdet==EcalBarrel) { + if (subdet == EcalBarrel) { preselCutValues = preselCutValuesBarrel_; - } else if (subdet==EcalEndcap) { + } else if (subdet == EcalEndcap) { preselCutValues = preselCutValuesEndcap_; } else if (EcalTools::isHGCalDet(thedet)) { preselCutValues = preselCutValuesEndcap_; } else { - edm::LogWarning("")<<"GEDPhotonProducer: do not know if it is a barrel or endcap SuperCluster" << thedet << ' ' << subdet; + edm::LogWarning("") << "GEDPhotonProducer: do not know if it is a barrel or endcap SuperCluster" << thedet << ' ' + << subdet; } - - // SC energy preselection if (parentSCRef.isNonnull() && - ptFast(parentSCRef->energy(),parentSCRef->position(),math::XYZPoint(0,0,0)) <= preselCutValues[0] ) continue; + ptFast(parentSCRef->energy(), parentSCRef->position(), math::XYZPoint(0, 0, 0)) <= preselCutValues[0]) + continue; reco::Photon newCandidate(*phoRef); - iSC++; - + iSC++; - // Calculate the PF isolation and ID - for the time being there is no calculation. Only the setting + // Calculate the PF isolation and ID - for the time being there is no calculation. Only the setting reco::Photon::PflowIsolationVariables pfIso; reco::Photon::PflowIDVariables pfID; - + //get the pointer for the photon object edm::Ptr photonPtr(photonHandle, lSC); - if(!recoStep_.isOOT()){ //out of time photons do not have PF info so skip in this case - pfIso.chargedHadronIso = (*chargedHadrons)[photonPtr] ; + if (!recoStep_.isOOT()) { //out of time photons do not have PF info so skip in this case + pfIso.chargedHadronIso = (*chargedHadrons)[photonPtr]; pfIso.neutralHadronIso = (*neutralHadrons)[photonPtr]; - pfIso.photonIso = (*photons)[photonPtr]; + pfIso.photonIso = (*photons)[photonPtr]; pfIso.chargedHadronWorstVtxIso = (*chargedHadronsWorstVtx)[photonPtr]; pfIso.chargedHadronWorstVtxGeomVetoIso = (*chargedHadronsWorstVtxGeomVeto)[photonPtr]; pfIso.chargedHadronPFPVIso = (*chargedHadronsPFPV)[photonPtr]; } - + //OOT photons in legacy 80X reminiAOD workflow dont have pf cluster isolation embeded into them at this stage - if(!phoPFECALClusIsolationToken_.isUninitialized()){ + if (!phoPFECALClusIsolationToken_.isUninitialized()) { pfIso.sumEcalClusterEt = (*pfEcalClusters)[photonPtr]; - }else pfIso.sumEcalClusterEt = 0.; - - if(!phoPFHCALClusIsolationToken_.isUninitialized()){ + } else + pfIso.sumEcalClusterEt = 0.; + + if (!phoPFHCALClusIsolationToken_.isUninitialized()) { pfIso.sumHcalClusterEt = (*pfHcalClusters)[photonPtr]; - }else pfIso.sumHcalClusterEt = 0.; + } else + pfIso.sumHcalClusterEt = 0.; newCandidate.setPflowIsolationVariables(pfIso); newCandidate.setPflowIDVariables(pfID); // do the regression thePhotonEnergyCorrector_->calculate(evt, newCandidate, subdet, *vertexHandle, es); - if ( candidateP4type_ == "fromEcalEnergy") { - newCandidate.setP4( newCandidate.p4(reco::Photon::ecal_photons) ); + if (candidateP4type_ == "fromEcalEnergy") { + newCandidate.setP4(newCandidate.p4(reco::Photon::ecal_photons)); newCandidate.setCandidateP4type(reco::Photon::ecal_photons); - } else if ( candidateP4type_ == "fromRegression1") { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression1) ); + } else if (candidateP4type_ == "fromRegression1") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression1)); newCandidate.setCandidateP4type(reco::Photon::regression1); - } else if ( candidateP4type_ == "fromRegression2") { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression2) ); + } else if (candidateP4type_ == "fromRegression2") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression2)); newCandidate.setCandidateP4type(reco::Photon::regression2); - } else if ( candidateP4type_ == "fromRefinedSCRegression" ) { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression2) ); + } else if (candidateP4type_ == "fromRefinedSCRegression") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression2)); newCandidate.setCandidateP4type(reco::Photon::regression2); } @@ -927,8 +888,6 @@ void GEDPhotonProducer::fillPhotonCollection(edm::Event& evt, //std::cout << " type " <(conf_.getParameter("scHybridBarrelProducer")); - scIslandEndcapProducer_ = - consumes(conf_.getParameter("scIslandEndcapProducer")); - conversionProducer_ = - consumes(conf_.getParameter("conversionProducer")); + scHybridBarrelProducer_ = + consumes(conf_.getParameter("scHybridBarrelProducer")); + scIslandEndcapProducer_ = + consumes(conf_.getParameter("scIslandEndcapProducer")); + conversionProducer_ = consumes(conf_.getParameter("conversionProducer")); PhotonCoreCollection_ = conf_.getParameter("photonCoreCollection"); - pixelSeedProducer_ = - consumes(conf_.getParameter("pixelSeedProducer")); - minSCEt_ = conf_.getParameter("minSCEt"); + pixelSeedProducer_ = consumes(conf_.getParameter("pixelSeedProducer")); + minSCEt_ = conf_.getParameter("minSCEt"); risolveAmbiguity_ = conf_.getParameter("risolveConversionAmbiguity"); // Register the product - produces< reco::PhotonCoreCollection >(PhotonCoreCollection_); - + produces(PhotonCoreCollection_); } PhotonCoreProducer::~PhotonCoreProducer() {} - - - -void PhotonCoreProducer::produce(edm::Event &theEvent, const edm::EventSetup& theEventSetup) { - - +void PhotonCoreProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { using namespace edm; // nEvt_++; @@ -55,194 +44,163 @@ void PhotonCoreProducer::produce(edm::Event &theEvent, const edm::EventSetup& th auto outputPhotonCoreCollection_p = std::make_unique(); // Get the Barrel Super Cluster collection - bool validBarrelSCHandle=true; + bool validBarrelSCHandle = true; Handle scBarrelHandle; - theEvent.getByToken(scHybridBarrelProducer_,scBarrelHandle); + theEvent.getByToken(scHybridBarrelProducer_, scBarrelHandle); if (!scBarrelHandle.isValid()) { - edm::LogError("PhotonCoreProducer") - << "Error! Can't get the scHybridBarrelProducer"; - validBarrelSCHandle=false; + edm::LogError("PhotonCoreProducer") << "Error! Can't get the scHybridBarrelProducer"; + validBarrelSCHandle = false; } - - // Get the Endcap Super Cluster collection - bool validEndcapSCHandle=true; + // Get the Endcap Super Cluster collection + bool validEndcapSCHandle = true; Handle scEndcapHandle; - theEvent.getByToken(scIslandEndcapProducer_,scEndcapHandle); + theEvent.getByToken(scIslandEndcapProducer_, scEndcapHandle); if (!scEndcapHandle.isValid()) { - edm::LogError("PhotonCoreProducer") - << "Error! Can't get the scIslandEndcapProducer"; - validEndcapSCHandle=false; + edm::LogError("PhotonCoreProducer") << "Error! Can't get the scIslandEndcapProducer"; + validEndcapSCHandle = false; } - ///// Get the conversion collection - validConversions_=true; - edm::Handle conversionHandle; + validConversions_ = true; + edm::Handle conversionHandle; theEvent.getByToken(conversionProducer_, conversionHandle); if (!conversionHandle.isValid()) { //edm::LogError("PhotonCoreProducer") << "Error! Can't get the product "<< conversionProducer_.label() << "\n" ; - validConversions_=false; + validConversions_ = false; } - - - // Get ElectronPixelSeeds - validPixelSeeds_=true; + validPixelSeeds_ = true; Handle pixelSeedHandle; reco::ElectronSeedCollection pixelSeeds; theEvent.getByToken(pixelSeedProducer_, pixelSeedHandle); if (!pixelSeedHandle.isValid()) { - validPixelSeeds_=false; + validPixelSeeds_ = false; } // if ( validPixelSeeds_) pixelSeeds = *(pixelSeedHandle.product()); - - - int iSC=0; // index in photon collection + int iSC = 0; // index in photon collection // Loop over barrel and endcap SC collections and fill the photon collection - if ( validBarrelSCHandle) fillPhotonCollection(theEvent, - theEventSetup, - scBarrelHandle, - conversionHandle, - pixelSeedHandle, - outputPhotonCoreCollection, - iSC); - if ( validEndcapSCHandle) fillPhotonCollection(theEvent, - theEventSetup, - scEndcapHandle, - conversionHandle, - pixelSeedHandle, - outputPhotonCoreCollection, - iSC); + if (validBarrelSCHandle) + fillPhotonCollection( + theEvent, theEventSetup, scBarrelHandle, conversionHandle, pixelSeedHandle, outputPhotonCoreCollection, iSC); + if (validEndcapSCHandle) + fillPhotonCollection( + theEvent, theEventSetup, scEndcapHandle, conversionHandle, pixelSeedHandle, outputPhotonCoreCollection, iSC); // put the product in the event edm::LogInfo("PhotonCoreProducer") << " Put in the event " << iSC << " Photon Candidates \n"; - outputPhotonCoreCollection_p->assign(outputPhotonCoreCollection.begin(),outputPhotonCoreCollection.end()); + outputPhotonCoreCollection_p->assign(outputPhotonCoreCollection.begin(), outputPhotonCoreCollection.end()); theEvent.put(std::move(outputPhotonCoreCollection_p), PhotonCoreCollection_); - } void PhotonCoreProducer::fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & scHandle, - const edm::Handle & conversionHandle, - const edm::Handle & pixelSeedHandle, - reco::PhotonCoreCollection & outputPhotonCoreCollection, int& iSC) { - - for(unsigned int lSC=0; lSC < scHandle->size(); lSC++) { - + edm::EventSetup const& es, + const edm::Handle& scHandle, + const edm::Handle& conversionHandle, + const edm::Handle& pixelSeedHandle, + reco::PhotonCoreCollection& outputPhotonCoreCollection, + int& iSC) { + for (unsigned int lSC = 0; lSC < scHandle->size(); lSC++) { // get SuperClusterRef reco::SuperClusterRef scRef(reco::SuperClusterRef(scHandle, lSC)); iSC++; //const reco::SuperCluster* pClus=&(*scRef); - + // SC energy preselection - if (scRef->energy()/cosh(scRef->eta()) <= minSCEt_) continue; - + if (scRef->energy() / cosh(scRef->eta()) <= minSCEt_) + continue; + reco::PhotonCore newCandidate(scRef); newCandidate.setParentSuperCluster(scRef); - if ( validConversions_) { + if (validConversions_) { + if (risolveAmbiguity_) { + reco::ConversionRef bestRef = solveAmbiguity(conversionHandle, scRef); + if (bestRef.isNonnull()) + newCandidate.addConversion(bestRef); - if ( risolveAmbiguity_ ) { - reco::ConversionRef bestRef=solveAmbiguity( conversionHandle , scRef); - if (bestRef.isNonnull() ) newCandidate.addConversion(bestRef); - } else { - - - for( unsigned int icp = 0; icp < conversionHandle->size(); icp++) { - reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle,icp)); - if ( cpRef->caloCluster().empty()) continue; - if (!( scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key() )) continue; - if ( !cpRef->isConverted() ) continue; - newCandidate.addConversion(cpRef); - - } - - } // solve or not the ambiguity of many conversion candidates - - } - - if ( validPixelSeeds_) { - for( unsigned int icp = 0; icp < pixelSeedHandle->size(); icp++) { - reco::ElectronSeedRef cpRef(reco::ElectronSeedRef(pixelSeedHandle,icp)); - if ( ! cpRef->isEcalDriven() ) continue; - if (!( scRef.id() == cpRef->caloCluster().id() && scRef.key() == cpRef->caloCluster().key() )) continue; - newCandidate.addElectronPixelSeed(cpRef); - } + for (unsigned int icp = 0; icp < conversionHandle->size(); icp++) { + reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle, icp)); + if (cpRef->caloCluster().empty()) + continue; + if (!(scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key())) + continue; + if (!cpRef->isConverted()) + continue; + newCandidate.addConversion(cpRef); + } + + } // solve or not the ambiguity of many conversion candidates } - - outputPhotonCoreCollection.push_back(newCandidate); - - } - - -} - - - - -reco::ConversionRef PhotonCoreProducer::solveAmbiguity(const edm::Handle & conversionHandle, reco::SuperClusterRef& scRef) { + if (validPixelSeeds_) { + for (unsigned int icp = 0; icp < pixelSeedHandle->size(); icp++) { + reco::ElectronSeedRef cpRef(reco::ElectronSeedRef(pixelSeedHandle, icp)); + if (!cpRef->isEcalDriven()) + continue; + if (!(scRef.id() == cpRef->caloCluster().id() && scRef.key() == cpRef->caloCluster().key())) + continue; + newCandidate.addElectronPixelSeed(cpRef); + } + } - std::multimap convMap; - for ( unsigned int icp=0; icp< conversionHandle->size(); icp++) { + outputPhotonCoreCollection.push_back(newCandidate); + } +} - reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle,icp)); +reco::ConversionRef PhotonCoreProducer::solveAmbiguity(const edm::Handle& conversionHandle, + reco::SuperClusterRef& scRef) { + std::multimap convMap; + for (unsigned int icp = 0; icp < conversionHandle->size(); icp++) { + reco::ConversionRef cpRef(reco::ConversionRef(conversionHandle, icp)); - if (!( scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key() )) continue; - if ( !cpRef->isConverted() ) continue; + if (!(scRef.id() == cpRef->caloCluster()[0].id() && scRef.key() == cpRef->caloCluster()[0].key())) + continue; + if (!cpRef->isConverted()) + continue; double like = cpRef->MVAout(); - convMap.insert ( std::make_pair(cpRef,like) ); + convMap.insert(std::make_pair(cpRef, like)); + } - } - - - - std::multimap::iterator iMap; + std::multimap::iterator iMap; double max_lh = -1.; reco::ConversionRef bestRef; // std::cout << " Pick up the best conv " << std::endl; - for (iMap=convMap.begin(); iMap!=convMap.end(); iMap++) { + for (iMap = convMap.begin(); iMap != convMap.end(); iMap++) { double like = iMap->second; - if (like > max_lh) { + if (like > max_lh) { max_lh = like; - bestRef=iMap->first; + bestRef = iMap->first; } - } - - //std::cout << " Best conv like " << max_lh << std::endl; - - float ep=0; - if ( max_lh <0 ) { + } + + //std::cout << " Best conv like " << max_lh << std::endl; + + float ep = 0; + if (max_lh < 0) { // std::cout << " Candidates with only one track " << std::endl; /// only one track reconstructed. Pick the one with best E/P - float epMin=999; - - for (iMap=convMap.begin(); iMap!=convMap.end(); iMap++) { - reco::ConversionRef convRef=iMap->first; - // std::vector tracks = convRef->tracks(); - const std::vector > tracks = convRef->tracks(); - float px=tracks[0]->innerMomentum().x(); - float py=tracks[0]->innerMomentum().y(); - float pz=tracks[0]->innerMomentum().z(); - float p=sqrt(px*px+py*py+pz*pz); - ep=fabs(1.-convRef->caloCluster()[0]->energy()/p); - // std::cout << " 1-E/P = " << ep << std::endl; - if ( epfirst; - } + float epMin = 999; + + for (iMap = convMap.begin(); iMap != convMap.end(); iMap++) { + reco::ConversionRef convRef = iMap->first; + // std::vector tracks = convRef->tracks(); + const std::vector > tracks = convRef->tracks(); + float px = tracks[0]->innerMomentum().x(); + float py = tracks[0]->innerMomentum().y(); + float pz = tracks[0]->innerMomentum().z(); + float p = sqrt(px * px + py * py + pz * pz); + ep = fabs(1. - convRef->caloCluster()[0]->energy() / p); + // std::cout << " 1-E/P = " << ep << std::endl; + if (ep < epMin) { + epMin = ep; + bestRef = iMap->first; + } } - // std::cout << " Best conv 1-E/P " << ep << std::endl; - + // std::cout << " Best conv 1-E/P " << ep << std::endl; } - return bestRef; - - -} - +} diff --git a/RecoEgamma/EgammaPhotonProducers/src/PhotonProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/PhotonProducer.cc index 36aeb7808b29e..1068fa5729c6f 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/PhotonProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/PhotonProducer.cc @@ -13,7 +13,6 @@ #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" - #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/EgammaReco/interface/ClusterShape.h" @@ -35,63 +34,51 @@ #include "RecoEcal/EgammaCoreTools/plugins/EcalClusterCrackCorrection.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaHadTower.h" -PhotonProducer::PhotonProducer(const edm::ParameterSet& config) : - - conf_(config) -{ +PhotonProducer::PhotonProducer(const edm::ParameterSet& config) + : + conf_(config) { // use onfiguration file to setup input/output collection names - photonCoreProducer_ = - consumes(conf_.getParameter("photonCoreProducer")); - barrelEcalHits_ = - consumes(conf_.getParameter("barrelEcalHits")); - endcapEcalHits_ = - consumes(conf_.getParameter("endcapEcalHits")); - vertexProducer_ = - consumes(conf_.getParameter("primaryVertexProducer")); - hcalTowers_ = - consumes(conf_.getParameter("hcalTowers")); - hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); - highEt_ = conf_.getParameter("highEt"); + photonCoreProducer_ = consumes(conf_.getParameter("photonCoreProducer")); + barrelEcalHits_ = consumes(conf_.getParameter("barrelEcalHits")); + endcapEcalHits_ = consumes(conf_.getParameter("endcapEcalHits")); + vertexProducer_ = consumes(conf_.getParameter("primaryVertexProducer")); + hcalTowers_ = consumes(conf_.getParameter("hcalTowers")); + hOverEConeSize_ = conf_.getParameter("hOverEConeSize"); + highEt_ = conf_.getParameter("highEt"); // R9 value to decide converted/unconverted - minR9Barrel_ = conf_.getParameter("minR9Barrel"); - minR9Endcap_ = conf_.getParameter("minR9Endcap"); - usePrimaryVertex_ = conf_.getParameter("usePrimaryVertex"); - runMIPTagger_ = conf_.getParameter("runMIPTagger"); + minR9Barrel_ = conf_.getParameter("minR9Barrel"); + minR9Endcap_ = conf_.getParameter("minR9Endcap"); + usePrimaryVertex_ = conf_.getParameter("usePrimaryVertex"); + runMIPTagger_ = conf_.getParameter("runMIPTagger"); - candidateP4type_ = config.getParameter("candidateP4type") ; + candidateP4type_ = config.getParameter("candidateP4type"); - edm::ParameterSet posCalcParameters = - config.getParameter("posCalcParameters"); + edm::ParameterSet posCalcParameters = config.getParameter("posCalcParameters"); posCalculator_ = PositionCalc(posCalcParameters); - //AA //Flags and Severities to be excluded from photon calculations const std::vector flagnamesEB = - config.getParameter >("RecHitFlagToBeExcludedEB"); + config.getParameter >("RecHitFlagToBeExcludedEB"); const std::vector flagnamesEE = - config.getParameter >("RecHitFlagToBeExcludedEE"); + config.getParameter >("RecHitFlagToBeExcludedEE"); - flagsexclEB_= - StringToEnumValue(flagnamesEB); + flagsexclEB_ = StringToEnumValue(flagnamesEB); - flagsexclEE_= - StringToEnumValue(flagnamesEE); + flagsexclEE_ = StringToEnumValue(flagnamesEE); const std::vector severitynamesEB = - config.getParameter >("RecHitSeverityToBeExcludedEB"); + config.getParameter >("RecHitSeverityToBeExcludedEB"); - severitiesexclEB_= - StringToEnumValue(severitynamesEB); + severitiesexclEB_ = StringToEnumValue(severitynamesEB); const std::vector severitynamesEE = - config.getParameter >("RecHitSeverityToBeExcludedEE"); + config.getParameter >("RecHitSeverityToBeExcludedEE"); - severitiesexclEE_= - StringToEnumValue(severitynamesEE); + severitiesexclEE_ = StringToEnumValue(severitynamesEE); //AA @@ -135,20 +122,18 @@ PhotonProducer::PhotonProducer(const edm::ParameterSet& config) : thePhotonEnergyCorrector_ = new PhotonEnergyCorrector(conf_, consumesCollector()); thePhotonIsolationCalculator_ = new PhotonIsolationCalculator(); edm::ParameterSet isolationSumsCalculatorSet = conf_.getParameter("isolationSumsCalculatorSet"); - thePhotonIsolationCalculator_->setup(isolationSumsCalculatorSet, flagsexclEB_, flagsexclEE_, severitiesexclEB_, severitiesexclEE_,consumesCollector()); - + thePhotonIsolationCalculator_->setup( + isolationSumsCalculatorSet, flagsexclEB_, flagsexclEE_, severitiesexclEB_, severitiesexclEE_, consumesCollector()); thePhotonMIPHaloTagger_ = new PhotonMIPHaloTagger(); edm::ParameterSet mipVariableSet = conf_.getParameter("mipVariableSet"); - thePhotonMIPHaloTagger_->setup(mipVariableSet,consumesCollector()); + thePhotonMIPHaloTagger_->setup(mipVariableSet, consumesCollector()); // Register the product - produces< reco::PhotonCollection >(PhotonCollection_); - + produces(PhotonCollection_); } -PhotonProducer::~PhotonProducer() -{ +PhotonProducer::~PhotonProducer() { delete thePhotonEnergyCorrector_; delete thePhotonIsolationCalculator_; delete thePhotonMIPHaloTagger_; @@ -156,46 +141,42 @@ PhotonProducer::~PhotonProducer() } void PhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { - using namespace edm; // nEvt_++; reco::PhotonCollection outputPhotonCollection; auto outputPhotonCollection_p = std::make_unique(); - // Get the PhotonCore collection - bool validPhotonCoreHandle=true; + bool validPhotonCoreHandle = true; Handle photonCoreHandle; - theEvent.getByToken(photonCoreProducer_,photonCoreHandle); + theEvent.getByToken(photonCoreProducer_, photonCoreHandle); if (!photonCoreHandle.isValid()) { - edm::LogError("PhotonProducer") - << "Error! Can't get the photonCoreProducer"; - validPhotonCoreHandle=false; + edm::LogError("PhotonProducer") << "Error! Can't get the photonCoreProducer"; + validPhotonCoreHandle = false; } - // Get EcalRecHits - bool validEcalRecHits=true; + // Get EcalRecHits + bool validEcalRecHits = true; Handle barrelHitHandle; EcalRecHitCollection barrelRecHits; theEvent.getByToken(barrelEcalHits_, barrelHitHandle); if (!barrelHitHandle.isValid()) { - edm::LogError("PhotonProducer") - << "Error! Can't get the barrelEcalHits"; - validEcalRecHits=false; + edm::LogError("PhotonProducer") << "Error! Can't get the barrelEcalHits"; + validEcalRecHits = false; } - if ( validEcalRecHits) barrelRecHits = *(barrelHitHandle.product()); - + if (validEcalRecHits) + barrelRecHits = *(barrelHitHandle.product()); Handle endcapHitHandle; theEvent.getByToken(endcapEcalHits_, endcapHitHandle); EcalRecHitCollection endcapRecHits; if (!endcapHitHandle.isValid()) { - edm::LogError("PhotonProducer") - << "Error! Can't get the endcapEcalHits"; - validEcalRecHits=false; + edm::LogError("PhotonProducer") << "Error! Can't get the endcapEcalHits"; + validEcalRecHits = false; } - if( validEcalRecHits) endcapRecHits = *(endcapHitHandle.product()); + if (validEcalRecHits) + endcapRecHits = *(endcapHitHandle.product()); //AA //Get the severity level object @@ -203,12 +184,10 @@ void PhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEve theEventSetup.get().get(sevLv); // - -// get Hcal towers collection + // get Hcal towers collection Handle hcalTowersHandle; theEvent.getByToken(hcalTowers_, hcalTowersHandle); - // get the geometry from the event setup: theEventSetup.get().get(theCaloGeom_); @@ -218,167 +197,169 @@ void PhotonProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEve edm::ESHandle pTopology; theEventSetup.get().get(theCaloTopo_); - const CaloTopology *topology = theCaloTopo_.product(); + const CaloTopology* topology = theCaloTopo_.product(); // Get the primary event vertex Handle vertexHandle; reco::VertexCollection vertexCollection; - bool validVertex=true; - if ( usePrimaryVertex_ ) { + bool validVertex = true; + if (usePrimaryVertex_) { theEvent.getByToken(vertexProducer_, vertexHandle); if (!vertexHandle.isValid()) { - edm::LogWarning("PhotonProducer") << "Error! Can't get the product primary Vertex Collection "<< "\n"; - validVertex=false; + edm::LogWarning("PhotonProducer") << "Error! Can't get the product primary Vertex Collection " + << "\n"; + validVertex = false; } - if (validVertex) vertexCollection = *(vertexHandle.product()); + if (validVertex) + vertexCollection = *(vertexHandle.product()); } // math::XYZPoint vtx(0.,0.,0.); //if (vertexCollection.size()>0) vtx = vertexCollection.begin()->position(); - - int iSC=0; // index in photon collection + int iSC = 0; // index in photon collection // Loop over barrel and endcap SC collections and fill the photon collection - if ( validPhotonCoreHandle) + if (validPhotonCoreHandle) fillPhotonCollection(theEvent, - theEventSetup, - photonCoreHandle, - topology, - &barrelRecHits, - &endcapRecHits, - hcalTowersHandle, - //vtx, - vertexCollection, - outputPhotonCollection, - iSC, - sevLv.product()); - + theEventSetup, + photonCoreHandle, + topology, + &barrelRecHits, + &endcapRecHits, + hcalTowersHandle, + //vtx, + vertexCollection, + outputPhotonCollection, + iSC, + sevLv.product()); // put the product in the event edm::LogInfo("PhotonProducer") << " Put in the event " << iSC << " Photon Candidates \n"; - outputPhotonCollection_p->assign(outputPhotonCollection.begin(),outputPhotonCollection.end()); + outputPhotonCollection_p->assign(outputPhotonCollection.begin(), outputPhotonCollection.end()); theEvent.put(std::move(outputPhotonCollection_p), PhotonCollection_); - } void PhotonProducer::fillPhotonCollection(edm::Event& evt, - edm::EventSetup const & es, - const edm::Handle & photonCoreHandle, - const CaloTopology* topology, - const EcalRecHitCollection* ecalBarrelHits, - const EcalRecHitCollection* ecalEndcapHits, - const edm::Handle & hcalTowersHandle, - // math::XYZPoint & vtx, - reco::VertexCollection & vertexCollection, - reco::PhotonCollection & outputPhotonCollection, int& iSC, - const EcalSeverityLevelAlgo * sevLv) { - + edm::EventSetup const& es, + const edm::Handle& photonCoreHandle, + const CaloTopology* topology, + const EcalRecHitCollection* ecalBarrelHits, + const EcalRecHitCollection* ecalEndcapHits, + const edm::Handle& hcalTowersHandle, + // math::XYZPoint & vtx, + reco::VertexCollection& vertexCollection, + reco::PhotonCollection& outputPhotonCollection, + int& iSC, + const EcalSeverityLevelAlgo* sevLv) { const CaloGeometry* geometry = theCaloGeom_.product(); - const CaloSubdetectorGeometry* subDetGeometry =nullptr ; + const CaloSubdetectorGeometry* subDetGeometry = nullptr; const CaloSubdetectorGeometry* geometryES = theCaloGeom_->getSubdetectorGeometry(DetId::Ecal, EcalPreshower); - const EcalRecHitCollection* hits = nullptr ; + const EcalRecHitCollection* hits = nullptr; std::vector preselCutValues; - float minR9=0; + float minR9 = 0; - thePhotonEnergyCorrector_ -> init(es); + thePhotonEnergyCorrector_->init(es); std::vector flags_, severitiesexcl_; - for(unsigned int lSC=0; lSC < photonCoreHandle->size(); lSC++) { - + for (unsigned int lSC = 0; lSC < photonCoreHandle->size(); lSC++) { reco::PhotonCoreRef coreRef(reco::PhotonCoreRef(photonCoreHandle, lSC)); - reco::SuperClusterRef scRef=coreRef->superCluster(); + reco::SuperClusterRef scRef = coreRef->superCluster(); // const reco::SuperCluster* pClus=&(*scRef); iSC++; int subdet = scRef->seed()->hitsAndFractions()[0].first.subdetId(); - subDetGeometry = theCaloGeom_->getSubdetectorGeometry(DetId::Ecal, subdet); + subDetGeometry = theCaloGeom_->getSubdetectorGeometry(DetId::Ecal, subdet); - if (subdet==EcalBarrel) { + if (subdet == EcalBarrel) { preselCutValues = preselCutValuesBarrel_; minR9 = minR9Barrel_; hits = ecalBarrelHits; flags_ = flagsexclEB_; severitiesexcl_ = severitiesexclEB_; - } else if (subdet==EcalEndcap) { + } else if (subdet == EcalEndcap) { preselCutValues = preselCutValuesEndcap_; minR9 = minR9Endcap_; hits = ecalEndcapHits; flags_ = flagsexclEE_; severitiesexcl_ = severitiesexclEE_; } else { - edm::LogWarning("")<<"PhotonProducer: do not know if it is a barrel or endcap SuperCluster"; + edm::LogWarning("") << "PhotonProducer: do not know if it is a barrel or endcap SuperCluster"; } - if(hits == nullptr) continue; + if (hits == nullptr) + continue; // SC energy preselection - if (scRef->energy()/cosh(scRef->eta()) <= preselCutValues[0] ) continue; + if (scRef->energy() / cosh(scRef->eta()) <= preselCutValues[0]) + continue; // calculate HoE const CaloTowerCollection* hcalTowersColl = hcalTowersHandle.product(); - EgammaTowerIsolation towerIso1(hOverEConeSize_,0.,0.,1,hcalTowersColl) ; - EgammaTowerIsolation towerIso2(hOverEConeSize_,0.,0.,2,hcalTowersColl) ; - double HoE1=towerIso1.getTowerESum(&(*scRef))/scRef->energy(); - double HoE2=towerIso2.getTowerESum(&(*scRef))/scRef->energy(); + EgammaTowerIsolation towerIso1(hOverEConeSize_, 0., 0., 1, hcalTowersColl); + EgammaTowerIsolation towerIso2(hOverEConeSize_, 0., 0., 2, hcalTowersColl); + double HoE1 = towerIso1.getTowerESum(&(*scRef)) / scRef->energy(); + double HoE2 = towerIso2.getTowerESum(&(*scRef)) / scRef->energy(); EgammaHadTower towerIsoBehindClus(es); towerIsoBehindClus.setTowerCollection(hcalTowersHandle.product()); - std::vector TowersBehindClus = towerIsoBehindClus.towersOf(*scRef); - float hcalDepth1OverEcalBc = towerIsoBehindClus.getDepth1HcalESum(TowersBehindClus)/scRef->energy(); - float hcalDepth2OverEcalBc = towerIsoBehindClus.getDepth2HcalESum(TowersBehindClus)/scRef->energy(); + std::vector TowersBehindClus = towerIsoBehindClus.towersOf(*scRef); + float hcalDepth1OverEcalBc = towerIsoBehindClus.getDepth1HcalESum(TowersBehindClus) / scRef->energy(); + float hcalDepth2OverEcalBc = towerIsoBehindClus.getDepth2HcalESum(TowersBehindClus) / scRef->energy(); // std::cout << " PhotonProducer calculation of HoE with towers in a cone " << HoE1 << " " << HoE2 << std::endl; //std::cout << " PhotonProducer calcualtion of HoE with towers behind the BCs " << hcalDepth1OverEcalBc << " " << hcalDepth2OverEcalBc << std::endl; - // recalculate position of seed BasicCluster taking shower depth for unconverted photon - math::XYZPoint unconvPos = posCalculator_.Calculate_Location(scRef->seed()->hitsAndFractions(),hits,subDetGeometry,geometryES); + math::XYZPoint unconvPos = + posCalculator_.Calculate_Location(scRef->seed()->hitsAndFractions(), hits, subDetGeometry, geometryES); - - float maxXtal = EcalClusterTools::eMax( *(scRef->seed()), &(*hits) ); + float maxXtal = EcalClusterTools::eMax(*(scRef->seed()), &(*hits)); //AA //Change these to consider severity level of hits - float e1x5 = EcalClusterTools::e1x5( *(scRef->seed()), &(*hits), &(*topology)); - float e2x5 = EcalClusterTools::e2x5Max( *(scRef->seed()), &(*hits), &(*topology)); - float e3x3 = EcalClusterTools::e3x3( *(scRef->seed()), &(*hits), &(*topology)); - float e5x5 = EcalClusterTools::e5x5( *(scRef->seed()), &(*hits), &(*topology)); - std::vector cov = EcalClusterTools::covariances( *(scRef->seed()), &(*hits), &(*topology), geometry); - std::vector locCov = EcalClusterTools::localCovariances( *(scRef->seed()), &(*hits), &(*topology)); + float e1x5 = EcalClusterTools::e1x5(*(scRef->seed()), &(*hits), &(*topology)); + float e2x5 = EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)); + float e3x3 = EcalClusterTools::e3x3(*(scRef->seed()), &(*hits), &(*topology)); + float e5x5 = EcalClusterTools::e5x5(*(scRef->seed()), &(*hits), &(*topology)); + std::vector cov = EcalClusterTools::covariances(*(scRef->seed()), &(*hits), &(*topology), geometry); + std::vector locCov = EcalClusterTools::localCovariances(*(scRef->seed()), &(*hits), &(*topology)); float sigmaEtaEta = sqrt(cov[0]); float sigmaIetaIeta = sqrt(locCov[0]); - float r9 =e3x3/(scRef->rawEnergy()); + float r9 = e3x3 / (scRef->rawEnergy()); - float full5x5_maxXtal = noZS::EcalClusterTools::eMax( *(scRef->seed()), &(*hits) ); + float full5x5_maxXtal = noZS::EcalClusterTools::eMax(*(scRef->seed()), &(*hits)); //AA //Change these to consider severity level of hits - float full5x5_e1x5 = noZS::EcalClusterTools::e1x5( *(scRef->seed()), &(*hits), &(*topology)); - float full5x5_e2x5 = noZS::EcalClusterTools::e2x5Max( *(scRef->seed()), &(*hits), &(*topology)); - float full5x5_e3x3 = noZS::EcalClusterTools::e3x3( *(scRef->seed()), &(*hits), &(*topology)); - float full5x5_e5x5 = noZS::EcalClusterTools::e5x5( *(scRef->seed()), &(*hits), &(*topology)); - std::vector full5x5_cov = noZS::EcalClusterTools::covariances( *(scRef->seed()), &(*hits), &(*topology), geometry); - std::vector full5x5_locCov = noZS::EcalClusterTools::localCovariances( *(scRef->seed()), &(*hits), &(*topology)); + float full5x5_e1x5 = noZS::EcalClusterTools::e1x5(*(scRef->seed()), &(*hits), &(*topology)); + float full5x5_e2x5 = noZS::EcalClusterTools::e2x5Max(*(scRef->seed()), &(*hits), &(*topology)); + float full5x5_e3x3 = noZS::EcalClusterTools::e3x3(*(scRef->seed()), &(*hits), &(*topology)); + float full5x5_e5x5 = noZS::EcalClusterTools::e5x5(*(scRef->seed()), &(*hits), &(*topology)); + std::vector full5x5_cov = + noZS::EcalClusterTools::covariances(*(scRef->seed()), &(*hits), &(*topology), geometry); + std::vector full5x5_locCov = + noZS::EcalClusterTools::localCovariances(*(scRef->seed()), &(*hits), &(*topology)); float full5x5_sigmaEtaEta = sqrt(full5x5_cov[0]); float full5x5_sigmaIetaIeta = sqrt(full5x5_locCov[0]); // compute position of ECAL shower math::XYZPoint caloPosition; - if (r9>minR9) { + if (r9 > minR9) { caloPosition = unconvPos; } else { caloPosition = scRef->position(); } //// energy determination -- Default to create the candidate. Afterwards corrections are applied - double photonEnergy=1.; - math::XYZPoint vtx(0.,0.,0.); - if (!vertexCollection.empty()) vtx = vertexCollection.begin()->position(); + double photonEnergy = 1.; + math::XYZPoint vtx(0., 0., 0.); + if (!vertexCollection.empty()) + vtx = vertexCollection.begin()->position(); // compute momentum vector of photon from primary vertex and cluster position math::XYZVector direction = caloPosition - vtx; //math::XYZVector momentum = direction.unit() * photonEnergy ; - math::XYZVector momentum = direction.unit() ; + math::XYZVector momentum = direction.unit(); // Create dummy candidate with unit momentum and zero energy to allow setting of all variables. The energy is set for last. - math::XYZTLorentzVectorD p4(momentum.x(), momentum.y(), momentum.z(), photonEnergy ); + math::XYZTLorentzVectorD p4(momentum.x(), momentum.y(), momentum.z(), photonEnergy); reco::Photon newCandidate(p4, caloPosition, coreRef, vtx); //std::cout << " standard p4 before " << newCandidate.p4() << " energy " << newCandidate.energy() << std::endl; //std::cout << " type " < calculate ( &newCandidate,evt,es,fiducialFlags,isolVarR04, isolVarR03); - newCandidate.setFiducialVolumeFlags( fiducialFlags ); - newCandidate.setIsolationVariables(isolVarR04, isolVarR03 ); - + thePhotonIsolationCalculator_->calculate(&newCandidate, evt, es, fiducialFlags, isolVarR04, isolVarR03); + newCandidate.setFiducialVolumeFlags(fiducialFlags); + newCandidate.setIsolationVariables(isolVarR04, isolVarR03); /// fill shower shape block - reco::Photon::ShowerShape showerShape; - showerShape.e1x5= e1x5; - showerShape.e2x5= e2x5; - showerShape.e3x3= e3x3; - showerShape.e5x5= e5x5; - showerShape.maxEnergyXtal = maxXtal; - showerShape.sigmaEtaEta = sigmaEtaEta; - showerShape.sigmaIetaIeta = sigmaIetaIeta; + reco::Photon::ShowerShape showerShape; + showerShape.e1x5 = e1x5; + showerShape.e2x5 = e2x5; + showerShape.e3x3 = e3x3; + showerShape.e5x5 = e5x5; + showerShape.maxEnergyXtal = maxXtal; + showerShape.sigmaEtaEta = sigmaEtaEta; + showerShape.sigmaIetaIeta = sigmaIetaIeta; showerShape.hcalDepth1OverEcal = HoE1; showerShape.hcalDepth2OverEcal = HoE2; showerShape.hcalDepth1OverEcalBc = hcalDepth1OverEcalBc; showerShape.hcalDepth2OverEcalBc = hcalDepth2OverEcalBc; - showerShape.hcalTowersBehindClusters = TowersBehindClus; - newCandidate.setShowerShapeVariables ( showerShape ); + showerShape.hcalTowersBehindClusters = TowersBehindClus; + newCandidate.setShowerShapeVariables(showerShape); /// fill full5x5 shower shape block - reco::Photon::ShowerShape full5x5_showerShape; - full5x5_showerShape.e1x5= full5x5_e1x5; - full5x5_showerShape.e2x5= full5x5_e2x5; - full5x5_showerShape.e3x3= full5x5_e3x3; - full5x5_showerShape.e5x5= full5x5_e5x5; - full5x5_showerShape.maxEnergyXtal = full5x5_maxXtal; - full5x5_showerShape.sigmaEtaEta = full5x5_sigmaEtaEta; - full5x5_showerShape.sigmaIetaIeta = full5x5_sigmaIetaIeta; - newCandidate.full5x5_setShowerShapeVariables ( full5x5_showerShape ); + reco::Photon::ShowerShape full5x5_showerShape; + full5x5_showerShape.e1x5 = full5x5_e1x5; + full5x5_showerShape.e2x5 = full5x5_e2x5; + full5x5_showerShape.e3x3 = full5x5_e3x3; + full5x5_showerShape.e5x5 = full5x5_e5x5; + full5x5_showerShape.maxEnergyXtal = full5x5_maxXtal; + full5x5_showerShape.sigmaEtaEta = full5x5_sigmaEtaEta; + full5x5_showerShape.sigmaIetaIeta = full5x5_sigmaIetaIeta; + newCandidate.full5x5_setShowerShapeVariables(full5x5_showerShape); /// get ecal photon specific corrected energy /// plus values from regressions and store them in the Photon // Photon candidate takes by default (set in photons_cfi.py) a 4-momentum derived from the ecal photon-specific corrections. - thePhotonEnergyCorrector_->calculate(evt, newCandidate, subdet, vertexCollection,es); - if ( candidateP4type_ == "fromEcalEnergy") { - newCandidate.setP4( newCandidate.p4(reco::Photon::ecal_photons) ); + thePhotonEnergyCorrector_->calculate(evt, newCandidate, subdet, vertexCollection, es); + if (candidateP4type_ == "fromEcalEnergy") { + newCandidate.setP4(newCandidate.p4(reco::Photon::ecal_photons)); newCandidate.setCandidateP4type(reco::Photon::ecal_photons); - } else if ( candidateP4type_ == "fromRegression") { - newCandidate.setP4( newCandidate.p4(reco::Photon::regression1) ); + } else if (candidateP4type_ == "fromRegression") { + newCandidate.setP4(newCandidate.p4(reco::Photon::regression1)); newCandidate.setCandidateP4type(reco::Photon::regression1); } // std::cout << " final p4 " << newCandidate.p4() << " energy " << newCandidate.energy() << std::endl; - // std::cout << " PhotonProducer from candidate HoE with towers in a cone " << newCandidate.hadronicOverEm() << " " << newCandidate.hadronicDepth1OverEm() << " " << newCandidate.hadronicDepth2OverEm() << std::endl; // std::cout << " PhotonProducer from candidate of HoE with towers behind the BCs " << newCandidate.hadTowOverEm() << " " << newCandidate.hadTowDepth1OverEm() << " " << newCandidate.hadTowDepth2OverEm() << std::endl; - - // fill MIP Vairables for Halo: Block for MIP are filled from PhotonMIPHaloTagger - reco::Photon::MIPVariables mipVar ; - if(subdet==EcalBarrel && runMIPTagger_ ) - { - - thePhotonMIPHaloTagger_-> MIPcalculate( &newCandidate,evt,es,mipVar); - newCandidate.setMIPVariables(mipVar); + // fill MIP Vairables for Halo: Block for MIP are filled from PhotonMIPHaloTagger + reco::Photon::MIPVariables mipVar; + if (subdet == EcalBarrel && runMIPTagger_) { + thePhotonMIPHaloTagger_->MIPcalculate(&newCandidate, evt, es, mipVar); + newCandidate.setMIPVariables(mipVar); } - - /// Pre-selection loose isolation cuts - bool isLooseEM=true; - if ( newCandidate.pt() < highEt_) { - if ( newCandidate.hadronicOverEm() >= preselCutValues[1] ) isLooseEM=false; - if ( newCandidate.ecalRecHitSumEtConeDR04() > preselCutValues[2]+ preselCutValues[3]*newCandidate.pt() ) isLooseEM=false; - if ( newCandidate.hcalTowerSumEtConeDR04() > preselCutValues[4]+ preselCutValues[5]*newCandidate.pt() ) isLooseEM=false; - if ( newCandidate.nTrkSolidConeDR04() > int(preselCutValues[6]) ) isLooseEM=false; - if ( newCandidate.nTrkHollowConeDR04() > int(preselCutValues[7]) ) isLooseEM=false; - if ( newCandidate.trkSumPtSolidConeDR04() > preselCutValues[8] ) isLooseEM=false; - if ( newCandidate.trkSumPtHollowConeDR04() > preselCutValues[9] ) isLooseEM=false; - if ( newCandidate.sigmaIetaIeta() > preselCutValues[10] ) isLooseEM=false; + bool isLooseEM = true; + if (newCandidate.pt() < highEt_) { + if (newCandidate.hadronicOverEm() >= preselCutValues[1]) + isLooseEM = false; + if (newCandidate.ecalRecHitSumEtConeDR04() > preselCutValues[2] + preselCutValues[3] * newCandidate.pt()) + isLooseEM = false; + if (newCandidate.hcalTowerSumEtConeDR04() > preselCutValues[4] + preselCutValues[5] * newCandidate.pt()) + isLooseEM = false; + if (newCandidate.nTrkSolidConeDR04() > int(preselCutValues[6])) + isLooseEM = false; + if (newCandidate.nTrkHollowConeDR04() > int(preselCutValues[7])) + isLooseEM = false; + if (newCandidate.trkSumPtSolidConeDR04() > preselCutValues[8]) + isLooseEM = false; + if (newCandidate.trkSumPtHollowConeDR04() > preselCutValues[9]) + isLooseEM = false; + if (newCandidate.sigmaIetaIeta() > preselCutValues[10]) + isLooseEM = false; } - - - if ( isLooseEM) + if (isLooseEM) outputPhotonCollection.push_back(newCandidate); - - } } diff --git a/RecoEgamma/EgammaPhotonProducers/src/ReducedEGProducer.cc b/RecoEgamma/EgammaPhotonProducers/src/ReducedEGProducer.cc index 4d3b7e811adf3..7cc4648c202b2 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/ReducedEGProducer.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/ReducedEGProducer.cc @@ -14,7 +14,6 @@ #include "Geometry/CaloTopology/interface/CaloTopology.h" #include "Geometry/CaloEventSetup/interface/CaloTopologyRecord.h" - #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" #include "DataFormats/EgammaReco/interface/ClusterShape.h" @@ -37,261 +36,258 @@ #include "RecoEgamma/EgammaPhotonProducers/interface/ReducedEGProducer.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaTowerIsolation.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" -#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionBaseClass.h" +#include "RecoEcal/EgammaCoreTools/interface/EcalClusterFunctionFactory.h" #include "RecoEcal/EgammaCoreTools/plugins/EcalClusterCrackCorrection.h" #include "RecoEgamma/EgammaIsolationAlgos/interface/EgammaHadTower.h" #include "RecoEgamma/EgammaTools/interface/ConversionTools.h" -ReducedEGProducer::ReducedEGProducer(const edm::ParameterSet& config) : - photonT_(consumes(config.getParameter("photons"))), - gsfElectronT_(consumes(config.getParameter("gsfElectrons"))), - gsfTrackT_(consumes(config.getParameter("gsfTracks"))), - conversionT_(consumes(config.getParameter("conversions"))), - singleConversionT_(consumes(config.getParameter("singleConversions"))), - barrelEcalHits_(consumes(config.getParameter("barrelEcalHits"))), - endcapEcalHits_(consumes(config.getParameter("endcapEcalHits"))), - doPreshowerEcalHits_(!config.getParameter("preshowerEcalHits").label().empty()), - preshowerEcalHits_(doPreshowerEcalHits_ ? consumes(config.getParameter("preshowerEcalHits")) : edm::EDGetTokenT()), - hbheHits_(consumes(config.getParameter("hbheHits"))), - photonPfCandMapT_(consumes > >(config.getParameter("photonsPFValMap"))), - gsfElectronPfCandMapT_(consumes > >(config.getParameter("gsfElectronsPFValMap"))), - //calibration flags - applyPhotonCalibOnData_(config.getParameter("applyPhotonCalibOnData")), - applyPhotonCalibOnMC_(config.getParameter("applyPhotonCalibOnMC")), - applyGsfElectronCalibOnData_(config.getParameter("applyGsfElectronCalibOnData")), - applyGsfElectronCalibOnMC_(config.getParameter("applyGsfElectronCalibOnMC")), - //output collections - outPhotons_("reducedGedPhotons"), - outPhotonCores_("reducedGedPhotonCores"), - outOOTPhotons_("reducedOOTPhotons"), - outOOTPhotonCores_("reducedOOTPhotonCores"), - outGsfElectrons_("reducedGedGsfElectrons"), - outGsfElectronCores_("reducedGedGsfElectronCores"), - outGsfTracks_("reducedGsfTracks"), - outConversions_("reducedConversions"), - outSingleConversions_("reducedSingleLegConversions"), - outSuperClusters_("reducedSuperClusters"), - outEBEEClusters_("reducedEBEEClusters"), - outESClusters_("reducedESClusters"), - outOOTSuperClusters_("reducedOOTSuperClusters"), - outOOTEBEEClusters_("reducedOOTEBEEClusters"), - outOOTESClusters_("reducedOOTESClusters"), - outEBRecHits_("reducedEBRecHits"), - outEERecHits_("reducedEERecHits"), - outESRecHits_("reducedESRecHits"), - outHBHERecHits_("reducedHBHEHits"), - outPhotonPfCandMap_("reducedPhotonPfCandMap"), - outGsfElectronPfCandMap_("reducedGsfElectronPfCandMap"), - outPhotonIds_(config.getParameter >("photonIDOutput")), - outGsfElectronIds_(config.getParameter >("gsfElectronIDOutput")), - outPhotonFloatValueMaps_(config.getParameter >("photonFloatValueMapOutput")), - outOOTPhotonFloatValueMaps_(config.getParameter >("ootPhotonFloatValueMapOutput")), - outGsfElectronFloatValueMaps_(config.getParameter >("gsfElectronFloatValueMapOutput")), - keepPhotonSel_(config.getParameter("keepPhotons")), - slimRelinkPhotonSel_(config.getParameter("slimRelinkPhotons")), - relinkPhotonSel_(config.getParameter("relinkPhotons")), - keepOOTPhotonSel_(config.getParameter("keepOOTPhotons")), - slimRelinkOOTPhotonSel_(config.getParameter("slimRelinkOOTPhotons")), - relinkOOTPhotonSel_(config.getParameter("relinkOOTPhotons")), - keepGsfElectronSel_(config.getParameter("keepGsfElectrons")), - slimRelinkGsfElectronSel_(config.getParameter("slimRelinkGsfElectrons")), - relinkGsfElectronSel_(config.getParameter("relinkGsfElectrons")), - hcalHitSel_(config.getParameter("hcalHitSel")) -{ - +ReducedEGProducer::ReducedEGProducer(const edm::ParameterSet& config) + : photonT_(consumes(config.getParameter("photons"))), + gsfElectronT_(consumes(config.getParameter("gsfElectrons"))), + gsfTrackT_(consumes(config.getParameter("gsfTracks"))), + conversionT_(consumes(config.getParameter("conversions"))), + singleConversionT_(consumes(config.getParameter("singleConversions"))), + barrelEcalHits_(consumes(config.getParameter("barrelEcalHits"))), + endcapEcalHits_(consumes(config.getParameter("endcapEcalHits"))), + doPreshowerEcalHits_(!config.getParameter("preshowerEcalHits").label().empty()), + preshowerEcalHits_(doPreshowerEcalHits_ + ? consumes(config.getParameter("preshowerEcalHits")) + : edm::EDGetTokenT()), + hbheHits_(consumes(config.getParameter("hbheHits"))), + photonPfCandMapT_(consumes>>( + config.getParameter("photonsPFValMap"))), + gsfElectronPfCandMapT_(consumes>>( + config.getParameter("gsfElectronsPFValMap"))), + //calibration flags + applyPhotonCalibOnData_(config.getParameter("applyPhotonCalibOnData")), + applyPhotonCalibOnMC_(config.getParameter("applyPhotonCalibOnMC")), + applyGsfElectronCalibOnData_(config.getParameter("applyGsfElectronCalibOnData")), + applyGsfElectronCalibOnMC_(config.getParameter("applyGsfElectronCalibOnMC")), + //output collections + outPhotons_("reducedGedPhotons"), + outPhotonCores_("reducedGedPhotonCores"), + outOOTPhotons_("reducedOOTPhotons"), + outOOTPhotonCores_("reducedOOTPhotonCores"), + outGsfElectrons_("reducedGedGsfElectrons"), + outGsfElectronCores_("reducedGedGsfElectronCores"), + outGsfTracks_("reducedGsfTracks"), + outConversions_("reducedConversions"), + outSingleConversions_("reducedSingleLegConversions"), + outSuperClusters_("reducedSuperClusters"), + outEBEEClusters_("reducedEBEEClusters"), + outESClusters_("reducedESClusters"), + outOOTSuperClusters_("reducedOOTSuperClusters"), + outOOTEBEEClusters_("reducedOOTEBEEClusters"), + outOOTESClusters_("reducedOOTESClusters"), + outEBRecHits_("reducedEBRecHits"), + outEERecHits_("reducedEERecHits"), + outESRecHits_("reducedESRecHits"), + outHBHERecHits_("reducedHBHEHits"), + outPhotonPfCandMap_("reducedPhotonPfCandMap"), + outGsfElectronPfCandMap_("reducedGsfElectronPfCandMap"), + outPhotonIds_(config.getParameter>("photonIDOutput")), + outGsfElectronIds_(config.getParameter>("gsfElectronIDOutput")), + outPhotonFloatValueMaps_(config.getParameter>("photonFloatValueMapOutput")), + outOOTPhotonFloatValueMaps_(config.getParameter>("ootPhotonFloatValueMapOutput")), + outGsfElectronFloatValueMaps_(config.getParameter>("gsfElectronFloatValueMapOutput")), + keepPhotonSel_(config.getParameter("keepPhotons")), + slimRelinkPhotonSel_(config.getParameter("slimRelinkPhotons")), + relinkPhotonSel_(config.getParameter("relinkPhotons")), + keepOOTPhotonSel_(config.getParameter("keepOOTPhotons")), + slimRelinkOOTPhotonSel_(config.getParameter("slimRelinkOOTPhotons")), + relinkOOTPhotonSel_(config.getParameter("relinkOOTPhotons")), + keepGsfElectronSel_(config.getParameter("keepGsfElectrons")), + slimRelinkGsfElectronSel_(config.getParameter("slimRelinkGsfElectrons")), + relinkGsfElectronSel_(config.getParameter("relinkGsfElectrons")), + hcalHitSel_(config.getParameter("hcalHitSel")) { const edm::InputTag& aTag = config.getParameter("ootPhotons"); - if (not aTag.label().empty()) ootPhotonT_ = consumes(aTag); - - const std::vector& photonidinputs = - config.getParameter >("photonIDSources"); - for (const edm::InputTag &tag : photonidinputs) { - photonIdTs_.emplace_back(consumes >(tag)); + if (not aTag.label().empty()) + ootPhotonT_ = consumes(aTag); + + const std::vector& photonidinputs = config.getParameter>("photonIDSources"); + for (const edm::InputTag& tag : photonidinputs) { + photonIdTs_.emplace_back(consumes>(tag)); } - - const std::vector& gsfelectronidinputs = - config.getParameter >("gsfElectronIDSources"); - for (const edm::InputTag &tag : gsfelectronidinputs) { - gsfElectronIdTs_.emplace_back(consumes >(tag)); - } - - const std::vector& photonpfclusterisoinputs = - config.getParameter >("photonFloatValueMapSources"); - for (const edm::InputTag &tag : photonpfclusterisoinputs) { - photonFloatValueMapTs_.emplace_back(consumes >(tag)); - } - - const std::vector& ootphotonpfclusterisoinputs = - config.getParameter >("ootPhotonFloatValueMapSources"); - for (const edm::InputTag &tag : ootphotonpfclusterisoinputs) { - ootPhotonFloatValueMapTs_.emplace_back(consumes >(tag)); - } - - const std::vector& gsfelectronpfclusterisoinputs = - config.getParameter >("gsfElectronFloatValueMapSources"); - for (const edm::InputTag &tag : gsfelectronpfclusterisoinputs) { - gsfElectronFloatValueMapTs_.emplace_back(consumes >(tag)); - } - - if(applyPhotonCalibOnData_ || applyPhotonCalibOnMC_){ - setToken(photonCalibEnergyT_,config,"photonCalibEnergySource"); - setToken(photonCalibEnergyErrT_,config,"photonCalibEnergyErrSource"); + + const std::vector& gsfelectronidinputs = + config.getParameter>("gsfElectronIDSources"); + for (const edm::InputTag& tag : gsfelectronidinputs) { + gsfElectronIdTs_.emplace_back(consumes>(tag)); } - if(applyGsfElectronCalibOnData_ || applyGsfElectronCalibOnMC_){ - setToken(gsfElectronCalibEnergyT_,config,"gsfElectronCalibEnergySource"); - setToken(gsfElectronCalibEnergyErrT_,config,"gsfElectronCalibEnergyErrSource"); - setToken(gsfElectronCalibEcalEnergyT_,config,"gsfElectronCalibEcalEnergySource"); - setToken(gsfElectronCalibEcalEnergyErrT_,config,"gsfElectronCalibEcalEnergyErrSource"); + + const std::vector& photonpfclusterisoinputs = + config.getParameter>("photonFloatValueMapSources"); + for (const edm::InputTag& tag : photonpfclusterisoinputs) { + photonFloatValueMapTs_.emplace_back(consumes>(tag)); } - produces< reco::PhotonCollection >(outPhotons_); - produces< reco::PhotonCoreCollection >(outPhotonCores_); - if(!ootPhotonT_.isUninitialized()){ - produces< reco::PhotonCollection >(outOOTPhotons_); - produces< reco::PhotonCoreCollection >(outOOTPhotonCores_); + const std::vector& ootphotonpfclusterisoinputs = + config.getParameter>("ootPhotonFloatValueMapSources"); + for (const edm::InputTag& tag : ootphotonpfclusterisoinputs) { + ootPhotonFloatValueMapTs_.emplace_back(consumes>(tag)); } - produces< reco::GsfElectronCollection >(outGsfElectrons_); - produces< reco::GsfElectronCoreCollection >(outGsfElectronCores_); - produces< reco::GsfTrackCollection >(outGsfTracks_); - produces< reco::ConversionCollection >(outConversions_); - produces< reco::ConversionCollection >(outSingleConversions_); - produces< reco::SuperClusterCollection >(outSuperClusters_); - produces< reco::CaloClusterCollection >(outEBEEClusters_); - produces< reco::CaloClusterCollection >(outESClusters_); - if(!ootPhotonT_.isUninitialized()){ - produces< reco::SuperClusterCollection >(outOOTSuperClusters_); - produces< reco::CaloClusterCollection >(outOOTEBEEClusters_); - produces< reco::CaloClusterCollection >(outOOTESClusters_); + + const std::vector& gsfelectronpfclusterisoinputs = + config.getParameter>("gsfElectronFloatValueMapSources"); + for (const edm::InputTag& tag : gsfelectronpfclusterisoinputs) { + gsfElectronFloatValueMapTs_.emplace_back(consumes>(tag)); } - produces< EcalRecHitCollection >(outEBRecHits_); - produces< EcalRecHitCollection >(outEERecHits_); - if (doPreshowerEcalHits_) produces< EcalRecHitCollection >(outESRecHits_); - produces< HBHERecHitCollection >(outHBHERecHits_); - produces< edm::ValueMap > >(outPhotonPfCandMap_); - produces< edm::ValueMap > >(outGsfElectronPfCandMap_); - for (const std::string &outid : outPhotonIds_) { - produces< edm::ValueMap >(outid); + + if (applyPhotonCalibOnData_ || applyPhotonCalibOnMC_) { + setToken(photonCalibEnergyT_, config, "photonCalibEnergySource"); + setToken(photonCalibEnergyErrT_, config, "photonCalibEnergyErrSource"); } - for (const std::string &outid : outGsfElectronIds_) { - produces< edm::ValueMap >(outid); - } - for (const std::string &outid : outPhotonFloatValueMaps_) { - produces< edm::ValueMap >(outid); + if (applyGsfElectronCalibOnData_ || applyGsfElectronCalibOnMC_) { + setToken(gsfElectronCalibEnergyT_, config, "gsfElectronCalibEnergySource"); + setToken(gsfElectronCalibEnergyErrT_, config, "gsfElectronCalibEnergyErrSource"); + setToken(gsfElectronCalibEcalEnergyT_, config, "gsfElectronCalibEcalEnergySource"); + setToken(gsfElectronCalibEcalEnergyErrT_, config, "gsfElectronCalibEcalEnergyErrSource"); } - if(!ootPhotonT_.isUninitialized()){ - for (const std::string &outid : outOOTPhotonFloatValueMaps_) { - produces< edm::ValueMap >(outid); + + produces(outPhotons_); + produces(outPhotonCores_); + if (!ootPhotonT_.isUninitialized()) { + produces(outOOTPhotons_); + produces(outOOTPhotonCores_); + } + produces(outGsfElectrons_); + produces(outGsfElectronCores_); + produces(outGsfTracks_); + produces(outConversions_); + produces(outSingleConversions_); + produces(outSuperClusters_); + produces(outEBEEClusters_); + produces(outESClusters_); + if (!ootPhotonT_.isUninitialized()) { + produces(outOOTSuperClusters_); + produces(outOOTEBEEClusters_); + produces(outOOTESClusters_); + } + produces(outEBRecHits_); + produces(outEERecHits_); + if (doPreshowerEcalHits_) + produces(outESRecHits_); + produces(outHBHERecHits_); + produces>>(outPhotonPfCandMap_); + produces>>(outGsfElectronPfCandMap_); + for (const std::string& outid : outPhotonIds_) { + produces>(outid); + } + for (const std::string& outid : outGsfElectronIds_) { + produces>(outid); + } + for (const std::string& outid : outPhotonFloatValueMaps_) { + produces>(outid); + } + if (!ootPhotonT_.isUninitialized()) { + for (const std::string& outid : outOOTPhotonFloatValueMaps_) { + produces>(outid); } } - for (const std::string &outid : outGsfElectronFloatValueMaps_) { - produces< edm::ValueMap >(outid); + for (const std::string& outid : outGsfElectronFloatValueMaps_) { + produces>(outid); } } -ReducedEGProducer::~ReducedEGProducer() -{ -} - -void ReducedEGProducer::beginRun (edm::Run const& run, const edm::EventSetup & iSetup) -{ - hcalHitSel_.setup(iSetup); -} +ReducedEGProducer::~ReducedEGProducer() {} +void ReducedEGProducer::beginRun(edm::Run const& run, const edm::EventSetup& iSetup) { hcalHitSel_.setup(iSetup); } void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& theEventSetup) { - //get input collections - + edm::Handle photonHandle; theEvent.getByToken(photonT_, photonHandle); edm::Handle ootPhotonHandle; - if(!ootPhotonT_.isUninitialized())theEvent.getByToken(ootPhotonT_, ootPhotonHandle); + if (!ootPhotonT_.isUninitialized()) + theEvent.getByToken(ootPhotonT_, ootPhotonHandle); edm::Handle gsfElectronHandle; - theEvent.getByToken(gsfElectronT_, gsfElectronHandle); + theEvent.getByToken(gsfElectronT_, gsfElectronHandle); edm::Handle gsfTrackHandle; theEvent.getByToken(gsfTrackT_, gsfTrackHandle); - + edm::Handle conversionHandle; - theEvent.getByToken(conversionT_, conversionHandle); + theEvent.getByToken(conversionT_, conversionHandle); edm::Handle singleConversionHandle; - theEvent.getByToken(singleConversionT_, singleConversionHandle); - + theEvent.getByToken(singleConversionT_, singleConversionHandle); + edm::Handle barrelHitHandle; - theEvent.getByToken(barrelEcalHits_, barrelHitHandle); - + theEvent.getByToken(barrelEcalHits_, barrelHitHandle); + edm::Handle endcapHitHandle; theEvent.getByToken(endcapEcalHits_, endcapHitHandle); edm::Handle preshowerHitHandle; - if (doPreshowerEcalHits_) theEvent.getByToken(preshowerEcalHits_, preshowerHitHandle); - + if (doPreshowerEcalHits_) + theEvent.getByToken(preshowerEcalHits_, preshowerHitHandle); + edm::Handle hbheHitHandle; theEvent.getByToken(hbheHits_, hbheHitHandle); - edm::Handle > > photonPfCandMapHandle; - theEvent.getByToken(photonPfCandMapT_, photonPfCandMapHandle); + edm::Handle>> photonPfCandMapHandle; + theEvent.getByToken(photonPfCandMapT_, photonPfCandMapHandle); - edm::Handle > > gsfElectronPfCandMapHandle; - theEvent.getByToken(gsfElectronPfCandMapT_, gsfElectronPfCandMapHandle); + edm::Handle>> gsfElectronPfCandMapHandle; + theEvent.getByToken(gsfElectronPfCandMapT_, gsfElectronPfCandMapHandle); - std::vector > > photonIdHandles(photonIdTs_.size()); - int index = 0; // universal index for range based loops + std::vector>> photonIdHandles(photonIdTs_.size()); + int index = 0; // universal index for range based loops for (const auto& photonIdT : photonIdTs_) { - theEvent.getByToken(photonIdT,photonIdHandles[index++]); + theEvent.getByToken(photonIdT, photonIdHandles[index++]); } - - std::vector > > gsfElectronIdHandles(gsfElectronIdTs_.size()); + + std::vector>> gsfElectronIdHandles(gsfElectronIdTs_.size()); index = 0; for (const auto& gsfElectronIdT : gsfElectronIdTs_) { - theEvent.getByToken(gsfElectronIdT,gsfElectronIdHandles[index++]); - } - - std::vector > > photonFloatValueMapHandles(photonFloatValueMapTs_.size()); + theEvent.getByToken(gsfElectronIdT, gsfElectronIdHandles[index++]); + } + + std::vector>> photonFloatValueMapHandles(photonFloatValueMapTs_.size()); index = 0; for (const auto& photonFloatValueMapT : photonFloatValueMapTs_) { - theEvent.getByToken(photonFloatValueMapT,photonFloatValueMapHandles[index++]); - } + theEvent.getByToken(photonFloatValueMapT, photonFloatValueMapHandles[index++]); + } - std::vector > > ootPhotonFloatValueMapHandles(ootPhotonFloatValueMapTs_.size()); - if (!ootPhotonT_.isUninitialized()){ + std::vector>> ootPhotonFloatValueMapHandles(ootPhotonFloatValueMapTs_.size()); + if (!ootPhotonT_.isUninitialized()) { index = 0; for (const auto& ootPhotonFloatValueMapT : ootPhotonFloatValueMapTs_) { - theEvent.getByToken(ootPhotonFloatValueMapT,ootPhotonFloatValueMapHandles[index++]); - } + theEvent.getByToken(ootPhotonFloatValueMapT, ootPhotonFloatValueMapHandles[index++]); + } } - std::vector > > gsfElectronFloatValueMapHandles(gsfElectronFloatValueMapTs_.size()); + std::vector>> gsfElectronFloatValueMapHandles(gsfElectronFloatValueMapTs_.size()); index = 0; for (const auto& gsfElectronFloatValueMapT : gsfElectronFloatValueMapTs_) { - theEvent.getByToken(gsfElectronFloatValueMapT,gsfElectronFloatValueMapHandles[index++]); - } - - - edm::Handle > gsfElectronCalibEnergyHandle; - edm::Handle > gsfElectronCalibEnergyErrHandle; - edm::Handle > gsfElectronCalibEcalEnergyHandle; - edm::Handle > gsfElectronCalibEcalEnergyErrHandle; - if(applyGsfElectronCalibOnData_ || applyGsfElectronCalibOnMC_) { - theEvent.getByToken(gsfElectronCalibEnergyT_,gsfElectronCalibEnergyHandle); - theEvent.getByToken(gsfElectronCalibEnergyErrT_,gsfElectronCalibEnergyErrHandle); - theEvent.getByToken(gsfElectronCalibEcalEnergyT_,gsfElectronCalibEcalEnergyHandle); - theEvent.getByToken(gsfElectronCalibEcalEnergyErrT_,gsfElectronCalibEcalEnergyErrHandle); + theEvent.getByToken(gsfElectronFloatValueMapT, gsfElectronFloatValueMapHandles[index++]); + } + + edm::Handle> gsfElectronCalibEnergyHandle; + edm::Handle> gsfElectronCalibEnergyErrHandle; + edm::Handle> gsfElectronCalibEcalEnergyHandle; + edm::Handle> gsfElectronCalibEcalEnergyErrHandle; + if (applyGsfElectronCalibOnData_ || applyGsfElectronCalibOnMC_) { + theEvent.getByToken(gsfElectronCalibEnergyT_, gsfElectronCalibEnergyHandle); + theEvent.getByToken(gsfElectronCalibEnergyErrT_, gsfElectronCalibEnergyErrHandle); + theEvent.getByToken(gsfElectronCalibEcalEnergyT_, gsfElectronCalibEcalEnergyHandle); + theEvent.getByToken(gsfElectronCalibEcalEnergyErrT_, gsfElectronCalibEcalEnergyErrHandle); } - edm::Handle > photonCalibEnergyHandle; - edm::Handle > photonCalibEnergyErrHandle; - if(applyPhotonCalibOnData_ || applyPhotonCalibOnMC_){ - theEvent.getByToken(photonCalibEnergyT_,photonCalibEnergyHandle); - theEvent.getByToken(photonCalibEnergyErrT_,photonCalibEnergyErrHandle); + edm::Handle> photonCalibEnergyHandle; + edm::Handle> photonCalibEnergyErrHandle; + if (applyPhotonCalibOnData_ || applyPhotonCalibOnMC_) { + theEvent.getByToken(photonCalibEnergyT_, photonCalibEnergyHandle); + theEvent.getByToken(photonCalibEnergyErrT_, photonCalibEnergyErrHandle); } edm::ESHandle theCaloTopology; - theEventSetup.get().get(theCaloTopology); - const CaloTopology *caloTopology = & (*theCaloTopology); + theEventSetup.get().get(theCaloTopology); + const CaloTopology* caloTopology = &(*theCaloTopology); //initialize output collections auto photons = std::make_unique(); @@ -331,43 +327,41 @@ void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& the std::map ootEsClusterMap; std::unordered_set rechitMap; std::unordered_set hcalRechitMap; - + std::unordered_set superClusterFullRelinkMap; std::unordered_set ootSuperClusterFullRelinkMap; - + //vectors for pfcandidate valuemaps - std::vector > pfCandIsoPairVecPho; - std::vector > pfCandIsoPairVecEle; - + std::vector> pfCandIsoPairVecPho; + std::vector> pfCandIsoPairVecEle; + //vectors for id valuemaps - std::vector > photonIdVals(photonIdHandles.size()); - std::vector > gsfElectronIdVals(gsfElectronIdHandles.size()); - std::vector > photonFloatValueMapVals(photonFloatValueMapHandles.size()); - std::vector > ootPhotonFloatValueMapVals(ootPhotonFloatValueMapHandles.size()); - std::vector > gsfElectronFloatValueMapVals(gsfElectronFloatValueMapHandles.size()); - + std::vector> photonIdVals(photonIdHandles.size()); + std::vector> gsfElectronIdVals(gsfElectronIdHandles.size()); + std::vector> photonFloatValueMapVals(photonFloatValueMapHandles.size()); + std::vector> ootPhotonFloatValueMapVals(ootPhotonFloatValueMapHandles.size()); + std::vector> gsfElectronFloatValueMapVals(gsfElectronFloatValueMapHandles.size()); + //loop over photons and fill maps index = -1; for (const auto& photon : *photonHandle) { index++; - reco::PhotonRef photonref(photonHandle,index); + reco::PhotonRef photonref(photonHandle, index); photons->push_back(photon); auto& newPhoton = photons->back(); - - if( (applyPhotonCalibOnData_ && theEvent.isRealData()) || - (applyPhotonCalibOnMC_ && !theEvent.isRealData()) ){ - calibratePhoton(newPhoton,photonref, - *photonCalibEnergyHandle,*photonCalibEnergyErrHandle); + + if ((applyPhotonCalibOnData_ && theEvent.isRealData()) || (applyPhotonCalibOnMC_ && !theEvent.isRealData())) { + calibratePhoton(newPhoton, photonref, *photonCalibEnergyHandle, *photonCalibEnergyErrHandle); } - + //we do this after calibration bool keep = keepPhotonSel_(newPhoton); - if (!keep){ + if (!keep) { photons->pop_back(); continue; - } - + } + //fill pf candidate value map vector pfCandIsoPairVecPho.push_back((*photonPfCandMapHandle)[photonref]); @@ -375,79 +369,81 @@ void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& the int subindex = 0; for (const auto& photonIdHandle : photonIdHandles) { photonIdVals[subindex++].push_back((*photonIdHandle)[photonref]); - } + } subindex = 0; for (const auto& photonFloatValueMapHandle : photonFloatValueMapHandles) { photonFloatValueMapVals[subindex++].push_back((*photonFloatValueMapHandle)[photonref]); - } - + } + //link photon core - const reco::PhotonCoreRef &photonCore = photon.photonCore(); + const reco::PhotonCoreRef& photonCore = photon.photonCore(); linkCore(photonCore, *photonCores, photonCoreMap); - + bool slimRelink = slimRelinkPhotonSel_(newPhoton); //no supercluster relinking unless slimRelink selection is satisfied - if (!slimRelink) continue; - + if (!slimRelink) + continue; + bool relink = relinkPhotonSel_(newPhoton); - + //link supercluster - const reco::SuperClusterRef &superCluster = photon.superCluster(); + const reco::SuperClusterRef& superCluster = photon.superCluster(); linkSuperCluster(superCluster, superClusterMap, *superClusters, relink, superClusterFullRelinkMap); - + //conversions only for full relinking - if (!relink) continue; - - const reco::ConversionRefVector &convrefs = photon.conversions(); + if (!relink) + continue; + + const reco::ConversionRefVector& convrefs = photon.conversions(); linkConversions(convrefs, *conversions, conversionMap); //explicitly references conversions - const reco::ConversionRefVector &singleconvrefs = photon.conversionsOneLeg(); + const reco::ConversionRefVector& singleconvrefs = photon.conversionsOneLeg(); linkConversions(singleconvrefs, *singleConversions, singleConversionMap); //hcal hits - linkHcalHits(*photon.superCluster(),*hbheHitHandle,hcalRechitMap); - + linkHcalHits(*photon.superCluster(), *hbheHitHandle, hcalRechitMap); } //loop over oot photons and fill maps //special note1: since not PFCand --> no PF isolation, IDs (but we do have FloatValueMap!) //special note2: conversion sequence not run over bcs from oot phos, so skip relinking of oot phos //special note3: clusters and superclusters in own collections! - if(!ootPhotonT_.isUninitialized()) { + if (!ootPhotonT_.isUninitialized()) { index = -1; for (const auto& ootPhoton : *ootPhotonHandle) { index++; - + bool keep = keepOOTPhotonSel_(ootPhoton); - if (!keep) continue; + if (!keep) + continue; + + reco::PhotonRef ootPhotonref(ootPhotonHandle, index); - reco::PhotonRef ootPhotonref(ootPhotonHandle,index); - ootPhotons->push_back(ootPhoton); - + //fill photon pfclusteriso valuemap vectors int subindex = 0; for (const auto& ootPhotonFloatValueMapHandle : ootPhotonFloatValueMapHandles) { - ootPhotonFloatValueMapVals[subindex++].push_back((*ootPhotonFloatValueMapHandle)[ootPhotonref]); - } - + ootPhotonFloatValueMapVals[subindex++].push_back((*ootPhotonFloatValueMapHandle)[ootPhotonref]); + } + //link photon core - const reco::PhotonCoreRef &ootPhotonCore = ootPhoton.photonCore(); + const reco::PhotonCoreRef& ootPhotonCore = ootPhoton.photonCore(); linkCore(ootPhotonCore, *ootPhotonCores, ootPhotonCoreMap); - + bool slimRelink = slimRelinkOOTPhotonSel_(ootPhoton); //no supercluster relinking unless slimRelink selection is satisfied - if (!slimRelink) continue; - + if (!slimRelink) + continue; + bool relink = relinkOOTPhotonSel_(ootPhoton); - - const reco::SuperClusterRef &ootSuperCluster = ootPhoton.superCluster(); + + const reco::SuperClusterRef& ootSuperCluster = ootPhoton.superCluster(); linkSuperCluster(ootSuperCluster, ootSuperClusterMap, *ootSuperClusters, relink, ootSuperClusterFullRelinkMap); //hcal hits - linkHcalHits(*ootPhoton.superCluster(),*hbheHitHandle,hcalRechitMap); - + linkHcalHits(*ootPhoton.superCluster(), *hbheHitHandle, hcalRechitMap); } } @@ -456,174 +452,196 @@ void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& the for (const auto& gsfElectron : *gsfElectronHandle) { index++; - reco::GsfElectronRef gsfElectronref(gsfElectronHandle,index); + reco::GsfElectronRef gsfElectronref(gsfElectronHandle, index); gsfElectrons->push_back(gsfElectron); auto& newGsfElectron = gsfElectrons->back(); - if( (applyGsfElectronCalibOnData_ && theEvent.isRealData()) || - (applyGsfElectronCalibOnMC_ && !theEvent.isRealData()) ){ - calibrateElectron(newGsfElectron, gsfElectronref, - *gsfElectronCalibEnergyHandle,*gsfElectronCalibEnergyErrHandle, - *gsfElectronCalibEcalEnergyHandle,*gsfElectronCalibEcalEnergyErrHandle); - + if ((applyGsfElectronCalibOnData_ && theEvent.isRealData()) || + (applyGsfElectronCalibOnMC_ && !theEvent.isRealData())) { + calibrateElectron(newGsfElectron, + gsfElectronref, + *gsfElectronCalibEnergyHandle, + *gsfElectronCalibEnergyErrHandle, + *gsfElectronCalibEcalEnergyHandle, + *gsfElectronCalibEcalEnergyErrHandle); } - - bool keep = keepGsfElectronSel_(newGsfElectron); + + bool keep = keepGsfElectronSel_(newGsfElectron); if (!keep) { gsfElectrons->pop_back(); continue; - } - + } + pfCandIsoPairVecEle.push_back((*gsfElectronPfCandMapHandle)[gsfElectronref]); - + //fill electron id valuemap vectors int subindex = 0; for (const auto& gsfElectronIdHandle : gsfElectronIdHandles) { gsfElectronIdVals[subindex++].push_back((*gsfElectronIdHandle)[gsfElectronref]); - } + } subindex = 0; for (const auto& gsfElectronFloatValueMapHandle : gsfElectronFloatValueMapHandles) { gsfElectronFloatValueMapVals[subindex++].push_back((*gsfElectronFloatValueMapHandle)[gsfElectronref]); - } + } - const reco::GsfElectronCoreRef &gsfElectronCore = gsfElectron.core(); + const reco::GsfElectronCoreRef& gsfElectronCore = gsfElectron.core(); linkCore(gsfElectronCore, *gsfElectronCores, gsfElectronCoreMap); - const reco::GsfTrackRef &gsfTrack = gsfElectron.gsfTrack(); - + const reco::GsfTrackRef& gsfTrack = gsfElectron.gsfTrack(); + // Save the main gsfTrack if (!gsfTrackMap.count(gsfTrack)) { gsfTracks->push_back(*gsfTrack); gsfTrackMap[gsfTrack] = gsfTracks->size() - 1; } - + // Save additional ambiguous gsf tracks in a map: - for (reco::GsfTrackRefVector::const_iterator igsf = gsfElectron.ambiguousGsfTracksBegin(); igsf != gsfElectron.ambiguousGsfTracksEnd(); ++igsf) { - const reco::GsfTrackRef &ambigGsfTrack = *igsf; + for (reco::GsfTrackRefVector::const_iterator igsf = gsfElectron.ambiguousGsfTracksBegin(); + igsf != gsfElectron.ambiguousGsfTracksEnd(); + ++igsf) { + const reco::GsfTrackRef& ambigGsfTrack = *igsf; if (!gsfTrackMap.count(ambigGsfTrack)) { - gsfTracks->push_back(*ambigGsfTrack); - gsfTrackMap[ambigGsfTrack] = gsfTracks->size() - 1; + gsfTracks->push_back(*ambigGsfTrack); + gsfTrackMap[ambigGsfTrack] = gsfTracks->size() - 1; } } - + bool slimRelink = slimRelinkGsfElectronSel_(newGsfElectron); //no supercluster relinking unless slimRelink selection is satisfied - if (!slimRelink) continue; - + if (!slimRelink) + continue; + bool relink = relinkGsfElectronSel_(newGsfElectron); - - const reco::SuperClusterRef &superCluster = gsfElectron.superCluster(); - linkSuperCluster(superCluster, superClusterMap, *superClusters, relink, superClusterFullRelinkMap); + + const reco::SuperClusterRef& superCluster = gsfElectron.superCluster(); + linkSuperCluster(superCluster, superClusterMap, *superClusters, relink, superClusterFullRelinkMap); //conversions only for full relinking - if (!relink) continue; - - const reco::ConversionRefVector &convrefs = gsfElectron.core()->conversions(); + if (!relink) + continue; + + const reco::ConversionRefVector& convrefs = gsfElectron.core()->conversions(); linkConversions(convrefs, *conversions, conversionMap); - + //explicitly references conversions - const reco::ConversionRefVector &singleconvrefs = gsfElectron.core()->conversionsOneLeg(); + const reco::ConversionRefVector& singleconvrefs = gsfElectron.core()->conversionsOneLeg(); linkConversions(singleconvrefs, *singleConversions, singleConversionMap); //conversions matched by trackrefs linkConversionsByTrackRef(conversionHandle, gsfElectron, *conversions, conversionMap); - + //single leg conversions matched by trackrefs linkConversionsByTrackRef(singleConversionHandle, gsfElectron, *singleConversions, singleConversionMap); //hcal hits - linkHcalHits(*gsfElectron.superCluster(),*hbheHitHandle,hcalRechitMap); - + linkHcalHits(*gsfElectron.superCluster(), *hbheHitHandle, hcalRechitMap); } //loop over output SuperClusters and fill maps index = 0; for (auto& superCluster : *superClusters) { - //link seed cluster no matter what - const reco::CaloClusterPtr &seedCluster = superCluster.seed(); + const reco::CaloClusterPtr& seedCluster = superCluster.seed(); linkCaloCluster(seedCluster, *ebeeClusters, ebeeClusterMap); - + //only proceed if superCluster is marked for full relinking bool fullrelink = superClusterFullRelinkMap.count(index++); if (!fullrelink) { //zero detid vector which is anyways not useful without stored rechits superCluster.clearHitsAndFractions(); - continue; + continue; } - + // link calo clusters - linkCaloClusters(superCluster, *ebeeClusters, ebeeClusterMap, rechitMap, barrelHitHandle, endcapHitHandle, caloTopology, *esClusters, esClusterMap); - + linkCaloClusters(superCluster, + *ebeeClusters, + ebeeClusterMap, + rechitMap, + barrelHitHandle, + endcapHitHandle, + caloTopology, + *esClusters, + esClusterMap); + //conversions matched geometrically linkConversionsByTrackRef(conversionHandle, superCluster, *conversions, conversionMap); - + //single leg conversions matched by trackrefs - linkConversionsByTrackRef(singleConversionHandle, superCluster, *singleConversions, singleConversionMap); + linkConversionsByTrackRef(singleConversionHandle, superCluster, *singleConversions, singleConversionMap); } //loop over output OOTSuperClusters and fill maps - if(!ootPhotonT_.isUninitialized()) { + if (!ootPhotonT_.isUninitialized()) { index = 0; for (auto& ootSuperCluster : *ootSuperClusters) { - //link seed cluster no matter what - const reco::CaloClusterPtr &ootSeedCluster = ootSuperCluster.seed(); + const reco::CaloClusterPtr& ootSeedCluster = ootSuperCluster.seed(); linkCaloCluster(ootSeedCluster, *ootEbeeClusters, ootEbeeClusterMap); - + //only proceed if ootSuperCluster is marked for full relinking bool fullrelink = ootSuperClusterFullRelinkMap.count(index++); if (!fullrelink) { - //zero detid vector which is anyways not useful without stored rechits - ootSuperCluster.clearHitsAndFractions(); - continue; + //zero detid vector which is anyways not useful without stored rechits + ootSuperCluster.clearHitsAndFractions(); + continue; } - + // link calo clusters - linkCaloClusters(ootSuperCluster, *ootEbeeClusters, ootEbeeClusterMap, rechitMap, barrelHitHandle, endcapHitHandle, caloTopology, *ootEsClusters, ootEsClusterMap); + linkCaloClusters(ootSuperCluster, + *ootEbeeClusters, + ootEbeeClusterMap, + rechitMap, + barrelHitHandle, + endcapHitHandle, + caloTopology, + *ootEsClusters, + ootEsClusterMap); } } //now finalize and add to the event collections in "reverse" order - + //rechits (fill output collections of rechits to be stored) - for (const EcalRecHit &rechit : *barrelHitHandle) { + for (const EcalRecHit& rechit : *barrelHitHandle) { if (rechitMap.count(rechit.detid())) { ebRecHits->push_back(rechit); } } - - for (const EcalRecHit &rechit : *endcapHitHandle) { + + for (const EcalRecHit& rechit : *endcapHitHandle) { if (rechitMap.count(rechit.detid())) { eeRecHits->push_back(rechit); } } - theEvent.put(std::move(ebRecHits),outEBRecHits_); - theEvent.put(std::move(eeRecHits),outEERecHits_); + theEvent.put(std::move(ebRecHits), outEBRecHits_); + theEvent.put(std::move(eeRecHits), outEERecHits_); - if (doPreshowerEcalHits_) { - for (const EcalRecHit &rechit : *preshowerHitHandle) { + if (doPreshowerEcalHits_) { + for (const EcalRecHit& rechit : *preshowerHitHandle) { if (rechitMap.count(rechit.detid())) { - esRecHits->push_back(rechit); + esRecHits->push_back(rechit); } } - theEvent.put(std::move(esRecHits),outESRecHits_); + theEvent.put(std::move(esRecHits), outESRecHits_); } - - for (const HBHERecHit &rechit : *hbheHitHandle) { + + for (const HBHERecHit& rechit : *hbheHitHandle) { if (hcalRechitMap.count(rechit.detid())) { hbheRecHits->push_back(rechit); } } - theEvent.put(std::move(hbheRecHits),outHBHERecHits_); + theEvent.put(std::move(hbheRecHits), outHBHERecHits_); //CaloClusters //put calocluster output collections in event and get orphan handles to create ptrs - const edm::OrphanHandle &outEBEEClusterHandle = theEvent.put(std::move(ebeeClusters),outEBEEClusters_); - const edm::OrphanHandle &outESClusterHandle = theEvent.put(std::move(esClusters),outESClusters_);; + const edm::OrphanHandle& outEBEEClusterHandle = + theEvent.put(std::move(ebeeClusters), outEBEEClusters_); + const edm::OrphanHandle& outESClusterHandle = + theEvent.put(std::move(esClusters), outESClusters_); + ; //Loop over SuperClusters and relink GEDPhoton + GSFElectron CaloClusters - for (reco::SuperCluster &superCluster : *superClusters) { + for (reco::SuperCluster& superCluster : *superClusters) { relinkCaloClusters(superCluster, ebeeClusterMap, esClusterMap, outEBEEClusterHandle, outESClusterHandle); } @@ -632,121 +650,132 @@ void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& the edm::OrphanHandle outOOTEBEEClusterHandle; edm::OrphanHandle outOOTESClusterHandle; //Loop over OOTSuperClusters and relink OOTPhoton CaloClusters - if(!ootPhotonT_.isUninitialized()) { - outOOTEBEEClusterHandle = theEvent.put(std::move(ootEbeeClusters),outOOTEBEEClusters_); - outOOTESClusterHandle = theEvent.put(std::move(ootEsClusters),outOOTESClusters_); - for (reco::SuperCluster &ootSuperCluster : *ootSuperClusters) { - relinkCaloClusters(ootSuperCluster, ootEbeeClusterMap, ootEsClusterMap, outOOTEBEEClusterHandle, outOOTESClusterHandle); + if (!ootPhotonT_.isUninitialized()) { + outOOTEBEEClusterHandle = theEvent.put(std::move(ootEbeeClusters), outOOTEBEEClusters_); + outOOTESClusterHandle = theEvent.put(std::move(ootEsClusters), outOOTESClusters_); + for (reco::SuperCluster& ootSuperCluster : *ootSuperClusters) { + relinkCaloClusters( + ootSuperCluster, ootEbeeClusterMap, ootEsClusterMap, outOOTEBEEClusterHandle, outOOTESClusterHandle); } } //put superclusters and conversions in the event - const edm::OrphanHandle &outSuperClusterHandle = theEvent.put(std::move(superClusters),outSuperClusters_); - const edm::OrphanHandle &outConversionHandle = theEvent.put(std::move(conversions),outConversions_); - const edm::OrphanHandle &outSingleConversionHandle = theEvent.put(std::move(singleConversions),outSingleConversions_); - const edm::OrphanHandle &outGsfTrackHandle = theEvent.put(std::move(gsfTracks),outGsfTracks_); + const edm::OrphanHandle& outSuperClusterHandle = + theEvent.put(std::move(superClusters), outSuperClusters_); + const edm::OrphanHandle& outConversionHandle = + theEvent.put(std::move(conversions), outConversions_); + const edm::OrphanHandle& outSingleConversionHandle = + theEvent.put(std::move(singleConversions), outSingleConversions_); + const edm::OrphanHandle& outGsfTrackHandle = + theEvent.put(std::move(gsfTracks), outGsfTracks_); //Loop over PhotonCores and relink GEDPhoton SuperClusters (and conversions) - for (reco::PhotonCore &photonCore : *photonCores) { + for (reco::PhotonCore& photonCore : *photonCores) { // superclusters relinkSuperCluster(photonCore, superClusterMap, outSuperClusterHandle); //conversions - const reco::ConversionRefVector &convrefs = photonCore.conversions(); + const reco::ConversionRefVector& convrefs = photonCore.conversions(); relinkConversions(photonCore, convrefs, conversionMap, outConversionHandle); //single leg conversions - const reco::ConversionRefVector &singleconvrefs = photonCore.conversionsOneLeg(); + const reco::ConversionRefVector& singleconvrefs = photonCore.conversionsOneLeg(); relinkConversions(photonCore, singleconvrefs, singleConversionMap, outSingleConversionHandle); } //Relink GSFElectron SuperClusters and main GSF Tracks - for (reco::GsfElectronCore &gsfElectronCore : *gsfElectronCores) { + for (reco::GsfElectronCore& gsfElectronCore : *gsfElectronCores) { relinkSuperCluster(gsfElectronCore, superClusterMap, outSuperClusterHandle); relinkGsfTrack(gsfElectronCore, gsfTrackMap, outGsfTrackHandle); } //put ootsuperclusters in the event edm::OrphanHandle outOOTSuperClusterHandle; - if(!ootPhotonT_.isUninitialized()) outOOTSuperClusterHandle = theEvent.put(std::move(ootSuperClusters),outOOTSuperClusters_); - + if (!ootPhotonT_.isUninitialized()) + outOOTSuperClusterHandle = theEvent.put(std::move(ootSuperClusters), outOOTSuperClusters_); + //Relink OOTPhoton SuperClusters - for (reco::PhotonCore &ootPhotonCore : *ootPhotonCores) { + for (reco::PhotonCore& ootPhotonCore : *ootPhotonCores) { relinkSuperCluster(ootPhotonCore, ootSuperClusterMap, outOOTSuperClusterHandle); } //put photoncores and gsfelectroncores into the event - const edm::OrphanHandle &outPhotonCoreHandle = theEvent.put(std::move(photonCores),outPhotonCores_); + const edm::OrphanHandle& outPhotonCoreHandle = + theEvent.put(std::move(photonCores), outPhotonCores_); edm::OrphanHandle outOOTPhotonCoreHandle; - if(!ootPhotonT_.isUninitialized()) outOOTPhotonCoreHandle = theEvent.put(std::move(ootPhotonCores),outOOTPhotonCores_); - const edm::OrphanHandle &outgsfElectronCoreHandle = theEvent.put(std::move(gsfElectronCores),outGsfElectronCores_); + if (!ootPhotonT_.isUninitialized()) + outOOTPhotonCoreHandle = theEvent.put(std::move(ootPhotonCores), outOOTPhotonCores_); + const edm::OrphanHandle& outgsfElectronCoreHandle = + theEvent.put(std::move(gsfElectronCores), outGsfElectronCores_); //loop over photons, oot photons, and electrons and relink the cores - for (reco::Photon &photon : *photons) { + for (reco::Photon& photon : *photons) { relinkPhotonCore(photon, photonCoreMap, outPhotonCoreHandle); } - if(!ootPhotonT_.isUninitialized()) { - for (reco::Photon &ootPhoton : *ootPhotons) { + if (!ootPhotonT_.isUninitialized()) { + for (reco::Photon& ootPhoton : *ootPhotons) { relinkPhotonCore(ootPhoton, ootPhotonCoreMap, outOOTPhotonCoreHandle); } } - for (reco::GsfElectron &gsfElectron : *gsfElectrons) { + for (reco::GsfElectron& gsfElectron : *gsfElectrons) { relinkGsfElectronCore(gsfElectron, gsfElectronCoreMap, outgsfElectronCoreHandle); // ----- // Also in this loop let's relink ambiguous tracks std::vector ambigTracksInThisElectron; // Here we loop over the ambiguous tracks and save them in a vector - for (reco::GsfTrackRefVector::const_iterator igsf = gsfElectron.ambiguousGsfTracksBegin(); igsf != gsfElectron.ambiguousGsfTracksEnd(); ++igsf) { + for (reco::GsfTrackRefVector::const_iterator igsf = gsfElectron.ambiguousGsfTracksBegin(); + igsf != gsfElectron.ambiguousGsfTracksEnd(); + ++igsf) { ambigTracksInThisElectron.push_back(*igsf); } - + // Now we need to clear them (they are the refs to original collection): gsfElectron.clearAmbiguousGsfTracks(); - + // And here we add them back, now from a new reduced collection: - for (const auto &it : ambigTracksInThisElectron) { - const auto &gsftkmapped = gsfTrackMap.find(it); - + for (const auto& it : ambigTracksInThisElectron) { + const auto& gsftkmapped = gsfTrackMap.find(it); + if (gsftkmapped != gsfTrackMap.end()) { - reco::GsfTrackRef gsftkref(outGsfTrackHandle, gsftkmapped->second); - gsfElectron.addAmbiguousGsfTrack(gsftkref); - } - else - throw cms::Exception("There must be a problem with linking and mapping of ambiguous gsf tracks..."); + reco::GsfTrackRef gsftkref(outGsfTrackHandle, gsftkmapped->second); + gsfElectron.addAmbiguousGsfTrack(gsftkref); + } else + throw cms::Exception("There must be a problem with linking and mapping of ambiguous gsf tracks..."); } - + if (gsfElectron.ambiguousGsfTracksSize() > 0) - gsfElectron.setAmbiguous(true); // Set the flag + gsfElectron.setAmbiguous(true); // Set the flag ambigTracksInThisElectron.clear(); - } //(finally) store the output photon and electron collections - const edm::OrphanHandle &outPhotonHandle = theEvent.put(std::move(photons),outPhotons_); + const edm::OrphanHandle& outPhotonHandle = theEvent.put(std::move(photons), outPhotons_); edm::OrphanHandle outOOTPhotonHandle; - if(!ootPhotonT_.isUninitialized()) outOOTPhotonHandle = theEvent.put(std::move(ootPhotons),outOOTPhotons_); - const edm::OrphanHandle &outGsfElectronHandle = theEvent.put(std::move(gsfElectrons),outGsfElectrons_); - + if (!ootPhotonT_.isUninitialized()) + outOOTPhotonHandle = theEvent.put(std::move(ootPhotons), outOOTPhotons_); + const edm::OrphanHandle& outGsfElectronHandle = + theEvent.put(std::move(gsfElectrons), outGsfElectrons_); + //still need to output relinked valuemaps - + //photon pfcand isolation valuemap edm::ValueMap>::Filler fillerPhotons(*photonPfCandMap); - fillerPhotons.insert(outPhotonHandle,pfCandIsoPairVecPho.begin(),pfCandIsoPairVecPho.end()); - fillerPhotons.fill(); - + fillerPhotons.insert(outPhotonHandle, pfCandIsoPairVecPho.begin(), pfCandIsoPairVecPho.end()); + fillerPhotons.fill(); + //electron pfcand isolation valuemap edm::ValueMap>::Filler fillerGsfElectrons(*gsfElectronPfCandMap); - fillerGsfElectrons.insert(outGsfElectronHandle,pfCandIsoPairVecEle.begin(),pfCandIsoPairVecEle.end()); + fillerGsfElectrons.insert(outGsfElectronHandle, pfCandIsoPairVecEle.begin(), pfCandIsoPairVecEle.end()); fillerGsfElectrons.fill(); - - theEvent.put(std::move(photonPfCandMap),outPhotonPfCandMap_); - theEvent.put(std::move(gsfElectronPfCandMap),outGsfElectronPfCandMap_); - - auto fillMap = [](auto refH, auto& vec, edm::Event& ev, const std::string& cAl = ""){ - typedef edm::ValueMap::type::value_type> MapType; + + theEvent.put(std::move(photonPfCandMap), outPhotonPfCandMap_); + theEvent.put(std::move(gsfElectronPfCandMap), outGsfElectronPfCandMap_); + + auto fillMap = [](auto refH, auto& vec, edm::Event& ev, const std::string& cAl = "") { + typedef edm::ValueMap::type::value_type> MapType; auto oMap = std::make_unique(); { typename MapType::Filler filler(*oMap); @@ -758,142 +787,134 @@ void ReducedEGProducer::produce(edm::Event& theEvent, const edm::EventSetup& the //photon id value maps index = 0; - for (auto const& vals : photonIdVals){ + for (auto const& vals : photonIdVals) { fillMap(outPhotonHandle, vals, theEvent, outPhotonIds_[index++]); } //electron id value maps index = 0; - for (auto const& vals : gsfElectronIdVals){ + for (auto const& vals : gsfElectronIdVals) { fillMap(outGsfElectronHandle, vals, theEvent, outGsfElectronIds_[index++]); } - + // photon iso value maps index = 0; - for (auto const& vals : photonFloatValueMapVals){ + for (auto const& vals : photonFloatValueMapVals) { fillMap(outPhotonHandle, vals, theEvent, outPhotonFloatValueMaps_[index++]); } - if(!ootPhotonT_.isUninitialized()) { + if (!ootPhotonT_.isUninitialized()) { //oot photon iso value maps index = 0; - for (auto const& vals : ootPhotonFloatValueMapVals){ + for (auto const& vals : ootPhotonFloatValueMapVals) { fillMap(outOOTPhotonHandle, vals, theEvent, outOOTPhotonFloatValueMaps_[index++]); } } //electron iso value maps index = 0; - for (auto const& vals : gsfElectronFloatValueMapVals){ + for (auto const& vals : gsfElectronFloatValueMapVals) { fillMap(outGsfElectronHandle, vals, theEvent, outGsfElectronFloatValueMaps_[index++]); } } template -void ReducedEGProducer::linkCore(const T& core, U& cores, std::map& coreMap) -{ +void ReducedEGProducer::linkCore(const T& core, U& cores, std::map& coreMap) { if (!coreMap.count(core)) { cores.push_back(*core); coreMap[core] = cores.size() - 1; } } - -void ReducedEGProducer::linkSuperCluster(const reco::SuperClusterRef& superCluster, - std::map& superClusterMap, - reco::SuperClusterCollection& superClusters, - const bool relink, - std::unordered_set& superClusterFullRelinkMap) -{ - const auto &mappedsc = superClusterMap.find(superCluster); + +void ReducedEGProducer::linkSuperCluster(const reco::SuperClusterRef& superCluster, + std::map& superClusterMap, + reco::SuperClusterCollection& superClusters, + const bool relink, + std::unordered_set& superClusterFullRelinkMap) { + const auto& mappedsc = superClusterMap.find(superCluster); //get index in output collection in order to keep track whether superCluster //will be subject to full relinking unsigned int mappedscidx = 0; - if (mappedsc==superClusterMap.end()) { + if (mappedsc == superClusterMap.end()) { superClusters.push_back(*superCluster); mappedscidx = superClusters.size() - 1; superClusterMap[superCluster] = mappedscidx; - } - else { + } else { mappedscidx = mappedsc->second; } //additionally mark supercluster for full relinking - if (relink) superClusterFullRelinkMap.insert(mappedscidx); + if (relink) + superClusterFullRelinkMap.insert(mappedscidx); } void ReducedEGProducer::linkConversions(const reco::ConversionRefVector& convrefs, - reco::ConversionCollection& conversions, - std::map& conversionMap) -{ + reco::ConversionCollection& conversions, + std::map& conversionMap) { for (const auto& convref : convrefs) { linkConversion(convref, conversions, conversionMap); } } void ReducedEGProducer::linkConversionsByTrackRef(const edm::Handle& conversionHandle, - const reco::GsfElectron& gsfElectron, - reco::ConversionCollection& conversions, - std::map& conversionMap) -{ + const reco::GsfElectron& gsfElectron, + reco::ConversionCollection& conversions, + std::map& conversionMap) { int index = 0; for (const auto& conversion : *conversionHandle) { + reco::ConversionRef convref(conversionHandle, index++); + + bool matched = ConversionTools::matchesConversion(gsfElectron, conversion, true, true); + if (!matched) + continue; - reco::ConversionRef convref(conversionHandle,index++); - - bool matched = ConversionTools::matchesConversion(gsfElectron,conversion,true,true); - if (!matched) continue; - linkConversion(convref, conversions, conversionMap); } } void ReducedEGProducer::linkConversionsByTrackRef(const edm::Handle& conversionHandle, - const reco::SuperCluster& superCluster, - reco::ConversionCollection& conversions, - std::map& conversionMap) -{ + const reco::SuperCluster& superCluster, + reco::ConversionCollection& conversions, + std::map& conversionMap) { int index = 0; for (const auto& conversion : *conversionHandle) { + reco::ConversionRef convref(conversionHandle, index++); + + bool matched = ConversionTools::matchesConversion(superCluster, conversion, 0.2); + if (!matched) + continue; - reco::ConversionRef convref(conversionHandle,index++); - - bool matched = ConversionTools::matchesConversion(superCluster,conversion,0.2); - if (!matched) continue; - linkConversion(convref, conversions, conversionMap); } } void ReducedEGProducer::linkConversion(const reco::ConversionRef& convref, - reco::ConversionCollection& conversions, - std::map& conversionMap) -{ + reco::ConversionCollection& conversions, + std::map& conversionMap) { if (!conversionMap.count(convref)) { conversions.push_back(*convref); conversionMap[convref] = conversions.size() - 1; } } -void ReducedEGProducer::linkCaloCluster(const reco::CaloClusterPtr& caloCluster, - reco::CaloClusterCollection& caloClusters, - std::map& caloClusterMap) -{ +void ReducedEGProducer::linkCaloCluster(const reco::CaloClusterPtr& caloCluster, + reco::CaloClusterCollection& caloClusters, + std::map& caloClusterMap) { if (!caloClusterMap.count(caloCluster)) { caloClusters.push_back(*caloCluster); caloClusterMap[caloCluster] = caloClusters.size() - 1; } } -void ReducedEGProducer::linkCaloClusters(const reco::SuperCluster& superCluster, - reco::CaloClusterCollection& ebeeClusters, - std::map& ebeeClusterMap, - std::unordered_set& rechitMap, - const edm::Handle& barrelHitHandle, - const edm::Handle& endcapHitHandle, - const CaloTopology *caloTopology, - reco::CaloClusterCollection& esClusters, - std::map& esClusterMap) -{ +void ReducedEGProducer::linkCaloClusters(const reco::SuperCluster& superCluster, + reco::CaloClusterCollection& ebeeClusters, + std::map& ebeeClusterMap, + std::unordered_set& rechitMap, + const edm::Handle& barrelHitHandle, + const edm::Handle& endcapHitHandle, + const CaloTopology* caloTopology, + reco::CaloClusterCollection& esClusters, + std::map& esClusterMap) { for (const auto& cluster : superCluster.clusters()) { linkCaloCluster(cluster, ebeeClusters, ebeeClusterMap); @@ -901,11 +922,12 @@ void ReducedEGProducer::linkCaloClusters(const reco::SuperCluster& superCluster, rechitMap.insert(hitfrac.first); } //make sure to also take all hits in the 5x5 around the max energy xtal - bool barrel = cluster->hitsAndFractions().front().first.subdetId()==EcalBarrel; - const EcalRecHitCollection *rhcol = barrel ? barrelHitHandle.product() : endcapHitHandle.product(); + bool barrel = cluster->hitsAndFractions().front().first.subdetId() == EcalBarrel; + const EcalRecHitCollection* rhcol = barrel ? barrelHitHandle.product() : endcapHitHandle.product(); DetId seed = EcalClusterTools::getMaximum(*cluster, rhcol).first; - - std::vector dets5x5 = caloTopology->getSubdetectorTopology(DetId::Ecal, barrel ? EcalBarrel : EcalEndcap)->getWindow(seed,5,5); + + std::vector dets5x5 = + caloTopology->getSubdetectorTopology(DetId::Ecal, barrel ? EcalBarrel : EcalEndcap)->getWindow(seed, 5, 5); for (const auto& detid : dets5x5) { rechitMap.insert(detid); } @@ -915,41 +937,38 @@ void ReducedEGProducer::linkCaloClusters(const reco::SuperCluster& superCluster, for (const auto& hitfrac : cluster->hitsAndFractions()) { rechitMap.insert(hitfrac.first); - } + } } } void ReducedEGProducer::linkHcalHits(const reco::SuperCluster& superClus, - const HBHERecHitCollection& recHits, - std::unordered_set& hcalDetIds) -{ - hcalHitSel_.addDetIds(superClus,recHits,hcalDetIds); + const HBHERecHitCollection& recHits, + std::unordered_set& hcalDetIds) { + hcalHitSel_.addDetIds(superClus, recHits, hcalDetIds); } -void ReducedEGProducer::relinkCaloClusters(reco::SuperCluster& superCluster, - const std::map& ebeeClusterMap, - const std::map& esClusterMap, - const edm::OrphanHandle& outEBEEClusterHandle, - const edm::OrphanHandle& outESClusterHandle) -{ +void ReducedEGProducer::relinkCaloClusters(reco::SuperCluster& superCluster, + const std::map& ebeeClusterMap, + const std::map& esClusterMap, + const edm::OrphanHandle& outEBEEClusterHandle, + const edm::OrphanHandle& outESClusterHandle) { //remap seed cluster - const auto &seedmapped = ebeeClusterMap.find(superCluster.seed()); + const auto& seedmapped = ebeeClusterMap.find(superCluster.seed()); if (seedmapped != ebeeClusterMap.end()) { //make new ptr - reco::CaloClusterPtr clusptr(outEBEEClusterHandle,seedmapped->second); + reco::CaloClusterPtr clusptr(outEBEEClusterHandle, seedmapped->second); superCluster.setSeed(clusptr); } - //remap all clusters + //remap all clusters reco::CaloClusterPtrVector clusters; - for (const auto &cluster : superCluster.clusters()) { - const auto &clustermapped = ebeeClusterMap.find(cluster); + for (const auto& cluster : superCluster.clusters()) { + const auto& clustermapped = ebeeClusterMap.find(cluster); if (clustermapped != ebeeClusterMap.end()) { //make new ptr - reco::CaloClusterPtr clusptr(outEBEEClusterHandle,clustermapped->second); + reco::CaloClusterPtr clusptr(outEBEEClusterHandle, clustermapped->second); clusters.push_back(clusptr); - } - else { + } else { //can only relink if all clusters are being relinked, so if one is missing, then skip the relinking completely clusters.clear(); break; @@ -958,17 +977,16 @@ void ReducedEGProducer::relinkCaloClusters(reco::SuperCluster& superCluster, if (!clusters.empty()) { superCluster.setClusters(clusters); } - + //remap preshower clusters reco::CaloClusterPtrVector esclusters; for (const auto& cluster : superCluster.preshowerClusters()) { - const auto &clustermapped = esClusterMap.find(cluster); + const auto& clustermapped = esClusterMap.find(cluster); if (clustermapped != esClusterMap.end()) { //make new ptr - reco::CaloClusterPtr clusptr(outESClusterHandle,clustermapped->second); + reco::CaloClusterPtr clusptr(outESClusterHandle, clustermapped->second); esclusters.push_back(clusptr); - } - else { + } else { //can only relink if all clusters are being relinked, so if one is missing, then skip the relinking completely esclusters.clear(); break; @@ -980,42 +998,39 @@ void ReducedEGProducer::relinkCaloClusters(reco::SuperCluster& superCluster, } template -void ReducedEGProducer::relinkSuperCluster(T& core, - const std::map& superClusterMap, - const edm::OrphanHandle& outSuperClusterHandle) -{ - const auto &scmapped = superClusterMap.find(core.superCluster()); +void ReducedEGProducer::relinkSuperCluster( + T& core, + const std::map& superClusterMap, + const edm::OrphanHandle& outSuperClusterHandle) { + const auto& scmapped = superClusterMap.find(core.superCluster()); if (scmapped != superClusterMap.end()) { //make new ref - reco::SuperClusterRef scref(outSuperClusterHandle,scmapped->second); + reco::SuperClusterRef scref(outSuperClusterHandle, scmapped->second); core.setSuperCluster(scref); } -} +} -void ReducedEGProducer::relinkGsfTrack(reco::GsfElectronCore& gsfElectronCore, - const std::map& gsfTrackMap, - const edm::OrphanHandle& outGsfTrackHandle) -{ - const auto &gsftkmapped = gsfTrackMap.find(gsfElectronCore.gsfTrack()); +void ReducedEGProducer::relinkGsfTrack(reco::GsfElectronCore& gsfElectronCore, + const std::map& gsfTrackMap, + const edm::OrphanHandle& outGsfTrackHandle) { + const auto& gsftkmapped = gsfTrackMap.find(gsfElectronCore.gsfTrack()); if (gsftkmapped != gsfTrackMap.end()) { reco::GsfTrackRef gsftkref(outGsfTrackHandle, gsftkmapped->second); gsfElectronCore.setGsfTrack(gsftkref); } -} +} -void ReducedEGProducer::relinkConversions(reco::PhotonCore& photonCore, - const reco::ConversionRefVector& convrefs, - const std::map& conversionMap, - const edm::OrphanHandle &outConversionHandle) -{ +void ReducedEGProducer::relinkConversions(reco::PhotonCore& photonCore, + const reco::ConversionRefVector& convrefs, + const std::map& conversionMap, + const edm::OrphanHandle& outConversionHandle) { reco::ConversionRefVector outconvrefs; for (const auto& convref : convrefs) { - const auto &convmapped = conversionMap.find(convref); + const auto& convmapped = conversionMap.find(convref); if (convmapped != conversionMap.end()) { //make new ref - reco::ConversionRef outref(outConversionHandle,convmapped->second); - } - else { + reco::ConversionRef outref(outConversionHandle, convmapped->second); + } else { //can only relink if all conversions are being relinked, so if one is missing, then skip the relinking completely outconvrefs.clear(); break; @@ -1026,65 +1041,57 @@ void ReducedEGProducer::relinkConversions(reco::PhotonCore& photonCore, } } -void ReducedEGProducer::relinkPhotonCore(reco::Photon& photon, - const std::map& photonCoreMap, - const edm::OrphanHandle& outPhotonCoreHandle) -{ - const auto &coremapped = photonCoreMap.find(photon.photonCore()); +void ReducedEGProducer::relinkPhotonCore(reco::Photon& photon, + const std::map& photonCoreMap, + const edm::OrphanHandle& outPhotonCoreHandle) { + const auto& coremapped = photonCoreMap.find(photon.photonCore()); if (coremapped != photonCoreMap.end()) { //make new ref - reco::PhotonCoreRef coreref(outPhotonCoreHandle,coremapped->second); + reco::PhotonCoreRef coreref(outPhotonCoreHandle, coremapped->second); photon.setPhotonCore(coreref); } } -void ReducedEGProducer::relinkGsfElectronCore(reco::GsfElectron& gsfElectron, - const std::map& gsfElectronCoreMap, - const edm::OrphanHandle& outgsfElectronCoreHandle) -{ - const auto &coremapped = gsfElectronCoreMap.find(gsfElectron.core()); +void ReducedEGProducer::relinkGsfElectronCore( + reco::GsfElectron& gsfElectron, + const std::map& gsfElectronCoreMap, + const edm::OrphanHandle& outgsfElectronCoreHandle) { + const auto& coremapped = gsfElectronCoreMap.find(gsfElectron.core()); if (coremapped != gsfElectronCoreMap.end()) { //make new ref - reco::GsfElectronCoreRef coreref(outgsfElectronCoreHandle,coremapped->second); + reco::GsfElectronCoreRef coreref(outgsfElectronCoreHandle, coremapped->second); gsfElectron.setCore(coreref); } } - -void ReducedEGProducer::calibratePhoton(reco::Photon& photon, - const reco::PhotonRef& oldPhoRef, - const edm::ValueMap& energyMap, - const edm::ValueMap& energyErrMap) -{ +void ReducedEGProducer::calibratePhoton(reco::Photon& photon, + const reco::PhotonRef& oldPhoRef, + const edm::ValueMap& energyMap, + const edm::ValueMap& energyErrMap) { float newEnergy = energyMap[oldPhoRef]; float newEnergyErr = energyErrMap[oldPhoRef]; photon.setCorrectedEnergy(reco::Photon::P4type::regression2, newEnergy, newEnergyErr, true); - } void ReducedEGProducer::calibrateElectron(reco::GsfElectron& electron, - const reco::GsfElectronRef& oldEleRef, - const edm::ValueMap& energyMap, - const edm::ValueMap& energyErrMap, - const edm::ValueMap& ecalEnergyMap, - const edm::ValueMap& ecalEnergyErrMap) -{ + const reco::GsfElectronRef& oldEleRef, + const edm::ValueMap& energyMap, + const edm::ValueMap& energyErrMap, + const edm::ValueMap& ecalEnergyMap, + const edm::ValueMap& ecalEnergyErrMap) { const float newEnergy = energyMap[oldEleRef]; const float newEnergyErr = energyErrMap[oldEleRef]; const float newEcalEnergy = ecalEnergyMap[oldEleRef]; const float newEcalEnergyErr = ecalEnergyErrMap[oldEleRef]; //make a copy of this as the setCorrectedEcalEnergy call with modifiy the electrons p4 - const math::XYZTLorentzVector oldP4 = electron.p4(); + const math::XYZTLorentzVector oldP4 = electron.p4(); const float corr = newEnergy / oldP4.E(); - + electron.setCorrectedEcalEnergy(newEcalEnergy); electron.setCorrectedEcalEnergyError(newEcalEnergyErr); - - math::XYZTLorentzVector newP4 = math::XYZTLorentzVector(oldP4.x() * corr, - oldP4.y() * corr, - oldP4.z() * corr, - newEnergy); - electron.correctMomentum(newP4, electron.trackMomentumError(), newEnergyErr); + math::XYZTLorentzVector newP4 = + math::XYZTLorentzVector(oldP4.x() * corr, oldP4.y() * corr, oldP4.z() * corr, newEnergy); + electron.correctMomentum(newP4, electron.trackMomentumError(), newEnergyErr); } diff --git a/RecoEgamma/EgammaPhotonProducers/src/TrackProducerWithSCAssociation.cc b/RecoEgamma/EgammaPhotonProducers/src/TrackProducerWithSCAssociation.cc index 23a39c50be646..acf060bd74926 100644 --- a/RecoEgamma/EgammaPhotonProducers/src/TrackProducerWithSCAssociation.cc +++ b/RecoEgamma/EgammaPhotonProducers/src/TrackProducerWithSCAssociation.cc @@ -17,56 +17,48 @@ #include "DataFormats/EgammaTrackReco/interface/TrackCaloClusterAssociation.h" #include "DataFormats/CaloRecHit/interface/CaloCluster.h" -TrackProducerWithSCAssociation::TrackProducerWithSCAssociation(const edm::ParameterSet& iConfig): - TrackProducerBase(iConfig.getParameter("TrajectoryInEvent")), - theAlgo(iConfig) -{ +TrackProducerWithSCAssociation::TrackProducerWithSCAssociation(const edm::ParameterSet& iConfig) + : TrackProducerBase(iConfig.getParameter("TrajectoryInEvent")), theAlgo(iConfig) { setConf(iConfig); - setSrc( consumes(iConfig.getParameter( "src" )), - consumes(iConfig.getParameter( "beamSpot" )), - consumes(iConfig.getParameter( "MeasurementTrackerEvent") )); - setAlias( iConfig.getParameter( "@module_label" ) ); + setSrc(consumes(iConfig.getParameter("src")), + consumes(iConfig.getParameter("beamSpot")), + consumes(iConfig.getParameter("MeasurementTrackerEvent"))); + setAlias(iConfig.getParameter("@module_label")); - if ( iConfig.exists("clusterRemovalInfo") ) { + if (iConfig.exists("clusterRemovalInfo")) { edm::InputTag tag = iConfig.getParameter("clusterRemovalInfo"); - if (!(tag == edm::InputTag())) { setClusterRemovalInfo( tag ); } + if (!(tag == edm::InputTag())) { + setClusterRemovalInfo(tag); + } } - myname_ = iConfig.getParameter("ComponentName"); conversionTrackCandidateProducer_ = iConfig.getParameter("producer"); trackCSuperClusterAssociationCollection_ = iConfig.getParameter("trackCandidateSCAssociationCollection"); trackSuperClusterAssociationCollection_ = iConfig.getParameter("recoTrackSCAssociationCollection"); myTrajectoryInEvent_ = iConfig.getParameter("TrajectoryInEvent"); - assoc_token = - consumes( - edm::InputTag(conversionTrackCandidateProducer_, - trackCSuperClusterAssociationCollection_)); - measurementTrkToken_= - consumes(edm::InputTag("MeasurementTrackerEvent")); //hardcoded because the original was and no time to fix (sigh) - - + assoc_token = consumes( + edm::InputTag(conversionTrackCandidateProducer_, trackCSuperClusterAssociationCollection_)); + measurementTrkToken_ = consumes( + edm::InputTag("MeasurementTrackerEvent")); //hardcoded because the original was and no time to fix (sigh) + //register your products - produces().setBranchAlias( alias_ + "Tracks" ); - produces().setBranchAlias( alias_ + "TrackExtras" ); - produces().setBranchAlias( alias_ + "RecHits" ); - produces >() ; + produces().setBranchAlias(alias_ + "Tracks"); + produces().setBranchAlias(alias_ + "TrackExtras"); + produces().setBranchAlias(alias_ + "RecHits"); + produces>(); produces(); // produces< reco::TrackSuperClusterAssociationCollection > (trackSuperClusterAssociationCollection_ ); - produces< reco::TrackCaloClusterPtrAssociation > (trackSuperClusterAssociationCollection_ ); - + produces(trackSuperClusterAssociationCollection_); } - -void TrackProducerWithSCAssociation::produce(edm::Event& theEvent, const edm::EventSetup& setup) -{ +void TrackProducerWithSCAssociation::produce(edm::Event& theEvent, const edm::EventSetup& setup) { //edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n"; //LogDebug("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n"; // std::cout << " TrackProducerWithSCAssociation Analyzing event number: " << theEvent.id() << "\n"; - // // create empty output collections // @@ -86,132 +78,137 @@ void TrackProducerWithSCAssociation::produce(edm::Event& theEvent, const edm::Ev edm::ESHandle thePropagator; edm::ESHandle theBuilder; edm::ESHandle theMeasTk; - getFromES(setup,theG,theMF,theFitter,thePropagator,theMeasTk,theBuilder); + getFromES(setup, theG, theMF, theFitter, thePropagator, theMeasTk, theBuilder); edm::ESHandle httopo; setup.get().get(httopo); - const TrackerTopology *ttopo = httopo.product(); - + const TrackerTopology* ttopo = httopo.product(); // //declare and get TrackColection to be retrieved from the event edm::Handle theTCCollection; //// Get the association map between candidate out in tracks and the SC where they originated - validTrackCandidateSCAssociationInput_=true; + validTrackCandidateSCAssociationInput_ = true; edm::Handle trkCandidateSCAssocHandle; theEvent.getByToken(assoc_token, trkCandidateSCAssocHandle); - if ( !trkCandidateSCAssocHandle.isValid() ) { + if (!trkCandidateSCAssocHandle.isValid()) { // std::cout << "Error! Can't get the product "< tccLocations; AlgoProductCollection algoResults; reco::BeamSpot bs; - - - getFromEvt(theEvent,theTCCollection,bs); - - if (theTCCollection.failedToGet()){ - edm::LogError("TrackProducerWithSCAssociation") <<"TrackProducerWithSCAssociation could not get the TrackCandidateCollection.";} - else{ + + getFromEvt(theEvent, theTCCollection, bs); + + if (theTCCollection.failedToGet()) { + edm::LogError("TrackProducerWithSCAssociation") + << "TrackProducerWithSCAssociation could not get the TrackCandidateCollection."; + } else { // - //run the algorithm + //run the algorithm // // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n"; - // theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection, + // theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection, // theFitter.product(), thePropagator.product(), theBuilder.product(), algoResults); // we have to copy this method from the algo in order to get the association track-seed // this is ugly temporary code that should be replaced!!!!! // start of copied code ====================================================== - + // std::cout << "TrackProducerWithSCAssociation Number of TrackCandidates: " << theTCCollection->size() << "\n"; - try{ + try { int cont = 0; - int tcc=0; - - for (TrackCandidateCollection::const_iterator i=theTCCollection->begin(); i!=theTCCollection->end();i++) - { - - const TrackCandidate * theTC = &(*i); - PTrajectoryStateOnDet state = theTC->trajectoryStateOnDet(); - const TrackCandidate::range& recHitVec=theTC->recHits(); - const TrajectorySeed& seed = theTC->seed(); - - //convert PTrajectoryStateOnDet to TrajectoryStateOnSurface - - - DetId detId(state.detId()); - TrajectoryStateOnSurface theTSOS = trajectoryStateTransform::transientState( state, - &(theG.product()->idToDet(detId)->surface()), - theMF.product()); - - //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Initial TSOS\n" << theTSOS << "\n"; - - //convert the TrackingRecHit vector to a TransientTrackingRecHit vector - //meanwhile computes the number of degrees of freedom - TransientTrackingRecHit::RecHitContainer hits; - - float ndof=0; - - for (edm::OwnVector::const_iterator i=recHitVec.first; - i!=recHitVec.second; i++){ - hits.push_back(theBuilder.product()->build(&(*i) )); - } - - - //build Track - // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation going to buildTrack"<< "\n"; - FitterCloner fc(theFitter.product(),theBuilder.product()); - bool ok = theAlgo.buildTrack(fc.fitter.get(),thePropagator.product(),algoResults, hits, theTSOS, seed, ndof, bs, theTC->seedRef()); - // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation buildTrack result: " << ok << "\n"; - if(ok) { - cont++; - tccLocations.push_back(tcc); - } - tcc++; - } + int tcc = 0; + + for (TrackCandidateCollection::const_iterator i = theTCCollection->begin(); i != theTCCollection->end(); i++) { + const TrackCandidate* theTC = &(*i); + PTrajectoryStateOnDet state = theTC->trajectoryStateOnDet(); + const TrackCandidate::range& recHitVec = theTC->recHits(); + const TrajectorySeed& seed = theTC->seed(); + + //convert PTrajectoryStateOnDet to TrajectoryStateOnSurface + + DetId detId(state.detId()); + TrajectoryStateOnSurface theTSOS = trajectoryStateTransform::transientState( + state, &(theG.product()->idToDet(detId)->surface()), theMF.product()); + + //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Initial TSOS\n" << theTSOS << "\n"; + + //convert the TrackingRecHit vector to a TransientTrackingRecHit vector + //meanwhile computes the number of degrees of freedom + TransientTrackingRecHit::RecHitContainer hits; + + float ndof = 0; + + for (edm::OwnVector::const_iterator i = recHitVec.first; i != recHitVec.second; i++) { + hits.push_back(theBuilder.product()->build(&(*i))); + } + + //build Track + // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation going to buildTrack"<< "\n"; + FitterCloner fc(theFitter.product(), theBuilder.product()); + bool ok = theAlgo.buildTrack( + fc.fitter.get(), thePropagator.product(), algoResults, hits, theTSOS, seed, ndof, bs, theTC->seedRef()); + // LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation buildTrack result: " << ok << "\n"; + if (ok) { + cont++; + tccLocations.push_back(tcc); + } + tcc++; + } edm::LogInfo("TrackProducerWithSCAssociation") << "Number of Tracks found: " << cont << "\n"; //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation Number of Tracks found: " << cont << "\n"; // end of copied code ====================================================== - - } catch (cms::Exception &e){ edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" << "\n" << e << "\n";} + + } catch (cms::Exception& e) { + edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" + << "\n" + << e << "\n"; + } // //put everything in the event // we copy putInEvt to get OrphanHandle filled... - putInEvt(theEvent,thePropagator.product(),theMeasTk.product(), - std::move(outputRHColl), std::move(outputTColl), std::move(outputTEColl), std::move(outputTrajectoryColl), - algoResults, theBuilder.product(), ttopo); - + putInEvt(theEvent, + thePropagator.product(), + theMeasTk.product(), + std::move(outputRHColl), + std::move(outputTColl), + std::move(outputTEColl), + std::move(outputTrajectoryColl), + algoResults, + theBuilder.product(), + ttopo); + // now construct associationmap and put it in the event - if ( validTrackCandidateSCAssociationInput_ ) { - int itrack=0; - std::vector > caloPtrVec; - for(AlgoProductCollection::iterator i=algoResults.begin(); i!=algoResults.end();i++){ - edm::Ref trackCRef(theTCCollection,tccLocations[itrack]); - const edm::Ptr& aClus = (*trkCandidateSCAssocHandle)[trackCRef]; - caloPtrVec.push_back( aClus ); - itrack++; + if (validTrackCandidateSCAssociationInput_) { + int itrack = 0; + std::vector> caloPtrVec; + for (AlgoProductCollection::iterator i = algoResults.begin(); i != algoResults.end(); i++) { + edm::Ref trackCRef(theTCCollection, tccLocations[itrack]); + const edm::Ptr& aClus = (*trkCandidateSCAssocHandle)[trackCRef]; + caloPtrVec.push_back(aClus); + itrack++; } - - + edm::ValueMap::Filler filler(*scTrkAssoc_p); filler.insert(rTracks_, caloPtrVec.begin(), caloPtrVec.end()); filler.fill(); - } - - theEvent.put(std::move(scTrkAssoc_p),trackSuperClusterAssociationCollection_ ); - + } + + theEvent.put(std::move(scTrkAssoc_p), trackSuperClusterAssociationCollection_); } +} -} - -std::vector TrackProducerWithSCAssociation::getTransient(edm::Event& theEvent, const edm::EventSetup& setup) -{ +std::vector TrackProducerWithSCAssociation::getTransient(edm::Event& theEvent, + const edm::EventSetup& setup) { edm::LogInfo("TrackProducerWithSCAssociation") << "Analyzing event number: " << theEvent.id() << "\n"; // // create empty output collections @@ -227,30 +224,39 @@ std::vector TrackProducerWithSCAssociation::getTransient(e edm::ESHandle thePropagator; edm::ESHandle theBuilder; edm::ESHandle theMeasTk; - getFromES(setup,theG,theMF,theFitter,thePropagator,theMeasTk,theBuilder); + getFromES(setup, theG, theMF, theFitter, thePropagator, theMeasTk, theBuilder); // //declare and get TrackColection to be retrieved from the event // AlgoProductCollection algoResults; reco::BeamSpot bs; - - try{ + + try { edm::Handle theTCCollection; - getFromEvt(theEvent,theTCCollection,bs); - + getFromEvt(theEvent, theTCCollection, bs); + // - //run the algorithm + //run the algorithm // //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation run the algorithm" << "\n"; - theAlgo.runWithCandidate(theG.product(), theMF.product(), *theTCCollection, - theFitter.product(), thePropagator.product(), theBuilder.product(), bs, algoResults); - - } catch (cms::Exception &e){ edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" << "\n" << e << "\n";} - + theAlgo.runWithCandidate(theG.product(), + theMF.product(), + *theTCCollection, + theFitter.product(), + thePropagator.product(), + theBuilder.product(), + bs, + algoResults); + + } catch (cms::Exception& e) { + edm::LogInfo("TrackProducerWithSCAssociation") << "cms::Exception caught!!!" + << "\n" + << e << "\n"; + } - for (auto & prod : algoResults){ - ttks.emplace_back(*prod.track,thePropagator.product()->magneticField()); + for (auto& prod : algoResults) { + ttks.emplace_back(*prod.track, thePropagator.product()->magneticField()); } //LogDebug("TrackProducerWithSCAssociation") << "TrackProducerWithSCAssociation end" << "\n"; @@ -258,50 +264,48 @@ std::vector TrackProducerWithSCAssociation::getTransient(e return ttks; } - #include "RecoTracker/TransientTrackingRecHit/interface/Traj2TrackHits.h" - void TrackProducerWithSCAssociation::putInEvt(edm::Event& evt, - const Propagator* thePropagator, - const MeasurementTracker* theMeasTk, - std::unique_ptr selHits, - std::unique_ptr selTracks, - std::unique_ptr selTrackExtras, - std::unique_ptr> selTrajectories, - AlgoProductCollection& algoResults, TransientTrackingRecHitBuilder const * hitBuilder, - const TrackerTopology *ttopo) -{ - -TrackingRecHitRefProd rHits = evt.getRefBeforePut(); + const Propagator* thePropagator, + const MeasurementTracker* theMeasTk, + std::unique_ptr selHits, + std::unique_ptr selTracks, + std::unique_ptr selTrackExtras, + std::unique_ptr> selTrajectories, + AlgoProductCollection& algoResults, + TransientTrackingRecHitBuilder const* hitBuilder, + const TrackerTopology* ttopo) { + TrackingRecHitRefProd rHits = evt.getRefBeforePut(); reco::TrackExtraRefProd rTrackExtras = evt.getRefBeforePut(); edm::Ref::key_type idx = 0; edm::Ref::key_type iTkRef = 0; - edm::Ref< std::vector >::key_type iTjRef = 0; + edm::Ref>::key_type iTjRef = 0; std::map tjTkMap; - for(auto & i : algoResults){ - Trajectory * theTraj = i.trajectory; - if(myTrajectoryInEvent_) { + for (auto& i : algoResults) { + Trajectory* theTraj = i.trajectory; + if (myTrajectoryInEvent_) { selTrajectories->push_back(*theTraj); iTjRef++; } - - reco::Track * theTrack = i.track; + + reco::Track* theTrack = i.track; PropagationDirection seedDir = i.pDir; - + //LogDebug("TrackProducer") << "In KfTrackProducerBase::putInEvt - seedDir=" << seedDir; - - reco::Track t = * theTrack; - selTracks->push_back( t ); + + reco::Track t = *theTrack; + selTracks->push_back(t); iTkRef++; - + // Store indices in local map (starts at 0) - if(trajectoryInEvent_) tjTkMap[iTjRef-1] = iTkRef-1; - + if (trajectoryInEvent_) + tjTkMap[iTjRef - 1] = iTkRef - 1; + //sets the outermost and innermost TSOSs - + TrajectoryStateOnSurface outertsos; TrajectoryStateOnSurface innertsos; unsigned int innerId, outerId; @@ -323,46 +327,51 @@ TrackingRecHitRefProd rHits = evt.getRefBeforePut(); //build the TrackExtra GlobalPoint v = outertsos.globalParameters().position(); GlobalVector p = outertsos.globalParameters().momentum(); - math::XYZVector outmom( p.x(), p.y(), p.z() ); - math::XYZPoint outpos( v.x(), v.y(), v.z() ); + math::XYZVector outmom(p.x(), p.y(), p.z()); + math::XYZPoint outpos(v.x(), v.y(), v.z()); v = innertsos.globalParameters().position(); p = innertsos.globalParameters().momentum(); - math::XYZVector inmom( p.x(), p.y(), p.z() ); - math::XYZPoint inpos( v.x(), v.y(), v.z() ); + math::XYZVector inmom(p.x(), p.y(), p.z()); + math::XYZPoint inpos(v.x(), v.y(), v.z()); - reco::TrackExtraRef teref= reco::TrackExtraRef ( rTrackExtras, idx ++ ); - reco::Track & track = selTracks->back(); - track.setExtra( teref ); + reco::TrackExtraRef teref = reco::TrackExtraRef(rTrackExtras, idx++); + reco::Track& track = selTracks->back(); + track.setExtra(teref); //======= I want to set the second hitPattern here ============= - if (theSchool.isValid()) - { - edm::Handle mte; - evt.getByToken(measurementTrkToken_, mte); - setSecondHitPattern(theTraj,track,thePropagator,&*mte, ttopo); - } + if (theSchool.isValid()) { + edm::Handle mte; + evt.getByToken(measurementTrkToken_, mte); + setSecondHitPattern(theTraj, track, thePropagator, &*mte, ttopo); + } //============================================================== - - selTrackExtras->push_back( reco::TrackExtra (outpos, outmom, true, inpos, inmom, true, - outertsos.curvilinearError(), outerId, - innertsos.curvilinearError(), innerId, - seedDir,theTraj->seedRef())); - - - reco::TrackExtra & tx = selTrackExtras->back(); - // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum". + selTrackExtras->push_back(reco::TrackExtra(outpos, + outmom, + true, + inpos, + inmom, + true, + outertsos.curvilinearError(), + outerId, + innertsos.curvilinearError(), + innerId, + seedDir, + theTraj->seedRef())); + + reco::TrackExtra& tx = selTrackExtras->back(); + // --- NOTA BENE: the convention is to sort hits and measurements "along the momentum". // This is consistent with innermost and outermost labels only for tracks from LHC collisions reco::TrackExtra::TrajParams trajParams; reco::TrackExtra::Chi2sFive chi2s; Traj2TrackHits t2t; auto ih = selHits->size(); - t2t(*theTraj,*selHits,trajParams,chi2s); + t2t(*theTraj, *selHits, trajParams, chi2s); auto ie = selHits->size(); - tx.setHits(rHits,ih,ie-ih); - tx.setTrajParams(std::move(trajParams),std::move(chi2s)); - for (;ih(); //LogTrace("TrackingRegressionTest") << "========== TrackProducer Info ==================="; //LogDebug("TrackProducerWithSCAssociation") << "number of finalTracks: " << selTracks->size() << std::endl; //for (reco::TrackCollection::const_iterator it = selTracks->begin(); it != selTracks->end(); it++) { - //LogDebug("TrackProducerWithSCAssociation") << "track's n valid and invalid hit, chi2, pt : " - // << it->found() << " , " - // << it->lost() <<" , " - // << it->normalizedChi2() << " , " - // << it->pt() << std::endl; + //LogDebug("TrackProducerWithSCAssociation") << "track's n valid and invalid hit, chi2, pt : " + // << it->found() << " , " + // << it->lost() <<" , " + // << it->normalizedChi2() << " , " + // << it->pt() << std::endl; // } //LogTrace("TrackingRegressionTest") << "================================================="; - rTracks_ = evt.put(std::move(selTracks)); - evt.put(std::move(selTrackExtras)); evt.put(std::move(selHits)); - - if(myTrajectoryInEvent_) { - edm::OrphanHandle > rTrajs = evt.put(std::move(selTrajectories)); - + + if (myTrajectoryInEvent_) { + edm::OrphanHandle> rTrajs = evt.put(std::move(selTrajectories)); + // Now Create traj<->tracks association map auto trajTrackMap = std::make_unique(rTrajs, rTracks_); - for ( std::map::iterator i = tjTkMap.begin(); - i != tjTkMap.end(); i++ ) { - edm::Ref > trajRef( rTrajs, (*i).first ); - edm::Ref tkRef( rTracks_, (*i).second ); - trajTrackMap->insert( edm::Ref >( rTrajs, (*i).first ), - edm::Ref( rTracks_, (*i).second ) ); + for (std::map::iterator i = tjTkMap.begin(); i != tjTkMap.end(); i++) { + edm::Ref> trajRef(rTrajs, (*i).first); + edm::Ref tkRef(rTracks_, (*i).second); + trajTrackMap->insert(edm::Ref>(rTrajs, (*i).first), + edm::Ref(rTracks_, (*i).second)); } evt.put(std::move(trajTrackMap)); } diff --git a/RecoLocalTracker/SiStripRecHitConverter/src/StripCPE.cc b/RecoLocalTracker/SiStripRecHitConverter/src/StripCPE.cc index edde79da9fb84..517f986f2d7cf 100644 --- a/RecoLocalTracker/SiStripRecHitConverter/src/StripCPE.cc +++ b/RecoLocalTracker/SiStripRecHitConverter/src/StripCPE.cc @@ -37,12 +37,13 @@ StripCPE::StripCPE(edm::ParameterSet& conf, modules["W6"] = SiStripModuleGeometry::W6; modules["W7"] = SiStripModuleGeometry::W7; - const unsigned size = static_cast(max_element(modules.begin(), - modules.end(), - boost::bind(&map_t::value_type::second, boost::lambda::_1) < - boost::bind(&map_t::value_type::second, boost::lambda::_2)) - ->second) + - 1; + const unsigned size = + static_cast(max_element(modules.begin(), + modules.end(), + boost::bind(&map_t::value_type::second, boost::lambda::_1) < + boost::bind(&map_t::value_type::second, boost::lambda::_2)) + ->second) + + 1; xtalk1.resize(size); xtalk2.resize(size); diff --git a/RecoLocalTracker/SiStripRecHitConverter/src/StripCPEgeometric.cc b/RecoLocalTracker/SiStripRecHitConverter/src/StripCPEgeometric.cc index 323e334e12677..bb6831c0b5ab2 100644 --- a/RecoLocalTracker/SiStripRecHitConverter/src/StripCPEgeometric.cc +++ b/RecoLocalTracker/SiStripRecHitConverter/src/StripCPEgeometric.cc @@ -21,7 +21,8 @@ StripClusterParameterEstimator::LocalValues StripCPEgeometric::localParameters( projection = stats_t::from_relative_uncertainty2(std::max(absProj, minProj), projection_rel_err2); } - const std::vector > Q = reco::InverseCrosstalkMatrix::unfold(cluster, xtalk1[static_cast(p.moduleGeom)]); + const std::vector > Q = + reco::InverseCrosstalkMatrix::unfold(cluster, xtalk1[static_cast(p.moduleGeom)]); const stats_t strip = cluster.firstStrip() + offset_from_firstStrip(Q, projection); const float corrected = diff --git a/RecoPixelVertexing/PixelTriplets/interface/CAHitTripletGenerator.h b/RecoPixelVertexing/PixelTriplets/interface/CAHitTripletGenerator.h index 9db56c4a74534..af0721895fef0 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/CAHitTripletGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/interface/CAHitTripletGenerator.h @@ -21,114 +21,112 @@ class TrackingRegion; class SeedingLayerSetsHits; namespace edm { - class Event; - class EventSetup; - class ParameterSetDescription; -} + class Event; + class EventSetup; + class ParameterSetDescription; +} // namespace edm class CAHitTripletGenerator { public: - typedef LayerHitMapCache LayerCacheType; + typedef LayerHitMapCache LayerCacheType; - static constexpr unsigned int minLayers = 3; - typedef OrderedHitSeeds ResultType; -public: + static constexpr unsigned int minLayers = 3; + typedef OrderedHitSeeds ResultType; - CAHitTripletGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC): CAHitTripletGenerator(cfg, iC) {} - CAHitTripletGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); +public: + CAHitTripletGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC) : CAHitTripletGenerator(cfg, iC) {} + CAHitTripletGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); - ~CAHitTripletGenerator() = default; + ~CAHitTripletGenerator() = default; - static void fillDescriptions(edm::ParameterSetDescription& desc); - static const char *fillDescriptionsLabel() { return "caHitTriplet"; } + static void fillDescriptions(edm::ParameterSetDescription& desc); + static const char* fillDescriptionsLabel() { return "caHitTriplet"; } - void initEvent(const edm::Event& ev, const edm::EventSetup& es); + void initEvent(const edm::Event& ev, const edm::EventSetup& es); - void hitNtuplets(const IntermediateHitDoublets& regionDoublets, - std::vector& result, - const edm::EventSetup& es, - const SeedingLayerSetsHits& layers); + void hitNtuplets(const IntermediateHitDoublets& regionDoublets, + std::vector& result, + const edm::EventSetup& es, + const SeedingLayerSetsHits& layers); private: - LayerCacheType theLayerCache; - - std::unique_ptr theComparitor; - - class QuantityDependsPtEval { - public: - - QuantityDependsPtEval(float v1, float v2, float c1, float c2) : - value1_(v1), value2_(v2), curvature1_(c1), curvature2_(c2) { - } - - float value(float curvature) const { - if (value1_ == value2_) // not enabled - return value1_; - - if (curvature1_ < curvature) - return value1_; - if (curvature2_ < curvature && curvature <= curvature1_) - return value2_ + (curvature - curvature2_) / (curvature1_ - curvature2_) * (value1_ - value2_); - return value2_; - } - - private: - const float value1_; - const float value2_; - const float curvature1_; - const float curvature2_; - }; - - // Linear interpolation (in curvature) between value1 at pt1 and - // value2 at pt2. If disabled, value2 is given (the point is to - // allow larger/smaller values of the quantity at low pt, so it - // makes more sense to have the high-pt value as the default). - - class QuantityDependsPt { - public: - - explicit QuantityDependsPt(const edm::ParameterSet& pset) : - value1_(pset.getParameter("value1")), - value2_(pset.getParameter("value2")), - pt1_(pset.getParameter("pt1")), - pt2_(pset.getParameter("pt2")), - enabled_(pset.getParameter("enabled")) { - if (enabled_ && pt1_ >= pt2_) - throw cms::Exception("Configuration") << "CAHitTripletGenerator::QuantityDependsPt: pt1 (" << pt1_ << ") needs to be smaller than pt2 (" << pt2_ << ")"; - if (pt1_ <= 0) - throw cms::Exception("Configuration") << "CAHitTripletGenerator::QuantityDependsPt: pt1 needs to be > 0; is " << pt1_; - if (pt2_ <= 0) - throw cms::Exception("Configuration") << "CAHitTripletGenerator::QuantityDependsPt: pt2 needs to be > 0; is " << pt2_; - } - - QuantityDependsPtEval evaluator(const edm::EventSetup& es) const { - if (enabled_) { - return QuantityDependsPtEval(value1_, value2_, - PixelRecoUtilities::curvature(1.f / pt1_, es), - PixelRecoUtilities::curvature(1.f / pt2_, es)); - } - return QuantityDependsPtEval(value2_, value2_, 0.f, 0.f); - } - - private: - const float value1_; - const float value2_; - const float pt1_; - const float pt2_; - const bool enabled_; - }; - - const float extraHitRPhitolerance; - - const QuantityDependsPt maxChi2; - const bool useBendingCorrection; - - const float caThetaCut = 0.00125f; - const float caPhiCut = 1.f; - const float caHardPtCut = 0.f; + LayerCacheType theLayerCache; + + std::unique_ptr theComparitor; + + class QuantityDependsPtEval { + public: + QuantityDependsPtEval(float v1, float v2, float c1, float c2) + : value1_(v1), value2_(v2), curvature1_(c1), curvature2_(c2) {} + + float value(float curvature) const { + if (value1_ == value2_) // not enabled + return value1_; + + if (curvature1_ < curvature) + return value1_; + if (curvature2_ < curvature && curvature <= curvature1_) + return value2_ + (curvature - curvature2_) / (curvature1_ - curvature2_) * (value1_ - value2_); + return value2_; + } + + private: + const float value1_; + const float value2_; + const float curvature1_; + const float curvature2_; + }; + + // Linear interpolation (in curvature) between value1 at pt1 and + // value2 at pt2. If disabled, value2 is given (the point is to + // allow larger/smaller values of the quantity at low pt, so it + // makes more sense to have the high-pt value as the default). + + class QuantityDependsPt { + public: + explicit QuantityDependsPt(const edm::ParameterSet& pset) + : value1_(pset.getParameter("value1")), + value2_(pset.getParameter("value2")), + pt1_(pset.getParameter("pt1")), + pt2_(pset.getParameter("pt2")), + enabled_(pset.getParameter("enabled")) { + if (enabled_ && pt1_ >= pt2_) + throw cms::Exception("Configuration") << "CAHitTripletGenerator::QuantityDependsPt: pt1 (" << pt1_ + << ") needs to be smaller than pt2 (" << pt2_ << ")"; + if (pt1_ <= 0) + throw cms::Exception("Configuration") + << "CAHitTripletGenerator::QuantityDependsPt: pt1 needs to be > 0; is " << pt1_; + if (pt2_ <= 0) + throw cms::Exception("Configuration") + << "CAHitTripletGenerator::QuantityDependsPt: pt2 needs to be > 0; is " << pt2_; + } + + QuantityDependsPtEval evaluator(const edm::EventSetup& es) const { + if (enabled_) { + return QuantityDependsPtEval(value1_, + value2_, + PixelRecoUtilities::curvature(1.f / pt1_, es), + PixelRecoUtilities::curvature(1.f / pt2_, es)); + } + return QuantityDependsPtEval(value2_, value2_, 0.f, 0.f); + } + + private: + const float value1_; + const float value2_; + const float pt1_; + const float pt2_; + const bool enabled_; + }; + + const float extraHitRPhitolerance; + + const QuantityDependsPt maxChi2; + const bool useBendingCorrection; + + const float caThetaCut = 0.00125f; + const float caPhiCut = 1.f; + const float caHardPtCut = 0.f; }; - - - #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGenerator.h b/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGenerator.h index 3dd9dca038cc0..327e0f30e9e59 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGenerator.h @@ -12,37 +12,29 @@ class DetLayer; class TrackingRegion; class CosmicLayerTriplets; - /** \class CosmicHitTripletGenerator * Hides set of HitTripletGeneratorFromLayerTriplet generators. */ class CosmicHitTripletGenerator { - - typedef std::vector > Container; + typedef std::vector > Container; public: CosmicHitTripletGenerator(CosmicLayerTriplets& layers, const edm::EventSetup& iSetup); CosmicHitTripletGenerator(CosmicLayerTriplets& layers); - ~CosmicHitTripletGenerator(); /// add generators based on layers - // void add(const DetLayer* inner, const DetLayer* outer); - void add(const LayerWithHits* inner, - const LayerWithHits* middle, - const LayerWithHits* outer, - const edm::EventSetup& iSetup); + // void add(const DetLayer* inner, const DetLayer* outer); + void add(const LayerWithHits* inner, + const LayerWithHits* middle, + const LayerWithHits* outer, + const edm::EventSetup& iSetup); - void hitTriplets( const TrackingRegion& reg, - OrderedHitTriplets & prs, - const edm::EventSetup& iSetup); + void hitTriplets(const TrackingRegion& reg, OrderedHitTriplets& prs, const edm::EventSetup& iSetup); private: - - - Container theGenerators; - + Container theGenerators; }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGeneratorFromLayerTriplet.h b/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGeneratorFromLayerTriplet.h index c534510b72b57..ec0af890622b1 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGeneratorFromLayerTriplet.h +++ b/RecoPixelVertexing/PixelTriplets/interface/CosmicHitTripletGeneratorFromLayerTriplet.h @@ -13,35 +13,29 @@ class DetLayer; class TrackingRegion; class LayerWithHits; - class CosmicHitTripletGeneratorFromLayerTriplet { - public: + CosmicHitTripletGeneratorFromLayerTriplet(const LayerWithHits* inner, + const LayerWithHits* middle, + const LayerWithHits* outer, + const edm::EventSetup& iSetup); + ~CosmicHitTripletGeneratorFromLayerTriplet() {} - - CosmicHitTripletGeneratorFromLayerTriplet( - const LayerWithHits* inner, - const LayerWithHits* middle, - const LayerWithHits* outer, - const edm::EventSetup& iSetup); - ~CosmicHitTripletGeneratorFromLayerTriplet() { } - - void hitTriplets( const TrackingRegion& ar, OrderedHitTriplets & ap, const edm::EventSetup& iSetup); + void hitTriplets(const TrackingRegion& ar, OrderedHitTriplets& ap, const edm::EventSetup& iSetup); const LayerWithHits* innerLayer() const { return theInnerLayer; } const LayerWithHits* middleLayer() const { return theMiddleLayer; } const LayerWithHits* outerLayer() const { return theOuterLayer; } private: - const TransientTrackingRecHitBuilder * TTRHbuilder; + const TransientTrackingRecHitBuilder* TTRHbuilder; const TrackerGeometry* trackerGeometry; - const LayerWithHits* theOuterLayer; - const LayerWithHits* theMiddleLayer; - const LayerWithHits* theInnerLayer; + const LayerWithHits* theOuterLayer; + const LayerWithHits* theMiddleLayer; + const LayerWithHits* theInnerLayer; const DetLayer* innerlay; const DetLayer* outerlay; const DetLayer* middlelay; - }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/CosmicLayerTriplets.h b/RecoPixelVertexing/PixelTriplets/interface/CosmicLayerTriplets.h index 6d9176fc8fad1..23e64e50fd206 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/CosmicLayerTriplets.h +++ b/RecoPixelVertexing/PixelTriplets/interface/CosmicLayerTriplets.h @@ -23,20 +23,17 @@ #include class CosmicLayerTriplets { public: - CosmicLayerTriplets() {}; + CosmicLayerTriplets(){}; ~CosmicLayerTriplets(); // explicit PixelSeedLayerPairs(const edm::EventSetup& iSetup); - typedef std::pair > LayerPairAndLayers; - + typedef std::pair > LayerPairAndLayers; // virtual std::vector operator()() const; // std::vector operator()() ; std::vector layers(); private: - - //definition of the map - + //definition of the map LayerWithHits *lh1; LayerWithHits *lh2; @@ -45,22 +42,19 @@ class CosmicLayerTriplets { edm::ESWatcher watchTrackerGeometry_; - std::vector bl; - //MP - std::vector allLayersWithHits; - public: - - void init(const SiStripRecHit2DCollection &collstereo, - const SiStripRecHit2DCollection &collrphi, - const SiStripMatchedRecHit2DCollection &collmatched, - std::string geometry, - const edm::EventSetup& iSetup); - - private: - std::string _geometry; -}; - + std::vector bl; + //MP + std::vector allLayersWithHits; +public: + void init(const SiStripRecHit2DCollection &collstereo, + const SiStripRecHit2DCollection &collrphi, + const SiStripMatchedRecHit2DCollection &collmatched, + std::string geometry, + const edm::EventSetup &iSetup); +private: + std::string _geometry; +}; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/HitTripletEDProducerT.h b/RecoPixelVertexing/PixelTriplets/interface/HitTripletEDProducerT.h index 77bd1897653ca..65e6dfbfb7871 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/HitTripletEDProducerT.h +++ b/RecoPixelVertexing/PixelTriplets/interface/HitTripletEDProducerT.h @@ -19,10 +19,12 @@ #include -namespace hitTripletEDProducerT { class ImplBase; } +namespace hitTripletEDProducerT { + class ImplBase; +} template -class HitTripletEDProducerT: public edm::stream::EDProducer<> { +class HitTripletEDProducerT : public edm::stream::EDProducer<> { public: HitTripletEDProducerT(const edm::ParameterSet& iConfig); ~HitTripletEDProducerT() override = default; @@ -45,7 +47,8 @@ namespace hitTripletEDProducerT { virtual void produces(edm::ProducerBase& producer) const = 0; virtual void produce(const IntermediateHitDoublets& regionDoublets, - edm::Event& iEvent, const edm::EventSetup& iSetup) = 0; + edm::Event& iEvent, + const edm::EventSetup& iSetup) = 0; protected: edm::RunningAverage localRA_; @@ -53,11 +56,9 @@ namespace hitTripletEDProducerT { ///// template - class ImplGeneratorBase: public ImplBase { + class ImplGeneratorBase : public ImplBase { public: - ImplGeneratorBase(const edm::ParameterSet& iConfig, edm::ConsumesCollector& iC): - generator_(iConfig, iC) - {} + ImplGeneratorBase(const edm::ParameterSet& iConfig, edm::ConsumesCollector& iC) : generator_(iConfig, iC) {} ~ImplGeneratorBase() override = default; protected: @@ -65,12 +66,11 @@ namespace hitTripletEDProducerT { }; ///// - template - class Impl: public ImplGeneratorBase { + template + class Impl : public ImplGeneratorBase { public: - Impl(const edm::ParameterSet& iConfig, edm::ConsumesCollector& iC): - ImplGeneratorBase(iConfig, iC) {} + Impl(const edm::ParameterSet& iConfig, edm::ConsumesCollector& iC) + : ImplGeneratorBase(iConfig, iC) {} ~Impl() override = default; void produces(edm::ProducerBase& producer) const override { @@ -79,13 +79,14 @@ namespace hitTripletEDProducerT { }; void produce(const IntermediateHitDoublets& regionDoublets, - edm::Event& iEvent, const edm::EventSetup& iSetup) override { + edm::Event& iEvent, + const edm::EventSetup& iSetup) override { const SeedingLayerSetsHits& seedingLayerHits = regionDoublets.seedingLayerHits(); auto seedingHitSetsProducer = T_SeedingHitSets(); auto intermediateHitTripletsProducer = T_IntermediateHitTriplets(&seedingLayerHits); - if(regionDoublets.empty()) { + if (regionDoublets.empty()) { seedingHitSetsProducer.putEmpty(iEvent); intermediateHitTripletsProducer.putEmpty(iEvent); return; @@ -101,13 +102,16 @@ namespace hitTripletEDProducerT { triplets.reserve(this->localRA_.upper()); size_t triplets_total = 0; - LogDebug("HitTripletEDProducer") << "Creating triplets for " << regionDoublets.regionSize() << " regions, and " << trilayers.size() << " pair+3rd layers from " << regionDoublets.layerPairsSize() << " layer pairs"; + LogDebug("HitTripletEDProducer") << "Creating triplets for " << regionDoublets.regionSize() << " regions, and " + << trilayers.size() << " pair+3rd layers from " + << regionDoublets.layerPairsSize() << " layer pairs"; - for(const auto& regionLayerPairs: regionDoublets) { + for (const auto& regionLayerPairs : regionDoublets) { const TrackingRegion& region = regionLayerPairs.region(); auto hitCachePtr_filler_shs = seedingHitSetsProducer.beginRegion(®ion, nullptr); - auto hitCachePtr_filler_iht = intermediateHitTripletsProducer.beginRegion(®ion, std::get<0>(hitCachePtr_filler_shs)); + auto hitCachePtr_filler_iht = + intermediateHitTripletsProducer.beginRegion(®ion, std::get<0>(hitCachePtr_filler_shs)); auto hitCachePtr = std::get<0>(hitCachePtr_filler_iht); LayerHitMapCache& hitCache = *hitCachePtr; @@ -115,19 +119,23 @@ namespace hitTripletEDProducerT { LogTrace("HitTripletEDProducer") << " starting region"; - for(const auto& layerPair: regionLayerPairs) { - LogTrace("HitTripletEDProducer") << " starting layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex(); + for (const auto& layerPair : regionLayerPairs) { + LogTrace("HitTripletEDProducer") + << " starting layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex(); auto found = std::find_if(trilayers.begin(), trilayers.end(), [&](const LayerTriplets::LayerSetAndLayers& a) { - return a.first[0].index() == layerPair.innerLayerIndex() && a.first[1].index() == layerPair.outerLayerIndex(); - }); - if(found == trilayers.end()) { - auto exp = cms::Exception("LogicError") << "Did not find the layer pair from vector. This is a sign of some internal inconsistency\n"; - exp << "I was looking for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() << ". Triplets have the following pairs:\n"; - for(const auto& a: trilayers) { + return a.first[0].index() == layerPair.innerLayerIndex() && + a.first[1].index() == layerPair.outerLayerIndex(); + }); + if (found == trilayers.end()) { + auto exp = cms::Exception("LogicError") << "Did not find the layer pair from vector. " + "This is a sign of some internal inconsistency\n"; + exp << "I was looking for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() + << ". Triplets have the following pairs:\n"; + for (const auto& a : trilayers) { exp << " " << a.first[0].index() << "," << a.first[1].index() << ": 3rd layers"; - for(const auto& b: a.second) { - exp << " " << b.index(); + for (const auto& b : a.second) { + exp << " " << b.index(); } exp << "\n"; } @@ -135,19 +143,28 @@ namespace hitTripletEDProducerT { } const auto& thirdLayers = found->second; - this->generator_.hitTriplets(region, triplets, iEvent, iSetup, layerPair.doublets(), thirdLayers, - intermediateHitTripletsProducer.tripletLastLayerIndexVector(), hitCache); + this->generator_.hitTriplets(region, + triplets, + iEvent, + iSetup, + layerPair.doublets(), + thirdLayers, + intermediateHitTripletsProducer.tripletLastLayerIndexVector(), + hitCache); #ifdef EDM_ML_DEBUG - LogTrace("HitTripletEDProducer") << " created " << triplets.size() << " triplets for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() << " and 3rd layers"; - for(const auto& l: thirdLayers) { + LogTrace("HitTripletEDProducer") + << " created " << triplets.size() << " triplets for layer pair " << layerPair.innerLayerIndex() << "," + << layerPair.outerLayerIndex() << " and 3rd layers"; + for (const auto& l : thirdLayers) { LogTrace("HitTripletEDProducer") << " " << l.index(); } #endif triplets_total += triplets.size(); seedingHitSetsProducer.fill(std::get<1>(hitCachePtr_filler_shs), triplets); - intermediateHitTripletsProducer.fill(std::get<1>(hitCachePtr_filler_iht), layerPair.layerPair(), thirdLayers, triplets); + intermediateHitTripletsProducer.fill( + std::get<1>(hitCachePtr_filler_iht), layerPair.layerPair(), thirdLayers, triplets); triplets.clear(); } @@ -159,31 +176,26 @@ namespace hitTripletEDProducerT { } }; - ///// class DoNothing { public: DoNothing() {} - explicit DoNothing(const SeedingLayerSetsHits *layers) {} + explicit DoNothing(const SeedingLayerSetsHits* layers) {} static void produces(edm::ProducerBase&) {} void reserve(size_t, size_t) {} - auto beginRegion(const TrackingRegion *, LayerHitMapCache *ptr) { - return std::make_tuple(ptr, 0); - } + auto beginRegion(const TrackingRegion*, LayerHitMapCache* ptr) { return std::make_tuple(ptr, 0); } - std::vector *tripletLastLayerIndexVector() { - return nullptr; - } + std::vector* tripletLastLayerIndexVector() { return nullptr; } void fill(int, const OrderedHitTriplets&) {} - void fill(int, const IntermediateHitTriplets::LayerPair&, + void fill(int, + const IntermediateHitTriplets::LayerPair&, const std::vector&, const OrderedHitTriplets&) {} - void put(edm::Event& iEvent) {} void putEmpty(edm::Event& iEvent) {} }; @@ -191,25 +203,19 @@ namespace hitTripletEDProducerT { ///// class ImplSeedingHitSets { public: - ImplSeedingHitSets(): - seedingHitSets_(std::make_unique()) - {} + ImplSeedingHitSets() : seedingHitSets_(std::make_unique()) {} - static void produces(edm::ProducerBase& producer) { - producer.produces(); - } + static void produces(edm::ProducerBase& producer) { producer.produces(); } - void reserve(size_t regionsSize, size_t localRAupper) { - seedingHitSets_->reserve(regionsSize, localRAupper); - } + void reserve(size_t regionsSize, size_t localRAupper) { seedingHitSets_->reserve(regionsSize, localRAupper); } - auto beginRegion(const TrackingRegion *region, LayerHitMapCache *ptr) { + auto beginRegion(const TrackingRegion* region, LayerHitMapCache* ptr) { hitCacheTmp_.clear(); return std::make_tuple(&hitCacheTmp_, seedingHitSets_->beginRegion(region)); } void fill(RegionsSeedingHitSets::RegionFiller& filler, const OrderedHitTriplets& triplets) { - for(const auto& trpl: triplets) { + for (const auto& trpl : triplets) { filler.emplace_back(trpl.inner(), trpl.middle(), trpl.outer()); } } @@ -218,54 +224,46 @@ namespace hitTripletEDProducerT { seedingHitSets_->shrink_to_fit(); putEmpty(iEvent); } - void putEmpty(edm::Event& iEvent) { - iEvent.put(std::move(seedingHitSets_)); - } + void putEmpty(edm::Event& iEvent) { iEvent.put(std::move(seedingHitSets_)); } private: std::unique_ptr seedingHitSets_; - LayerHitMapCache hitCacheTmp_; // used if !produceIntermediateHitDoublets + LayerHitMapCache hitCacheTmp_; // used if !produceIntermediateHitDoublets }; ///// class ImplIntermediateHitTriplets { public: - explicit ImplIntermediateHitTriplets(const SeedingLayerSetsHits *layers): - intermediateHitTriplets_(std::make_unique(layers)), - layers_(layers) - {} + explicit ImplIntermediateHitTriplets(const SeedingLayerSetsHits* layers) + : intermediateHitTriplets_(std::make_unique(layers)), layers_(layers) {} - static void produces(edm::ProducerBase& producer) { - producer.produces(); - } + static void produces(edm::ProducerBase& producer) { producer.produces(); } void reserve(size_t regionsSize, size_t localRAupper) { intermediateHitTriplets_->reserve(regionsSize, layers_->size(), localRAupper); tripletLastLayerIndex_.reserve(localRAupper); } - auto beginRegion(const TrackingRegion *region, LayerHitMapCache *) { + auto beginRegion(const TrackingRegion* region, LayerHitMapCache*) { auto filler = intermediateHitTriplets_->beginRegion(region); return std::make_tuple(&(filler.layerHitMapCache()), std::move(filler)); } - std::vector *tripletLastLayerIndexVector() { - return &tripletLastLayerIndex_; - } + std::vector* tripletLastLayerIndexVector() { return &tripletLastLayerIndex_; } void fill(IntermediateHitTriplets::RegionFiller& filler, const IntermediateHitTriplets::LayerPair& layerPair, const std::vector& thirdLayers, const OrderedHitTriplets& triplets) { - if(tripletLastLayerIndex_.size() != triplets.size()) { + if (tripletLastLayerIndex_.size() != triplets.size()) { throw cms::Exception("LogicError") << "tripletLastLayerIndex_.size() " << tripletLastLayerIndex_.size() << " triplets.size() " << triplets.size(); } tripletPermutation_.resize(tripletLastLayerIndex_.size()); - std::iota(tripletPermutation_.begin(), tripletPermutation_.end(), 0); // assign 0,1,2,...,N + std::iota(tripletPermutation_.begin(), tripletPermutation_.end(), 0); // assign 0,1,2,...,N std::stable_sort(tripletPermutation_.begin(), tripletPermutation_.end(), [&](size_t i, size_t j) { - return tripletLastLayerIndex_[i] < tripletLastLayerIndex_[j]; - }); + return tripletLastLayerIndex_[i] < tripletLastLayerIndex_[j]; + }); // empty triplets need to propagate here filler.addTriplets(layerPair, thirdLayers, triplets, tripletLastLayerIndex_, tripletPermutation_); @@ -276,24 +274,19 @@ namespace hitTripletEDProducerT { intermediateHitTriplets_->shrink_to_fit(); putEmpty(iEvent); } - void putEmpty(edm::Event& iEvent) { - iEvent.put(std::move(intermediateHitTriplets_)); - } + void putEmpty(edm::Event& iEvent) { iEvent.put(std::move(intermediateHitTriplets_)); } private: std::unique_ptr intermediateHitTriplets_; - const SeedingLayerSetsHits *layers_; + const SeedingLayerSetsHits* layers_; std::vector tripletPermutation_; std::vector tripletLastLayerIndex_; }; -} - - +} // namespace hitTripletEDProducerT template -HitTripletEDProducerT::HitTripletEDProducerT(const edm::ParameterSet& iConfig): - doubletToken_(consumes(iConfig.getParameter("doublets"))) -{ +HitTripletEDProducerT::HitTripletEDProducerT(const edm::ParameterSet& iConfig) + : doubletToken_(consumes(iConfig.getParameter("doublets"))) { const bool produceSeedingHitSets = iConfig.getParameter("produceSeedingHitSets"); const bool produceIntermediateHitTriplets = iConfig.getParameter("produceIntermediateHitTriplets"); @@ -301,14 +294,16 @@ HitTripletEDProducerT::HitTripletEDProducerT(const edm::P using namespace hitTripletEDProducerT; - if(produceSeedingHitSets && produceIntermediateHitTriplets) + if (produceSeedingHitSets && produceIntermediateHitTriplets) impl_ = std::make_unique>(iConfig, iC); - else if(produceSeedingHitSets) + else if (produceSeedingHitSets) impl_ = std::make_unique>(iConfig, iC); - else if(produceIntermediateHitTriplets) + else if (produceIntermediateHitTriplets) impl_ = std::make_unique>(iConfig, iC); else - throw cms::Exception("Configuration") << "HitTripletEDProducerT requires either produceIntermediateHitTriplets or produceSeedingHitSets to be True. If neither are needed, just remove this module from your sequence/path as it doesn't do anything useful"; + throw cms::Exception("Configuration") + << "HitTripletEDProducerT requires either produceIntermediateHitTriplets or produceSeedingHitSets to be True. " + "If neither are needed, just remove this module from your sequence/path as it doesn't do anything useful"; impl_->produces(*this); } @@ -334,12 +329,15 @@ void HitTripletEDProducerT::produce(edm::Event& iEvent, c const auto& regionDoublets = *hdoublets; const SeedingLayerSetsHits& seedingLayerHits = regionDoublets.seedingLayerHits(); - if(seedingLayerHits.numberOfLayersInSet() < 3) { - throw cms::Exception("LogicError") << "HitTripletEDProducerT expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= 3, got " << seedingLayerHits.numberOfLayersInSet() << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or SeedingLayersEDProducer."; + if (seedingLayerHits.numberOfLayersInSet() < 3) { + throw cms::Exception("LogicError") + << "HitTripletEDProducerT expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= 3, got " + << seedingLayerHits.numberOfLayersInSet() + << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or " + "SeedingLayersEDProducer."; } impl_->produce(regionDoublets, iEvent, iSetup); } - #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGenerator.h b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGenerator.h index f83d641324f58..781b1d2117029 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGenerator.h @@ -10,28 +10,29 @@ #include "FWCore/Utilities/interface/RunningAverage.h" - class TrackingRegion; -namespace edm { class Event; class EventSetup; } +namespace edm { + class Event; + class EventSetup; +} // namespace edm #include class HitTripletGenerator : public OrderedHitsGenerator { public: + HitTripletGenerator(unsigned int size = 500); + HitTripletGenerator(HitTripletGenerator const& other) : localRA(other.localRA.mean()) {} - HitTripletGenerator(unsigned int size=500); - HitTripletGenerator(HitTripletGenerator const & other) : localRA(other.localRA.mean()){} - - ~HitTripletGenerator() override { } + ~HitTripletGenerator() override {} - const OrderedHitTriplets & run( - const TrackingRegion& region, const edm::Event & ev, const edm::EventSetup& es) final; + const OrderedHitTriplets& run(const TrackingRegion& region, const edm::Event& ev, const edm::EventSetup& es) final; // temporary interface, for bckwd compatibility - virtual void hitTriplets( const TrackingRegion& reg, OrderedHitTriplets & prs, - const edm::EventSetup& es){} + virtual void hitTriplets(const TrackingRegion& reg, OrderedHitTriplets& prs, const edm::EventSetup& es) {} - virtual void hitTriplets( const TrackingRegion& reg, OrderedHitTriplets & prs, - const edm::Event & ev, const edm::EventSetup& es) = 0; + virtual void hitTriplets(const TrackingRegion& reg, + OrderedHitTriplets& prs, + const edm::Event& ev, + const edm::EventSetup& es) = 0; void clear() final; @@ -40,5 +41,4 @@ class HitTripletGenerator : public OrderedHitsGenerator { edm::RunningAverage localRA; }; - #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h index 05c7fcc992268..c978ecfaa0dd0 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h +++ b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h @@ -12,44 +12,48 @@ #include "TrackingTools/TransientTrackingRecHit/interface/SeedingLayerSetsHits.h" #include "RecoTracker/TkHitPairs/interface/LayerHitMapCache.h" -namespace edm { class ParameterSet; class Event; class EventSetup; class ConsumesCollector; class ParameterSetDescription;} +namespace edm { + class ParameterSet; + class Event; + class EventSetup; + class ConsumesCollector; + class ParameterSetDescription; +} // namespace edm class TrackingRegion; class HitPairGeneratorFromLayerPair; class HitTripletGeneratorFromPairAndLayers { - public: - typedef LayerHitMapCache LayerCacheType; + typedef LayerHitMapCache LayerCacheType; - explicit HitTripletGeneratorFromPairAndLayers(unsigned int maxElement=0); + explicit HitTripletGeneratorFromPairAndLayers(unsigned int maxElement = 0); explicit HitTripletGeneratorFromPairAndLayers(const edm::ParameterSet& pset); virtual ~HitTripletGeneratorFromPairAndLayers(); static void fillDescriptions(edm::ParameterSetDescription& desc); - void init( std::unique_ptr&& pairs, LayerCacheType* layerCache); + void init(std::unique_ptr&& pairs, LayerCacheType* layerCache); const HitPairGeneratorFromLayerPair& pairGenerator() const { return *thePairGenerator; } - virtual void hitTriplets( const TrackingRegion& region, OrderedHitTriplets & trs, - const edm::Event & ev, const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) = 0; - - virtual void hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)=0; + virtual void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) = 0; + + virtual void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) = 0; protected: std::unique_ptr thePairGenerator; - LayerCacheType *theLayerCache; + LayerCacheType* theLayerCache; const unsigned int theMaxElement; }; #endif - - diff --git a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h index b2698c1457034..9f5ae80b13a23 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h +++ b/RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h @@ -1,12 +1,16 @@ -#ifndef PixelTriplets_HitTripletGeneratorFromPairAndLayersFactory_H +#ifndef PixelTriplets_HitTripletGeneratorFromPairAndLayersFactory_H #define PixelTriplets_HitTripletGeneratorFromPairAndLayersFactory_H #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h" #include "FWCore/PluginManager/interface/PluginFactory.h" -namespace edm {class ParameterSet; class ConsumesCollector;} +namespace edm { + class ParameterSet; + class ConsumesCollector; +} // namespace edm + +typedef edmplugin::PluginFactory + HitTripletGeneratorFromPairAndLayersFactory; -typedef edmplugin::PluginFactory - HitTripletGeneratorFromPairAndLayersFactory; - #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/IntermediateHitTriplets.h b/RecoPixelVertexing/PixelTriplets/interface/IntermediateHitTriplets.h index 425b675b14dbd..5998bce1746e5 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/IntermediateHitTriplets.h +++ b/RecoPixelVertexing/PixelTriplets/interface/IntermediateHitTriplets.h @@ -21,11 +21,9 @@ */ class IntermediateHitTriplets { public: - using LayerPair = std::tuple; - using LayerTriplet = std::tuple; + using LayerPair = std::tuple; + using LayerTriplet = + std::tuple; using RegionIndex = ihd::RegionIndex; //////////////////// @@ -40,14 +38,12 @@ class IntermediateHitTriplets { */ class PLayerHitTriplets { public: - PLayerHitTriplets(const LayerTriplet& layerTriplet, unsigned int tripletsBegin): - layerTriplet_(layerTriplet), - tripletsBegin_(tripletsBegin), tripletsEnd_(tripletsBegin) - {} + PLayerHitTriplets(const LayerTriplet &layerTriplet, unsigned int tripletsBegin) + : layerTriplet_(layerTriplet), tripletsBegin_(tripletsBegin), tripletsEnd_(tripletsBegin) {} void setTripletsEnd(unsigned int end) { tripletsEnd_ = end; } - const LayerTriplet& layerTriplet() const { return layerTriplet_; } + const LayerTriplet &layerTriplet() const { return layerTriplet_; } unsigned int tripletsBegin() const { return tripletsBegin_; } unsigned int tripletsEnd() const { return tripletsEnd_; } @@ -68,14 +64,11 @@ class IntermediateHitTriplets { public: using const_iterator = std::vector::const_iterator; - LayerHitTriplets(const IntermediateHitTriplets *hitSets, - const PLayerHitTriplets *layerTriplet): - hitSets_(hitSets), - layerTriplet_(layerTriplet) - {} + LayerHitTriplets(const IntermediateHitTriplets *hitSets, const PLayerHitTriplets *layerTriplet) + : hitSets_(hitSets), layerTriplet_(layerTriplet) {} - using TripletRange = std::pair::const_iterator, - std::vector::const_iterator>; + using TripletRange = + std::pair::const_iterator, std::vector::const_iterator>; SeedingLayerSetsHits::LayerIndex innerLayerIndex() const { return std::get<0>(layerTriplet_->layerTriplet()); } SeedingLayerSetsHits::LayerIndex middleLayerIndex() const { return std::get<1>(layerTriplet_->layerTriplet()); } @@ -119,11 +112,8 @@ class IntermediateHitTriplets { /** * Constructor for an iterator pointing to a valid element */ - const_iterator(const IntermediateHitTriplets *hitSets, const RegionLayerSets *regionLayerSets): - hitSets_(hitSets), - regionLayerSets_(regionLayerSets), - iter_(regionLayerSets->layerSetsBegin()) - { + const_iterator(const IntermediateHitTriplets *hitSets, const RegionLayerSets *regionLayerSets) + : hitSets_(hitSets), regionLayerSets_(regionLayerSets), iter_(regionLayerSets->layerSetsBegin()) { assert(regionLayerSets->layerSetsBegin() != regionLayerSets->layerSetsEnd()); } @@ -132,15 +122,12 @@ class IntermediateHitTriplets { * * The end_tag parameter is used to differentiate this constructor from the other one. */ - const_iterator(const IntermediateHitTriplets *hitSets, const RegionLayerSets *regionLayerSets, end_tag): - iter_(regionLayerSets->layerSetsEnd()) - {} + const_iterator(const IntermediateHitTriplets *hitSets, const RegionLayerSets *regionLayerSets, end_tag) + : iter_(regionLayerSets->layerSetsEnd()) {} - value_type operator*() const { - return value_type(hitSets_, &(*iter_)); - } + value_type operator*() const { return value_type(hitSets_, &(*iter_)); } - const_iterator& operator++() { + const_iterator &operator++() { ++iter_; return *this; } @@ -151,8 +138,8 @@ class IntermediateHitTriplets { return clone; } - bool operator==(const const_iterator& other) const { return iter_ == other.iter_; } - bool operator!=(const const_iterator& other) const { return !operator==(other); } + bool operator==(const const_iterator &other) const { return iter_ == other.iter_; } + bool operator!=(const const_iterator &other) const { return !operator==(other); } private: const IntermediateHitTriplets *hitSets_; @@ -160,23 +147,19 @@ class IntermediateHitTriplets { internal_iterator_type iter_; }; - RegionLayerSets(const TrackingRegion* region, + RegionLayerSets(const TrackingRegion *region, const LayerHitMapCache *cache, const IntermediateHitTriplets *hitSets, PLayerHitTripletsConstIterator tripletBegin, - PLayerHitTripletsConstIterator tripletEnd): - region_(region), - cache_(cache), - hitSets_(hitSets), - layerSetsBegin_(tripletBegin), layerSetsEnd_(tripletEnd) - {} - - const TrackingRegion& region() const { return *region_; } - const LayerHitMapCache& layerHitMapCache() const { return *cache_; } + PLayerHitTripletsConstIterator tripletEnd) + : region_(region), cache_(cache), hitSets_(hitSets), layerSetsBegin_(tripletBegin), layerSetsEnd_(tripletEnd) {} + + const TrackingRegion ®ion() const { return *region_; } + const LayerHitMapCache &layerHitMapCache() const { return *cache_; } size_t layerTripletsSize() const { return std::distance(layerSetsBegin_, layerSetsEnd_); } const_iterator begin() const { - if(layerSetsBegin_ != layerSetsEnd_) + if (layerSetsBegin_ != layerSetsEnd_) return const_iterator(hitSets_, this); else return end(); @@ -207,38 +190,40 @@ class IntermediateHitTriplets { /// Helper class enforcing correct way of filling the doublets of a region class RegionFiller { public: - RegionFiller(): obj_(nullptr) {} - explicit RegionFiller(IntermediateHitTriplets *obj): obj_(obj) {} + RegionFiller() : obj_(nullptr) {} + explicit RegionFiller(IntermediateHitTriplets *obj) : obj_(obj) {} ~RegionFiller() = default; bool valid() const { return obj_ != nullptr; } - LayerHitMapCache& layerHitMapCache() { return obj_->regions_.back().layerHitMapCache(); } + LayerHitMapCache &layerHitMapCache() { return obj_->regions_.back().layerHitMapCache(); } - void addTriplets(const LayerPair& layerPair, - const std::vector& thirdLayers, - const OrderedHitTriplets& triplets, - const std::vector& thirdLayerIndex, - const std::vector& permutations) { + void addTriplets(const LayerPair &layerPair, + const std::vector &thirdLayers, + const OrderedHitTriplets &triplets, + const std::vector &thirdLayerIndex, + const std::vector &permutations) { assert(triplets.size() == thirdLayerIndex.size()); assert(triplets.size() == permutations.size()); - if(triplets.empty()) { + if (triplets.empty()) { return; } int prevLayer = -1; - for(size_t i=0, size=permutations.size(); ilayerTriplets_.emplace_back(LayerTriplet(std::get<0>(layerPair), std::get<1>(layerPair), thirdLayers[layer].index()), obj_->hitTriplets_.size()); + obj_->layerTriplets_.emplace_back( + LayerTriplet(std::get<0>(layerPair), std::get<1>(layerPair), thirdLayers[layer].index()), + obj_->hitTriplets_.size()); } obj_->hitTriplets_.emplace_back(triplets[realIndex]); @@ -247,6 +232,7 @@ class IntermediateHitTriplets { obj_->regions_.back().setLayerSetsEnd(obj_->layerTriplets_.size()); } + private: IntermediateHitTriplets *obj_; }; @@ -256,16 +242,16 @@ class IntermediateHitTriplets { //////////////////// - IntermediateHitTriplets(): seedingLayers_(nullptr) {} - explicit IntermediateHitTriplets(const SeedingLayerSetsHits *seedingLayers): seedingLayers_(seedingLayers) {} - IntermediateHitTriplets(const IntermediateHitTriplets& rh); // only to make ROOT dictionary generation happy - IntermediateHitTriplets(IntermediateHitTriplets&&) = default; - IntermediateHitTriplets& operator=(IntermediateHitTriplets&&) = default; + IntermediateHitTriplets() : seedingLayers_(nullptr) {} + explicit IntermediateHitTriplets(const SeedingLayerSetsHits *seedingLayers) : seedingLayers_(seedingLayers) {} + IntermediateHitTriplets(const IntermediateHitTriplets &rh); // only to make ROOT dictionary generation happy + IntermediateHitTriplets(IntermediateHitTriplets &&) = default; + IntermediateHitTriplets &operator=(IntermediateHitTriplets &&) = default; ~IntermediateHitTriplets() = default; void reserve(size_t nregions, size_t nlayersets, size_t ntriplets) { regions_.reserve(nregions); - layerTriplets_.reserve(nregions*nlayersets); + layerTriplets_.reserve(nregions * nlayersets); hitTriplets_.reserve(ntriplets); } @@ -280,7 +266,7 @@ class IntermediateHitTriplets { return RegionFiller(this); } - const SeedingLayerSetsHits& seedingLayerHits() const { return *seedingLayers_; } + const SeedingLayerSetsHits &seedingLayerHits() const { return *seedingLayers_; } bool empty() const { return regions_.empty(); } size_t regionSize() const { return regions_.size(); } size_t tripletsSize() const { return hitTriplets_.size(); } @@ -299,11 +285,12 @@ class IntermediateHitTriplets { std::vector::const_iterator tripletsEnd() const { return hitTriplets_.end(); } private: - const SeedingLayerSetsHits *seedingLayers_; /// Pointer to SeedingLayerSetsHits (owned elsewhere) + const SeedingLayerSetsHits *seedingLayers_; /// Pointer to SeedingLayerSetsHits (owned elsewhere) - std::vector regions_; /// Container of regions, each element has indices pointing to layerTriplets_ - std::vector layerTriplets_; /// Container of layer triplets, each element has indices pointing to hitTriplets_ - std::vector hitTriplets_; /// Container of hit triplets for all layer triplets and regions + std::vector regions_; /// Container of regions, each element has indices pointing to layerTriplets_ + std::vector + layerTriplets_; /// Container of layer triplets, each element has indices pointing to hitTriplets_ + std::vector hitTriplets_; /// Container of hit triplets for all layer triplets and regions }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h b/RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h index c1bfc9756dbea..b557906a05fa7 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h +++ b/RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h @@ -16,7 +16,6 @@ namespace LayerTriplets { using LayerSetAndLayers = std::pair >; std::vector layers(const SeedingLayerSetsHits& sets); -} +} // namespace LayerTriplets #endif - diff --git a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitSeeds.h b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitSeeds.h index 0a0059c3513a6..0cf7df6aa6a9e 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitSeeds.h +++ b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitSeeds.h @@ -8,14 +8,10 @@ class OrderedHitSeeds : public std::vector, public OrderedSeedingHits { public: - - ~OrderedHitSeeds() override{} + ~OrderedHitSeeds() override {} unsigned int size() const override { return std::vector::size(); } - const SeedingHitSet & operator[](unsigned int i) const override { - return std::vector::operator[](i); - } - + const SeedingHitSet& operator[](unsigned int i) const override { return std::vector::operator[](i); } }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplet.h b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplet.h index b1ffe533445bb..548ba054dd9a4 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplet.h +++ b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplet.h @@ -1,6 +1,5 @@ #ifndef OrderedHitTriplet_H -#define OrderedHitTriplet_H - +#define OrderedHitTriplet_H /** \class OrderedHitTriplet * Associate 3 RecHits into hit triplet of InnerHit,MiddleHit,OuterHit @@ -10,20 +9,16 @@ #include "RecoTracker/TkSeedingLayers/interface/SeedingHitSet.h" class OrderedHitTriplet : public SeedingHitSet { - public: - typedef SeedingHitSet::ConstRecHitPointer InnerRecHit; typedef SeedingHitSet::ConstRecHitPointer OuterRecHit; typedef SeedingHitSet::ConstRecHitPointer MiddleRecHit; + OrderedHitTriplet(const InnerRecHit& ih, const MiddleRecHit& mh, const OuterRecHit& oh) : SeedingHitSet(ih, mh, oh) {} - OrderedHitTriplet( const InnerRecHit & ih, const MiddleRecHit & mh, const OuterRecHit & oh) : SeedingHitSet(ih,mh,oh){} - - InnerRecHit inner() const { return get(0); } - MiddleRecHit middle() const { return get(1); } - OuterRecHit outer() const { return get(2); } - + InnerRecHit inner() const { return get(0); } + MiddleRecHit middle() const { return get(1); } + OuterRecHit outer() const { return get(2); } }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplets.h b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplets.h index bcd8d505669d8..85138c13fc5db 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplets.h +++ b/RecoPixelVertexing/PixelTriplets/interface/OrderedHitTriplets.h @@ -8,14 +8,12 @@ class OrderedHitTriplets : public std::vector, public OrderedSeedingHits { public: - - ~OrderedHitTriplets() override{} + ~OrderedHitTriplets() override {} unsigned int size() const override { return std::vector::size(); } - const OrderedHitTriplet & operator[](unsigned int i) const override { + const OrderedHitTriplet& operator[](unsigned int i) const override { return std::vector::operator[](i); } - }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/interface/ThirdHitPredictionFromCircle.h b/RecoPixelVertexing/PixelTriplets/interface/ThirdHitPredictionFromCircle.h index ede3a5b346e6c..5c38604c9e26b 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/ThirdHitPredictionFromCircle.h +++ b/RecoPixelVertexing/PixelTriplets/interface/ThirdHitPredictionFromCircle.h @@ -7,17 +7,14 @@ #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "RecoTracker/TkMSParametrization/interface/PixelRecoRange.h" - class ThirdHitPredictionFromCircle { - public: using Scalar = double; typedef PixelRecoRange Range; typedef Basic2DVector Vector2D; typedef Basic2DVector VectorF2D; - ThirdHitPredictionFromCircle(const GlobalPoint & P1, const GlobalPoint & P2, - float tolerance); + ThirdHitPredictionFromCircle(const GlobalPoint &P1, const GlobalPoint &P2, float tolerance); float phi(float curvature, float radius) const; float angle(float curvature, float radius) const; @@ -25,28 +22,26 @@ class ThirdHitPredictionFromCircle { Range operator()(Range curvature, float radius) const; Range curvature(double transverseIP) const; - double curvature(const Vector2D &thirdPoint) const; - double transverseIP(const Vector2D &thirdPoint) const; + double curvature(const Vector2D &thirdPoint) const; + double transverseIP(const Vector2D &thirdPoint) const; // like PixelRecoLineRZ, but makes use of the bending computation // from the circle fit to get an actual Helix propagation class HelixRZ { - public: - using Vector2D=ThirdHitPredictionFromCircle::Vector2D; - using Scalar=ThirdHitPredictionFromCircle::Scalar; + public: + using Vector2D = ThirdHitPredictionFromCircle::Vector2D; + using Scalar = ThirdHitPredictionFromCircle::Scalar; // using Vector2D=ThirdHitPredictionFromCircle::VectorF2D; // using Scalar=float; - + HelixRZ() : circle(nullptr) {} - HelixRZ(const ThirdHitPredictionFromCircle *icircle, - double iz1, double z2, double curv); - + HelixRZ(const ThirdHitPredictionFromCircle *icircle, double iz1, double z2, double curv); + Scalar zAtR(Scalar r) const; Scalar rAtZ(Scalar z) const; - - static double maxCurvature(const ThirdHitPredictionFromCircle *circle, - double z1, double z2, double z3); - + + static double maxCurvature(const ThirdHitPredictionFromCircle *circle, double z1, double z2, double z3); + private: const ThirdHitPredictionFromCircle *circle; Vector2D center; @@ -56,7 +51,7 @@ class ThirdHitPredictionFromCircle { private: friend class HelixRZ; - Scalar invCenterOnAxis(const Vector2D &thirdPoint) const; + Scalar invCenterOnAxis(const Vector2D &thirdPoint) const; Vector2D p1, center, axis; Scalar delta, delta2; diff --git a/RecoPixelVertexing/PixelTriplets/interface/ThirdHitRZPredictionBase.h b/RecoPixelVertexing/PixelTriplets/interface/ThirdHitRZPredictionBase.h index 46ebec58add13..8f7d839178996 100644 --- a/RecoPixelVertexing/PixelTriplets/interface/ThirdHitRZPredictionBase.h +++ b/RecoPixelVertexing/PixelTriplets/interface/ThirdHitRZPredictionBase.h @@ -23,11 +23,11 @@ class ThirdHitRZPredictionBase { ThirdHitRZPredictionBase(); ThirdHitRZPredictionBase(float tolerance, const DetLayer* layer = nullptr); - const Range & detRange() const { return theDetRange; } - const Range & detSize() const { return theDetSize; } + const Range& detRange() const { return theDetRange; } + const Range& detSize() const { return theDetSize; } void initTolerance(float tolerance) { theTolerance = Margin(tolerance, tolerance); } - void initLayer(const DetLayer *layer); + void initLayer(const DetLayer* layer); protected: bool theBarrel, theForward; diff --git a/RecoPixelVertexing/PixelTriplets/plugins/CAHitNtupletEDProducerT.cc b/RecoPixelVertexing/PixelTriplets/plugins/CAHitNtupletEDProducerT.cc index 4acbd3050bddf..685a249454cb0 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/CAHitNtupletEDProducerT.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/CAHitNtupletEDProducerT.cc @@ -13,16 +13,15 @@ #include "RecoTracker/TkHitPairs/interface/IntermediateHitDoublets.h" namespace { - void fillNtuplets(RegionsSeedingHitSets::RegionFiller& seedingHitSetsFiller, - const OrderedHitSeeds& quadruplets) { - for(const auto& quad: quadruplets) { + void fillNtuplets(RegionsSeedingHitSets::RegionFiller& seedingHitSetsFiller, const OrderedHitSeeds& quadruplets) { + for (const auto& quad : quadruplets) { seedingHitSetsFiller.emplace_back(quad[0], quad[1], quad[2], quad[3]); } } -} +} // namespace template -class CAHitNtupletEDProducerT: public edm::stream::EDProducer<> { +class CAHitNtupletEDProducerT : public edm::stream::EDProducer<> { public: CAHitNtupletEDProducerT(const edm::ParameterSet& iConfig); ~CAHitNtupletEDProducerT() override = default; @@ -40,10 +39,9 @@ class CAHitNtupletEDProducerT: public edm::stream::EDProducer<> { }; template -CAHitNtupletEDProducerT::CAHitNtupletEDProducerT(const edm::ParameterSet& iConfig): - doubletToken_(consumes(iConfig.getParameter("doublets"))), - generator_(iConfig, consumesCollector()) -{ +CAHitNtupletEDProducerT::CAHitNtupletEDProducerT(const edm::ParameterSet& iConfig) + : doubletToken_(consumes(iConfig.getParameter("doublets"))), + generator_(iConfig, consumesCollector()) { produces(); } @@ -65,26 +63,32 @@ void CAHitNtupletEDProducerT::produce(edm::Event& iEvent, const edm const auto& regionDoublets = *hdoublets; const SeedingLayerSetsHits& seedingLayerHits = regionDoublets.seedingLayerHits(); - if(seedingLayerHits.numberOfLayersInSet() < T_Generator::minLayers) { - throw cms::Exception("LogicError") << "CAHitNtupletEDProducer expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= " << T_Generator::minLayers << ", got " << seedingLayerHits.numberOfLayersInSet() << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or SeedingLayersEDProducer."; + if (seedingLayerHits.numberOfLayersInSet() < T_Generator::minLayers) { + throw cms::Exception("LogicError") + << "CAHitNtupletEDProducer expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= " + << T_Generator::minLayers << ", got " << seedingLayerHits.numberOfLayersInSet() + << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or " + "SeedingLayersEDProducer."; } auto seedingHitSets = std::make_unique(); - if(regionDoublets.empty()) { + if (regionDoublets.empty()) { iEvent.put(std::move(seedingHitSets)); return; } seedingHitSets->reserve(regionDoublets.regionSize(), localRA_.upper()); generator_.initEvent(iEvent, iSetup); - LogDebug("CAHitNtupletEDProducer") << "Creating ntuplets for " << regionDoublets.regionSize() << " regions, and " << regionDoublets.layerPairsSize() << " layer pairs"; + LogDebug("CAHitNtupletEDProducer") << "Creating ntuplets for " << regionDoublets.regionSize() << " regions, and " + << regionDoublets.layerPairsSize() << " layer pairs"; std::vector ntuplets; ntuplets.resize(regionDoublets.regionSize()); - for(auto& ntuplet : ntuplets) ntuplet.reserve(localRA_.upper()); + for (auto& ntuplet : ntuplets) + ntuplet.reserve(localRA_.upper()); generator_.hitNtuplets(regionDoublets, ntuplets, iSetup, seedingLayerHits); int index = 0; - for(const auto& regionLayerPairs: regionDoublets) { + for (const auto& regionLayerPairs : regionDoublets) { const TrackingRegion& region = regionLayerPairs.region(); auto seedingHitSetsFiller = seedingHitSets->beginRegion(®ion); diff --git a/RecoPixelVertexing/PixelTriplets/plugins/CombinedHitTripletGenerator.h b/RecoPixelVertexing/PixelTriplets/plugins/CombinedHitTripletGenerator.h index c82aff699e7df..9980eb3df06a7 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/CombinedHitTripletGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/CombinedHitTripletGenerator.h @@ -4,7 +4,7 @@ /** A HitTripletGenerator consisting of a set of * triplet generators of type HitTripletGeneratorFromPairAndLayers * initialised from provided layers in the form of PixelLayerTriplets - */ + */ #include #include @@ -20,27 +20,32 @@ class TrackingRegion; class HitTripletGeneratorFromPairAndLayers; class SeedingLayerSetsHits; -namespace edm { class Event; } -namespace edm { class EventSetup; } +namespace edm { + class Event; +} +namespace edm { + class EventSetup; +} class CombinedHitTripletGenerator : public HitTripletGenerator { public: - typedef LayerHitMapCache LayerCacheType; + typedef LayerHitMapCache LayerCacheType; public: - - CombinedHitTripletGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); + CombinedHitTripletGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); ~CombinedHitTripletGenerator() override; /// from base class - void hitTriplets( const TrackingRegion& reg, OrderedHitTriplets & triplets, - const edm::Event & ev, const edm::EventSetup& es) override; + void hitTriplets(const TrackingRegion& reg, + OrderedHitTriplets& triplets, + const edm::Event& ev, + const edm::EventSetup& es) override; private: edm::EDGetTokenT theSeedingLayerToken; - LayerCacheType theLayerCache; + LayerCacheType theLayerCache; std::unique_ptr theGenerator; }; diff --git a/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.cc b/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.cc index 27128efbfcde1..7a516291168ef 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.cc @@ -11,19 +11,15 @@ // Note: only the TIB layers seem to cause a significant effect, // so only z correction is implemented -MatchedHitRZCorrectionFromBending:: -MatchedHitRZCorrectionFromBending(DetId detId, const TrackerTopology *tTopo) - : rFixup(nullptr), zFixup(nullptr) -{ - if (detId.subdetId() == SiStripDetId::TIB && - tTopo->tibIsDoubleSide(detId)) +MatchedHitRZCorrectionFromBending::MatchedHitRZCorrectionFromBending(DetId detId, const TrackerTopology *tTopo) + : rFixup(nullptr), zFixup(nullptr) { + if (detId.subdetId() == SiStripDetId::TIB && tTopo->tibIsDoubleSide(detId)) zFixup = tibMatchedHitZFixup; } -MatchedHitRZCorrectionFromBending:: - MatchedHitRZCorrectionFromBending(const DetLayer *layer, const TrackerTopology *tTopo) - : rFixup(nullptr), zFixup(nullptr) -{ +MatchedHitRZCorrectionFromBending::MatchedHitRZCorrectionFromBending(const DetLayer *layer, + const TrackerTopology *tTopo) + : rFixup(nullptr), zFixup(nullptr) { if (layer->subDetector() == GeomDetEnumerators::TIB) { const GeometricSearchDet *tibLayer = layer; @@ -32,16 +28,14 @@ MatchedHitRZCorrectionFromBending:: } } -double MatchedHitRZCorrectionFromBending:: - tibMatchedHitZFixup(const ThirdHitPredictionFromCircle &pred, - double curvature, double r, - const TrackingRecHit &hit, - const TrackerTopology *tTopo) -{ +double MatchedHitRZCorrectionFromBending::tibMatchedHitZFixup(const ThirdHitPredictionFromCircle &pred, + double curvature, + double r, + const TrackingRecHit &hit, + const TrackerTopology *tTopo) { // the factors for [ TIB1=0, TIB2=1 ] [ inner string=0, outer string=1 ] - static const double factors[2][2] = { { -2.4, 2.4 }, { 2.4, -2.4 } }; + static const double factors[2][2] = {{-2.4, 2.4}, {2.4, -2.4}}; - unsigned int layer = tTopo->tibLayer(hit.det()->geographicalId()) - 1; unsigned int string = !tTopo->tibIsInternalString(hit.det()->geographicalId()); return factors[layer][string] * pred.angle(curvature, r); diff --git a/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.h b/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.h index 970d4ae15a7bb..fdaecf70ccff3 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/MatchedHitRZCorrectionFromBending.h @@ -9,32 +9,39 @@ class DetLayer; class TrackerTopology; class MatchedHitRZCorrectionFromBending { - public: - MatchedHitRZCorrectionFromBending() : rFixup(nullptr), zFixup(nullptr) {} - MatchedHitRZCorrectionFromBending(DetId detId, const TrackerTopology *tTopo ); - MatchedHitRZCorrectionFromBending(const DetLayer *layer, const TrackerTopology *tTopo); - - inline void operator()(const ThirdHitPredictionFromCircle &pred, - double curvature, const TrackingRecHit &hit, - double &r, double &z, const TrackerTopology *tTopo) const - { - if (!rFixup && !zFixup) return; - if (rFixup) r += rFixup(pred, curvature, z, hit,tTopo); - if (zFixup) z += zFixup(pred, curvature, r, hit,tTopo); - } - - private: - typedef double (*FixupFn)(const ThirdHitPredictionFromCircle &pred, - double curvature, double rOrZ, - const TrackingRecHit &hit, - const TrackerTopology *tTopo); - - static double tibMatchedHitZFixup(const ThirdHitPredictionFromCircle &pred, - double curvature, double rOrZ, - const TrackingRecHit &hit, - const TrackerTopology *tTopo); - - FixupFn rFixup, zFixup; +public: + MatchedHitRZCorrectionFromBending() : rFixup(nullptr), zFixup(nullptr) {} + MatchedHitRZCorrectionFromBending(DetId detId, const TrackerTopology *tTopo); + MatchedHitRZCorrectionFromBending(const DetLayer *layer, const TrackerTopology *tTopo); + + inline void operator()(const ThirdHitPredictionFromCircle &pred, + double curvature, + const TrackingRecHit &hit, + double &r, + double &z, + const TrackerTopology *tTopo) const { + if (!rFixup && !zFixup) + return; + if (rFixup) + r += rFixup(pred, curvature, z, hit, tTopo); + if (zFixup) + z += zFixup(pred, curvature, r, hit, tTopo); + } + +private: + typedef double (*FixupFn)(const ThirdHitPredictionFromCircle &pred, + double curvature, + double rOrZ, + const TrackingRecHit &hit, + const TrackerTopology *tTopo); + + static double tibMatchedHitZFixup(const ThirdHitPredictionFromCircle &pred, + double curvature, + double rOrZ, + const TrackingRecHit &hit, + const TrackerTopology *tTopo); + + FixupFn rFixup, zFixup; }; -#endif // MatchedHitRZCorrectionFromBending_H +#endif // MatchedHitRZCorrectionFromBending_H diff --git a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletHLTGenerator.h b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletHLTGenerator.h index 7449f433c0f33..667d9bc3c3a81 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletHLTGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletHLTGenerator.h @@ -18,46 +18,50 @@ class SeedComparitor; class PixelTripletHLTGenerator : public HitTripletGeneratorFromPairAndLayers { - -typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; + typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; public: - PixelTripletHLTGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC): PixelTripletHLTGenerator(cfg, iC) {} - PixelTripletHLTGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); + PixelTripletHLTGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC) + : PixelTripletHLTGenerator(cfg, iC) {} + PixelTripletHLTGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); ~PixelTripletHLTGenerator() override; static void fillDescriptions(edm::ParameterSetDescription& desc); - static const char *fillDescriptionsLabel() { return "pixelTripletHLT"; } - - void hitTriplets( const TrackingRegion& region, OrderedHitTriplets & trs, - const edm::Event & ev, const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) override; - - void hitTriplets(const TrackingRegion& region, OrderedHitTriplets& trs, - const edm::Event& ev, const edm::EventSetup& es, + static const char* fillDescriptionsLabel() { return "pixelTripletHLT"; } + + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) override; + + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, const HitDoublets& doublets, const std::vector& thirdLayers, - std::vector *tripletLastLayerIndex, + std::vector* tripletLastLayerIndex, LayerCacheType& layerCache); - void hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)override; + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) override; - void hitTriplets(const TrackingRegion& region, OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, const int nThirdLayers, - std::vector *tripletLastLayerIndex); + std::vector* tripletLastLayerIndex); private: const bool useFixedPreFiltering; @@ -67,8 +71,5 @@ typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; const bool useBend; const float dphi; std::unique_ptr theComparitor; - }; #endif - - diff --git a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.cc b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.cc index 08af9539f0d46..2662b65e406c1 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.cc @@ -28,8 +28,8 @@ using namespace std; -using Range=PixelRecoRange; -using HelixRZ=ThirdHitPredictionFromCircle::HelixRZ; +using Range = PixelRecoRange; +using HelixRZ = ThirdHitPredictionFromCircle::HelixRZ; namespace { struct LayerRZPredictions { @@ -38,21 +38,20 @@ namespace { MatchedHitRZCorrectionFromBending rzPositionFixup; ThirdHitCorrection correction; }; -} +} // namespace -constexpr double nSigmaRZ = 3.4641016151377544; // sqrt(12.) +constexpr double nSigmaRZ = 3.4641016151377544; // sqrt(12.) constexpr float nSigmaPhi = 3.; constexpr float fnSigmaRZ = nSigmaRZ; - PixelTripletLargeTipGenerator::PixelTripletLargeTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) - : HitTripletGeneratorFromPairAndLayers(cfg), - useFixedPreFiltering(cfg.getParameter("useFixedPreFiltering")), - extraHitRZtolerance(cfg.getParameter("extraHitRZtolerance")), - extraHitRPhitolerance(cfg.getParameter("extraHitRPhitolerance")), - useMScat(cfg.getParameter("useMultScattering")), - useBend(cfg.getParameter("useBending")), - dphi(useFixedPreFiltering ? cfg.getParameter("phiPreFiltering") : 0) {} + : HitTripletGeneratorFromPairAndLayers(cfg), + useFixedPreFiltering(cfg.getParameter("useFixedPreFiltering")), + extraHitRZtolerance(cfg.getParameter("extraHitRZtolerance")), + extraHitRPhitolerance(cfg.getParameter("extraHitRPhitolerance")), + useMScat(cfg.getParameter("useMultScattering")), + useBend(cfg.getParameter("useBending")), + dphi(useFixedPreFiltering ? cfg.getParameter("phiPreFiltering") : 0) {} PixelTripletLargeTipGenerator::~PixelTripletLargeTipGenerator() {} @@ -60,8 +59,8 @@ void PixelTripletLargeTipGenerator::fillDescriptions(edm::ParameterSetDescriptio HitTripletGeneratorFromPairAndLayers::fillDescriptions(desc); // Defaults for the extraHit*tolerance are set to 0 here since that // was already the case in practice in all offline occurrances. - desc.add("extraHitRPhitolerance", 0); // default in old python was 0.032 - desc.add("extraHitRZtolerance", 0); // default in old python was 0.037 + desc.add("extraHitRPhitolerance", 0); // default in old python was 0.032 + desc.add("extraHitRZtolerance", 0); // default in old python was 0.037 desc.add("useMultScattering", true); desc.add("useBending", true); desc.add("useFixedPreFiltering", false); @@ -69,10 +68,8 @@ void PixelTripletLargeTipGenerator::fillDescriptions(edm::ParameterSetDescriptio } namespace { - inline - bool intersect(Range &range, const Range &second) - { - if ( (range.min() > second.max()) | (range.max() < second.min()) ) + inline bool intersect(Range& range, const Range& second) { + if ((range.min() > second.max()) | (range.max() < second.min())) return false; if (range.first < second.min()) range.first = second.min(); @@ -80,161 +77,168 @@ namespace { range.second = second.max(); return range.first < range.second; } -} +} // namespace -void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::Event & ev, - const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) -{ - auto const & doublets = thePairGenerator->doublets(region,ev,es, pairLayers); - - if (doublets.empty()) return; +void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) { + auto const& doublets = thePairGenerator->doublets(region, ev, es, pairLayers); + + if (doublets.empty()) + return; assert(theLayerCache); - hitTriplets(region, result, ev, es, doublets,thirdLayers, nullptr, *theLayerCache); + hitTriplets(region, result, ev, es, doublets, thirdLayers, nullptr, *theLayerCache); } -void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, OrderedHitTriplets& result, - const edm::Event& ev, const edm::EventSetup& es, +void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::Event& ev, + const edm::EventSetup& es, const HitDoublets& doublets, const std::vector& thirdLayers, - std::vector *tripletLastLayerIndex, + std::vector* tripletLastLayerIndex, LayerCacheType& layerCache) { int size = thirdLayers.size(); - const RecHitsSortedInPhi * thirdHitMap[size]; - vector thirdLayerDetLayer(size,nullptr); - for (int il=0; il thirdLayerDetLayer(size, nullptr); + for (int il = 0; il < size; ++il) { + thirdHitMap[il] = &layerCache(thirdLayers[il], region, es); + thirdLayerDetLayer[il] = thirdLayers[il].detLayer(); + } hitTriplets(region, result, es, doublets, thirdHitMap, thirdLayerDetLayer, size, tripletLastLayerIndex); } - -void PixelTripletLargeTipGenerator::hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers) -{ +void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) { hitTriplets(region, result, es, doublets, thirdHitMap, thirdLayerDetLayer, nThirdLayers, nullptr); } -void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, +void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, const int nThirdLayers, - std::vector *tripletLastLayerIndex) { + std::vector* tripletLastLayerIndex) { edm::ESHandle tracker; es.get().get(tracker); //Retrieve tracker topology from geometry edm::ESHandle tTopoHand; es.get().get(tTopoHand); - const TrackerTopology *tTopo=tTopoHand.product(); + const TrackerTopology* tTopo = tTopoHand.product(); - - auto outSeq = doublets.detLayer(HitDoublets::outer)->seqNum(); + auto outSeq = doublets.detLayer(HitDoublets::outer)->seqNum(); - using NodeInfo = KDTreeNodeInfo; - std::vector layerTree; // re-used throughout - std::vector foundNodes; // re-used throughout + using NodeInfo = KDTreeNodeInfo; + std::vector layerTree; // re-used throughout + std::vector foundNodes; // re-used throughout foundNodes.reserve(100); declareDynArray(KDTreeLinkerAlgo, nThirdLayers, hitTree); declareDynArray(LayerRZPredictions, nThirdLayers, mapPred); - float rzError[nThirdLayers]; //save maximum errors + float rzError[nThirdLayers]; //save maximum errors - const float maxDelphi = region.ptMin() < 0.3f ? float(M_PI)/4.f : float(M_PI)/8.f; // FIXME move to config?? - const float maxphi = M_PI+maxDelphi, minphi = -maxphi; // increase to cater for any range - const float safePhi = M_PI-maxDelphi; // sideband + const float maxDelphi = region.ptMin() < 0.3f ? float(M_PI) / 4.f : float(M_PI) / 8.f; // FIXME move to config?? + const float maxphi = M_PI + maxDelphi, minphi = -maxphi; // increase to cater for any range + const float safePhi = M_PI - maxDelphi; // sideband - for(int il = 0; il < nThirdLayers; il++) { - - auto const & hits = *thirdHitMap[il]; - - const DetLayer *layer = thirdLayerDetLayer[il]; - LayerRZPredictions &predRZ = mapPred[il]; + for (int il = 0; il < nThirdLayers; il++) { + auto const& hits = *thirdHitMap[il]; + + const DetLayer* layer = thirdLayerDetLayer[il]; + LayerRZPredictions& predRZ = mapPred[il]; predRZ.line.initLayer(layer); predRZ.helix1.initLayer(layer); predRZ.helix2.initLayer(layer); predRZ.line.initTolerance(extraHitRZtolerance); predRZ.helix1.initTolerance(extraHitRZtolerance); predRZ.helix2.initTolerance(extraHitRZtolerance); - predRZ.rzPositionFixup = MatchedHitRZCorrectionFromBending(layer,tTopo); - predRZ.correction.init(es, region.ptMin(), *doublets.detLayer(HitDoublets::inner), *doublets.detLayer(HitDoublets::outer), *thirdLayerDetLayer[il], useMScat, false); - + predRZ.rzPositionFixup = MatchedHitRZCorrectionFromBending(layer, tTopo); + predRZ.correction.init(es, + region.ptMin(), + *doublets.detLayer(HitDoublets::inner), + *doublets.detLayer(HitDoublets::outer), + *thirdLayerDetLayer[il], + useMScat, + false); layerTree.clear(); - float minv=999999.0; float maxv = -999999.0; // Initialise to extreme values in case no hits - float maxErr=0.0f; - for (unsigned int i=0; i!=hits.size(); ++i) { + float minv = 999999.0; + float maxv = -999999.0; // Initialise to extreme values in case no hits + float maxErr = 0.0f; + for (unsigned int i = 0; i != hits.size(); ++i) { auto angle = hits.phi(i); - auto v = hits.gv(i); + auto v = hits.gv(i); //use (phi,r) for endcaps rather than (phi,z) - minv = std::min(minv,v); maxv = std::max(maxv,v); + minv = std::min(minv, v); + maxv = std::max(maxv, v); float myerr = hits.dv[i]; - maxErr = std::max(maxErr,myerr); - layerTree.emplace_back(i, angle, v); // save it + maxErr = std::max(maxErr, myerr); + layerTree.emplace_back(i, angle, v); // save it // populate side-bands - if (angle>safePhi) layerTree.emplace_back(i, angle-Geom::ftwoPi(), v); - else if (angle<-safePhi) layerTree.emplace_back(i, angle+Geom::ftwoPi(), v); + if (angle > safePhi) + layerTree.emplace_back(i, angle - Geom::ftwoPi(), v); + else if (angle < -safePhi) + layerTree.emplace_back(i, angle + Geom::ftwoPi(), v); } - KDTreeBox phiZ(minphi, maxphi, minv-0.01f, maxv+0.01f); // declare our bounds + KDTreeBox phiZ(minphi, maxphi, minv - 0.01f, maxv + 0.01f); // declare our bounds //add fudge factors in case only one hit and also for floating-point inaccuracy - hitTree[il].build(layerTree, phiZ); // make KDtree - rzError[il] = maxErr; //save error + hitTree[il].build(layerTree, phiZ); // make KDtree + rzError[il] = maxErr; //save error } double curv = PixelRecoUtilities::curvature(1. / region.ptMin(), es); - - for (std::size_t ip =0; ip!=doublets.size(); ip++) { - auto xi = doublets.x(ip,HitDoublets::inner); - auto yi = doublets.y(ip,HitDoublets::inner); - auto zi = doublets.z(ip,HitDoublets::inner); + + for (std::size_t ip = 0; ip != doublets.size(); ip++) { + auto xi = doublets.x(ip, HitDoublets::inner); + auto yi = doublets.y(ip, HitDoublets::inner); + auto zi = doublets.z(ip, HitDoublets::inner); // auto rvi = doublets.rv(ip,HitDoublets::inner); - auto xo = doublets.x(ip,HitDoublets::outer); - auto yo = doublets.y(ip,HitDoublets::outer); - auto zo = doublets.z(ip,HitDoublets::outer); + auto xo = doublets.x(ip, HitDoublets::outer); + auto yo = doublets.y(ip, HitDoublets::outer); + auto zo = doublets.z(ip, HitDoublets::outer); // auto rvo = doublets.rv(ip,HitDoublets::outer); - GlobalPoint gp1(xi,yi,zi); - GlobalPoint gp2(xo,yo,zo); + GlobalPoint gp1(xi, yi, zi); + GlobalPoint gp2(xo, yo, zo); - auto toPos = std::signbit(zo-zi); + auto toPos = std::signbit(zo - zi); PixelRecoLineRZ line(gp1, gp2); PixelRecoPointRZ point2(gp2.perp(), zo); ThirdHitPredictionFromCircle predictionRPhi(gp1, gp2, extraHitRPhitolerance); Range generalCurvature = predictionRPhi.curvature(region.originRBound()); - if (!intersect(generalCurvature, Range(-curv, curv))) continue; + if (!intersect(generalCurvature, Range(-curv, curv))) + continue; - for(int il = 0; il < nThirdLayers; il++) { - if (hitTree[il].empty()) continue; // Don't bother if no hits - const DetLayer *layer = thirdLayerDetLayer[il]; + for (int il = 0; il < nThirdLayers; il++) { + if (hitTree[il].empty()) + continue; // Don't bother if no hits + const DetLayer* layer = thirdLayerDetLayer[il]; bool barrelLayer = layer->isBarrel(); - if ( (!barrelLayer) & (toPos != std::signbit(layer->position().z())) ) continue; + if ((!barrelLayer) & (toPos != std::signbit(layer->position().z()))) + continue; - Range curvature = generalCurvature; - LayerRZPredictions &predRZ = mapPred[il]; + LayerRZPredictions& predRZ = mapPred[il]; predRZ.line.initPropagator(&line); - auto & correction = predRZ.correction; - correction.init(line, point2, outSeq); - + auto& correction = predRZ.correction; + correction.init(line, point2, outSeq); Range rzRange; if (useBend) { @@ -243,7 +247,7 @@ void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, Or // negative to positive bending, can give us a sort of U-shaped // projection onto the phi-z (barrel) or r-z plane (forward) // so we checking minimum/maximum of all three possible extrema - // + // // For the endcap region: // Checking minimum/maximum radius of the helix projection // onto an endcap plane, here we have to guard against @@ -255,30 +259,28 @@ void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, Or // In order to avoid looking for potential looping tracks at all // we also clamp the allowed curvature range for this layer, // and potentially fail the layer entirely - + if (!barrelLayer) { Range z3s = predRZ.line.detRange(); - double z3 = z3s.first < 0 ? std::max(z3s.first, z3s.second) - : std::min(z3s.first, z3s.second); - double maxCurvature = HelixRZ::maxCurvature(&predictionRPhi, - gp1.z(), gp2.z(), z3); + double z3 = z3s.first < 0 ? std::max(z3s.first, z3s.second) : std::min(z3s.first, z3s.second); + double maxCurvature = HelixRZ::maxCurvature(&predictionRPhi, gp1.z(), gp2.z(), z3); if (!intersect(curvature, Range(-maxCurvature, maxCurvature))) continue; } - + HelixRZ helix1(&predictionRPhi, gp1.z(), gp2.z(), curvature.first); HelixRZ helix2(&predictionRPhi, gp1.z(), gp2.z(), curvature.second); - + predRZ.helix1.initPropagator(&helix1); predRZ.helix2.initPropagator(&helix2); - - Range rzRanges[2] = { predRZ.helix1(), predRZ.helix2() }; + + Range rzRanges[2] = {predRZ.helix1(), predRZ.helix2()}; predRZ.helix1.initPropagator(nullptr); predRZ.helix2.initPropagator(nullptr); rzRange.first = std::min(rzRanges[0].first, rzRanges[1].first); rzRange.second = std::max(rzRanges[0].second, rzRanges[1].second); - + // if the allowed curvatures include a straight line, // this can give us another extremum for allowed r/z if (curvature.first * curvature.second < 0.0) { @@ -297,11 +299,11 @@ void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, Or Range phiRange; if (useFixedPreFiltering) { - float phi0 = doublets.phi(ip,HitDoublets::outer); + float phi0 = doublets.phi(ip, HitDoublets::outer); phiRange = Range(phi0 - dphi, phi0 + dphi); } else { Range radius; - + if (barrelLayer) { radius = predRZ.line.detRange(); if (!intersect(rzRange, predRZ.line.detSize())) @@ -311,115 +313,117 @@ void PixelTripletLargeTipGenerator::hitTriplets(const TrackingRegion& region, Or if (!intersect(radius, predRZ.line.detSize())) continue; } - + //gc: predictionRPhi uses the cosine rule to find the phi of the 3rd point at radius, assuming the pairCurvature range [-c,+c] - if ( (curvature.first<0.0f) & (curvature.second<0.0f) ) { + if ((curvature.first < 0.0f) & (curvature.second < 0.0f)) { radius.swap(); - } else if ( (curvature.first>=0.0f) & (curvature.second>=0.0f) ) {;} - else { - radius.first=radius.second; + } else if ((curvature.first >= 0.0f) & (curvature.second >= 0.0f)) { + ; + } else { + radius.first = radius.second; } - auto phi12 = predictionRPhi.phi(curvature.first,radius.first); - auto phi22 = predictionRPhi.phi(curvature.second,radius.second); + auto phi12 = predictionRPhi.phi(curvature.first, radius.first); + auto phi22 = predictionRPhi.phi(curvature.second, radius.second); phi12 = normalizedPhi(phi12); - phi22 = proxim(phi22,phi12); - phiRange = Range(phi12,phi22); phiRange.sort(); + phi22 = proxim(phi22, phi12); + phiRange = Range(phi12, phi22); + phiRange.sort(); auto rmean = radius.mean(); phiRange.first *= rmean; - phiRange.second *= rmean; - correction.correctRPhiRange(phiRange); - phiRange.first /= rmean; + phiRange.second *= rmean; + correction.correctRPhiRange(phiRange); + phiRange.first /= rmean; phiRange.second /= rmean; - } - - foundNodes.clear(); // Now recover hits in bounding box... - float prmin=phiRange.min(), prmax=phiRange.max(); //get contiguous range - if (prmax-prmin>maxDelphi) { + foundNodes.clear(); // Now recover hits in bounding box... + float prmin = phiRange.min(), prmax = phiRange.max(); //get contiguous range + + if (prmax - prmin > maxDelphi) { auto prm = phiRange.mean(); - prmin = prm - 0.5f*maxDelphi; - prmax = prm + 0.5f*maxDelphi; + prmin = prm - 0.5f * maxDelphi; + prmax = prm + 0.5f * maxDelphi; } if (barrelLayer) { - Range regMax = predRZ.line.detRange(); - Range regMin = predRZ.line(regMax.min()); - regMax = predRZ.line(regMax.max()); - correction.correctRZRange(regMin); - correction.correctRZRange(regMax); - if (regMax.min() < regMin.min()) { std::swap(regMax, regMin);} - KDTreeBox phiZ(prmin, prmax, - regMin.min()-fnSigmaRZ*rzError[il], - regMax.max()+fnSigmaRZ*rzError[il]); - hitTree[il].search(phiZ, foundNodes); - } - else { - KDTreeBox phiZ(prmin, prmax, - rzRange.min()-fnSigmaRZ*rzError[il], - rzRange.max()+fnSigmaRZ*rzError[il]); - hitTree[il].search(phiZ, foundNodes); + Range regMax = predRZ.line.detRange(); + Range regMin = predRZ.line(regMax.min()); + regMax = predRZ.line(regMax.max()); + correction.correctRZRange(regMin); + correction.correctRZRange(regMax); + if (regMax.min() < regMin.min()) { + std::swap(regMax, regMin); + } + KDTreeBox phiZ(prmin, prmax, regMin.min() - fnSigmaRZ * rzError[il], regMax.max() + fnSigmaRZ * rzError[il]); + hitTree[il].search(phiZ, foundNodes); + } else { + KDTreeBox phiZ(prmin, prmax, rzRange.min() - fnSigmaRZ * rzError[il], rzRange.max() + fnSigmaRZ * rzError[il]); + hitTree[il].search(phiZ, foundNodes); } - - MatchedHitRZCorrectionFromBending l2rzFixup(doublets.hit(ip,HitDoublets::outer)->det()->geographicalId(), tTopo); + + MatchedHitRZCorrectionFromBending l2rzFixup(doublets.hit(ip, HitDoublets::outer)->det()->geographicalId(), tTopo); MatchedHitRZCorrectionFromBending l3rzFixup = predRZ.rzPositionFixup; - auto const & hits = *thirdHitMap[il]; + auto const& hits = *thirdHitMap[il]; for (auto KDdata : foundNodes) { - GlobalPoint p3 = hits.gp(KDdata); - double p3_r = p3.perp(); - double p3_z = p3.z(); - float p3_phi = hits.phi(KDdata); + GlobalPoint p3 = hits.gp(KDdata); + double p3_r = p3.perp(); + double p3_z = p3.z(); + float p3_phi = hits.phi(KDdata); - Range rangeRPhi = predictionRPhi(curvature, p3_r); - correction.correctRPhiRange(rangeRPhi); + Range rangeRPhi = predictionRPhi(curvature, p3_r); + correction.correctRPhiRange(rangeRPhi); - float ir = 1.f/p3_r; + float ir = 1.f / p3_r; // limit error to 90 degree - constexpr float maxPhiErr = 0.5*M_PI; - float phiErr = nSigmaPhi * hits.drphi[KDdata]*ir; + constexpr float maxPhiErr = 0.5 * M_PI; + float phiErr = nSigmaPhi * hits.drphi[KDdata] * ir; phiErr = std::min(maxPhiErr, phiErr); - if (!checkPhiInRange(p3_phi, rangeRPhi.first*ir-phiErr, rangeRPhi.second*ir+phiErr, maxPhiErr)) - continue; - - Basic2DVector thc(p3.x(), p3.y()); - - auto curv_ = predictionRPhi.curvature(thc); - double p2_r = point2.r(); double p2_z = point2.z(); // they will be modified! - - l2rzFixup(predictionRPhi, curv_, *doublets.hit(ip,HitDoublets::outer), p2_r, p2_z, tTopo); - l3rzFixup(predictionRPhi, curv_, *hits.theHits[KDdata].hit(), p3_r, p3_z, tTopo); - - Range rangeRZ; - if (useBend) { - HelixRZ updatedHelix(&predictionRPhi, gp1.z(), p2_z, curv_); - rangeRZ = predRZ.helix1(barrelLayer ? p3_r : p3_z, updatedHelix); - } else { - float tIP = predictionRPhi.transverseIP(thc); - PixelRecoPointRZ updatedPoint2(p2_r, p2_z); - PixelRecoLineRZ updatedLine(line.origin(), point2, tIP); - rangeRZ = predRZ.line(barrelLayer ? p3_r : p3_z, line); - } - correction.correctRZRange(rangeRZ); - - double err = nSigmaRZ * hits.dv[KDdata]; - - rangeRZ.first -= err, rangeRZ.second += err; - - if (!rangeRZ.inside(barrelLayer ? p3_z : p3_r)) continue; - - if (theMaxElement!=0 && result.size() >= theMaxElement) { - result.clear(); - if(tripletLastLayerIndex) tripletLastLayerIndex->clear(); - edm::LogError("TooManyTriplets")<<" number of triples exceed maximum. no triplets produced."; - return; - } - result.emplace_back( doublets.hit(ip,HitDoublets::inner), doublets.hit(ip,HitDoublets::outer), hits.theHits[KDdata].hit()); + if (!checkPhiInRange(p3_phi, rangeRPhi.first * ir - phiErr, rangeRPhi.second * ir + phiErr, maxPhiErr)) + continue; + + Basic2DVector thc(p3.x(), p3.y()); + + auto curv_ = predictionRPhi.curvature(thc); + double p2_r = point2.r(); + double p2_z = point2.z(); // they will be modified! + + l2rzFixup(predictionRPhi, curv_, *doublets.hit(ip, HitDoublets::outer), p2_r, p2_z, tTopo); + l3rzFixup(predictionRPhi, curv_, *hits.theHits[KDdata].hit(), p3_r, p3_z, tTopo); + + Range rangeRZ; + if (useBend) { + HelixRZ updatedHelix(&predictionRPhi, gp1.z(), p2_z, curv_); + rangeRZ = predRZ.helix1(barrelLayer ? p3_r : p3_z, updatedHelix); + } else { + float tIP = predictionRPhi.transverseIP(thc); + PixelRecoPointRZ updatedPoint2(p2_r, p2_z); + PixelRecoLineRZ updatedLine(line.origin(), point2, tIP); + rangeRZ = predRZ.line(barrelLayer ? p3_r : p3_z, line); + } + correction.correctRZRange(rangeRZ); + + double err = nSigmaRZ * hits.dv[KDdata]; + + rangeRZ.first -= err, rangeRZ.second += err; + + if (!rangeRZ.inside(barrelLayer ? p3_z : p3_r)) + continue; + + if (theMaxElement != 0 && result.size() >= theMaxElement) { + result.clear(); + if (tripletLastLayerIndex) + tripletLastLayerIndex->clear(); + edm::LogError("TooManyTriplets") << " number of triples exceed maximum. no triplets produced."; + return; + } + result.emplace_back( + doublets.hit(ip, HitDoublets::inner), doublets.hit(ip, HitDoublets::outer), hits.theHits[KDdata].hit()); // to bookkeep the triplets and 3rd layers in triplet EDProducer - if(tripletLastLayerIndex) tripletLastLayerIndex->push_back(il); + if (tripletLastLayerIndex) + tripletLastLayerIndex->push_back(il); } } } // std::cout << "found triplets " << result.size() << std::endl; } - diff --git a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.h b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.h index cbdb67e36508e..b1950806bfb76 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletLargeTipGenerator.h @@ -15,48 +15,51 @@ #include #include - class PixelTripletLargeTipGenerator : public HitTripletGeneratorFromPairAndLayers { - -typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; + typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; public: - PixelTripletLargeTipGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC): PixelTripletLargeTipGenerator(cfg, iC) {} - PixelTripletLargeTipGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); + PixelTripletLargeTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector&& iC) + : PixelTripletLargeTipGenerator(cfg, iC) {} + PixelTripletLargeTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); ~PixelTripletLargeTipGenerator() override; static void fillDescriptions(edm::ParameterSetDescription& desc); - static const char *fillDescriptionsLabel() { return "pixelTripletLargeTip"; } - - void hitTriplets( const TrackingRegion& region, OrderedHitTriplets & trs, - const edm::Event & ev, const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) override; - - void hitTriplets(const TrackingRegion& region, OrderedHitTriplets& trs, - const edm::Event& ev, const edm::EventSetup& es, + static const char* fillDescriptionsLabel() { return "pixelTripletLargeTip"; } + + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) override; + + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, const HitDoublets& doublets, const std::vector& thirdLayers, - std::vector *tripletLastLayerIndex, + std::vector* tripletLastLayerIndex, LayerCacheType& layerCache); - void hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)override; + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) override; - void hitTriplets(const TrackingRegion& region, OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, const int nThirdLayers, - std::vector *tripletLastLayerIndex); + std::vector* tripletLastLayerIndex); private: const bool useFixedPreFiltering; @@ -67,5 +70,3 @@ typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; const float dphi; }; #endif - - diff --git a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.cc b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.cc index b641f03215be0..4ad44d9cde294 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.cc @@ -17,168 +17,178 @@ #include "DataFormats/GeometrySurface/interface/SimpleDiskBounds.h" typedef PixelRecoRange Range; -template T sqr(T t) { return t * t;} +template +T sqr(T t) { + return t * t; +} using namespace std; -PixelTripletNoTipGenerator:: PixelTripletNoTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) +PixelTripletNoTipGenerator::PixelTripletNoTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC) : HitTripletGeneratorFromPairAndLayers(cfg), extraHitRZtolerance(cfg.getParameter("extraHitRZtolerance")), extraHitRPhitolerance(cfg.getParameter("extraHitRPhitolerance")), - extraHitPhiToleranceForPreFiltering(cfg.getParameter("extraHitPhiToleranceForPreFiltering")), + extraHitPhiToleranceForPreFiltering(cfg.getParameter("extraHitPhiToleranceForPreFiltering")), theNSigma(cfg.getParameter("nSigma")), - theChi2Cut(cfg.getParameter("chi2Cut")) -{ } + theChi2Cut(cfg.getParameter("chi2Cut")) {} PixelTripletNoTipGenerator::~PixelTripletNoTipGenerator() {} -void PixelTripletNoTipGenerator::hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::Event & ev, - const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) -{ - -// -//edm::Handle bsHandle; -//ev.getByLabel( theBeamSpotTag, bsHandle); -//if(!bsHandle.isValid()) return; -//const reco::BeamSpot & bs = *bsHandle; -//double errorXY = sqrt( sqr(bs.BeamWidthX()) + sqr(bs.BeamWidthY()) ); -// +void PixelTripletNoTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) { + // + //edm::Handle bsHandle; + //ev.getByLabel( theBeamSpotTag, bsHandle); + //if(!bsHandle.isValid()) return; + //const reco::BeamSpot & bs = *bsHandle; + //double errorXY = sqrt( sqr(bs.BeamWidthX()) + sqr(bs.BeamWidthY()) ); + // const GlobalPoint& bsPoint = region.origin(); double errorXY = region.originRBound(); - GlobalVector shift = bsPoint - GlobalPoint(0.,0.,0.); + GlobalVector shift = bsPoint - GlobalPoint(0., 0., 0.); - OrderedHitPairs pairs; pairs.reserve(30000); + OrderedHitPairs pairs; + pairs.reserve(30000); OrderedHitPairs::const_iterator ip; - thePairGenerator->hitPairs(region,pairs,ev,es, pairLayers); + thePairGenerator->hitPairs(region, pairs, ev, es, pairLayers); - if (pairs.empty()) return; + if (pairs.empty()) + return; - const DetLayer * firstLayer = thePairGenerator->innerLayer(pairLayers).detLayer(); - const DetLayer * secondLayer = thePairGenerator->outerLayer(pairLayers).detLayer(); - if (!firstLayer || !secondLayer) return; + const DetLayer* firstLayer = thePairGenerator->innerLayer(pairLayers).detLayer(); + const DetLayer* secondLayer = thePairGenerator->outerLayer(pairLayers).detLayer(); + if (!firstLayer || !secondLayer) + return; int size = thirdLayers.size(); - const RecHitsSortedInPhi **thirdHitMap = new const RecHitsSortedInPhi*[size]; - for (int il=0; il <=size-1; il++) { - thirdHitMap[il] = &(*theLayerCache)(thirdLayers[il], region, es); + const RecHitsSortedInPhi** thirdHitMap = new const RecHitsSortedInPhi*[size]; + for (int il = 0; il <= size - 1; il++) { + thirdHitMap[il] = &(*theLayerCache)(thirdLayers[il], region, es); } - MultipleScatteringParametrisation sigma1RPhi( firstLayer, es); - MultipleScatteringParametrisation sigma2RPhi( secondLayer, es); + MultipleScatteringParametrisation sigma1RPhi(firstLayer, es); + MultipleScatteringParametrisation sigma2RPhi(secondLayer, es); typedef RecHitsSortedInPhi::Hit Hit; for (ip = pairs.begin(); ip != pairs.end(); ip++) { + GlobalPoint p1((*ip).inner()->globalPosition() - shift); + GlobalPoint p2((*ip).outer()->globalPosition() - shift); - GlobalPoint p1((*ip).inner()->globalPosition()-shift); - GlobalPoint p2((*ip).outer()->globalPosition()-shift); - - ThirdHitPredictionFromInvLine predictionRPhiTMP(p1, p2 ); - double pt_p1p2 = 1./PixelRecoUtilities::inversePt(predictionRPhiTMP.curvature(),es); + ThirdHitPredictionFromInvLine predictionRPhiTMP(p1, p2); + double pt_p1p2 = 1. / PixelRecoUtilities::inversePt(predictionRPhiTMP.curvature(), es); PixelRecoPointRZ point1(p1.perp(), p1.z()); PixelRecoPointRZ point2(p2.perp(), p2.z()); - PixelRecoLineRZ line(point1, point2); + PixelRecoLineRZ line(point1, point2); double msRPhi1 = sigma1RPhi(pt_p1p2, line.cotLine(), 0.f); - double msRPhi2 = sigma2RPhi(pt_p1p2, line.cotLine(),point1); - double sinTheta = 1/sqrt(1+sqr(line.cotLine())); - double cosTheta = fabs(line.cotLine())/sqrt(1+sqr(line.cotLine())); - - double p1_errorRPhi = sqrt(sqr((*ip).inner()->errorGlobalRPhi())+sqr(msRPhi1) +sqr(errorXY)); - double p2_errorRPhi = sqrt(sqr((*ip).outer()->errorGlobalRPhi())+sqr(msRPhi2) +sqr(errorXY)); + double msRPhi2 = sigma2RPhi(pt_p1p2, line.cotLine(), point1); + double sinTheta = 1 / sqrt(1 + sqr(line.cotLine())); + double cosTheta = fabs(line.cotLine()) / sqrt(1 + sqr(line.cotLine())); - ThirdHitPredictionFromInvLine predictionRPhi(p1, p2, p1_errorRPhi, p2_errorRPhi ); + double p1_errorRPhi = sqrt(sqr((*ip).inner()->errorGlobalRPhi()) + sqr(msRPhi1) + sqr(errorXY)); + double p2_errorRPhi = sqrt(sqr((*ip).outer()->errorGlobalRPhi()) + sqr(msRPhi2) + sqr(errorXY)); - for (int il=0; il <=size-1; il++) { + ThirdHitPredictionFromInvLine predictionRPhi(p1, p2, p1_errorRPhi, p2_errorRPhi); - const DetLayer * layer = thirdLayers[il].detLayer(); + for (int il = 0; il <= size - 1; il++) { + const DetLayer* layer = thirdLayers[il].detLayer(); bool barrelLayer = (layer->location() == GeomDetEnumerators::barrel); - MultipleScatteringParametrisation sigma3RPhi( layer, es); - double msRPhi3 = sigma3RPhi(pt_p1p2, line.cotLine(),point2); + MultipleScatteringParametrisation sigma3RPhi(layer, es); + double msRPhi3 = sigma3RPhi(pt_p1p2, line.cotLine(), point2); Range rRange; if (barrelLayer) { - const BarrelDetLayer& bl = dynamic_cast(*layer); - float halfThickness = bl.surface().bounds().thickness()/2; - float radius = bl.specificSurface().radius(); - rRange = Range(radius-halfThickness, radius+halfThickness); + const BarrelDetLayer& bl = dynamic_cast(*layer); + float halfThickness = bl.surface().bounds().thickness() / 2; + float radius = bl.specificSurface().radius(); + rRange = Range(radius - halfThickness, radius + halfThickness); } else { const ForwardDetLayer& fl = dynamic_cast(*layer); - float halfThickness = fl.surface().bounds().thickness()/2; - float zLayer = fl.position().z() ; - float zMin = zLayer-halfThickness; - float zMax = zLayer+halfThickness; - GlobalVector dr = p2-p1; - GlobalPoint p3_a = p2+dr*(zMin-p2.z())/dr.z(); - GlobalPoint p3_b = p2+dr*(zMax-p2.z())/dr.z(); - if (zLayer * p3_a.z() < 0) continue; + float halfThickness = fl.surface().bounds().thickness() / 2; + float zLayer = fl.position().z(); + float zMin = zLayer - halfThickness; + float zMax = zLayer + halfThickness; + GlobalVector dr = p2 - p1; + GlobalPoint p3_a = p2 + dr * (zMin - p2.z()) / dr.z(); + GlobalPoint p3_b = p2 + dr * (zMax - p2.z()) / dr.z(); + if (zLayer * p3_a.z() < 0) + continue; rRange = Range(p3_a.perp(), p3_b.perp()); rRange.sort(); } double displacment = shift.perp(); - GlobalPoint crossing1 = predictionRPhi.crossing(rRange.min()-displacment)+shift; - GlobalPoint crossing2 = predictionRPhi.crossing(rRange.max()+displacment)+shift; - float c1_phi= crossing1.phi(); - float c2_phi= crossing2.phi(); - if (c2_phi < c1_phi) swap(c1_phi,c2_phi); - if (c2_phi-c1_phi > M_PI) { c2_phi -= 2*M_PI; swap(c1_phi,c2_phi); } - double extraAngle = (displacment+theNSigma*msRPhi3)/rRange.min()+extraHitPhiToleranceForPreFiltering; - c1_phi -= extraAngle; + GlobalPoint crossing1 = predictionRPhi.crossing(rRange.min() - displacment) + shift; + GlobalPoint crossing2 = predictionRPhi.crossing(rRange.max() + displacment) + shift; + float c1_phi = crossing1.phi(); + float c2_phi = crossing2.phi(); + if (c2_phi < c1_phi) + swap(c1_phi, c2_phi); + if (c2_phi - c1_phi > M_PI) { + c2_phi -= 2 * M_PI; + swap(c1_phi, c2_phi); + } + double extraAngle = (displacment + theNSigma * msRPhi3) / rRange.min() + extraHitPhiToleranceForPreFiltering; + c1_phi -= extraAngle; c2_phi += extraAngle; - vector thirdHits = thirdHitMap[il]->hits(c1_phi, c2_phi) ; + vector thirdHits = thirdHitMap[il]->hits(c1_phi, c2_phi); typedef vector::const_iterator IH; - for (IH th=thirdHits.begin(), eh=thirdHits.end(); th < eh; ++th) { - GlobalPoint p3((*th)->globalPosition()-shift); - double p3_errorRPhi = sqrt(sqr((*th)->errorGlobalRPhi()) +sqr(msRPhi3) + sqr(errorXY)); + for (IH th = thirdHits.begin(), eh = thirdHits.end(); th < eh; ++th) { + GlobalPoint p3((*th)->globalPosition() - shift); + double p3_errorRPhi = sqrt(sqr((*th)->errorGlobalRPhi()) + sqr(msRPhi3) + sqr(errorXY)); - predictionRPhi.add(p3,p3_errorRPhi); + predictionRPhi.add(p3, p3_errorRPhi); double curvature = predictionRPhi.curvature(); - - ThirdHitZPrediction zPrediction( (*ip).inner()->globalPosition(), sqrt(sqr((*ip).inner()->errorGlobalR())+sqr(msRPhi1/cosTheta)), sqrt( sqr((*ip).inner()->errorGlobalZ())+ sqr(msRPhi1/sinTheta)), - (*ip).outer()->globalPosition(), sqrt(sqr((*ip).outer()->errorGlobalR())+sqr(msRPhi2/cosTheta)), sqrt( sqr((*ip).outer()->errorGlobalZ())+sqr(msRPhi2/sinTheta)), - curvature, theNSigma); - ThirdHitZPrediction::Range zRange = zPrediction((*th)->globalPosition(), sqrt(sqr((*th)->errorGlobalR()))+sqr(msRPhi3/cosTheta)); - - double z3Hit = (*th)->globalPosition().z(); - double z3HitError = theNSigma*(sqrt(sqr((*th)->errorGlobalZ()) + sqr(msRPhi3/sinTheta) ))+extraHitRZtolerance; - Range hitZRange(z3Hit-z3HitError, z3Hit+z3HitError); - bool inside = hitZRange.hasIntersection(zRange); - - double curvatureMS = PixelRecoUtilities::curvature(1./region.ptMin(),es); - bool ptCut = (predictionRPhi.curvature()-theNSigma*predictionRPhi.errorCurvature() < curvatureMS); - bool chi2Cut = (predictionRPhi.chi2() < theChi2Cut); - if (inside && ptCut && chi2Cut) { - if (theMaxElement!=0 && result.size() >= theMaxElement){ - result.clear(); - edm::LogError("TooManyTriplets")<<" number of triples exceed maximum. no triplets produced."; - delete [] thirdHitMap; - return; - } - result.push_back( OrderedHitTriplet( (*ip).inner(), (*ip).outer(), *th)); - } - predictionRPhi.remove(p3,p3_errorRPhi); - } + + ThirdHitZPrediction zPrediction((*ip).inner()->globalPosition(), + sqrt(sqr((*ip).inner()->errorGlobalR()) + sqr(msRPhi1 / cosTheta)), + sqrt(sqr((*ip).inner()->errorGlobalZ()) + sqr(msRPhi1 / sinTheta)), + (*ip).outer()->globalPosition(), + sqrt(sqr((*ip).outer()->errorGlobalR()) + sqr(msRPhi2 / cosTheta)), + sqrt(sqr((*ip).outer()->errorGlobalZ()) + sqr(msRPhi2 / sinTheta)), + curvature, + theNSigma); + ThirdHitZPrediction::Range zRange = + zPrediction((*th)->globalPosition(), sqrt(sqr((*th)->errorGlobalR())) + sqr(msRPhi3 / cosTheta)); + + double z3Hit = (*th)->globalPosition().z(); + double z3HitError = + theNSigma * (sqrt(sqr((*th)->errorGlobalZ()) + sqr(msRPhi3 / sinTheta))) + extraHitRZtolerance; + Range hitZRange(z3Hit - z3HitError, z3Hit + z3HitError); + bool inside = hitZRange.hasIntersection(zRange); + + double curvatureMS = PixelRecoUtilities::curvature(1. / region.ptMin(), es); + bool ptCut = (predictionRPhi.curvature() - theNSigma * predictionRPhi.errorCurvature() < curvatureMS); + bool chi2Cut = (predictionRPhi.chi2() < theChi2Cut); + if (inside && ptCut && chi2Cut) { + if (theMaxElement != 0 && result.size() >= theMaxElement) { + result.clear(); + edm::LogError("TooManyTriplets") << " number of triples exceed maximum. no triplets produced."; + delete[] thirdHitMap; + return; + } + result.push_back(OrderedHitTriplet((*ip).inner(), (*ip).outer(), *th)); + } + predictionRPhi.remove(p3, p3_errorRPhi); + } } } - delete [] thirdHitMap; + delete[] thirdHitMap; } -void PixelTripletNoTipGenerator::hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers) -{ - throw cms::Exception("Error")<<"PixelTripletNoTipGenerator::hitTriplets is not implemented \n"; +void PixelTripletNoTipGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) { + throw cms::Exception("Error") << "PixelTripletNoTipGenerator::hitTriplets is not implemented \n"; } diff --git a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.h b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.h index 90fb4ebb63ba3..3f01abf8b2bff 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/PixelTripletNoTipGenerator.h @@ -4,31 +4,35 @@ #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h" #include "CombinedHitTripletGenerator.h" -namespace edm { class Event; class EventSetup; } +namespace edm { + class Event; + class EventSetup; +} // namespace edm #include #include - class PixelTripletNoTipGenerator : public HitTripletGeneratorFromPairAndLayers { -typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; + typedef CombinedHitTripletGenerator::LayerCacheType LayerCacheType; + public: PixelTripletNoTipGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); ~PixelTripletNoTipGenerator() override; - void hitTriplets( const TrackingRegion& region, OrderedHitTriplets & trs, - const edm::Event & ev, const edm::EventSetup& es, - const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, - const std::vector& thirdLayers) override; - void hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)override; + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& trs, + const edm::Event& ev, + const edm::EventSetup& es, + const SeedingLayerSetsHits::SeedingLayerSet& pairLayers, + const std::vector& thirdLayers) override; + void hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) override; private: float extraHitRZtolerance; diff --git a/RecoPixelVertexing/PixelTriplets/plugins/SealModule.cc b/RecoPixelVertexing/PixelTriplets/plugins/SealModule.cc index f89f9eb9dc106..150c2d6783391 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/SealModule.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/SealModule.cc @@ -1,17 +1,20 @@ #include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" - #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h" #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h" #include "PixelTripletHLTGenerator.h" DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, PixelTripletHLTGenerator, "PixelTripletHLTGenerator"); #include "PixelTripletLargeTipGenerator.h" -DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, PixelTripletLargeTipGenerator, "PixelTripletLargeTipGenerator"); +DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, + PixelTripletLargeTipGenerator, + "PixelTripletLargeTipGenerator"); #include "PixelTripletNoTipGenerator.h" -DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory,PixelTripletNoTipGenerator,"PixelTripletNoTipGenerator"); +DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, + PixelTripletNoTipGenerator, + "PixelTripletNoTipGenerator"); #include "RecoTracker/TkTrackingRegions/interface/OrderedHitsGeneratorFactory.h" #include "RecoTracker/TkTrackingRegions/interface/OrderedHitsGenerator.h" diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.cc b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.cc index 58da47fdd086c..e1e8c294c9ad9 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.cc @@ -3,61 +3,57 @@ #include "TrackingTools/DetLayers/interface/BarrelDetLayer.h" #include "TrackingTools/DetLayers/interface/ForwardDetLayer.h" - using namespace pixelrecoutilities; namespace { - template inline T sqr( T t) {return t*t;} -} + template + inline T sqr(T t) { + return t * t; + } +} // namespace using pixelrecoutilities::LongitudinalBendingCorrection; - - -void ThirdHitCorrection::init( - const edm::EventSetup &es, - float pt, - const DetLayer & layer3, - bool useMultipleScattering, - bool useBendingCorrection) { - +void ThirdHitCorrection::init(const edm::EventSetup &es, + float pt, + const DetLayer &layer3, + bool useMultipleScattering, + bool useBendingCorrection) { theUseMultipleScattering = useMultipleScattering; theUseBendingCorrection = useBendingCorrection; - if (useBendingCorrection) theBendingCorrection.init(pt,es); + if (useBendingCorrection) + theBendingCorrection.init(pt, es); - theMultScattCorrRPhi=0; - theMScoeff=0; + theMultScattCorrRPhi = 0; + theMScoeff = 0; theBarrel = layer3.isBarrel(); thePt = pt; - if (theUseMultipleScattering) sigmaRPhi.init(&layer3,es); + if (theUseMultipleScattering) + sigmaRPhi.init(&layer3, es); } +void ThirdHitCorrection::init(const edm::EventSetup &es, + float pt, + const DetLayer &layer1, + const DetLayer &layer2, + const DetLayer &layer3, + bool useMultipleScattering, + bool useBendingCorrection) { + init(es, pt, layer3, useMultipleScattering, useBendingCorrection); + if (!theUseMultipleScattering) + return; -void -ThirdHitCorrection::init( - const edm::EventSetup &es, - float pt, - const DetLayer & layer1, - const DetLayer & layer2, - const DetLayer & layer3, - bool useMultipleScattering, - bool useBendingCorrection) { - - init(es,pt,layer3, useMultipleScattering, useBendingCorrection); - - if (!theUseMultipleScattering) return; - - auto point3 = [&]()->PixelRecoPointRZ { - if(theBarrel) { - const BarrelDetLayer& bl = static_cast(layer3); + auto point3 = [&]() -> PixelRecoPointRZ { + if (theBarrel) { + const BarrelDetLayer &bl = static_cast(layer3); float rLayer = bl.specificSurface().radius(); - auto zmax = 0.5f*layer3.surface().bounds().length(); + auto zmax = 0.5f * layer3.surface().bounds().length(); return PixelRecoPointRZ(rLayer, zmax); } else { - const ForwardDetLayer &fl = static_cast(layer3); + const ForwardDetLayer &fl = static_cast(layer3); auto maxR = fl.specificSurface().outerRadius(); auto layerZ = layer3.position().z(); return PixelRecoPointRZ(maxR, layerZ); @@ -65,11 +61,11 @@ ThirdHitCorrection::init( }; PixelRecoPointRZ zero(0., 0.); - SimpleLineRZ line(zero,point3()); - - auto point2 = [&]()->PixelRecoPointRZ { + SimpleLineRZ line(zero, point3()); + + auto point2 = [&]() -> PixelRecoPointRZ { if (layer2.isBarrel()) { - const BarrelDetLayer& bl = static_cast(layer2); + const BarrelDetLayer &bl = static_cast(layer2); float rLayer = bl.specificSurface().radius(); return PixelRecoPointRZ(rLayer, line.zAtR(rLayer)); } else { @@ -78,37 +74,29 @@ ThirdHitCorrection::init( } }; - theMultScattCorrRPhi = 3.f*sigmaRPhi(pt, line.cotLine(), point2(), layer2.seqNum()); - + theMultScattCorrRPhi = 3.f * sigmaRPhi(pt, line.cotLine(), point2(), layer2.seqNum()); } -void ThirdHitCorrection::init( - const PixelRecoLineRZ & line, - const PixelRecoPointRZ & constraint, int il) { - +void ThirdHitCorrection::init(const PixelRecoLineRZ &line, const PixelRecoPointRZ &constraint, int il) { theLine = line; - if (!theUseMultipleScattering) return; - - // auto newCorr = theMultScattCorrRPhi; - theMultScattCorrRPhi = 3.f*sigmaRPhi(thePt, line.cotLine(), constraint, il); - // std::cout << "ThirdHitCorr " << (theBarrel ? "B " : "F " )<< theMultScattCorrRPhi << ' ' << newCorr << ' ' << newCorr/theMultScattCorrRPhi << std::endl; - float overSinTheta = std::sqrt(1.f+sqr(line.cotLine())); - if (theBarrel) { - theMScoeff = theMultScattCorrRPhi*overSinTheta; - } else { - float overCosTheta = std::abs(line.cotLine()) < 1.e-4f ? - 1.e4f : overSinTheta/std::abs(line.cotLine()); - theMScoeff = theMultScattCorrRPhi*overCosTheta; - } - + if (!theUseMultipleScattering) + return; + + // auto newCorr = theMultScattCorrRPhi; + theMultScattCorrRPhi = 3.f * sigmaRPhi(thePt, line.cotLine(), constraint, il); + // std::cout << "ThirdHitCorr " << (theBarrel ? "B " : "F " )<< theMultScattCorrRPhi << ' ' << newCorr << ' ' << newCorr/theMultScattCorrRPhi << std::endl; + float overSinTheta = std::sqrt(1.f + sqr(line.cotLine())); + if (theBarrel) { + theMScoeff = theMultScattCorrRPhi * overSinTheta; + } else { + float overCosTheta = std::abs(line.cotLine()) < 1.e-4f ? 1.e4f : overSinTheta / std::abs(line.cotLine()); + theMScoeff = theMultScattCorrRPhi * overCosTheta; + } } - -void ThirdHitCorrection::correctRZRange( Range & range) const -{ +void ThirdHitCorrection::correctRZRange(Range &range) const { range.first -= theMScoeff; range.second += theMScoeff; - if (theUseBendingCorrection) { if (theBarrel) { @@ -116,14 +104,13 @@ void ThirdHitCorrection::correctRZRange( Range & range) const if (cotTheta > 0) { float radius = theLine.rAtZ(range.max()); float corr = theBendingCorrection(radius) * cotTheta; - range.second += corr; + range.second += corr; } else { float radius = theLine.rAtZ(range.min()); float corr = theBendingCorrection(radius) * std::abs(cotTheta); - range.first -= corr; + range.first -= corr; } - } - else { + } else { float radius = range.max(); float corr = theBendingCorrection(radius); range.first -= corr; diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.h b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.h index cc2ef1cd2f7e1..7e1111bfe54a4 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitCorrection.h @@ -1,7 +1,9 @@ #ifndef RecoPixelVertexing_PixelTriplets_ThirdHitCorrection_H #define RecoPixelVertexing_PixelTriplets_ThirdHitCorrection_H -namespace edm {class EventSetup; } +namespace edm { + class EventSetup; +} #include "RecoTracker/TkMSParametrization/interface/LongitudinalBendingCorrection.h" #include "RecoTracker/TkMSParametrization/interface/MultipleScatteringParametrisation.h" @@ -13,54 +15,44 @@ class DetLayer; class ThirdHitCorrection { public: - - typedef PixelRecoRange Range; - - ThirdHitCorrection(){} - - void init( - const edm::EventSetup &es, - float pt, - const DetLayer & layer1, - const DetLayer & layer2, - const DetLayer & layer3, - bool useMultipleScattering, - bool useBendingCorrection - ); - - void init( - const edm::EventSetup &es, - float pt, - const DetLayer & layer3, - bool useMultipleScattering, - bool useBendingCorrection - ); - - - ThirdHitCorrection( - const edm::EventSetup &es, - float pt, - const DetLayer * layer, - const PixelRecoLineRZ & line, - const PixelRecoPointRZ & constraint, int ol, - bool useMultipleScattering, - bool useBendingCorrection) - { + typedef PixelRecoRange Range; + + ThirdHitCorrection() {} + + void init(const edm::EventSetup &es, + float pt, + const DetLayer &layer1, + const DetLayer &layer2, + const DetLayer &layer3, + bool useMultipleScattering, + bool useBendingCorrection); + + void init(const edm::EventSetup &es, + float pt, + const DetLayer &layer3, + bool useMultipleScattering, + bool useBendingCorrection); + + ThirdHitCorrection(const edm::EventSetup &es, + float pt, + const DetLayer *layer, + const PixelRecoLineRZ &line, + const PixelRecoPointRZ &constraint, + int ol, + bool useMultipleScattering, + bool useBendingCorrection) { init(es, pt, *layer, useMultipleScattering, useBendingCorrection); init(line, constraint, ol); } - void init( - const PixelRecoLineRZ & line, - const PixelRecoPointRZ & constraint, int ol); + void init(const PixelRecoLineRZ &line, const PixelRecoPointRZ &constraint, int ol); - - void correctRPhiRange( Range & range) const { + void correctRPhiRange(Range &range) const { range.first -= theMultScattCorrRPhi; range.second += theMultScattCorrRPhi; } - void correctRZRange( Range & range) const; + void correctRZRange(Range &range) const; private: bool theBarrel; @@ -69,13 +61,12 @@ class ThirdHitCorrection { bool theUseBendingCorrection; PixelRecoLineRZ theLine; - float theMultScattCorrRPhi=0; - float theMScoeff=0; + float theMultScattCorrRPhi = 0; + float theMScoeff = 0; float thePt; pixelrecoutilities::LongitudinalBendingCorrection theBendingCorrection; MultipleScatteringParametrisation sigmaRPhi; - }; #endif diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvLine.cc b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvLine.cc index 299c77859b76f..f35031677fdb8 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvLine.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvLine.cc @@ -7,7 +7,10 @@ #include "RecoTracker/TkMSParametrization/interface/PixelRecoUtilities.h" #include "RecoTracker/TkMSParametrization/interface/PixelRecoRange.h" -template T sqr( T t) {return t*t;} +template +T sqr(T t) { + return t * t; +} typedef Basic3DVector Point3D; typedef Basic2DVector Point2D; @@ -17,89 +20,92 @@ typedef PixelRecoRange Ranged; using namespace std; -ThirdHitPredictionFromInvLine::ThirdHitPredictionFromInvLine( - const GlobalPoint & P1, const GlobalPoint & P2, - double errorRPhiP1, double errorRPhiP2) - : nPoints(0), theSum(0.), theSumU(0.), theSumUU(0.), theSumV(0.), theSumUV(0.), theSumVV(0.), - hasParameters(false), theCurvatureValue(0.), theCurvatureError(0.), theChi2(0.) -{ - GlobalVector aX = GlobalVector( P1.x(), P1.y(), 0.).unit(); - GlobalVector aY( -aX.y(), aX.x(), 0.); - GlobalVector aZ( 0., 0., 1.); - theRotation = Rotation(aX,aY,aZ); +ThirdHitPredictionFromInvLine::ThirdHitPredictionFromInvLine(const GlobalPoint &P1, + const GlobalPoint &P2, + double errorRPhiP1, + double errorRPhiP2) + : nPoints(0), + theSum(0.), + theSumU(0.), + theSumUU(0.), + theSumV(0.), + theSumUV(0.), + theSumVV(0.), + hasParameters(false), + theCurvatureValue(0.), + theCurvatureError(0.), + theChi2(0.) { + GlobalVector aX = GlobalVector(P1.x(), P1.y(), 0.).unit(); + GlobalVector aY(-aX.y(), aX.x(), 0.); + GlobalVector aZ(0., 0., 1.); + theRotation = Rotation(aX, aY, aZ); add(P1, errorRPhiP1); add(P2, errorRPhiP2); } -GlobalPoint ThirdHitPredictionFromInvLine::crossing(double radius) const -{ - double A = -(theSum*theSumUV-theSumU*theSumV)/(sqr(theSumU)-theSum*theSumUU); - double B = (theSumU*theSumUV - theSumUU*theSumV)/(sqr(theSumU)-theSum*theSumUU); - double delta = sqr(2.*A*B) - 4*(1+sqr(A))*(sqr(B)-sqr(1/radius)); - double sqrtdelta = (delta > 0.) ? sqrt(delta) : 0.; - double u1 = (-2.*A*B + sqrtdelta)/2./(1+sqr(A)); - double v1 = A*u1+B; - Point2D tmp = PointUV(u1,v1, &theRotation).unmap(); +GlobalPoint ThirdHitPredictionFromInvLine::crossing(double radius) const { + double A = -(theSum * theSumUV - theSumU * theSumV) / (sqr(theSumU) - theSum * theSumUU); + double B = (theSumU * theSumUV - theSumUU * theSumV) / (sqr(theSumU) - theSum * theSumUU); + double delta = sqr(2. * A * B) - 4 * (1 + sqr(A)) * (sqr(B) - sqr(1 / radius)); + double sqrtdelta = (delta > 0.) ? sqrt(delta) : 0.; + double u1 = (-2. * A * B + sqrtdelta) / 2. / (1 + sqr(A)); + double v1 = A * u1 + B; + Point2D tmp = PointUV(u1, v1, &theRotation).unmap(); return GlobalPoint(tmp.x(), tmp.y(), 0.); } - -void ThirdHitPredictionFromInvLine::add(const GlobalPoint &p, double errorRPhi) -{ - double weigth = sqr(sqr(p.perp())/errorRPhi); - add(PointUV(Point2D(p.x(),p.y()), &theRotation), weigth); +void ThirdHitPredictionFromInvLine::add(const GlobalPoint &p, double errorRPhi) { + double weigth = sqr(sqr(p.perp()) / errorRPhi); + add(PointUV(Point2D(p.x(), p.y()), &theRotation), weigth); } -void ThirdHitPredictionFromInvLine::add(const ThirdHitPredictionFromInvLine::PointUV & point, double weigth) -{ +void ThirdHitPredictionFromInvLine::add(const ThirdHitPredictionFromInvLine::PointUV &point, double weigth) { hasParameters = false; nPoints++; theSum += weigth; - theSumU += point.u()*weigth; - theSumUU += sqr(point.u())*weigth; - theSumV += point.v()*weigth; - theSumUV += point.u()*point.v()*weigth; - theSumVV += sqr(point.v())*weigth; + theSumU += point.u() * weigth; + theSumUU += sqr(point.u()) * weigth; + theSumV += point.v() * weigth; + theSumUV += point.u() * point.v() * weigth; + theSumVV += sqr(point.v()) * weigth; check(); } -void ThirdHitPredictionFromInvLine::remove(const GlobalPoint &p, double errorRPhi) -{ +void ThirdHitPredictionFromInvLine::remove(const GlobalPoint &p, double errorRPhi) { hasParameters = false; - PointUV point(Point2D(p.x(),p.y()), &theRotation); - double weigth = sqr(sqr(p.perp())/errorRPhi); + PointUV point(Point2D(p.x(), p.y()), &theRotation); + double weigth = sqr(sqr(p.perp()) / errorRPhi); nPoints--; theSum -= weigth; - theSumU -= point.u()*weigth; - theSumUU -= sqr(point.u())*weigth; - theSumV -= point.v()*weigth; - theSumUV -= point.u()*point.v()*weigth; - theSumVV -= sqr(point.v())*weigth; + theSumU -= point.u() * weigth; + theSumUU -= sqr(point.u()) * weigth; + theSumV -= point.v() * weigth; + theSumUV -= point.u() * point.v() * weigth; + theSumVV -= sqr(point.v()) * weigth; check(); } -void ThirdHitPredictionFromInvLine::print() const -{ - std::cout <<" nPoints: " << nPoints <<" theSumU: "<< theSumU <<" theSumUU: "< class ThirdHitPredictionFromInvLine { - public: - typedef TkRotation Rotation; typedef PixelRecoRange Range; - ThirdHitPredictionFromInvLine(const GlobalPoint & P1, const GlobalPoint & P2, double errorRPhiP1 = 1., double errorRPhiP2 = 1. ); + ThirdHitPredictionFromInvLine(const GlobalPoint& P1, + const GlobalPoint& P2, + double errorRPhiP1 = 1., + double errorRPhiP2 = 1.); - int size() const { return nPoints;} + int size() const { return nPoints; } - void add(const GlobalPoint& p, double erroriRPhi =1.); + void add(const GlobalPoint& p, double erroriRPhi = 1.); - void remove(const GlobalPoint& p, double erroriRPhi =1.); + void remove(const GlobalPoint& p, double erroriRPhi = 1.); GlobalPoint crossing(double radius) const; - double curvature() const { assert(hasParameters); return theCurvatureValue; } + double curvature() const { + assert(hasParameters); + return theCurvatureValue; + } - double errorCurvature() const { assert(hasParameters); return theCurvatureError; } + double errorCurvature() const { + assert(hasParameters); + return theCurvatureError; + } - double chi2() const { assert(hasParameters); return theChi2; } + double chi2() const { + assert(hasParameters); + return theChi2; + } void print() const; -private: - template class MappedPoint { +private: + template + class MappedPoint { public: - MappedPoint() : theU(0), theV(0), pRot(0) { } - MappedPoint(const T & aU, const T & aV, const TkRotation * aRot) - : theU(aU), theV(aV), pRot(aRot) { } - MappedPoint(const Basic2DVector & point, const TkRotation * aRot) - : pRot(aRot) { + MappedPoint() : theU(0), theV(0), pRot(0) {} + MappedPoint(const T& aU, const T& aV, const TkRotation* aRot) : theU(aU), theV(aV), pRot(aRot) {} + MappedPoint(const Basic2DVector& point, const TkRotation* aRot) : pRot(aRot) { T radius2 = point.mag2(); Basic3DVector rotated = (*pRot) * point; theU = rotated.x() / radius2; theV = rotated.y() / radius2; } - T u() const {return theU; } - T v() const {return theV; } - Basic2DVector unmap () const { - T invRadius2 = theU*theU+theV*theV; - Basic3DVector tmp - = (*pRot).multiplyInverse(Basic2DVector(theU,theV)); - return Basic2DVector( tmp.x()/invRadius2, tmp.y()/invRadius2); + T u() const { return theU; } + T v() const { return theV; } + Basic2DVector unmap() const { + T invRadius2 = theU * theU + theV * theV; + Basic3DVector tmp = (*pRot).multiplyInverse(Basic2DVector(theU, theV)); + return Basic2DVector(tmp.x() / invRadius2, tmp.y() / invRadius2); } + private: T theU, theV; - const TkRotation * pRot; + const TkRotation* pRot; }; private: typedef MappedPoint PointUV; - void add(const ThirdHitPredictionFromInvLine::PointUV & point, double weight); + void add(const ThirdHitPredictionFromInvLine::PointUV& point, double weight); void check(); private: Rotation theRotation; - int nPoints; + int nPoints; long double theSum, theSumU, theSumUU, theSumV, theSumUV, theSumVV; bool hasParameters; - double theCurvatureValue, theCurvatureError, theChi2; + double theCurvatureValue, theCurvatureError, theChi2; }; - #endif diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.cc b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.cc index e5a2da806ec53..2832a504a16eb 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.cc @@ -13,135 +13,124 @@ #include "DataFormats/Math/interface/approx_atan2.h" namespace { - inline - float f_atan2f(float y, float x) { return unsafe_atan2f<7>(y,x); } - template inline float f_phi(V v) { return f_atan2f(v.y(),v.x());} -} + inline float f_atan2f(float y, float x) { return unsafe_atan2f<7>(y, x); } + template + inline float f_phi(V v) { + return f_atan2f(v.y(), v.x()); + } +} // namespace namespace { - template inline T sqr( T t) {return t*t;} -} + template + inline T sqr(T t) { + return t * t; + } +} // namespace using namespace std; -ThirdHitPredictionFromInvParabola::ThirdHitPredictionFromInvParabola( - const GlobalPoint& P1, const GlobalPoint& P2,Scalar ip, Scalar curv, Scalar tolerance) - : theTolerance(tolerance) -{ - init(P1,P2,ip,std::abs(curv)); +ThirdHitPredictionFromInvParabola::ThirdHitPredictionFromInvParabola( + const GlobalPoint& P1, const GlobalPoint& P2, Scalar ip, Scalar curv, Scalar tolerance) + : theTolerance(tolerance) { + init(P1, P2, ip, std::abs(curv)); } +void ThirdHitPredictionFromInvParabola::init(Scalar x1, Scalar y1, Scalar x2, Scalar y2, Scalar ip, Scalar curv) { + // GlobalVector aX = GlobalVector( P2.x()-P1.x(), P2.y()-P1.y(), 0.).unit(); -void ThirdHitPredictionFromInvParabola:: init(Scalar x1,Scalar y1, Scalar x2,Scalar y2, Scalar ip, Scalar curv) { -// GlobalVector aX = GlobalVector( P2.x()-P1.x(), P2.y()-P1.y(), 0.).unit(); - - Point2D p1(x1,y1); - Point2D p2(x2,y2); + Point2D p1(x1, y1); + Point2D p2(x2, y2); theRotation = Rotation(p1); - p1 = transform(p1); // (1./P1.xy().mag(),0); + p1 = transform(p1); // (1./P1.xy().mag(),0); p2 = transform(p2); - - u1u2 = p1.x()*p2.x(); - overDu = 1./(p2.x() - p1.x()); - pv = p1.y()*p2.x() - p2.y()*p1.x(); + u1u2 = p1.x() * p2.x(); + overDu = 1. / (p2.x() - p1.x()); + pv = p1.y() * p2.x() - p2.y() * p1.x(); dv = p2.y() - p1.y(); su = p2.x() + p1.x(); ip = std::abs(ip); - RangeD ipRange(-ip, ip); + RangeD ipRange(-ip, ip); - - Scalar ipIntyPlus = ipFromCurvature(0.,true); + Scalar ipIntyPlus = ipFromCurvature(0., true); Scalar ipCurvPlus = ipFromCurvature(curv, true); Scalar ipCurvMinus = ipFromCurvature(curv, false); - - RangeD ipRangePlus(std::min(ipIntyPlus, ipCurvPlus),std::max(ipIntyPlus, ipCurvPlus)); - RangeD ipRangeMinus(std::min(-ipIntyPlus, ipCurvMinus),std::max(-ipIntyPlus, ipCurvMinus)); + RangeD ipRangePlus(std::min(ipIntyPlus, ipCurvPlus), std::max(ipIntyPlus, ipCurvPlus)); + RangeD ipRangeMinus(std::min(-ipIntyPlus, ipCurvMinus), std::max(-ipIntyPlus, ipCurvMinus)); - theIpRangePlus = ipRangePlus.intersection(ipRange); + theIpRangePlus = ipRangePlus.intersection(ipRange); theIpRangeMinus = ipRangeMinus.intersection(ipRange); - emptyP = theIpRangePlus.empty(); - emptyM = theIpRangeMinus.empty(); - + emptyP = theIpRangePlus.empty(); + emptyM = theIpRangeMinus.empty(); } - - -ThirdHitPredictionFromInvParabola::Range -ThirdHitPredictionFromInvParabola::rangeRPhi(Scalar radius, int icharge) const -{ - bool pos = icharge>0; +ThirdHitPredictionFromInvParabola::Range ThirdHitPredictionFromInvParabola::rangeRPhi(Scalar radius, + int icharge) const { + bool pos = icharge > 0; RangeD ip = (pos) ? theIpRangePlus : theIpRangeMinus; - // it will vectorize with gcc 4.7 (with -O3 -fno-math-errno) // change sign as intersect assume -ip for negative charge... - Scalar ipv[2]={(pos)? ip.min() : -ip.min() ,(pos)? ip.max() : -ip.max()}; + Scalar ipv[2] = {(pos) ? ip.min() : -ip.min(), (pos) ? ip.max() : -ip.max()}; Scalar u[2], v[2]; - for (int i=0; i!=2; ++i) - findPointAtCurve(radius,ipv[i],u[i],v[i]); + for (int i = 0; i != 2; ++i) + findPointAtCurve(radius, ipv[i], u[i], v[i]); + + // + Scalar phi1 = f_phi(theRotation.rotateBack(Point2D(u[0], v[0]))); + Scalar phi2 = phi1 + (v[1] - v[0]); - // - Scalar phi1 = f_phi(theRotation.rotateBack(Point2D(u[0],v[0]))); - Scalar phi2 = phi1+(v[1]-v[0]); - - if (phi2RangeD { - - if (phi2 RangeD { + if (phi2 < phi1) + std::swap(phi1, phi2); if (empty) { - RangeD r1(phi1*radius-theTolerance, phi1*radius+theTolerance); - RangeD r2(phi2*radius-theTolerance, phi2*radius+theTolerance); + RangeD r1(phi1 * radius - theTolerance, phi1 * radius + theTolerance); + RangeD r2(phi2 * radius - theTolerance, phi2 * radius + theTolerance); return r1.intersection(r2); } - - return RangeD(radius*phi1-theTolerance, radius*phi2+theTolerance); - }; + return RangeD(radius * phi1 - theTolerance, radius * phi2 + theTolerance); + }; // it will vectorize with gcc 4.7 (with -O3 -fno-math-errno) // change sign as intersect assume -ip for negative charge... - Scalar ipv[4]={theIpRangePlus.min(), -theIpRangeMinus.min(), theIpRangePlus.max(), -theIpRangeMinus.max()}; + Scalar ipv[4] = {theIpRangePlus.min(), -theIpRangeMinus.min(), theIpRangePlus.max(), -theIpRangeMinus.max()}; Scalar u[4], v[4]; - for (int i=0; i<4; ++i) - findPointAtCurve(radius,ipv[i],u[i],v[i]); + for (int i = 0; i < 4; ++i) + findPointAtCurve(radius, ipv[i], u[i], v[i]); - // + // auto xr = theRotation.x(); auto yr = theRotation.y(); - Scalar phi1[2],phi2[2]; - for (int i=0; i<2; ++i) { - auto x = xr[0]*u[i] + yr[0]*v[i]; - auto y = xr[1]*u[i] + yr[1]*v[i]; - phi1[i] = f_atan2f(y,x); - phi2[i] = phi1[i]+(v[i+2]-v[i]); + Scalar phi1[2], phi2[2]; + for (int i = 0; i < 2; ++i) { + auto x = xr[0] * u[i] + yr[0] * v[i]; + auto y = xr[1] * u[i] + yr[1] * v[i]; + phi1[i] = f_atan2f(y, x); + phi2[i] = phi1[i] + (v[i + 2] - v[i]); } - return getRange(phi1[1],phi2[1],emptyM).sum(getRange(phi1[0],phi2[0],emptyP)); + return getRange(phi1[1], phi2[1], emptyM).sum(getRange(phi1[0], phi2[0], emptyP)); } - /* ThirdHitPredictionFromInvParabola::Range ThirdHitPredictionFromInvParabola::rangeRPhiSlow( Scalar radius, int charge, int nIter) const @@ -193,4 +182,3 @@ ThirdHitPredictionFromInvParabola::Range ThirdHitPredictionFromInvParabola::rang } */ - diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.h b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.h index 29357b8575de5..0f9bac7791816 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.h @@ -6,8 +6,6 @@ The "inverse parabola method" is used. M.Hansroul, H.Jeremie, D.Savard NIM A270 (1998) 490. */ - - #include "DataFormats/GeometryVector/interface/Basic2DVector.h" #include "DataFormats/GeometryVector/interface/Basic3DVector.h" @@ -19,7 +17,6 @@ #include "FWCore/Utilities/interface/Visibility.h" - class TrackingRegion; class OrderedHitPair; @@ -31,8 +28,7 @@ namespace test { namespace PixelTriplets_InvPrbl_t { int test(); } -} - +} // namespace test class ThirdHitPredictionFromInvParabola { // For tests @@ -40,107 +36,82 @@ class ThirdHitPredictionFromInvParabola { friend int test::PixelTriplets_InvPrbl_t::test(); public: - using Scalar=double; + using Scalar = double; typedef TkRotation2D Rotation; typedef PixelRecoRange Range; typedef PixelRecoRange RangeD; typedef Basic2DVector Point2D; - ThirdHitPredictionFromInvParabola(){} - ThirdHitPredictionFromInvParabola(Scalar x1,Scalar y1, Scalar x2,Scalar y2, Scalar ip, Scalar curv, - Scalar tolerance): theTolerance(tolerance) - { - init(x1,y1,x2,y2,ip,std::abs(curv)); + ThirdHitPredictionFromInvParabola() {} + ThirdHitPredictionFromInvParabola(Scalar x1, Scalar y1, Scalar x2, Scalar y2, Scalar ip, Scalar curv, Scalar tolerance) + : theTolerance(tolerance) { + init(x1, y1, x2, y2, ip, std::abs(curv)); } - ThirdHitPredictionFromInvParabola(const GlobalPoint & P1, const GlobalPoint & P2, - Scalar ip, Scalar curv, Scalar tolerance); + ThirdHitPredictionFromInvParabola( + const GlobalPoint &P1, const GlobalPoint &P2, Scalar ip, Scalar curv, Scalar tolerance); -// inline Range operator()(Scalar radius, int charge) const { return rangeRPhiSlow(radius,charge,1); } - inline Range operator()(Scalar radius, int charge) const { return rangeRPhi(radius,charge); } + // inline Range operator()(Scalar radius, int charge) const { return rangeRPhiSlow(radius,charge,1); } + inline Range operator()(Scalar radius, int charge) const { return rangeRPhi(radius, charge); } - inline Range operator()(Scalar radius) const { return rangeRPhi(radius); } + inline Range operator()(Scalar radius) const { return rangeRPhi(radius); } - - Range rangeRPhi(Scalar radius, int charge) const; // __attribute__ ((optimize(3, "fast-math"))); + Range rangeRPhi(Scalar radius, int charge) const; // __attribute__ ((optimize(3, "fast-math"))); Range rangeRPhi(Scalar radius) const; - // Range rangeRPhiSlow(Scalar radius, int charge, int nIter=5) const; - void init( const GlobalPoint & P1, const GlobalPoint & P2, Scalar ip, Scalar curv) { - init( P1.x(), P1.y(), P2.x(),P2.y(),ip,curv); + void init(const GlobalPoint &P1, const GlobalPoint &P2, Scalar ip, Scalar curv) { + init(P1.x(), P1.y(), P2.x(), P2.y(), ip, curv); } - void init(Scalar x1,Scalar y1, Scalar x2,Scalar y2, Scalar ip, Scalar curv); + void init(Scalar x1, Scalar y1, Scalar x2, Scalar y2, Scalar ip, Scalar curv); private: - - - inline Scalar coeffA(Scalar impactParameter) const; inline Scalar coeffB(Scalar impactParameter) const; - inline Scalar predV(Scalar u, Scalar ip) const; - inline Scalar ipFromCurvature(Scalar curvature, bool pos) const; + inline Scalar predV(Scalar u, Scalar ip) const; + inline Scalar ipFromCurvature(Scalar curvature, bool pos) const; - Point2D transform(Point2D const & p) const { - return theRotation.rotate(p)/p.mag2(); - } + Point2D transform(Point2D const &p) const { return theRotation.rotate(p) / p.mag2(); } - Point2D transformBack(Point2D const & p) const { - return theRotation.rotateBack(p)/p.mag2(); - } + Point2D transformBack(Point2D const &p) const { return theRotation.rotateBack(p) / p.mag2(); } private: - Rotation theRotation; Scalar u1u2, overDu, pv, dv, su; // formula is symmetric for (ip,pos) -> (-ip,neg) inline void findPointAtCurve(Scalar radius, Scalar ip, Scalar &u, Scalar &v) const; - RangeD theIpRangePlus, theIpRangeMinus; + RangeD theIpRangePlus, theIpRangeMinus; Scalar theTolerance; bool emptyP, emptyM; - }; - - -ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola:: - coeffA(Scalar impactParameter) const -{ - auto c = -pv*overDu; - return c - u1u2*impactParameter; +ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola::coeffA(Scalar impactParameter) const { + auto c = -pv * overDu; + return c - u1u2 * impactParameter; } -ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola:: - coeffB(Scalar impactParameter) const -{ - auto c = dv*overDu; - return c - su*impactParameter; +ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola::coeffB(Scalar impactParameter) const { + auto c = dv * overDu; + return c - su * impactParameter; } -ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola:: - ipFromCurvature(Scalar curvature, bool pos) const -{ - Scalar overU1u2 = 1./u1u2; - Scalar inInf = -pv*overDu*overU1u2; - return (pos? inInf : -inInf) -curvature*overU1u2*0.5; +ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola::ipFromCurvature(Scalar curvature, + bool pos) const { + Scalar overU1u2 = 1. / u1u2; + Scalar inInf = -pv * overDu * overU1u2; + return (pos ? inInf : -inInf) - curvature * overU1u2 * 0.5; } - -ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola:: -predV( Scalar u, Scalar ip) const -{ - auto c = -( coeffA(ip) - coeffB(ip*u) - ip*u*u); +ThirdHitPredictionFromInvParabola::Scalar ThirdHitPredictionFromInvParabola::predV(Scalar u, Scalar ip) const { + auto c = -(coeffA(ip) - coeffB(ip * u) - ip * u * u); return c; } - -void ThirdHitPredictionFromInvParabola::findPointAtCurve(Scalar r, Scalar ip, - Scalar & u, Scalar & v) const -{ +void ThirdHitPredictionFromInvParabola::findPointAtCurve(Scalar r, Scalar ip, Scalar &u, Scalar &v) const { // // assume u=(1-alpha^2/2)/r v=alpha/r // solve qudratic equation neglecting aplha^4 term @@ -149,24 +120,23 @@ void ThirdHitPredictionFromInvParabola::findPointAtCurve(Scalar r, Scalar ip, Scalar B = coeffB(ip); // Scalar overR = 1./r; - Scalar ipOverR = ip/r; // *overR; + Scalar ipOverR = ip / r; // *overR; - Scalar a = 0.5*B+ipOverR; - Scalar c = -B+A*r-ipOverR; + Scalar a = 0.5 * B + ipOverR; + Scalar c = -B + A * r - ipOverR; - Scalar delta = 1-4*a*c; + Scalar delta = 1 - 4 * a * c; // Scalar sqrtdelta = (delta > 0) ? std::sqrt(delta) : 0.; Scalar sqrtdelta = std::sqrt(delta); // Scalar alpha = (-1+sqrtdelta)/(2*a); - Scalar alpha = (-2*c)/(1+sqrtdelta); + Scalar alpha = (-2 * c) / (1 + sqrtdelta); - v = alpha; // *overR - Scalar d2 = 1. - v*v; // overR*overR - v*v + v = alpha; // *overR + Scalar d2 = 1. - v * v; // overR*overR - v*v // u = (d2 > 0) ? std::sqrt(d2) : 0.; u = std::sqrt(d2); // u,v not rotated! not multiplied by 1/r } - #endif diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitRZPrediction.h b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitRZPrediction.h index b90f89d8024ff..a83eb0cdba172 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitRZPrediction.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitRZPrediction.h @@ -10,13 +10,12 @@ #include "RecoPixelVertexing/PixelTriplets/interface/ThirdHitRZPredictionBase.h" -template +template class ThirdHitRZPrediction : public ThirdHitRZPredictionBase { public: - ThirdHitRZPrediction() : ThirdHitRZPredictionBase(), thePropagator(nullptr) {} - ThirdHitRZPrediction(const Propagator *propagator, float tolerance, const DetLayer* layer = nullptr) : - ThirdHitRZPredictionBase(tolerance, layer), thePropagator(propagator) {} + ThirdHitRZPrediction(const Propagator *propagator, float tolerance, const DetLayer *layer = nullptr) + : ThirdHitRZPredictionBase(tolerance, layer), thePropagator(propagator) {} inline Range operator()(const DetLayer *layer = nullptr); inline Range operator()(float rORz) const { return (*this)(rORz, *thePropagator); } @@ -25,28 +24,29 @@ class ThirdHitRZPrediction : public ThirdHitRZPredictionBase { void initPropagator(const Propagator *propagator) { thePropagator = propagator; } private: - float transform( const Propagator &propagator, float rOrZ) const - { return theBarrel ? propagator.zAtR(rOrZ) : propagator.rAtZ(rOrZ); } + float transform(const Propagator &propagator, float rOrZ) const { + return theBarrel ? propagator.zAtR(rOrZ) : propagator.rAtZ(rOrZ); + } const Propagator *thePropagator; }; -template -typename ThirdHitRZPrediction::Range -ThirdHitRZPrediction::operator()(const DetLayer *layer) -{ - if (layer) initLayer(layer); - if (!theBarrel && !theForward) return Range(0., 0.); +template +typename ThirdHitRZPrediction::Range ThirdHitRZPrediction::operator()(const DetLayer *layer) { + if (layer) + initLayer(layer); + if (!theBarrel && !theForward) + return Range(0., 0.); float v1 = transform(*thePropagator, theDetRange.min()); float v2 = transform(*thePropagator, theDetRange.max()); - if (v1 > v2) std::swap(v1, v2); + if (v1 > v2) + std::swap(v1, v2); return Range(v1 - theTolerance.left(), v2 + theTolerance.right()); } -template -typename ThirdHitRZPrediction::Range -ThirdHitRZPrediction::operator()(float rOrZ, const Propagator &propagator) const -{ +template +typename ThirdHitRZPrediction::Range ThirdHitRZPrediction::operator()( + float rOrZ, const Propagator &propagator) const { float v = transform(propagator, rOrZ); return Range(v - theTolerance.left(), v + theTolerance.right()); } diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.cc b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.cc index 499b09081a4e4..8142bbb5a878c 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.cc +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.cc @@ -1,29 +1,24 @@ #include "ThirdHitZPrediction.h" namespace { - template T sqr(T t) { return t * t; } -} - + template + T sqr(T t) { + return t * t; + } +} // namespace -ThirdHitZPrediction::Range ThirdHitZPrediction::operator()( - const GlobalPoint& thePoint3, float erroRPhi3) const -{ - double dR23 = (thePoint3-thePoint2).perp(); +ThirdHitZPrediction::Range ThirdHitZPrediction::operator()(const GlobalPoint& thePoint3, float erroRPhi3) const { + double dR23 = (thePoint3 - thePoint2).perp(); - double slope = dR23/dR12; - if ( (theCurvature > 1.e-4) - && (std::abs(0.5*dR23*theCurvature) < 1.) - ) slope = std::asin(0.5*dR23*theCurvature)/dS12; + double slope = dR23 / dR12; + if ((theCurvature > 1.e-4) && (std::abs(0.5 * dR23 * theCurvature) < 1.)) + slope = std::asin(0.5 * dR23 * theCurvature) / dS12; - double z3 = thePoint2.z() + dZ12*slope; + double z3 = thePoint2.z() + dZ12 * slope; - double sqr_errorXY23 = sqr_errorXY2+sqr(erroRPhi3); - double error = sqrt( sqr( (1+dR23/dR12)*theErrorZ2 ) - + sqr( dR23/dR12 * theErrorZ1 ) - + sqr(dZ12/dR12 )*sqr_errorXY23 - + sqr((dZ12/dR12)*(dR23/dR12))*sqr_errorXY12 - ); + double sqr_errorXY23 = sqr_errorXY2 + sqr(erroRPhi3); + double error = sqrt(sqr((1 + dR23 / dR12) * theErrorZ2) + sqr(dR23 / dR12 * theErrorZ1) + + sqr(dZ12 / dR12) * sqr_errorXY23 + sqr((dZ12 / dR12) * (dR23 / dR12)) * sqr_errorXY12); error *= theNSigma; - return Range(z3-error,z3+error); + return Range(z3 - error, z3 + error); } - diff --git a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.h b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.h index 8fae3038e9bcc..80304fa99994b 100644 --- a/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.h +++ b/RecoPixelVertexing/PixelTriplets/plugins/ThirdHitZPrediction.h @@ -3,35 +3,42 @@ #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "RecoTracker/TkMSParametrization/interface/PixelRecoRange.h" -#include +#include - -class ThirdHitZPrediction { +class ThirdHitZPrediction { public: typedef PixelRecoRange Range; - ThirdHitZPrediction(const GlobalPoint& p1, float erroRPhi1, float errorZ1, - const GlobalPoint& p2, float erroRPhi2, float errorZ2, - double curvature, double nSigma = 3.) : - thePoint2(p2), - sqr_errorXY12(erroRPhi1*erroRPhi1+erroRPhi2*erroRPhi2), - sqr_errorXY2(erroRPhi2*erroRPhi2), - theErrorZ1(errorZ1), - theErrorZ2(errorZ2), - theCurvature(curvature), theNSigma(nSigma){ - auto d = p2-p1; - dR12 = d.perp(); if (dR12 < 1.e-5) dR12 = 1.e-5; - dS12 = std::abs(0.5*dR12*theCurvature) <1 ? std::asin(0.5*dR12*theCurvature) : 1.; + ThirdHitZPrediction(const GlobalPoint& p1, + float erroRPhi1, + float errorZ1, + const GlobalPoint& p2, + float erroRPhi2, + float errorZ2, + double curvature, + double nSigma = 3.) + : thePoint2(p2), + sqr_errorXY12(erroRPhi1 * erroRPhi1 + erroRPhi2 * erroRPhi2), + sqr_errorXY2(erroRPhi2 * erroRPhi2), + theErrorZ1(errorZ1), + theErrorZ2(errorZ2), + theCurvature(curvature), + theNSigma(nSigma) { + auto d = p2 - p1; + dR12 = d.perp(); + if (dR12 < 1.e-5) + dR12 = 1.e-5; + dS12 = std::abs(0.5 * dR12 * theCurvature) < 1 ? std::asin(0.5 * dR12 * theCurvature) : 1.; dZ12 = d.z(); } Range operator()(const GlobalPoint& p3, float erroRPhi3) const; + private: GlobalPoint thePoint2; double dR12, dZ12, dS12; - double sqr_errorXY12; - double sqr_errorXY2; + double sqr_errorXY12; + double sqr_errorXY2; double theErrorZ1, theErrorZ2; double theCurvature; double theNSigma; }; #endif - diff --git a/RecoPixelVertexing/PixelTriplets/src/CACell.h b/RecoPixelVertexing/PixelTriplets/src/CACell.h index bbe12ce093176..3a8bc35bc1f14 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CACell.h +++ b/RecoPixelVertexing/PixelTriplets/src/CACell.h @@ -10,26 +10,17 @@ #include "TrackingTools/TransientTrackingRecHit/interface/SeedingLayerSetsHits.h" class CACellStatus { - public: - - unsigned char getCAState() const { - return theCAState; - } - + unsigned char getCAState() const { return theCAState; } + // if there is at least one left neighbor with the same state (friend), the state has to be increased by 1. - void updateState() { - theCAState += hasSameStateNeighbors; - } - - bool isRootCell(const unsigned int minimumCAState) const { - return (theCAState >= minimumCAState); - } - - public: - unsigned char theCAState=0; - unsigned char hasSameStateNeighbors=0; - + void updateState() { theCAState += hasSameStateNeighbors; } + + bool isRootCell(const unsigned int minimumCAState) const { return (theCAState >= minimumCAState); } + +public: + unsigned char theCAState = 0; + unsigned char hasSameStateNeighbors = 0; }; class CACell { @@ -39,86 +30,60 @@ class CACell { using CAntuplet = std::vector; using CAColl = std::vector; using CAStatusColl = std::vector; - - - CACell(const HitDoublets* doublets, int doubletId, const int innerHitId, const int outerHitId) : - theDoublets(doublets), theDoubletId(doubletId) - ,theInnerR(doublets->rv(doubletId, HitDoublets::inner)) - ,theInnerZ(doublets->z(doubletId, HitDoublets::inner)) - {} - - - - Hit const & getInnerHit() const { - return theDoublets->hit(theDoubletId, HitDoublets::inner); - } - - Hit const & getOuterHit() const { - return theDoublets->hit(theDoubletId, HitDoublets::outer); - } - - - float getInnerX() const { - return theDoublets->x(theDoubletId, HitDoublets::inner); - } - - float getOuterX() const { - return theDoublets->x(theDoubletId, HitDoublets::outer); - } - - float getInnerY() const { - return theDoublets->y(theDoubletId, HitDoublets::inner); - } - - float getOuterY() const { - return theDoublets->y(theDoubletId, HitDoublets::outer); - } - - float getInnerZ() const { - return theInnerZ; - } - - float getOuterZ() const { - return theDoublets->z(theDoubletId, HitDoublets::outer); - } - - float getInnerR() const { - return theInnerR; - } - - float getOuterR() const { - return theDoublets->rv(theDoubletId, HitDoublets::outer); - } - - float getInnerPhi() const { - return theDoublets->phi(theDoubletId, HitDoublets::inner); - } - - float getOuterPhi() const { - return theDoublets->phi(theDoubletId, HitDoublets::outer); - } - + + CACell(const HitDoublets* doublets, int doubletId, const int innerHitId, const int outerHitId) + : theDoublets(doublets), + theDoubletId(doubletId), + theInnerR(doublets->rv(doubletId, HitDoublets::inner)), + theInnerZ(doublets->z(doubletId, HitDoublets::inner)) {} + + Hit const& getInnerHit() const { return theDoublets->hit(theDoubletId, HitDoublets::inner); } + + Hit const& getOuterHit() const { return theDoublets->hit(theDoubletId, HitDoublets::outer); } + + float getInnerX() const { return theDoublets->x(theDoubletId, HitDoublets::inner); } + + float getOuterX() const { return theDoublets->x(theDoubletId, HitDoublets::outer); } + + float getInnerY() const { return theDoublets->y(theDoubletId, HitDoublets::inner); } + + float getOuterY() const { return theDoublets->y(theDoubletId, HitDoublets::outer); } + + float getInnerZ() const { return theInnerZ; } + + float getOuterZ() const { return theDoublets->z(theDoubletId, HitDoublets::outer); } + + float getInnerR() const { return theInnerR; } + + float getOuterR() const { return theDoublets->rv(theDoubletId, HitDoublets::outer); } + + float getInnerPhi() const { return theDoublets->phi(theDoubletId, HitDoublets::inner); } + + float getOuterPhi() const { return theDoublets->phi(theDoubletId, HitDoublets::outer); } + void evolve(unsigned int me, CAStatusColl& allStatus) { - allStatus[me].hasSameStateNeighbors = 0; auto mystate = allStatus[me].theCAState; - - for (auto oc : theOuterNeighbors ) { - + + for (auto oc : theOuterNeighbors) { if (allStatus[oc].getCAState() == mystate) { - - allStatus[me].hasSameStateNeighbors = 1; - - break; + allStatus[me].hasSameStateNeighbors = 1; + + break; } } - } - - void checkAlignmentAndAct(CAColl& allCells, CAntuple & innerCells, const float ptmin, const float region_origin_x, - const float region_origin_y, const float region_origin_radius, const float thetaCut, - const float phiCut, const float hardPtCut, std::vector * foundTriplets) { + void checkAlignmentAndAct(CAColl& allCells, + CAntuple& innerCells, + const float ptmin, + const float region_origin_x, + const float region_origin_y, + const float region_origin_radius, + const float thetaCut, + const float phiCut, + const float hardPtCut, + std::vector* foundTriplets) { int ncells = innerCells.size(); int constexpr VSIZE = 16; int ok[VSIZE]; @@ -128,173 +93,190 @@ class CACell { auto zo = getOuterZ(); unsigned int cellId = this - &allCells.front(); auto loop = [&](int i, int vs) { - for (int j=0;jemplace_back(CACell::CAntuplet{koc,cellId}); - else { - oc.tagAsOuterNeighbor(cellId); - } - } + for (int j = 0; j < vs; ++j) + ok[j] = areAlignedRZ(r1[j], z1[j], ro, zo, ptmin, thetaCut); + for (int j = 0; j < vs; ++j) { + auto koc = innerCells[i + j]; + auto& oc = allCells[koc]; + if (ok[j] && haveSimilarCurvature( + oc, ptmin, region_origin_x, region_origin_y, region_origin_radius, phiCut, hardPtCut)) { + if (foundTriplets) + foundTriplets->emplace_back(CACell::CAntuplet{koc, cellId}); + else { + oc.tagAsOuterNeighbor(cellId); + } + } } }; - auto lim = VSIZE*(ncells/VSIZE); - for (int i=0; i& foundTriplets, - const float ptmin, const float region_origin_x, const float region_origin_y, - const float region_origin_radius, const float thetaCut, const float phiCut, - const float hardPtCut) { - checkAlignmentAndAct(allCells, innerCells, ptmin, region_origin_x, region_origin_y, region_origin_radius, thetaCut, - phiCut, hardPtCut, &foundTriplets); + void checkAlignmentAndPushTriplet(CAColl& allCells, + CAntuple& innerCells, + std::vector& foundTriplets, + const float ptmin, + const float region_origin_x, + const float region_origin_y, + const float region_origin_radius, + const float thetaCut, + const float phiCut, + const float hardPtCut) { + checkAlignmentAndAct(allCells, + innerCells, + ptmin, + region_origin_x, + region_origin_y, + region_origin_radius, + thetaCut, + phiCut, + hardPtCut, + &foundTriplets); } - - - int areAlignedRZ(float r1, float z1, float ro, float zo, const float ptmin, const float thetaCut) const - { + + int areAlignedRZ(float r1, float z1, float ro, float zo, const float ptmin, const float thetaCut) const { float radius_diff = std::abs(r1 - ro); - float distance_13_squared = radius_diff*radius_diff + (z1 - zo)*(z1 - zo); - - float pMin = ptmin*std::sqrt(distance_13_squared); //this needs to be divided by radius_diff later - - float tan_12_13_half_mul_distance_13_squared = fabs(z1 * (getInnerR() - ro) + getInnerZ() * (ro - r1) + zo * (r1 - getInnerR())) ; + float distance_13_squared = radius_diff * radius_diff + (z1 - zo) * (z1 - zo); + + float pMin = ptmin * std::sqrt(distance_13_squared); //this needs to be divided by radius_diff later + + float tan_12_13_half_mul_distance_13_squared = + fabs(z1 * (getInnerR() - ro) + getInnerZ() * (ro - r1) + zo * (r1 - getInnerR())); return tan_12_13_half_mul_distance_13_squared * pMin <= thetaCut * distance_13_squared * radius_diff; } - - - void tagAsOuterNeighbor(unsigned int otherCell) - { - theOuterNeighbors.push_back(otherCell); - } - - - bool haveSimilarCurvature(const CACell & otherCell, const float ptmin, - const float region_origin_x, const float region_origin_y, const float region_origin_radius, const float phiCut, const float hardPtCut) const - { - - + + void tagAsOuterNeighbor(unsigned int otherCell) { theOuterNeighbors.push_back(otherCell); } + + bool haveSimilarCurvature(const CACell& otherCell, + const float ptmin, + const float region_origin_x, + const float region_origin_y, + const float region_origin_radius, + const float phiCut, + const float hardPtCut) const { auto x1 = otherCell.getInnerX(); auto y1 = otherCell.getInnerY(); - + auto x2 = getInnerX(); auto y2 = getInnerY(); - + auto x3 = getOuterX(); auto y3 = getOuterY(); - - float distance_13_squared = (x1 - x3)*(x1 - x3) + (y1 - y3)*(y1 - y3); - float tan_12_13_half_mul_distance_13_squared = std::abs(y1 * (x2 - x3) + y2 * (x3 - x1) + y3 * (x1 - x2)) ; + + float distance_13_squared = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3); + float tan_12_13_half_mul_distance_13_squared = std::abs(y1 * (x2 - x3) + y2 * (x3 - x1) + y3 * (x1 - x2)); // high pt : just straight - if(tan_12_13_half_mul_distance_13_squared * ptmin <= 1.0e-4f*distance_13_squared) - { - - float distance_3_beamspot_squared = (x3-region_origin_x) * (x3-region_origin_x) + (y3-region_origin_y) * (y3-region_origin_y); - - float dot_bs3_13 = ((x1 - x3)*( region_origin_x - x3) + (y1 - y3) * (region_origin_y-y3)); - float proj_bs3_on_13_squared = dot_bs3_13*dot_bs3_13/distance_13_squared; - - float distance_13_beamspot_squared = distance_3_beamspot_squared - proj_bs3_on_13_squared; - - return distance_13_beamspot_squared < (region_origin_radius+phiCut)*(region_origin_radius+phiCut); - } - + if (tan_12_13_half_mul_distance_13_squared * ptmin <= 1.0e-4f * distance_13_squared) { + float distance_3_beamspot_squared = + (x3 - region_origin_x) * (x3 - region_origin_x) + (y3 - region_origin_y) * (y3 - region_origin_y); + + float dot_bs3_13 = ((x1 - x3) * (region_origin_x - x3) + (y1 - y3) * (region_origin_y - y3)); + float proj_bs3_on_13_squared = dot_bs3_13 * dot_bs3_13 / distance_13_squared; + + float distance_13_beamspot_squared = distance_3_beamspot_squared - proj_bs3_on_13_squared; + + return distance_13_beamspot_squared < (region_origin_radius + phiCut) * (region_origin_radius + phiCut); + } + //87 cm/GeV = 1/(3.8T * 0.3) - + //take less than radius given by the hardPtCut and reject everything below - float minRadius = hardPtCut*87.f; // FIXME move out and use real MagField - + float minRadius = hardPtCut * 87.f; // FIXME move out and use real MagField + auto det = (x1 - x2) * (y2 - y3) - (x2 - x3) * (y1 - y2); - - - auto offset = x2 * x2 + y2*y2; - - auto bc = (x1 * x1 + y1 * y1 - offset)*0.5f; - - auto cd = (offset - x3 * x3 - y3 * y3)*0.5f; - - - + + auto offset = x2 * x2 + y2 * y2; + + auto bc = (x1 * x1 + y1 * y1 - offset) * 0.5f; + + auto cd = (offset - x3 * x3 - y3 * y3) * 0.5f; + auto idet = 1.f / det; - + auto x_center = (bc * (y2 - y3) - cd * (y1 - y2)) * idet; auto y_center = (cd * (x1 - x2) - bc * (x2 - x3)) * idet; - - auto radius = std::sqrt((x2 - x_center)*(x2 - x_center) + (y2 - y_center)*(y2 - y_center)); - - if(radius < minRadius) return false; // hard cut on pt - - auto centers_distance_squared = (x_center - region_origin_x)*(x_center - region_origin_x) + (y_center - region_origin_y)*(y_center - region_origin_y); + + auto radius = std::sqrt((x2 - x_center) * (x2 - x_center) + (y2 - y_center) * (y2 - y_center)); + + if (radius < minRadius) + return false; // hard cut on pt + + auto centers_distance_squared = (x_center - region_origin_x) * (x_center - region_origin_x) + + (y_center - region_origin_y) * (y_center - region_origin_y); auto region_origin_radius_plus_tolerance = region_origin_radius + phiCut; - auto minimumOfIntersectionRange = (radius - region_origin_radius_plus_tolerance)*(radius - region_origin_radius_plus_tolerance); - + auto minimumOfIntersectionRange = + (radius - region_origin_radius_plus_tolerance) * (radius - region_origin_radius_plus_tolerance); + if (centers_distance_squared >= minimumOfIntersectionRange) { - auto maximumOfIntersectionRange = (radius + region_origin_radius_plus_tolerance)*(radius + region_origin_radius_plus_tolerance); + auto maximumOfIntersectionRange = + (radius + region_origin_radius_plus_tolerance) * (radius + region_origin_radius_plus_tolerance); return centers_distance_squared <= maximumOfIntersectionRange; - } - + } + return false; - } - - + // trying to free the track building process from hardcoded layers, leaving the visit of the graph // based on the neighborhood connections between cells. - - void findNtuplets(CAColl& allCells, std::vector& foundNtuplets, CAntuplet& tmpNtuplet, const unsigned int minHitsPerNtuplet) const { - + + void findNtuplets(CAColl& allCells, + std::vector& foundNtuplets, + CAntuplet& tmpNtuplet, + const unsigned int minHitsPerNtuplet) const { // the building process for a track ends if: // it has no outer neighbor // it has no compatible neighbor // the ntuplets is then saved if the number of hits it contains is greater than a threshold - - if (tmpNtuplet.size() == minHitsPerNtuplet - 1) - { - foundNtuplets.push_back(tmpNtuplet); - } - else - { - unsigned int numberOfOuterNeighbors = theOuterNeighbors.size(); - for (unsigned int i = 0; i < numberOfOuterNeighbors; ++i) { - tmpNtuplet.push_back((theOuterNeighbors[i])); - allCells[theOuterNeighbors[i]].findNtuplets(allCells,foundNtuplets, tmpNtuplet, minHitsPerNtuplet); - tmpNtuplet.pop_back(); - } + + if (tmpNtuplet.size() == minHitsPerNtuplet - 1) { + foundNtuplets.push_back(tmpNtuplet); + } else { + unsigned int numberOfOuterNeighbors = theOuterNeighbors.size(); + for (unsigned int i = 0; i < numberOfOuterNeighbors; ++i) { + tmpNtuplet.push_back((theOuterNeighbors[i])); + allCells[theOuterNeighbors[i]].findNtuplets(allCells, foundNtuplets, tmpNtuplet, minHitsPerNtuplet); + tmpNtuplet.pop_back(); } - + } } - - + private: - CAntuple theOuterNeighbors; - - const HitDoublets* theDoublets; + + const HitDoublets* theDoublets; const int theDoubletId; - + const float theInnerR; const float theInnerZ; - }; - -#endif // RecoPixelVertexing_PixelTriplets_src_CACell_h +#endif // RecoPixelVertexing_PixelTriplets_src_CACell_h diff --git a/RecoPixelVertexing/PixelTriplets/src/CAGraph.h b/RecoPixelVertexing/PixelTriplets/src/CAGraph.h index dc679abce5492..f5c8e2f354d67 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CAGraph.h +++ b/RecoPixelVertexing/PixelTriplets/src/CAGraph.h @@ -5,19 +5,14 @@ #include #include -struct CALayer -{ - CALayer(const std::string &layerName, std::size_t numberOfHits) - : theName(layerName) - { +struct CALayer { + CALayer(const std::string &layerName, std::size_t numberOfHits) : theName(layerName) { isOuterHitOfCell.resize(numberOfHits); } - bool operator==(const std::string &otherString) { - return otherString == theName; - } + bool operator==(const std::string &otherString) { return otherString == theName; } - const std::string& name() const { return theName; } + const std::string &name() const { return theName; } std::vector theOuterLayerPairs; std::vector theInnerLayerPairs; @@ -30,8 +25,7 @@ struct CALayer std::string theName; }; -struct CALayerPair -{ +struct CALayerPair { CALayerPair(int a, int b) { @@ -40,19 +34,17 @@ struct CALayerPair } bool operator==(const CALayerPair &otherLayerPair) { - return (theLayers[0] == otherLayerPair.theLayers[0]) && - (theLayers[1] == otherLayerPair.theLayers[1]); + return (theLayers[0] == otherLayerPair.theLayers[0]) && (theLayers[1] == otherLayerPair.theLayers[1]); } std::array theLayers; std::array theFoundCells = {{0, 0}}; }; -struct CAGraph -{ +struct CAGraph { std::vector theLayers; std::vector theLayerPairs; std::vector theRootLayers; }; -#endif // RecoPixelVertexing_PixelTriplets_src_CAGraph_h +#endif // RecoPixelVertexing_PixelTriplets_src_CAGraph_h diff --git a/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.cc b/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.cc index 6e5e6cbc2ff37..7a76a06f28c0d 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.cc +++ b/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.cc @@ -2,13 +2,11 @@ #include "CellularAutomaton.h" -void CellularAutomaton::createAndConnectCells( - const std::vector & hitDoublets, - const TrackingRegion & region, - const float thetaCut, - const float phiCut, - const float hardPtCut) -{ +void CellularAutomaton::createAndConnectCells(const std::vector &hitDoublets, + const TrackingRegion ®ion, + const float thetaCut, + const float phiCut, + const float hardPtCut) { int tsize = 0; for (auto hd : hitDoublets) { tsize += hd->size(); @@ -36,9 +34,9 @@ void CellularAutomaton::createAndConnectCells( while (not LayerPairsToVisit.empty()) { auto currentLayerPair = LayerPairsToVisit.front(); - auto & currentLayerPairRef = theLayerGraph.theLayerPairs[currentLayerPair]; - auto & currentInnerLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[0]]; - auto & currentOuterLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[1]]; + auto ¤tLayerPairRef = theLayerGraph.theLayerPairs[currentLayerPair]; + auto ¤tInnerLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[0]]; + auto ¤tOuterLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[1]]; bool allInnerLayerPairsAlreadyVisited{true}; for (auto innerLayerPair : currentInnerLayerRef.theInnerLayerPairs) { @@ -51,18 +49,23 @@ void CellularAutomaton::createAndConnectCells( currentLayerPairRef.theFoundCells[0] = cellId; currentLayerPairRef.theFoundCells[1] = cellId + numberOfDoublets; for (unsigned int i = 0; i < numberOfDoublets; ++i) { - allCells.emplace_back(doubletLayerPairId, i, - doubletLayerPairId->innerHitId(i), - doubletLayerPairId->outerHitId(i)); + allCells.emplace_back( + doubletLayerPairId, i, doubletLayerPairId->innerHitId(i), doubletLayerPairId->outerHitId(i)); currentOuterLayerRef.isOuterHitOfCell[doubletLayerPairId->outerHitId(i)].push_back(cellId); cellId++; - auto & neigCells = currentInnerLayerRef.isOuterHitOfCell[doubletLayerPairId->innerHitId(i)]; - allCells.back().checkAlignmentAndTag( - allCells, neigCells, ptmin, region_origin_x, region_origin_y, - region_origin_radius, thetaCut, phiCut, hardPtCut); + auto &neigCells = currentInnerLayerRef.isOuterHitOfCell[doubletLayerPairId->innerHitId(i)]; + allCells.back().checkAlignmentAndTag(allCells, + neigCells, + ptmin, + region_origin_x, + region_origin_y, + region_origin_radius, + thetaCut, + phiCut, + hardPtCut); } assert(cellId == currentLayerPairRef.theFoundCells[1]); for (auto outerLayerPair : currentOuterLayerRef.theOuterLayerPairs) { @@ -80,20 +83,19 @@ void CellularAutomaton::createAndConnectCells( } } -void CellularAutomaton::evolve(const unsigned int minHitsPerNtuplet) -{ +void CellularAutomaton::evolve(const unsigned int minHitsPerNtuplet) { allStatus.resize(allCells.size()); unsigned int numberOfIterations = minHitsPerNtuplet - 2; // keeping the last iteration for later for (unsigned int iteration = 0; iteration < numberOfIterations - 1; ++iteration) { - for (auto & layerPair : theLayerGraph.theLayerPairs) { + for (auto &layerPair : theLayerGraph.theLayerPairs) { for (auto i = layerPair.theFoundCells[0]; i < layerPair.theFoundCells[1]; ++i) { allCells[i].evolve(i, allStatus); } } - for (auto & layerPair : theLayerGraph.theLayerPairs) { + for (auto &layerPair : theLayerGraph.theLayerPairs) { for (auto i = layerPair.theFoundCells[0]; i < layerPair.theFoundCells[1]; ++i) { allStatus[i].updateState(); } @@ -106,7 +108,7 @@ void CellularAutomaton::evolve(const unsigned int minHitsPerNtuplet) for (int rootLayerPair : theLayerGraph.theLayers[rootLayerId].theOuterLayerPairs) { auto foundCells = theLayerGraph.theLayerPairs[rootLayerPair].theFoundCells; for (auto i = foundCells[0]; i < foundCells[1]; ++i) { - auto & cell = allStatus[i]; + auto &cell = allStatus[i]; allCells[i].evolve(i, allStatus); cell.updateState(); if (cell.isRootCell(minHitsPerNtuplet - 2)) { @@ -117,26 +119,24 @@ void CellularAutomaton::evolve(const unsigned int minHitsPerNtuplet) } } -void CellularAutomaton::findNtuplets(std::vector & foundNtuplets, const unsigned int minHitsPerNtuplet) -{ +void CellularAutomaton::findNtuplets(std::vector &foundNtuplets, + const unsigned int minHitsPerNtuplet) { CACell::CAntuple tmpNtuplet; tmpNtuplet.reserve(minHitsPerNtuplet); - for (auto root_cell : theRootCells) - { + for (auto root_cell : theRootCells) { tmpNtuplet.clear(); tmpNtuplet.push_back(root_cell); allCells[root_cell].findNtuplets(allCells, foundNtuplets, tmpNtuplet, minHitsPerNtuplet); } } -void CellularAutomaton::findTriplets( - std::vector const& hitDoublets, - std::vector & foundTriplets, TrackingRegion const& region, - const float thetaCut, - const float phiCut, - const float hardPtCut) -{ +void CellularAutomaton::findTriplets(std::vector const &hitDoublets, + std::vector &foundTriplets, + TrackingRegion const ®ion, + const float thetaCut, + const float phiCut, + const float hardPtCut) { int tsize = 0; for (auto hd : hitDoublets) { tsize += hd->size(); @@ -165,9 +165,9 @@ void CellularAutomaton::findTriplets( while (not LayerPairsToVisit.empty()) { auto currentLayerPair = LayerPairsToVisit.front(); - auto & currentLayerPairRef = theLayerGraph.theLayerPairs[currentLayerPair]; - auto & currentInnerLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[0]]; - auto & currentOuterLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[1]]; + auto ¤tLayerPairRef = theLayerGraph.theLayerPairs[currentLayerPair]; + auto ¤tInnerLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[0]]; + auto ¤tOuterLayerRef = theLayerGraph.theLayers[currentLayerPairRef.theLayers[1]]; bool allInnerLayerPairsAlreadyVisited{true}; for (auto innerLayerPair : currentInnerLayerRef.theInnerLayerPairs) { @@ -180,18 +180,24 @@ void CellularAutomaton::findTriplets( currentLayerPairRef.theFoundCells[0] = cellId; currentLayerPairRef.theFoundCells[1] = cellId + numberOfDoublets; for (unsigned int i = 0; i < numberOfDoublets; ++i) { - allCells.emplace_back(doubletLayerPairId, i, - doubletLayerPairId->innerHitId(i), - doubletLayerPairId->outerHitId(i)); + allCells.emplace_back( + doubletLayerPairId, i, doubletLayerPairId->innerHitId(i), doubletLayerPairId->outerHitId(i)); currentOuterLayerRef.isOuterHitOfCell[doubletLayerPairId->outerHitId(i)].push_back(cellId); cellId++; - auto & neigCells = currentInnerLayerRef.isOuterHitOfCell[doubletLayerPairId->innerHitId(i)]; - allCells.back().checkAlignmentAndPushTriplet( - allCells, neigCells, foundTriplets, ptmin, region_origin_x, region_origin_y, - region_origin_radius, thetaCut, phiCut, hardPtCut); + auto &neigCells = currentInnerLayerRef.isOuterHitOfCell[doubletLayerPairId->innerHitId(i)]; + allCells.back().checkAlignmentAndPushTriplet(allCells, + neigCells, + foundTriplets, + ptmin, + region_origin_x, + region_origin_y, + region_origin_radius, + thetaCut, + phiCut, + hardPtCut); } assert(cellId == currentLayerPairRef.theFoundCells[1]); for (auto outerLayerPair : currentOuterLayerRef.theOuterLayerPairs) { diff --git a/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.h b/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.h index 7fafc2d597a48..cd91497bd01b2 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.h +++ b/RecoPixelVertexing/PixelTriplets/src/CellularAutomaton.h @@ -9,32 +9,32 @@ #include "CACell.h" #include "CAGraph.h" -class CellularAutomaton -{ +class CellularAutomaton { public: - CellularAutomaton(CAGraph& graph) - : theLayerGraph(graph) - { } - - std::vector & getAllCells() { return allCells; } - - void createAndConnectCells(const std::vector&, - const TrackingRegion&, const float, const float, const float); - + CellularAutomaton(CAGraph& graph) : theLayerGraph(graph) {} + + std::vector& getAllCells() { return allCells; } + + void createAndConnectCells( + const std::vector&, const TrackingRegion&, const float, const float, const float); + void evolve(const unsigned int); void findNtuplets(std::vector&, const unsigned int); - void findTriplets(const std::vector& hitDoublets,std::vector& foundTriplets, const TrackingRegion& region, - const float thetaCut, const float phiCut, const float hardPtCut); - + void findTriplets(const std::vector& hitDoublets, + std::vector& foundTriplets, + const TrackingRegion& region, + const float thetaCut, + const float phiCut, + const float hardPtCut); + private: - CAGraph & theLayerGraph; + CAGraph& theLayerGraph; std::vector allCells; std::vector allStatus; std::vector theRootCells; std::vector > theNtuplets; - }; -#endif // RecoPixelVertexing_PixelTriplets_src_CellularAutomaton_h +#endif // RecoPixelVertexing_PixelTriplets_src_CellularAutomaton_h diff --git a/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGenerator.cc b/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGenerator.cc index b08a66db3c2d8..1eca20a664826 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGenerator.cc +++ b/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGenerator.cc @@ -6,52 +6,36 @@ using namespace std; -CosmicHitTripletGenerator::CosmicHitTripletGenerator(CosmicLayerTriplets& layers, - const edm::EventSetup& iSetup) -{ +CosmicHitTripletGenerator::CosmicHitTripletGenerator(CosmicLayerTriplets& layers, const edm::EventSetup& iSetup) { // vector layerTriplets = layers(); vector layerTriplets = layers.layers(); vector::const_iterator it; for (it = layerTriplets.begin(); it != layerTriplets.end(); it++) { vector::const_iterator ilwh; - for(ilwh=(*it).second.begin();ilwh!=(*it).second.end();ilwh++){ - // const LayerWithHits* first=(*it).first.first; -// const LayerWithHits* second=(*it).first.second; -// const LayerWithHits* third=(*ilwh); + for (ilwh = (*it).second.begin(); ilwh != (*it).second.end(); ilwh++) { + // const LayerWithHits* first=(*it).first.first; + // const LayerWithHits* second=(*it).first.second; + // const LayerWithHits* third=(*ilwh); // add( (*it).first.first, (*it).first.second, (*it).second,iSetup); - add( (*it).first.first, (*it).first.second, (*ilwh),iSetup); + add((*it).first.first, (*it).first.second, (*ilwh), iSetup); } } - -} - - - -CosmicHitTripletGenerator::~CosmicHitTripletGenerator() -{ } +CosmicHitTripletGenerator::~CosmicHitTripletGenerator() {} -void CosmicHitTripletGenerator::add( - const LayerWithHits *inner, - const LayerWithHits* middle, - const LayerWithHits *outer, - const edm::EventSetup& iSetup) -{ - theGenerators.push_back(std::make_unique( inner,middle, outer, iSetup)); +void CosmicHitTripletGenerator::add(const LayerWithHits* inner, + const LayerWithHits* middle, + const LayerWithHits* outer, + const edm::EventSetup& iSetup) { + theGenerators.push_back(std::make_unique(inner, middle, outer, iSetup)); } -void CosmicHitTripletGenerator::hitTriplets( - const TrackingRegion& region, - OrderedHitTriplets & pairs, - const edm::EventSetup& iSetup) -{ - +void CosmicHitTripletGenerator::hitTriplets(const TrackingRegion& region, + OrderedHitTriplets& pairs, + const edm::EventSetup& iSetup) { Container::const_iterator i; - for (i=theGenerators.begin(); i!=theGenerators.end(); i++) { - (**i).hitTriplets( region, pairs, iSetup); + for (i = theGenerators.begin(); i != theGenerators.end(); i++) { + (**i).hitTriplets(region, pairs, iSetup); } - } - - diff --git a/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGeneratorFromLayerTriplet.cc b/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGeneratorFromLayerTriplet.cc index d604efae7abbd..8cafa3803701f 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGeneratorFromLayerTriplet.cc +++ b/RecoPixelVertexing/PixelTriplets/src/CosmicHitTripletGeneratorFromLayerTriplet.cc @@ -13,94 +13,92 @@ typedef TransientTrackingRecHit::ConstRecHitPointer TkHitPairsCachedHit; -CosmicHitTripletGeneratorFromLayerTriplet::CosmicHitTripletGeneratorFromLayerTriplet -(const LayerWithHits* inner, - const LayerWithHits* middle, - const LayerWithHits* outer, - const edm::EventSetup& iSetup) - : TTRHbuilder(nullptr),trackerGeometry(nullptr), - //theLayerCache(*layerCache), - theOuterLayer(outer),theMiddleLayer(middle), theInnerLayer(inner) -{ - +CosmicHitTripletGeneratorFromLayerTriplet::CosmicHitTripletGeneratorFromLayerTriplet(const LayerWithHits *inner, + const LayerWithHits *middle, + const LayerWithHits *outer, + const edm::EventSetup &iSetup) + : TTRHbuilder(nullptr), + trackerGeometry(nullptr), + //theLayerCache(*layerCache), + theOuterLayer(outer), + theMiddleLayer(middle), + theInnerLayer(inner) { edm::ESHandle tracker; iSetup.get().get(tracker); trackerGeometry = tracker.product(); } -void CosmicHitTripletGeneratorFromLayerTriplet::hitTriplets( - const TrackingRegion & region, OrderedHitTriplets & result, - const edm::EventSetup& iSetup) -{ - - if (theInnerLayer->recHits().empty()) return; - if (theMiddleLayer->recHits().empty()) return; - if (theOuterLayer->recHits().empty()) return; - float radius1 =dynamic_cast(theInnerLayer->layer())->specificSurface().radius(); - float radius2 =dynamic_cast(theMiddleLayer->layer())->specificSurface().radius(); - float radius3 =dynamic_cast(theOuterLayer->layer())->specificSurface().radius(); - bool seedfromoverlaps=((std::abs(radius1-radius2)<0.1)|| (std::abs(radius3-radius2)<0.1))? true : false; - std::vector::const_iterator ohh; - std::vector::const_iterator mhh; - std::vector::const_iterator ihh; +void CosmicHitTripletGeneratorFromLayerTriplet::hitTriplets(const TrackingRegion ®ion, + OrderedHitTriplets &result, + const edm::EventSetup &iSetup) { + if (theInnerLayer->recHits().empty()) + return; + if (theMiddleLayer->recHits().empty()) + return; + if (theOuterLayer->recHits().empty()) + return; + float radius1 = dynamic_cast(theInnerLayer->layer())->specificSurface().radius(); + float radius2 = dynamic_cast(theMiddleLayer->layer())->specificSurface().radius(); + float radius3 = dynamic_cast(theOuterLayer->layer())->specificSurface().radius(); + bool seedfromoverlaps = ((std::abs(radius1 - radius2) < 0.1) || (std::abs(radius3 - radius2) < 0.1)) ? true : false; + std::vector::const_iterator ohh; + std::vector::const_iterator mhh; + std::vector::const_iterator ihh; std::string builderName = "WithTrackAngle"; edm::ESHandle builder; iSetup.get().get(builderName, builder); - if(!seedfromoverlaps){ - for(ohh=theOuterLayer->recHits().begin();ohh!=theOuterLayer->recHits().end();ohh++){ - auto oh= (BaseTrackerRecHit const *)(&*ohh); - for(mhh=theMiddleLayer->recHits().begin();mhh!=theMiddleLayer->recHits().end();mhh++){ - auto mh= (BaseTrackerRecHit const *)(&*mhh); - float z_diff =mh->globalPosition().z()-oh->globalPosition().z(); - float midy=mh->globalPosition().y(); - float outy=oh->globalPosition().y(); - float midx=mh->globalPosition().x(); - float outx=oh->globalPosition().x(); - float dxdy=std::abs((outx-midx)/(outy-midy)); - if((std::abs(z_diff)<30) && (outy*midy>0) &&(dxdy<2)) - { - for(ihh=theInnerLayer->recHits().begin();ihh!=theInnerLayer->recHits().end();ihh++){ - auto ih= (BaseTrackerRecHit const *)(&*ihh); - float z_diff =mh->globalPosition().z()-ih->globalPosition().z(); - float inny=ih->globalPosition().y(); - float innx=ih->globalPosition().x(); - float dxdy=std::abs((innx-midx)/(inny-midy)); - if ((std::abs(z_diff)<30) && (inny*midy>0) &&(dxdy<2)&&(!seedfromoverlaps)) - { - result.push_back( OrderedHitTriplet(ih,mh,oh) ); - } - } - } + if (!seedfromoverlaps) { + for (ohh = theOuterLayer->recHits().begin(); ohh != theOuterLayer->recHits().end(); ohh++) { + auto oh = (BaseTrackerRecHit const *)(&*ohh); + for (mhh = theMiddleLayer->recHits().begin(); mhh != theMiddleLayer->recHits().end(); mhh++) { + auto mh = (BaseTrackerRecHit const *)(&*mhh); + float z_diff = mh->globalPosition().z() - oh->globalPosition().z(); + float midy = mh->globalPosition().y(); + float outy = oh->globalPosition().y(); + float midx = mh->globalPosition().x(); + float outx = oh->globalPosition().x(); + float dxdy = std::abs((outx - midx) / (outy - midy)); + if ((std::abs(z_diff) < 30) && (outy * midy > 0) && (dxdy < 2)) { + for (ihh = theInnerLayer->recHits().begin(); ihh != theInnerLayer->recHits().end(); ihh++) { + auto ih = (BaseTrackerRecHit const *)(&*ihh); + float z_diff = mh->globalPosition().z() - ih->globalPosition().z(); + float inny = ih->globalPosition().y(); + float innx = ih->globalPosition().x(); + float dxdy = std::abs((innx - midx) / (inny - midy)); + if ((std::abs(z_diff) < 30) && (inny * midy > 0) && (dxdy < 2) && (!seedfromoverlaps)) { + result.push_back(OrderedHitTriplet(ih, mh, oh)); + } + } + } } } } else { - for(ohh=theOuterLayer->recHits().begin();ohh!=theOuterLayer->recHits().end();ohh++){ - auto oh= (BaseTrackerRecHit const *)(&*ohh); - for(mhh=theMiddleLayer->recHits().begin();mhh!=theMiddleLayer->recHits().end();mhh++){ - auto mh= (BaseTrackerRecHit const *)(&*mhh); - float z_diff =mh->globalPosition().z()-oh->globalPosition().z(); - float midy=mh->globalPosition().y(); - float outy=oh->globalPosition().y(); - float midx=mh->globalPosition().x(); - float outx=oh->globalPosition().x(); - float dxdy=std::abs((outx-midx)/(outy-midy)); - float DeltaR=oh->globalPosition().perp()-mh->globalPosition().perp(); - if((std::abs(z_diff)<18) && (std::abs(oh->globalPosition().phi()-mh->globalPosition().phi())<0.05) &&(DeltaR<0)&&(dxdy<2)){ - for(ihh=theInnerLayer->recHits().begin();ihh!=theInnerLayer->recHits().end();ihh++){ - auto ih= (BaseTrackerRecHit const *)(&*ihh); - float z_diff =mh->globalPosition().z()-ih->globalPosition().z(); - float inny=ih->globalPosition().y(); - float innx=ih->globalPosition().x(); - float dxdy=std::abs((innx-midx)/(inny-midy)); - if ((std::abs(z_diff)<30) && (inny*midy>0) &&(dxdy<2)) - { - result.push_back( OrderedHitTriplet(ih,mh,oh)); - } - } - } + for (ohh = theOuterLayer->recHits().begin(); ohh != theOuterLayer->recHits().end(); ohh++) { + auto oh = (BaseTrackerRecHit const *)(&*ohh); + for (mhh = theMiddleLayer->recHits().begin(); mhh != theMiddleLayer->recHits().end(); mhh++) { + auto mh = (BaseTrackerRecHit const *)(&*mhh); + float z_diff = mh->globalPosition().z() - oh->globalPosition().z(); + float midy = mh->globalPosition().y(); + float outy = oh->globalPosition().y(); + float midx = mh->globalPosition().x(); + float outx = oh->globalPosition().x(); + float dxdy = std::abs((outx - midx) / (outy - midy)); + float DeltaR = oh->globalPosition().perp() - mh->globalPosition().perp(); + if ((std::abs(z_diff) < 18) && (std::abs(oh->globalPosition().phi() - mh->globalPosition().phi()) < 0.05) && + (DeltaR < 0) && (dxdy < 2)) { + for (ihh = theInnerLayer->recHits().begin(); ihh != theInnerLayer->recHits().end(); ihh++) { + auto ih = (BaseTrackerRecHit const *)(&*ihh); + float z_diff = mh->globalPosition().z() - ih->globalPosition().z(); + float inny = ih->globalPosition().y(); + float innx = ih->globalPosition().x(); + float dxdy = std::abs((innx - midx) / (inny - midy)); + if ((std::abs(z_diff) < 30) && (inny * midy > 0) && (dxdy < 2)) { + result.push_back(OrderedHitTriplet(ih, mh, oh)); + } + } + } } } } } - diff --git a/RecoPixelVertexing/PixelTriplets/src/CosmicLayerTriplets.cc b/RecoPixelVertexing/PixelTriplets/src/CosmicLayerTriplets.cc index a4a7ceaa3e43c..0efa73ded159c 100644 --- a/RecoPixelVertexing/PixelTriplets/src/CosmicLayerTriplets.cc +++ b/RecoPixelVertexing/PixelTriplets/src/CosmicLayerTriplets.cc @@ -14,90 +14,91 @@ #include "Geometry/Records/interface/TrackerTopologyRcd.h" using std::vector; -vector CosmicLayerTriplets::layers() -{ +vector CosmicLayerTriplets::layers() { vector result; - if (_geometry=="STANDARD"){ + if (_geometry == "STANDARD") { vector third; third.push_back(lh3); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh1,lh2),third)); - + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh1, lh2), third)); } - if (_geometry=="TECPAIRS_TOBTRIPLETS"){ + if (_geometry == "TECPAIRS_TOBTRIPLETS") { vector third; third.push_back(lh3); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh1,lh2),third)); - + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh1, lh2), third)); } - if (_geometry=="MTCC"){ + if (_geometry == "MTCC") { vector third1; vector third2; vector third3; vector third4; - third1.clear();third2.clear();third3.clear();third4.clear(); + third1.clear(); + third2.clear(); + third3.clear(); + third4.clear(); third1.push_back(lh1); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh3,lh2),third1)); + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh3, lh2), third1)); third2.push_back(lh1); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh2,lh1),third2)); + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh2, lh1), third2)); third3.push_back(lh2); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh3,lh2),third3)); + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh3, lh2), third3)); third4.push_back(lh4); - result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh2,lh3),third4)); + result.push_back(LayerPairAndLayers(SeedLayerPairs::LayerPair(lh2, lh3), third4)); } return result; } -CosmicLayerTriplets::~CosmicLayerTriplets() -{ - for(vector::const_iterator it=allLayersWithHits.begin(); it!=allLayersWithHits.end();it++){ +CosmicLayerTriplets::~CosmicLayerTriplets() { + for (vector::const_iterator it = allLayersWithHits.begin(); it != allLayersWithHits.end(); it++) { delete *it; } } - - -void CosmicLayerTriplets::init(const SiStripRecHit2DCollection &collstereo, - const SiStripRecHit2DCollection &collrphi, - const SiStripMatchedRecHit2DCollection &collmatched, - std::string geometry, - const edm::EventSetup& iSetup){ - - _geometry=geometry; - if(watchTrackerGeometry_.check(iSetup)){ +void CosmicLayerTriplets::init(const SiStripRecHit2DCollection& collstereo, + const SiStripRecHit2DCollection& collrphi, + const SiStripMatchedRecHit2DCollection& collmatched, + std::string geometry, + const edm::EventSetup& iSetup) { + _geometry = geometry; + if (watchTrackerGeometry_.check(iSetup)) { edm::ESHandle track; - iSetup.get().get( track ); - bl=track->barrelLayers(); + iSetup.get().get(track); + bl = track->barrelLayers(); } edm::ESHandle httopo; iSetup.get().get(httopo); const TrackerTopology& ttopo = *httopo; - for(vector::const_iterator it=allLayersWithHits.begin(); - it!=allLayersWithHits.end();it++){ + for (vector::const_iterator it = allLayersWithHits.begin(); it != allLayersWithHits.end(); it++) { delete *it; } allLayersWithHits.clear(); - LogDebug("CosmicSeedFinder") <<"Reconstruction for geometry "<<_geometry; - if (_geometry=="STANDARD" || _geometry=="TECPAIRS_TOBTRIPLETS"){ - const DetLayer* bl1=dynamic_cast(bl[10]); - const DetLayer* bl2=dynamic_cast(bl[11]); - const DetLayer* bl3=dynamic_cast(bl[12]); + LogDebug("CosmicSeedFinder") << "Reconstruction for geometry " << _geometry; + if (_geometry == "STANDARD" || _geometry == "TECPAIRS_TOBTRIPLETS") { + const DetLayer* bl1 = dynamic_cast(bl[10]); + const DetLayer* bl2 = dynamic_cast(bl[11]); + const DetLayer* bl3 = dynamic_cast(bl[12]); // //LayersWithHits - lh1=new LayerWithHits(bl1,collrphi,ttopo.tobDetIdLayerComparator(4)); allLayersWithHits.push_back(lh1); - lh2=new LayerWithHits(bl2,collrphi,ttopo.tobDetIdLayerComparator(5)); allLayersWithHits.push_back(lh2); - lh3=new LayerWithHits(bl3,collrphi,ttopo.tobDetIdLayerComparator(6)); allLayersWithHits.push_back(lh3); + lh1 = new LayerWithHits(bl1, collrphi, ttopo.tobDetIdLayerComparator(4)); + allLayersWithHits.push_back(lh1); + lh2 = new LayerWithHits(bl2, collrphi, ttopo.tobDetIdLayerComparator(5)); + allLayersWithHits.push_back(lh2); + lh3 = new LayerWithHits(bl3, collrphi, ttopo.tobDetIdLayerComparator(6)); + allLayersWithHits.push_back(lh3); } - if(_geometry=="MTCC"){ - - const DetLayer* bl1=dynamic_cast(bl[0]); - const DetLayer* bl2=dynamic_cast(bl[1]); - const DetLayer* bl3=dynamic_cast(bl[2]); - const DetLayer* bl4=dynamic_cast(bl[3]); + if (_geometry == "MTCC") { + const DetLayer* bl1 = dynamic_cast(bl[0]); + const DetLayer* bl2 = dynamic_cast(bl[1]); + const DetLayer* bl3 = dynamic_cast(bl[2]); + const DetLayer* bl4 = dynamic_cast(bl[3]); - lh1=new LayerWithHits(bl1,collrphi,ttopo.tibDetIdLayerComparator(1)); allLayersWithHits.push_back(lh1); - lh2=new LayerWithHits(bl2,collrphi,ttopo.tibDetIdLayerComparator(2)); allLayersWithHits.push_back(lh2); - lh3=new LayerWithHits(bl3,collrphi,ttopo.tobDetIdLayerComparator(1)); allLayersWithHits.push_back(lh3); - lh4=new LayerWithHits(bl4,collrphi,ttopo.tobDetIdLayerComparator(2)); allLayersWithHits.push_back(lh4); + lh1 = new LayerWithHits(bl1, collrphi, ttopo.tibDetIdLayerComparator(1)); + allLayersWithHits.push_back(lh1); + lh2 = new LayerWithHits(bl2, collrphi, ttopo.tibDetIdLayerComparator(2)); + allLayersWithHits.push_back(lh2); + lh3 = new LayerWithHits(bl3, collrphi, ttopo.tobDetIdLayerComparator(1)); + allLayersWithHits.push_back(lh3); + lh4 = new LayerWithHits(bl4, collrphi, ttopo.tobDetIdLayerComparator(2)); + allLayersWithHits.push_back(lh4); } } diff --git a/RecoPixelVertexing/PixelTriplets/src/HitTripletGenerator.cc b/RecoPixelVertexing/PixelTriplets/src/HitTripletGenerator.cc index 59e88dd517152..8aa39c41f16fe 100644 --- a/RecoPixelVertexing/PixelTriplets/src/HitTripletGenerator.cc +++ b/RecoPixelVertexing/PixelTriplets/src/HitTripletGenerator.cc @@ -2,10 +2,11 @@ HitTripletGenerator::HitTripletGenerator(unsigned int nSize) : localRA(nSize) {} -const OrderedHitTriplets & HitTripletGenerator::run( - const TrackingRegion& region, const edm::Event & ev, const edm::EventSetup& es) -{ - assert(theTriplets.empty());assert(theTriplets.capacity()==0); +const OrderedHitTriplets& HitTripletGenerator::run(const TrackingRegion& region, + const edm::Event& ev, + const edm::EventSetup& es) { + assert(theTriplets.empty()); + assert(theTriplets.capacity() == 0); theTriplets.reserve(localRA.upper()); hitTriplets(region, theTriplets, ev, es); localRA.update(theTriplets.size()); @@ -13,8 +14,7 @@ const OrderedHitTriplets & HitTripletGenerator::run( return theTriplets; } -void HitTripletGenerator::clear() -{ - theTriplets.clear(); theTriplets.shrink_to_fit(); +void HitTripletGenerator::clear() { + theTriplets.clear(); + theTriplets.shrink_to_fit(); } - diff --git a/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayers.cc b/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayers.cc index 364c3409e0340..6246043a7df54 100644 --- a/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayers.cc +++ b/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayers.cc @@ -3,14 +3,11 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" -HitTripletGeneratorFromPairAndLayers::HitTripletGeneratorFromPairAndLayers(unsigned int maxElement): - theLayerCache(nullptr), - theMaxElement(maxElement) -{} +HitTripletGeneratorFromPairAndLayers::HitTripletGeneratorFromPairAndLayers(unsigned int maxElement) + : theLayerCache(nullptr), theMaxElement(maxElement) {} -HitTripletGeneratorFromPairAndLayers::HitTripletGeneratorFromPairAndLayers(const edm::ParameterSet& pset): - HitTripletGeneratorFromPairAndLayers(pset.getParameter("maxElement")) -{} +HitTripletGeneratorFromPairAndLayers::HitTripletGeneratorFromPairAndLayers(const edm::ParameterSet& pset) + : HitTripletGeneratorFromPairAndLayers(pset.getParameter("maxElement")) {} HitTripletGeneratorFromPairAndLayers::~HitTripletGeneratorFromPairAndLayers() {} @@ -18,7 +15,8 @@ void HitTripletGeneratorFromPairAndLayers::fillDescriptions(edm::ParameterSetDes desc.add("maxElement", 1000000); } -void HitTripletGeneratorFromPairAndLayers::init(std::unique_ptr&& pairGenerator, LayerCacheType *layerCache) { +void HitTripletGeneratorFromPairAndLayers::init(std::unique_ptr&& pairGenerator, + LayerCacheType* layerCache) { thePairGenerator = std::move(pairGenerator); theLayerCache = layerCache; } diff --git a/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayersFactory.cc b/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayersFactory.cc index 68bb6cc23fe11..a17f6938daa8b 100644 --- a/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayersFactory.cc +++ b/RecoPixelVertexing/PixelTriplets/src/HitTripletGeneratorFromPairAndLayersFactory.cc @@ -2,5 +2,4 @@ #include "FWCore/PluginManager/interface/PluginFactory.h" -EDM_REGISTER_PLUGINFACTORY(HitTripletGeneratorFromPairAndLayersFactory,"HitTripletGeneratorFromPairAndLayersFactory"); - +EDM_REGISTER_PLUGINFACTORY(HitTripletGeneratorFromPairAndLayersFactory, "HitTripletGeneratorFromPairAndLayersFactory"); diff --git a/RecoPixelVertexing/PixelTriplets/src/IntermediateHitTriplets.cc b/RecoPixelVertexing/PixelTriplets/src/IntermediateHitTriplets.cc index e25291bc19b6b..47a397565547b 100644 --- a/RecoPixelVertexing/PixelTriplets/src/IntermediateHitTriplets.cc +++ b/RecoPixelVertexing/PixelTriplets/src/IntermediateHitTriplets.cc @@ -2,6 +2,6 @@ #include "FWCore/Utilities/interface/Exception.h" IntermediateHitTriplets::IntermediateHitTriplets(const IntermediateHitTriplets& rh) { - throw cms::Exception("Not Implemented") << "The copy constructor of IntermediateHitTriplets should never be called. The function exists only to make ROOT dictionary generation happy."; + throw cms::Exception("Not Implemented") << "The copy constructor of IntermediateHitTriplets should never be called. " + "The function exists only to make ROOT dictionary generation happy."; } - diff --git a/RecoPixelVertexing/PixelTriplets/src/LayerTriplets.cc b/RecoPixelVertexing/PixelTriplets/src/LayerTriplets.cc index 5af57a8a5ba33..964a174728a21 100644 --- a/RecoPixelVertexing/PixelTriplets/src/LayerTriplets.cc +++ b/RecoPixelVertexing/PixelTriplets/src/LayerTriplets.cc @@ -1,31 +1,32 @@ #include "RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h" namespace LayerTriplets { -std::vector layers(const SeedingLayerSetsHits& sets) { - std::vector result; - if(sets.numberOfLayersInSet() < 3) - return result; + std::vector layers(const SeedingLayerSetsHits& sets) { + std::vector result; + if (sets.numberOfLayersInSet() < 3) + return result; - for(LayerSet set: sets) { - bool added = false; + for (LayerSet set : sets) { + bool added = false; - for(auto ir = result.begin(); ir < result.end(); ++ir) { - const LayerSet & resSet = ir->first; - if (resSet[0].index() == set[0].index() && resSet[1].index() == set[1].index()) { - std::vector& thirds = ir->second; - // 3rd layer can already be there if we are dealing with quadruplet layer sets - auto found = std::find_if(thirds.begin(), thirds.end(), [&](const Layer& l) { return l.index() == set[2].index(); }); - if(found == thirds.end()) - thirds.push_back( set[2] ); - added = true; - break; + for (auto ir = result.begin(); ir < result.end(); ++ir) { + const LayerSet& resSet = ir->first; + if (resSet[0].index() == set[0].index() && resSet[1].index() == set[1].index()) { + std::vector& thirds = ir->second; + // 3rd layer can already be there if we are dealing with quadruplet layer sets + auto found = + std::find_if(thirds.begin(), thirds.end(), [&](const Layer& l) { return l.index() == set[2].index(); }); + if (found == thirds.end()) + thirds.push_back(set[2]); + added = true; + break; + } + } + if (!added) { + LayerSetAndLayers lpl = std::make_pair(set, std::vector(1, set[2])); + result.push_back(lpl); } } - if (!added) { - LayerSetAndLayers lpl = std::make_pair(set, std::vector(1, set[2]) ); - result.push_back(lpl); - } + return result; } - return result; -} -} +} // namespace LayerTriplets diff --git a/RecoPixelVertexing/PixelTriplets/src/ThirdHitPredictionFromCircle.cc b/RecoPixelVertexing/PixelTriplets/src/ThirdHitPredictionFromCircle.cc index c555362af3b01..69288cddb7978 100644 --- a/RecoPixelVertexing/PixelTriplets/src/ThirdHitPredictionFromCircle.cc +++ b/RecoPixelVertexing/PixelTriplets/src/ThirdHitPredictionFromCircle.cc @@ -8,8 +8,8 @@ #include "RecoPixelVertexing/PixelTriplets/interface/ThirdHitPredictionFromCircle.h" #include "FWCore/Utilities/interface/Likely.h" -#include -#include +#include +#include #include "DataFormats/Math/interface/normalizedPhi.h" #include "DataFormats/Math/interface/approx_asin.h" @@ -18,27 +18,38 @@ // Try to move all of the out the regular control flow using gcc magic #include "DataFormats/Math/interface/approx_atan2.h" namespace { - inline - float f_atan2f(float y, float x) { return unsafe_atan2f<7>(y,x); } - template inline float f_phi(V v) { return f_atan2f(v.y(),v.x());} -} - + inline float f_atan2f(float y, float x) { return unsafe_atan2f<7>(y, x); } + template + inline float f_phi(V v) { + return f_atan2f(v.y(), v.x()); + } +} // namespace namespace { - template inline T sqr(T t) { return t * t; } - template inline T sgn(T t) { return std::signbit(t) ? -T(1.) : T(1.); } - template inline T clamped_acos(T x) { - x = std::min(T(1.),std::max(-T(1.),x)); + template + inline T sqr(T t) { + return t * t; + } + template + inline T sgn(T t) { + return std::signbit(t) ? -T(1.) : T(1.); + } + template + inline T clamped_acos(T x) { + x = std::min(T(1.), std::max(-T(1.), x)); return unsafe_acos<5>(x); } - template inline T clamped_sqrt(T t) { return std::sqrt(std::max(T(0),t)); } -} + template + inline T clamped_sqrt(T t) { + return std::sqrt(std::max(T(0), t)); + } +} // namespace -ThirdHitPredictionFromCircle::ThirdHitPredictionFromCircle( - const GlobalPoint& P1, const GlobalPoint& P2, float tolerance) - : p1(P1.x(), P1.y()), theTolerance(tolerance) -{ +ThirdHitPredictionFromCircle::ThirdHitPredictionFromCircle(const GlobalPoint &P1, + const GlobalPoint &P2, + float tolerance) + : p1(P1.x(), P1.y()), theTolerance(tolerance) { Vector2D p2(P2.x(), P2.y()); Vector2D diff = 0.5 * (p2 - p1); delta2 = diff.mag2(); @@ -47,8 +58,7 @@ ThirdHitPredictionFromCircle::ThirdHitPredictionFromCircle( center = p1 + diff; } -float ThirdHitPredictionFromCircle::phi(float curvature, float radius) const -{ +float ThirdHitPredictionFromCircle::phi(float curvature, float radius) const { float phi; if (UNLIKELY(std::abs(curvature) < float(1.0e-5))) { float cos = (center * axis) / radius; @@ -57,17 +67,16 @@ float ThirdHitPredictionFromCircle::phi(float curvature, float radius) const float sign = sgn(curvature); float radius2 = sqr(1.0f / curvature); float orthog = clamped_sqrt(radius2 - delta2); - Basic2DVector lcenter = Basic2DVector(center) - sign * orthog * Basic2DVector(axis); + Basic2DVector lcenter = Basic2DVector(center) - sign * orthog * Basic2DVector(axis); float rc2 = lcenter.mag2(); float r2 = sqr(radius); - float cos = (rc2 + r2 - radius2)/std::sqrt(4.f*rc2*r2); + float cos = (rc2 + r2 - radius2) / std::sqrt(4.f * rc2 * r2); phi = f_phi(lcenter) + sign * clamped_acos(cos); - } + } return phi; // not normalized } -float ThirdHitPredictionFromCircle::angle(float curvature, float radius) const -{ +float ThirdHitPredictionFromCircle::angle(float curvature, float radius) const { if (UNLIKELY(std::abs(curvature) < float(1.0e-5))) { float sin = (center * axis) / radius; return sin / clamped_sqrt(1 - sqr(sin)); @@ -75,26 +84,22 @@ float ThirdHitPredictionFromCircle::angle(float curvature, float radius) const float radius2 = sqr(1.0f / curvature); float orthog = clamped_sqrt(radius2 - delta2); Basic2DVector lcenter = Basic2DVector(center) - sgn(curvature) * orthog * Basic2DVector(axis); - - float cos = (radius2 + sqr(radius) - lcenter.mag2()) * - curvature / (2 * radius); - return - cos / clamped_sqrt(1.f - sqr(cos)); - } + + float cos = (radius2 + sqr(radius) - lcenter.mag2()) * curvature / (2 * radius); + return -cos / clamped_sqrt(1.f - sqr(cos)); + } } -ThirdHitPredictionFromCircle::Range -ThirdHitPredictionFromCircle::operator()(Range curvature, float radius) const -{ +ThirdHitPredictionFromCircle::Range ThirdHitPredictionFromCircle::operator()(Range curvature, float radius) const { float phi1 = normalizedPhi(phi(curvature.second, radius)); - float phi2 = proxim(phi(curvature.first, radius),phi1); - if(phi2 < phi1) std::swap(phi2,phi1); + float phi2 = proxim(phi(curvature.first, radius), phi1); + if (phi2 < phi1) + std::swap(phi2, phi1); return Range(phi1 * radius - theTolerance, phi2 * radius + theTolerance); } -ThirdHitPredictionFromCircle::Range -ThirdHitPredictionFromCircle::curvature(double transverseIP) const -{ +ThirdHitPredictionFromCircle::Range ThirdHitPredictionFromCircle::curvature(double transverseIP) const { // this is a mess. Use a CAS and lots of drawings to verify... transverseIP = std::abs(transverseIP); @@ -115,7 +120,7 @@ ThirdHitPredictionFromCircle::curvature(double transverseIP) const // but you never know what crap you might get fed // VI fixed for finiteMath - double u1=0, u2=0; + double u1 = 0, u2 = 0; constexpr double SMALL = 1.0e-23; constexpr double LARGE = 1.0e23; @@ -154,13 +159,10 @@ ThirdHitPredictionFromCircle::curvature(double transverseIP) const } } - return Range(sgn(u1) / std::sqrt(sqr(u1) + delta2), - sgn(u2) / std::sqrt(sqr(u2) + delta2)); + return Range(sgn(u1) / std::sqrt(sqr(u1) + delta2), sgn(u2) / std::sqrt(sqr(u2) + delta2)); } -ThirdHitPredictionFromCircle::Scalar -ThirdHitPredictionFromCircle::invCenterOnAxis(const Vector2D &p2) const -{ +ThirdHitPredictionFromCircle::Scalar ThirdHitPredictionFromCircle::invCenterOnAxis(const Vector2D &p2) const { Vector2D del = p2 - p1; Vector2D axis2 = Vector2D(-del.y(), del.x()) / del.mag(); Vector2D diff = p1 + 0.5f * del - center; @@ -169,16 +171,14 @@ ThirdHitPredictionFromCircle::invCenterOnAxis(const Vector2D &p2) const return b / a; } -double ThirdHitPredictionFromCircle::curvature(const Vector2D &p2) const -{ +double ThirdHitPredictionFromCircle::curvature(const Vector2D &p2) const { double invDist = invCenterOnAxis(p2); double invDist2 = sqr(invDist); double curv = std::sqrt(invDist2 / (1. + invDist2 * delta2)); return sgn(invDist) * curv; } -double ThirdHitPredictionFromCircle::transverseIP(const Vector2D &p2) const -{ +double ThirdHitPredictionFromCircle::transverseIP(const Vector2D &p2) const { double invDist = invCenterOnAxis(p2); if (UNLIKELY(std::abs(invDist) < 1.0e-5)) return std::abs(p2 * axis); @@ -191,38 +191,38 @@ double ThirdHitPredictionFromCircle::transverseIP(const Vector2D &p2) const //------------------------------------------------------------------------------ - namespace { // 2asin(cd)/c - inline -float arc(float c, float d) { - float z = c*d; z*=z; - float x = 2.f*d; - - if (z>0.5f) return std::min(1.f,2.f*unsafe_asin<5>(c*d)/c); + inline float arc(float c, float d) { + float z = c * d; + z *= z; + float x = 2.f * d; - return x*approx_asin_P<7>(z); + if (z > 0.5f) + return std::min(1.f, 2.f * unsafe_asin<5>(c * d) / c); + return x * approx_asin_P<7>(z); } -} - - -ThirdHitPredictionFromCircle::HelixRZ::HelixRZ( - const ThirdHitPredictionFromCircle * icircle, double iz1, double z2, double curv) : - circle(icircle), curvature(curv), radius(1./curv), z1(iz1) -{ - Scalar orthog = sgn(curv) * clamped_sqrt(radius*radius - circle->delta2); +} // namespace + +ThirdHitPredictionFromCircle::HelixRZ::HelixRZ(const ThirdHitPredictionFromCircle *icircle, + double iz1, + double z2, + double curv) + : circle(icircle), curvature(curv), radius(1. / curv), z1(iz1) { + Scalar orthog = sgn(curv) * clamped_sqrt(radius * radius - circle->delta2); center = circle->center + orthog * circle->axis; Scalar absCurv = std::abs(curv); seg = circle->delta; - seg = arc(absCurv,seg); + seg = arc(absCurv, seg); dzdu = (z2 - z1) / seg; } -double ThirdHitPredictionFromCircle::HelixRZ::maxCurvature( - const ThirdHitPredictionFromCircle *circle, double z1, double z2, double z3) -{ +double ThirdHitPredictionFromCircle::HelixRZ::maxCurvature(const ThirdHitPredictionFromCircle *circle, + double z1, + double z2, + double z3) { constexpr double maxAngle = M_PI; double halfAngle = (0.5 * maxAngle) * (z2 - z1) / (z3 - z1); if (UNLIKELY(halfAngle <= 0.0)) @@ -231,14 +231,11 @@ double ThirdHitPredictionFromCircle::HelixRZ::maxCurvature( return std::sin(halfAngle) / circle->delta; } - -ThirdHitPredictionFromCircle::HelixRZ::Scalar -ThirdHitPredictionFromCircle::HelixRZ::zAtR(Scalar r) const { +ThirdHitPredictionFromCircle::HelixRZ::Scalar ThirdHitPredictionFromCircle::HelixRZ::zAtR(Scalar r) const { if (UNLIKELY(std::abs(curvature) < 1.0e-5)) { - Scalar tip = circle->axis * circle->p1; - Scalar lip = circle->axis.y() * circle->p1.x() - - circle->axis.x() * circle->p1.y(); - return z1 + (std::sqrt(sqr(r) - sqr(tip)) - lip) * dzdu; + Scalar tip = circle->axis * circle->p1; + Scalar lip = circle->axis.y() * circle->p1.x() - circle->axis.x() * circle->p1.y(); + return z1 + (std::sqrt(sqr(r) - sqr(tip)) - lip) * dzdu; } Scalar radius2 = sqr(radius); @@ -247,7 +244,7 @@ ThirdHitPredictionFromCircle::HelixRZ::zAtR(Scalar r) const { Scalar b = std::sqrt(b2); Scalar cos1 = 0.5 * curvature * (radius2 + b2 - sqr(r)) / b; - Scalar cos2 = 0.5 * curvature * (radius2 + b2 - circle->p1.mag2()) / b; + Scalar cos2 = 0.5 * curvature * (radius2 + b2 - circle->p1.mag2()) / b; Scalar phi1 = clamped_acos(cos1); Scalar phi2 = clamped_acos(cos2); @@ -257,28 +254,25 @@ ThirdHitPredictionFromCircle::HelixRZ::zAtR(Scalar r) const { Scalar u1 = std::abs((phi1 - phi2) * radius); Scalar u2 = std::abs((phi1 + phi2) * radius); - return z1 + ((u1 >= seg && u1 < u2)? u1 : u2) * dzdu; + return z1 + ((u1 >= seg && u1 < u2) ? u1 : u2) * dzdu; } +#include -#include - -ThirdHitPredictionFromCircle::HelixRZ::Scalar -ThirdHitPredictionFromCircle::HelixRZ::rAtZ(Scalar z) const { +ThirdHitPredictionFromCircle::HelixRZ::Scalar ThirdHitPredictionFromCircle::HelixRZ::rAtZ(Scalar z) const { if (UNLIKELY(std::abs(dzdu) < 1.0e-5)) return 99999.0; if (UNLIKELY(std::abs(curvature) < 1.0e-5)) { Scalar tip = circle->axis * circle->p1; - Scalar lip = circle->axis.y() * circle->p1.x() - - circle->axis.x() * circle->p1.y(); + Scalar lip = circle->axis.y() * circle->p1.x() - circle->axis.x() * circle->p1.y(); return std::sqrt(sqr(tip) + sqr(lip + (z - z1) / dzdu)); } // we won't go below that (see comment below) Scalar minR2 = (2. * circle->center - circle->p1).mag2(); - float phi = curvature * (z - z1) / dzdu; + float phi = curvature * (z - z1) / dzdu; if (UNLIKELY(std::abs(phi) > 2. * M_PI)) { // with a helix we can get problems here - this is used to get the limits @@ -297,10 +291,9 @@ ThirdHitPredictionFromCircle::HelixRZ::rAtZ(Scalar z) const { float c; float s; - vdt::fast_sincosf(phi,s,c); + vdt::fast_sincosf(phi, s, c); - Vector2D p(center.x() + c * rel.x() - s * rel.y(), - center.y() + s * rel.x() + c * rel.y()); + Vector2D p(center.x() + c * rel.x() - s * rel.y(), center.y() + s * rel.x() + c * rel.y()); return std::sqrt(std::max(minR2, p.mag2())); } diff --git a/RecoPixelVertexing/PixelTriplets/src/ThirdHitRZPredictionBase.cc b/RecoPixelVertexing/PixelTriplets/src/ThirdHitRZPredictionBase.cc index 3f99d07f30ece..4bacb0bf1e43c 100644 --- a/RecoPixelVertexing/PixelTriplets/src/ThirdHitRZPredictionBase.cc +++ b/RecoPixelVertexing/PixelTriplets/src/ThirdHitRZPredictionBase.cc @@ -6,40 +6,34 @@ #include "DataFormats/GeometrySurface/interface/SimpleDiskBounds.h" #include "RecoTracker/TkMSParametrization/interface/MultipleScatteringParametrisation.h" -ThirdHitRZPredictionBase::ThirdHitRZPredictionBase() : - theBarrel(false), theForward(false), theTolerance(0.,0.) -{} +ThirdHitRZPredictionBase::ThirdHitRZPredictionBase() : theBarrel(false), theForward(false), theTolerance(0., 0.) {} -ThirdHitRZPredictionBase::ThirdHitRZPredictionBase( - float tolerance, const DetLayer* layer) - : theBarrel(false), theForward(false), theTolerance(tolerance, tolerance) -{ - if (layer) initLayer(layer); +ThirdHitRZPredictionBase::ThirdHitRZPredictionBase(float tolerance, const DetLayer* layer) + : theBarrel(false), theForward(false), theTolerance(tolerance, tolerance) { + if (layer) + initLayer(layer); } -void ThirdHitRZPredictionBase::initLayer(const DetLayer *layer) -{ +void ThirdHitRZPredictionBase::initLayer(const DetLayer* layer) { if (layer->location() == GeomDetEnumerators::barrel) { theBarrel = true; theForward = false; const BarrelDetLayer& bl = reinterpret_cast(*layer); - float halfThickness = bl.surface().bounds().thickness()/2; + float halfThickness = bl.surface().bounds().thickness() / 2; float radius = bl.specificSurface().radius(); - theDetRange = Range(radius-halfThickness, radius+halfThickness); - float maxZ = bl.surface().bounds().length()/2; + theDetRange = Range(radius - halfThickness, radius + halfThickness); + float maxZ = bl.surface().bounds().length() / 2; theDetSize = Range(-maxZ, maxZ); } else if (layer->location() == GeomDetEnumerators::endcap) { - theBarrel= false; + theBarrel = false; theForward = true; const ForwardDetLayer& fl = reinterpret_cast(*layer); - float halfThickness = fl.surface().bounds().thickness()/2; - float zLayer = fl.position().z() ; - theDetRange = Range(zLayer-halfThickness, zLayer+halfThickness); - const SimpleDiskBounds& diskRadialBounds = - static_cast(fl.surface().bounds()); + float halfThickness = fl.surface().bounds().thickness() / 2; + float zLayer = fl.position().z(); + theDetRange = Range(zLayer - halfThickness, zLayer + halfThickness); + const SimpleDiskBounds& diskRadialBounds = static_cast(fl.surface().bounds()); theDetSize = Range(diskRadialBounds.innerRadius(), diskRadialBounds.outerRadius()); } else { theBarrel = theForward = false; - } } diff --git a/RecoPixelVertexing/PixelTriplets/src/classes.h b/RecoPixelVertexing/PixelTriplets/src/classes.h index 465decf805c73..4f495027ac186 100644 --- a/RecoPixelVertexing/PixelTriplets/src/classes.h +++ b/RecoPixelVertexing/PixelTriplets/src/classes.h @@ -8,4 +8,4 @@ namespace RecoPixelVertexing_PixelTriplets { IntermediateHitTriplets iht; edm::Wrapper wiht; }; -} +} // namespace RecoPixelVertexing_PixelTriplets diff --git a/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_prec.cpp b/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_prec.cpp index 79946bb4a156c..ee7edba8619ca 100644 --- a/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_prec.cpp +++ b/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_prec.cpp @@ -1,7 +1,7 @@ #include "RecoPixelVertexing/PixelTriplets/plugins/ThirdHitPredictionFromInvParabola.cc" -#include -#include +#include +#include namespace test { namespace PixelTriplets_InvPrbl_prec { @@ -11,36 +11,32 @@ namespace test { std::string a; double par[7]; double q[2]; - while(std::cin) { + while (std::cin) { ThirdHitPredictionFromInvParabola pred; std::cin >> a; - if (a==c) { - for ( auto & p : par ) std::cin >> p; - pred =ThirdHitPredictionFromInvParabola(par[0],par[1],par[2],par[3],par[4],par[5],par[6]); - std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() - << " " << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; - } - else if (a==r) { + if (a == c) { + for (auto& p : par) + std::cin >> p; + pred = ThirdHitPredictionFromInvParabola(par[0], par[1], par[2], par[3], par[4], par[5], par[6]); + std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() << " " + << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; + } else if (a == r) { std::cin >> q[0] >> q[1]; { - auto rp = pred.rangeRPhi(q[0],1); - auto rn = pred.rangeRPhi(q[0],-1); - std::cout << "range " << rp.min() << " " << rp.max() - << " " << rn.min() << " " << rn.max() << std::endl; + auto rp = pred.rangeRPhi(q[0], 1); + auto rn = pred.rangeRPhi(q[0], -1); + std::cout << "range " << rp.min() << " " << rp.max() << " " << rn.min() << " " << rn.max() << std::endl; } { - auto rp = pred.rangeRPhi(q[1],1); - auto rn = pred.rangeRPhi(q[1],-1); - std::cout << "range " << rp.min() << " " << rp.max() - << " " << rn.min() << " " << rn.max() << std::endl; + auto rp = pred.rangeRPhi(q[1], 1); + auto rn = pred.rangeRPhi(q[1], -1); + std::cout << "range " << rp.min() << " " << rp.max() << " " << rn.min() << " " << rn.max() << std::endl; } } } - return 0; + return 0; } - } -} + } // namespace PixelTriplets_InvPrbl_prec +} // namespace test -int main() { - return test::PixelTriplets_InvPrbl_prec::test(); -} +int main() { return test::PixelTriplets_InvPrbl_prec::test(); } diff --git a/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_t.cpp b/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_t.cpp index 80fed4d826e32..e11f5bb408aec 100644 --- a/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_t.cpp +++ b/RecoPixelVertexing/PixelTriplets/test/PixelTriplets_InvPrbl_t.cpp @@ -4,134 +4,120 @@ #include "DataFormats/GeometryVector/interface/GlobalVector.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" -#include +#include // oldcode -template class MappedPoint { +template +class MappedPoint { public: - MappedPoint() : theU(0), theV(0), pRot(0) { } - MappedPoint(const T & aU, const T & aV, const TkRotation * aRot) - : theU(aU), theV(aV), pRot(aRot) { } - MappedPoint(const Basic2DVector & point, const TkRotation * aRot) - : pRot(aRot) { - T invRadius2 = T(1)/point.mag2(); + MappedPoint() : theU(0), theV(0), pRot(0) {} + MappedPoint(const T& aU, const T& aV, const TkRotation* aRot) : theU(aU), theV(aV), pRot(aRot) {} + MappedPoint(const Basic2DVector& point, const TkRotation* aRot) : pRot(aRot) { + T invRadius2 = T(1) / point.mag2(); Basic3DVector rotated = (*pRot) * point; theU = rotated.x() * invRadius2; theV = rotated.y() * invRadius2; } - T u() const {return theU; } - T v() const {return theV; } - Basic2DVector unmap () const { - T radius2 = T(1)/(theU*theU+theV*theV); - Basic3DVector tmp - = (*pRot).multiplyInverse(Basic2DVector(theU,theV)); - return Basic2DVector( tmp.x()*radius2, tmp.y()*radius2); + T u() const { return theU; } + T v() const { return theV; } + Basic2DVector unmap() const { + T radius2 = T(1) / (theU * theU + theV * theV); + Basic3DVector tmp = (*pRot).multiplyInverse(Basic2DVector(theU, theV)); + return Basic2DVector(tmp.x() * radius2, tmp.y() * radius2); } + private: T theU, theV; - const TkRotation * pRot; + const TkRotation* pRot; }; -typedef MappedPoint PointUV; - -void oldCode(const GlobalPoint & P1, const GlobalPoint & P2) { +typedef MappedPoint PointUV; +void oldCode(const GlobalPoint& P1, const GlobalPoint& P2) { typedef TkRotation Rotation; typedef Basic2DVector Point2D; - GlobalVector aX = GlobalVector( P1.x(), P1.y(), 0.).unit(); - GlobalVector aY( -aX.y(), aX.x(), 0.); - GlobalVector aZ( 0., 0., 1.); - TkRotation theRotation = Rotation(aX,aY,aZ); + GlobalVector aX = GlobalVector(P1.x(), P1.y(), 0.).unit(); + GlobalVector aY(-aX.y(), aX.x(), 0.); + GlobalVector aZ(0., 0., 1.); + TkRotation theRotation = Rotation(aX, aY, aZ); - PointUV p1(Point2D(P1.x(),P1.y()), &theRotation); - PointUV p2(Point2D(P2.x(),P2.y()), &theRotation); + PointUV p1(Point2D(P1.x(), P1.y()), &theRotation); + PointUV p2(Point2D(P2.x(), P2.y()), &theRotation); - std::cout << "\nold for " << P1 <<", " << P2 << std::endl; + std::cout << "\nold for " << P1 << ", " << P2 << std::endl; std::cout << theRotation << std::endl; std::cout << p1.u() << " " << p1.v() << std::endl; std::cout << p2.u() << " " << p2.v() << std::endl; std::cout << p1.unmap() << std::endl; std::cout << p2.unmap() << std::endl; - } -inline -Basic2DVector transform( Basic2DVector const & p, TkRotation2D const & theRotation) { - return theRotation.rotate(p)/p.mag2(); +inline Basic2DVector transform(Basic2DVector const& p, TkRotation2D const& theRotation) { + return theRotation.rotate(p) / p.mag2(); } -inline -Basic2DVector transformBack( Basic2DVector const & p, TkRotation2D const & theRotation) { - return theRotation.rotateBack(p)/p.mag2(); +inline Basic2DVector transformBack(Basic2DVector const& p, TkRotation2D const& theRotation) { + return theRotation.rotateBack(p) / p.mag2(); } - -void newCode(const GlobalPoint & P1, const GlobalPoint & P2) { - +void newCode(const GlobalPoint& P1, const GlobalPoint& P2) { typedef TkRotation2D Rotation; typedef Basic2DVector Point2D; Rotation theRotation = Rotation(Basic2DVector(P1.basicVector().xy())); - Point2D p1 = transform(Basic2DVector(P1.basicVector().xy()), theRotation); // (1./P1.xy().mag(),0); + Point2D p1 = transform(Basic2DVector(P1.basicVector().xy()), theRotation); // (1./P1.xy().mag(),0); Point2D p2 = transform(Basic2DVector(P2.basicVector().xy()), theRotation); - std::cout << "\nnew for " << P1 <<", " << P2 << std::endl; + std::cout << "\nnew for " << P1 << ", " << P2 << std::endl; std::cout << theRotation << std::endl; std::cout << p1.x() << " " << p1.y() << std::endl; std::cout << p2.x() << " " << p2.y() << std::endl; std::cout << transformBack(p1, theRotation) << std::endl; std::cout << transformBack(p2, theRotation) << std::endl; - } namespace test { namespace PixelTriplets_InvPrbl_t { int test() { - GlobalPoint P1(3., 4., 7.); GlobalPoint P2(-2., 5., 7.); - - oldCode(P1,P2); - newCode(P1,P2); - - oldCode(P2,P1); - newCode(P2,P1); - + + oldCode(P1, P2); + newCode(P1, P2); + + oldCode(P2, P1); + newCode(P2, P1); + { - ThirdHitPredictionFromInvParabola pred(P1,P2,0.2,0.05,0.1); - std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() - << " " << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; - std::cout << "A,B +pos " << pred.coeffA(0.1) << " " << pred.coeffB(0.1) << std::endl; - std::cout << "A,B -pos " << pred.coeffA(-0.1) << " " << pred.coeffB(-0.1) << std::endl; - - auto rp = pred.rangeRPhi(5.,1); - auto rn = pred.rangeRPhi(5.,-1); - std::cout << "range " << rp.min() << " " << rp.max() - << " " << rn.min() << " " << rn.max() << std::endl; + ThirdHitPredictionFromInvParabola pred(P1, P2, 0.2, 0.05, 0.1); + std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() << " " + << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; + std::cout << "A,B +pos " << pred.coeffA(0.1) << " " << pred.coeffB(0.1) << std::endl; + std::cout << "A,B -pos " << pred.coeffA(-0.1) << " " << pred.coeffB(-0.1) << std::endl; + + auto rp = pred.rangeRPhi(5., 1); + auto rn = pred.rangeRPhi(5., -1); + std::cout << "range " << rp.min() << " " << rp.max() << " " << rn.min() << " " << rn.max() << std::endl; } - + ThirdHitPredictionFromInvParabola pred(-1.092805, 4.187564, -2.361283, 7.892722, 0.111413, 0.019043, 0.032000); - std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() - << " " << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; + std::cout << "ip min, max " << pred.theIpRangePlus.min() << " " << pred.theIpRangePlus.max() << " " + << pred.theIpRangeMinus.min() << " " << pred.theIpRangeMinus.max() << std::endl; { - auto rp = pred.rangeRPhi(11.4356,1); - auto rn = pred.rangeRPhi(11.4356,-1); - std::cout << "range " << rp.min() << " " << rp.max() - << " " << rn.min() << " " << rn.max() << std::endl; + auto rp = pred.rangeRPhi(11.4356, 1); + auto rn = pred.rangeRPhi(11.4356, -1); + std::cout << "range " << rp.min() << " " << rp.max() << " " << rn.min() << " " << rn.max() << std::endl; } { - auto rp = pred.rangeRPhi(13.2131,1); - auto rn = pred.rangeRPhi(13.2131,-1); - std::cout << "range " << rp.min() << " " << rp.max() - << " " << rn.min() << " " << rn.max() << std::endl; + auto rp = pred.rangeRPhi(13.2131, 1); + auto rn = pred.rangeRPhi(13.2131, -1); + std::cout << "range " << rp.min() << " " << rp.max() << " " << rn.min() << " " << rn.max() << std::endl; } - + return 0; } - } -} + } // namespace PixelTriplets_InvPrbl_t +} // namespace test -int main() { - return test::PixelTriplets_InvPrbl_t::test(); -} +int main() { return test::PixelTriplets_InvPrbl_t::test(); } diff --git a/RecoTracker/TkSeedGenerator/interface/ClusterChecker.h b/RecoTracker/TkSeedGenerator/interface/ClusterChecker.h index 4c2e719aa6404..9bde678222b79 100644 --- a/RecoTracker/TkSeedGenerator/interface/ClusterChecker.h +++ b/RecoTracker/TkSeedGenerator/interface/ClusterChecker.h @@ -9,30 +9,36 @@ #include "FWCore/Framework/interface/ConsumesCollector.h" -namespace edm { class Event; class ParameterSet; class ParameterSetDescription; } - -namespace reco { namespace utils { +namespace edm { + class Event; + class ParameterSet; + class ParameterSetDescription; +} // namespace edm + +namespace reco { + namespace utils { struct ClusterTotals { - ClusterTotals() : strip(0), pixel(0), stripdets(0), pixeldets(0) {} - int strip; /// number of strip clusters - int pixel; /// number of pixel clusters - int stripdets; /// number of strip detectors with at least one cluster - int pixeldets; /// number of pixel detectors with at least one cluster + ClusterTotals() : strip(0), pixel(0), stripdets(0), pixeldets(0) {} + int strip; /// number of strip clusters + int pixel; /// number of pixel clusters + int stripdets; /// number of strip detectors with at least one cluster + int pixeldets; /// number of pixel detectors with at least one cluster }; -} } + } // namespace utils +} // namespace reco class ClusterChecker { - public: - ClusterChecker(const edm::ParameterSet & conf, edm::ConsumesCollector & iC) ; - ClusterChecker(const edm::ParameterSet & conf, edm::ConsumesCollector && iC) ; +public: + ClusterChecker(const edm::ParameterSet& conf, edm::ConsumesCollector& iC); + ClusterChecker(const edm::ParameterSet& conf, edm::ConsumesCollector&& iC); static void fillDescriptions(edm::ParameterSetDescription& description); - ~ClusterChecker() ; - size_t tooManyClusters(const edm::Event & e) const ; + ~ClusterChecker(); + size_t tooManyClusters(const edm::Event& e) const; - private: - ClusterChecker() = delete; // This is only needed for StringCutObjectSelector +private: + ClusterChecker() = delete; // This is only needed for StringCutObjectSelector bool doACheck_; edm::InputTag clusterCollectionInputTag_; edm::InputTag pixelClusterCollectionInputTag_; diff --git a/RecoTracker/TkSeedGenerator/interface/FastCircle.h b/RecoTracker/TkSeedGenerator/interface/FastCircle.h index c77adefcd5097..06176ae9b3052 100644 --- a/RecoTracker/TkSeedGenerator/interface/FastCircle.h +++ b/RecoTracker/TkSeedGenerator/interface/FastCircle.h @@ -31,65 +31,55 @@ */ class FastCircle { - public: - - FastCircle(const GlobalPoint& outerHit, - const GlobalPoint& middleHit, - const GlobalPoint& aVertex); - - FastCircle(const GlobalPoint& outerHit, - const GlobalPoint& middleHit, - const GlobalPoint& aVertex, - double norm); - + FastCircle(const GlobalPoint& outerHit, const GlobalPoint& middleHit, const GlobalPoint& aVertex); + + FastCircle(const GlobalPoint& outerHit, const GlobalPoint& middleHit, const GlobalPoint& aVertex, double norm); + ~FastCircle() {} - + // all returned values have dimensions of cm // parameters of the circle (circle is valid) - double x0() const {return theX0;} - - double y0() const {return theY0;} - - double rho() const {return theRho;} - - bool isValid() const {return theValid;} - - bool isLine() const {return theIsLine;} - - // parameters of the straight line - // (if circle is invalid only these are available) - double n1() const {return theN1;} - - double n2() const {return theN2;} - - double c() const {return theC;} - - GlobalPoint const & outerPoint() const { return theOuterPoint;} - GlobalPoint const & innerPoint() const { return theInnerPoint;} - GlobalPoint const & vertexPoint() const { return theVertexPoint;} + double x0() const { return theX0; } + double y0() const { return theY0; } -private: + double rho() const { return theRho; } + + bool isValid() const { return theValid; } + + bool isLine() const { return theIsLine; } + + // parameters of the straight line + // (if circle is invalid only these are available) + double n1() const { return theN1; } + + double n2() const { return theN2; } - GlobalPoint theOuterPoint; - GlobalPoint theInnerPoint; - GlobalPoint theVertexPoint; + double c() const { return theC; } + + GlobalPoint const& outerPoint() const { return theOuterPoint; } + GlobalPoint const& innerPoint() const { return theInnerPoint; } + GlobalPoint const& vertexPoint() const { return theVertexPoint; } + +private: + GlobalPoint theOuterPoint; + GlobalPoint theInnerPoint; + GlobalPoint theVertexPoint; double theNorm; - + double theX0; double theY0; double theRho; - + double theN1; double theN2; double theC; - + bool theValid; bool theIsLine; - + void createCircleParameters() dso_hidden; - }; -#endif //TR_Circle_H_ +#endif //TR_Circle_H_ diff --git a/RecoTracker/TkSeedGenerator/interface/FastCircleFit.h b/RecoTracker/TkSeedGenerator/interface/FastCircleFit.h index f60743cb549cf..1e3d2b093a4c4 100644 --- a/RecoTracker/TkSeedGenerator/interface/FastCircleFit.h +++ b/RecoTracker/TkSeedGenerator/interface/FastCircleFit.h @@ -40,7 +40,7 @@ class FastCircleFit { declareDynArray(float, N, x); declareDynArray(float, N, y); declareDynArray(float, N, z); - declareDynArray(float, N, weight); // 1/sigma^2 + declareDynArray(float, N, weight); // 1/sigma^2 calculate(points, errors, x, y, z, weight); } @@ -52,7 +52,7 @@ class FastCircleFit { std::array x; std::array y; std::array z; - std::array weight; // 1/sigma^2 + std::array weight; // 1/sigma^2 calculate(points, errors, x, y, z, weight); } @@ -70,7 +70,9 @@ class FastCircleFit { void calculate(const P& points, const E& errors, C& x, C& y, C& z, C& weight); template - T sqr(T t) { return t*t; } + T sqr(T t) { + return t * t; + } float x0_; float y0_; @@ -83,7 +85,7 @@ void FastCircleFit::calculate(const P& points, const E& errors, C& x, C& y, C& z const auto N = points.size(); // transform - for(size_t i=0; i(N); + A *= 1. / static_cast(N); - PRINT << " A " << A(0,0) << " " << A(0,1) << " " << A(0,2) << std::endl - << " " << A(1,0) << " " << A(1,1) << " " << A(1,2) << std::endl - << " " << A(2,0) << " " << A(2,1) << " " << A(2,2) << std::endl; + PRINT << " A " << A(0, 0) << " " << A(0, 1) << " " << A(0, 2) << std::endl + << " " << A(1, 0) << " " << A(1, 1) << " " << A(1, 2) << std::endl + << " " << A(2, 0) << " " << A(2, 1) << " " << A(2, 2) << std::endl; // find eigenvalues and vectors Eigen::SelfAdjointEigenSolver eigen(A); @@ -149,46 +146,39 @@ void FastCircleFit::calculate(const P& points, const E& errors, C& x, C& y, C& z const auto& eigenVectors = eigen.eigenvectors(); // in Eigen the first eigenvalue is the smallest - PRINT << " eigenvalues " << eigenValues[0] - << " " << eigenValues[1] - << " " << eigenValues[2] - << std::endl; + PRINT << " eigenvalues " << eigenValues[0] << " " << eigenValues[1] << " " << eigenValues[2] << std::endl; - PRINT << " eigen " << eigenVectors(0,0) << " " << eigenVectors(0,1) << " " << eigenVectors(0,2) << std::endl - << " " << eigenVectors(1,0) << " " << eigenVectors(1,1) << " " << eigenVectors(1,2) << std::endl - << " " << eigenVectors(2,0) << " " << eigenVectors(2,1) << " " << eigenVectors(2,2) << std::endl; + PRINT << " eigen " << eigenVectors(0, 0) << " " << eigenVectors(0, 1) << " " << eigenVectors(0, 2) << std::endl + << " " << eigenVectors(1, 0) << " " << eigenVectors(1, 1) << " " << eigenVectors(1, 2) << std::endl + << " " << eigenVectors(2, 0) << " " << eigenVectors(2, 1) << " " << eigenVectors(2, 2) << std::endl; // eivenvector corresponding smallest eigenvalue auto n = eigenVectors.col(0); PRINT << " n (unit) " << n[0] << " " << n[1] << " " << n[2] << std::endl; - const float c = -1.f * (n[0]*mean[0] + n[1]*mean[1] + n[2]*mean[2]); + const float c = -1.f * (n[0] * mean[0] + n[1] * mean[1] + n[2] * mean[2]); PRINT << " c " << c << std::endl; // calculate fit parameters - const auto tmp = 0.5f * 1.f/n[2]; - x0_ = -n[0]*tmp; - y0_ = -n[1]*tmp; - const float rho2 = (1 - sqr(n[2]) - 4*c*n[2]) * sqr(tmp); + const auto tmp = 0.5f * 1.f / n[2]; + x0_ = -n[0] * tmp; + y0_ = -n[1] * tmp; + const float rho2 = (1 - sqr(n[2]) - 4 * c * n[2]) * sqr(tmp); rho_ = std::sqrt(rho2); // calculate square sum float S = 0; - for(size_t i=0; i class MultiHitGenerator : public OrderedHitsGenerator { public: + MultiHitGenerator(unsigned int size = 400) : localRA(size) {} + MultiHitGenerator(MultiHitGenerator const& other) : localRA(other.localRA.mean()) {} - MultiHitGenerator(unsigned int size=400) : localRA(size){} - MultiHitGenerator( MultiHitGenerator const & other) : localRA(other.localRA.mean()){} - + ~MultiHitGenerator() override {} - ~MultiHitGenerator() override { } - - const OrderedMultiHits & run( - const TrackingRegion& region, const edm::Event & ev, const edm::EventSetup& es) final; + const OrderedMultiHits& run(const TrackingRegion& region, const edm::Event& ev, const edm::EventSetup& es) final; // temporary interface, for bckwd compatibility - virtual void hitSets( const TrackingRegion& reg, OrderedMultiHits & prs, - const edm::EventSetup& es){} + virtual void hitSets(const TrackingRegion& reg, OrderedMultiHits& prs, const edm::EventSetup& es) {} - virtual void hitSets( const TrackingRegion& reg, OrderedMultiHits & prs, - const edm::Event & ev, const edm::EventSetup& es) = 0; + virtual void hitSets(const TrackingRegion& reg, + OrderedMultiHits& prs, + const edm::Event& ev, + const edm::EventSetup& es) = 0; void clear() override; @@ -45,5 +45,4 @@ class MultiHitGenerator : public OrderedHitsGenerator { edm::RunningAverage localRA; }; - #endif diff --git a/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h b/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h index 90500ed94801c..78df55143d9cf 100644 --- a/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h +++ b/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h @@ -12,37 +12,42 @@ #include "TrackingTools/TransientTrackingRecHit/interface/SeedingLayerSetsHits.h" #include "RecoTracker/TkHitPairs/interface/LayerHitMapCache.h" -namespace edm { class ParameterSet; class Event; class EventSetup; class ParameterSetDescription;} +namespace edm { + class ParameterSet; + class Event; + class EventSetup; + class ParameterSetDescription; +} // namespace edm class TrackingRegion; class HitPairGeneratorFromLayerPair; class MultiHitGeneratorFromPairAndLayers { - public: - typedef LayerHitMapCache LayerCacheType; + typedef LayerHitMapCache LayerCacheType; explicit MultiHitGeneratorFromPairAndLayers(const edm::ParameterSet& pset); virtual ~MultiHitGeneratorFromPairAndLayers(); static void fillDescriptions(edm::ParameterSetDescription& desc); - virtual void initES(const edm::EventSetup& es) = 0; + virtual void initES(const edm::EventSetup& es) = 0; - void init(std::unique_ptr&& pairGenerator, LayerCacheType *layerCache); + void init(std::unique_ptr&& pairGenerator, LayerCacheType* layerCache); - virtual void hitSets( const TrackingRegion& region, OrderedMultiHits & trs, - const edm::Event & ev, const edm::EventSetup& es, - SeedingLayerSetsHits::SeedingLayerSet pairLayers, - std::vector thirdLayers) = 0; + virtual void hitSets(const TrackingRegion& region, + OrderedMultiHits& trs, + const edm::Event& ev, + const edm::EventSetup& es, + SeedingLayerSetsHits::SeedingLayerSet pairLayers, + std::vector thirdLayers) = 0; - virtual void hitTriplets( - const TrackingRegion& region, - OrderedMultiHits & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)=0; + virtual void hitTriplets(const TrackingRegion& region, + OrderedMultiHits& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) = 0; const HitPairGeneratorFromLayerPair& pairGenerator() const { return *thePairGenerator; } @@ -50,13 +55,11 @@ class MultiHitGeneratorFromPairAndLayers { protected: using cacheHitPointer = std::unique_ptr; - using cacheHits=std::vector; - cacheHits cache; // ownes what is by reference above... + using cacheHits = std::vector; + cacheHits cache; // ownes what is by reference above... std::unique_ptr thePairGenerator; - LayerCacheType *theLayerCache; + LayerCacheType* theLayerCache; const unsigned int theMaxElement; }; #endif - - diff --git a/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h b/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h index e215262a15d0e..0d855bbcda02d 100644 --- a/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h +++ b/RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h @@ -1,12 +1,14 @@ -#ifndef MultiHitGeneratorFromPairAndLayersFactory_H +#ifndef MultiHitGeneratorFromPairAndLayersFactory_H #define MultiHitGeneratorFromPairAndLayersFactory_H #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h" #include "FWCore/PluginManager/interface/PluginFactory.h" -namespace edm {class ParameterSet;} +namespace edm { + class ParameterSet; +} typedef edmplugin::PluginFactory - MultiHitGeneratorFromPairAndLayersFactory; - + MultiHitGeneratorFromPairAndLayersFactory; + #endif diff --git a/RecoTracker/TkSeedGenerator/interface/SeedCreator.h b/RecoTracker/TkSeedGenerator/interface/SeedCreator.h index d10c21c98e87b..51b8ae386e280 100644 --- a/RecoTracker/TkSeedGenerator/interface/SeedCreator.h +++ b/RecoTracker/TkSeedGenerator/interface/SeedCreator.h @@ -5,26 +5,24 @@ #include "FWCore/Utilities/interface/GCC11Compatibility.h" - class TrackingRegion; class SeedingHitSet; class SeedComparitor; -namespace edm { class Event; class EventSetup; } +namespace edm { + class Event; + class EventSetup; +} // namespace edm class SeedCreator { public: - - virtual ~SeedCreator(){} + virtual ~SeedCreator() {} // initialize the "event dependent state" - virtual void init(const TrackingRegion & region, - const edm::EventSetup& es, - const SeedComparitor *filter) = 0; + virtual void init(const TrackingRegion& region, const edm::EventSetup& es, const SeedComparitor* filter) = 0; - // make job + // make job // fill seedCollection with the "TrajectorySeed" - virtual void makeSeed(TrajectorySeedCollection & seedCollection, - const SeedingHitSet & hits) = 0; + virtual void makeSeed(TrajectorySeedCollection& seedCollection, const SeedingHitSet& hits) = 0; }; -#endif +#endif diff --git a/RecoTracker/TkSeedGenerator/interface/SeedCreatorFactory.h b/RecoTracker/TkSeedGenerator/interface/SeedCreatorFactory.h index 83faba566a863..b1d60e19e73ae 100644 --- a/RecoTracker/TkSeedGenerator/interface/SeedCreatorFactory.h +++ b/RecoTracker/TkSeedGenerator/interface/SeedCreatorFactory.h @@ -4,8 +4,10 @@ #include "RecoTracker/TkSeedGenerator/interface/SeedCreator.h" #include "FWCore/PluginManager/interface/PluginFactory.h" -namespace edm {class ParameterSet;} +namespace edm { + class ParameterSet; +} -typedef edmplugin::PluginFactory SeedCreatorFactory; +typedef edmplugin::PluginFactory SeedCreatorFactory; #endif diff --git a/RecoTracker/TkSeedGenerator/interface/SeedFromProtoTrack.h b/RecoTracker/TkSeedGenerator/interface/SeedFromProtoTrack.h index e0784fcf62769..b58f5d78d6eb8 100644 --- a/RecoTracker/TkSeedGenerator/interface/SeedFromProtoTrack.h +++ b/RecoTracker/TkSeedGenerator/interface/SeedFromProtoTrack.h @@ -7,16 +7,17 @@ #include "RecoTracker/TkSeedingLayers/interface/SeedingHitSet.h" #include -namespace reco { class Track; } -namespace edm { class EventSetup; } +namespace reco { + class Track; +} +namespace edm { + class EventSetup; +} class SeedFromProtoTrack { public: - - - SeedFromProtoTrack(const reco::Track & proto, const edm::EventSetup& ); - SeedFromProtoTrack(const reco::Track & proto,const SeedingHitSet & hits, - const edm::EventSetup& es); + SeedFromProtoTrack(const reco::Track& proto, const edm::EventSetup&); + SeedFromProtoTrack(const reco::Track& proto, const SeedingHitSet& hits, const edm::EventSetup& es); ~SeedFromProtoTrack() {} @@ -25,22 +26,18 @@ class SeedFromProtoTrack { bool isValid() const { return theValid; } private: - - void init(const reco::Track & proto, const edm::EventSetup& es); + void init(const reco::Track& proto, const edm::EventSetup& es); PropagationDirection direction() const { return alongMomentum; } - PTrajectoryStateOnDet const & trajectoryState() const { return thePTraj; } - + PTrajectoryStateOnDet const& trajectoryState() const { return thePTraj; } typedef edm::OwnVector RecHitContainer; - const RecHitContainer & hits() const { return theHits; } + const RecHitContainer& hits() const { return theHits; } private: - bool theValid; RecHitContainer theHits; PTrajectoryStateOnDet thePTraj; - }; #endif diff --git a/RecoTracker/TkSeedGenerator/interface/SeedGeneratorFromRegionHits.h b/RecoTracker/TkSeedGenerator/interface/SeedGeneratorFromRegionHits.h index ddfc347db9939..f113874a7d9cf 100644 --- a/RecoTracker/TkSeedGenerator/interface/SeedGeneratorFromRegionHits.h +++ b/RecoTracker/TkSeedGenerator/interface/SeedGeneratorFromRegionHits.h @@ -7,29 +7,30 @@ #include "RecoTracker/TkSeedingLayers/interface/SeedComparitor.h" #include "RecoTracker/TkSeedGenerator/interface/SeedCreator.h" - #include class TrackingRegion; - -namespace edm { class Event; class EventSetup; } + +namespace edm { + class Event; + class EventSetup; +} // namespace edm class SeedGeneratorFromRegionHits { public: - - SeedGeneratorFromRegionHits( - std::unique_ptr aGenerator, - std::unique_ptr aComparitor = nullptr, - std::unique_ptr aSeedCreator = nullptr - ); + SeedGeneratorFromRegionHits(std::unique_ptr aGenerator, + std::unique_ptr aComparitor = nullptr, + std::unique_ptr aSeedCreator = nullptr); // make job - void run(TrajectorySeedCollection & seedCollection, const TrackingRegion & region, - const edm::Event& ev, const edm::EventSetup& es); - + void run(TrajectorySeedCollection& seedCollection, + const TrackingRegion& region, + const edm::Event& ev, + const edm::EventSetup& es); + private: std::unique_ptr theHitsGenerator; std::unique_ptr theComparitor; std::unique_ptr theSeedCreator; }; -#endif +#endif diff --git a/RecoTracker/TkSeedGenerator/plugins/ClusterCheckerEDProducer.cc b/RecoTracker/TkSeedGenerator/plugins/ClusterCheckerEDProducer.cc index 8320e09762f50..1725ceff28d19 100644 --- a/RecoTracker/TkSeedGenerator/plugins/ClusterCheckerEDProducer.cc +++ b/RecoTracker/TkSeedGenerator/plugins/ClusterCheckerEDProducer.cc @@ -6,9 +6,8 @@ #include "RecoTracker/TkSeedGenerator/interface/ClusterChecker.h" -class ClusterCheckerEDProducer: public edm::stream::EDProducer<> { +class ClusterCheckerEDProducer : public edm::stream::EDProducer<> { public: - ClusterCheckerEDProducer(const edm::ParameterSet& iConfig); ~ClusterCheckerEDProducer() override = default; @@ -21,10 +20,9 @@ class ClusterCheckerEDProducer: public edm::stream::EDProducer<> { bool theSilentOnClusterCheck; }; -ClusterCheckerEDProducer::ClusterCheckerEDProducer(const edm::ParameterSet& iConfig): - theClusterCheck(iConfig, consumesCollector()), - theSilentOnClusterCheck(iConfig.getUntrackedParameter("silentClusterCheck")) -{ +ClusterCheckerEDProducer::ClusterCheckerEDProducer(const edm::ParameterSet& iConfig) + : theClusterCheck(iConfig, consumesCollector()), + theSilentOnClusterCheck(iConfig.getUntrackedParameter("silentClusterCheck")) { produces(); } @@ -41,15 +39,14 @@ void ClusterCheckerEDProducer::produce(edm::Event& iEvent, const edm::EventSetup //protection for big ass events... size_t clustsOrZero = theClusterCheck.tooManyClusters(iEvent); - if (clustsOrZero){ + if (clustsOrZero) { if (!theSilentOnClusterCheck) - edm::LogError("TooManyClusters") << "Found too many clusters (" << clustsOrZero << "), bailing out."; + edm::LogError("TooManyClusters") << "Found too many clusters (" << clustsOrZero << "), bailing out."; *ret = false; } iEvent.put(std::move(ret)); } - #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(ClusterCheckerEDProducer); diff --git a/RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.h b/RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.h index 54f3946bbddcc..e626b576adfba 100644 --- a/RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.h +++ b/RecoTracker/TkSeedGenerator/plugins/CombinedMultiHitGenerator.h @@ -4,7 +4,7 @@ /** A MultiHitGenerator consisting of a set of * triplet generators of type MultiHitGeneratorFromPairAndLayers * initialised from provided layers in the form of PixelLayerTriplets - */ + */ #include "RecoTracker/TkSeedGenerator/interface/MultiHitGenerator.h" #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h" @@ -12,28 +12,33 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/EDGetToken.h" -#include +#include class TrackingRegion; class dso_hidden SeedingLayerSetsHits; // class MultiHitGeneratorFromPairAndLayers; -namespace edm { class Event; } -namespace edm { class EventSetup; } +namespace edm { + class Event; +} +namespace edm { + class EventSetup; +} class dso_hidden CombinedMultiHitGenerator final : public MultiHitGenerator { public: - typedef LayerHitMapCache LayerCacheType; + typedef LayerHitMapCache LayerCacheType; public: - - CombinedMultiHitGenerator( const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); + CombinedMultiHitGenerator(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC); ~CombinedMultiHitGenerator() override; /// from base class - void hitSets( const TrackingRegion& reg, OrderedMultiHits & result, - const edm::Event & ev, const edm::EventSetup& es) override; + void hitSets(const TrackingRegion& reg, + OrderedMultiHits& result, + const edm::Event& ev, + const edm::EventSetup& es) override; void clear() override { MultiHitGenerator::clear(); @@ -43,7 +48,7 @@ class dso_hidden CombinedMultiHitGenerator final : public MultiHitGenerator { private: edm::EDGetTokenT theSeedingLayerToken; - LayerCacheType theLayerCache; + LayerCacheType theLayerCache; std::unique_ptr theGenerator; }; diff --git a/RecoTracker/TkSeedGenerator/plugins/MultiHitFromChi2EDProducer.cc b/RecoTracker/TkSeedGenerator/plugins/MultiHitFromChi2EDProducer.cc index af5cc153bcec5..ddd217370219c 100644 --- a/RecoTracker/TkSeedGenerator/plugins/MultiHitFromChi2EDProducer.cc +++ b/RecoTracker/TkSeedGenerator/plugins/MultiHitFromChi2EDProducer.cc @@ -14,7 +14,7 @@ #include "RecoPixelVertexing/PixelTriplets/interface/LayerTriplets.h" #include "MultiHitGeneratorFromChi2.h" -class MultiHitFromChi2EDProducer: public edm::stream::EDProducer<> { +class MultiHitFromChi2EDProducer : public edm::stream::EDProducer<> { public: MultiHitFromChi2EDProducer(const edm::ParameterSet& iConfig); ~MultiHitFromChi2EDProducer() override = default; @@ -31,10 +31,9 @@ class MultiHitFromChi2EDProducer: public edm::stream::EDProducer<> { MultiHitGeneratorFromChi2 generator_; }; -MultiHitFromChi2EDProducer::MultiHitFromChi2EDProducer(const edm::ParameterSet& iConfig): - doubletToken_(consumes(iConfig.getParameter("doublets"))), - generator_(iConfig) -{ +MultiHitFromChi2EDProducer::MultiHitFromChi2EDProducer(const edm::ParameterSet& iConfig) + : doubletToken_(consumes(iConfig.getParameter("doublets"))), + generator_(iConfig) { produces(); produces >(); } @@ -56,12 +55,16 @@ void MultiHitFromChi2EDProducer::produce(edm::Event& iEvent, const edm::EventSet const auto& regionDoublets = *hdoublets; const SeedingLayerSetsHits& seedingLayerHits = regionDoublets.seedingLayerHits(); - if(seedingLayerHits.numberOfLayersInSet() < 3) { - throw cms::Exception("LogicError") << "MultiHitFromChi2EDProducer expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= 3, got " << seedingLayerHits.numberOfLayersInSet() << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or SeedingLayersEDProducer."; + if (seedingLayerHits.numberOfLayersInSet() < 3) { + throw cms::Exception("LogicError") + << "MultiHitFromChi2EDProducer expects SeedingLayerSetsHits::numberOfLayersInSet() to be >= 3, got " + << seedingLayerHits.numberOfLayersInSet() + << ". This is likely caused by a configuration error of this module, HitPairEDProducer, or " + "SeedingLayersEDProducer."; } auto seedingHitSets = std::make_unique(); - if(regionDoublets.empty()) { + if (regionDoublets.empty()) { iEvent.put(std::move(seedingHitSets)); return; } @@ -74,12 +77,14 @@ void MultiHitFromChi2EDProducer::produce(edm::Event& iEvent, const edm::EventSet OrderedMultiHits multihits; multihits.reserve(localRA_.upper()); std::vector > refittedHitStorage; - refittedHitStorage.reserve(localRA_.upper()*2); + refittedHitStorage.reserve(localRA_.upper() * 2); - LogDebug("MultiHitFromChi2EDProducer") << "Creating multihits for " << regionDoublets.regionSize() << " regions, and " << trilayers.size() << " pair+3rd layers from " << regionDoublets.layerPairsSize() << " layer pairs"; + LogDebug("MultiHitFromChi2EDProducer") << "Creating multihits for " << regionDoublets.regionSize() << " regions, and " + << trilayers.size() << " pair+3rd layers from " + << regionDoublets.layerPairsSize() << " layer pairs"; LayerHitMapCache hitCache; - for(const auto& regionLayerPairs: regionDoublets) { + for (const auto& regionLayerPairs : regionDoublets) { const TrackingRegion& region = regionLayerPairs.region(); auto seedingHitSetsFiller = RegionsSeedingHitSets::dummyFiller(); @@ -90,18 +95,21 @@ void MultiHitFromChi2EDProducer::produce(edm::Event& iEvent, const edm::EventSet LogTrace("MultiHitFromChi2EDProducer") << " starting region"; - for(const auto& layerPair: regionLayerPairs) { - LogTrace("MultiHitFromChi2EDProducer") << " starting layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex(); + for (const auto& layerPair : regionLayerPairs) { + LogTrace("MultiHitFromChi2EDProducer") + << " starting layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex(); auto found = std::find_if(trilayers.begin(), trilayers.end(), [&](const LayerTriplets::LayerSetAndLayers& a) { - return a.first[0].index() == layerPair.innerLayerIndex() && a.first[1].index() == layerPair.outerLayerIndex(); - }); - if(found == trilayers.end()) { - auto exp = cms::Exception("LogicError") << "Did not find the layer pair from vector. This is a sign of some internal inconsistency\n"; - exp << "I was looking for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() << ". Triplets have the following pairs:\n"; - for(const auto& a: trilayers) { + return a.first[0].index() == layerPair.innerLayerIndex() && a.first[1].index() == layerPair.outerLayerIndex(); + }); + if (found == trilayers.end()) { + auto exp = cms::Exception("LogicError") << "Did not find the layer pair from vector. This " + "is a sign of some internal inconsistency\n"; + exp << "I was looking for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() + << ". Triplets have the following pairs:\n"; + for (const auto& a : trilayers) { exp << " " << a.first[0].index() << "," << a.first[1].index() << ": 3rd layers"; - for(const auto& b: a.second) { + for (const auto& b : a.second) { exp << " " << b.index(); } exp << "\n"; @@ -110,16 +118,19 @@ void MultiHitFromChi2EDProducer::produce(edm::Event& iEvent, const edm::EventSet } const auto& thirdLayers = found->second; - generator_.hitSets(region, multihits, iEvent, iSetup, layerPair.doublets(), thirdLayers, hitCache, refittedHitStorage); + generator_.hitSets( + region, multihits, iEvent, iSetup, layerPair.doublets(), thirdLayers, hitCache, refittedHitStorage); #ifdef EDM_ML_DEBUG - LogTrace("MultiHitFromChi2EDProducer") << " created " << multihits.size() << " multihits for layer pair " << layerPair.innerLayerIndex() << "," << layerPair.outerLayerIndex() << " and 3rd layers"; - for(const auto& l: thirdLayers) { + LogTrace("MultiHitFromChi2EDProducer") + << " created " << multihits.size() << " multihits for layer pair " << layerPair.innerLayerIndex() << "," + << layerPair.outerLayerIndex() << " and 3rd layers"; + for (const auto& l : thirdLayers) { LogTrace("MultiHitFromChi2EDProducer") << " " << l.index(); } #endif - for(const SeedingHitSet& hitSet: multihits) { + for (const SeedingHitSet& hitSet : multihits) { seedingHitSetsFiller.emplace_back(hitSet); } multihits.clear(); @@ -129,7 +140,7 @@ void MultiHitFromChi2EDProducer::produce(edm::Event& iEvent, const edm::EventSet auto storage = std::make_unique >(); storage->reserve(refittedHitStorage.size()); - for(auto& ptr: refittedHitStorage) + for (auto& ptr : refittedHitStorage) storage->push_back(ptr.release()); seedingHitSets->shrink_to_fit(); diff --git a/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.cc b/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.cc index aa84fe534f03b..75bf3c03789af 100644 --- a/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.cc +++ b/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.cc @@ -29,10 +29,8 @@ #include "TrackingTools/Records/interface/TransientRecHitRecord.h" - #include "DataFormats/Math/interface/normalizedPhi.h" - #include "FWCore/Utilities/interface/isFinite.h" #include "CommonTools/Utils/interface/DynArray.h" @@ -51,31 +49,36 @@ namespace { struct LayerRZPredictions { ThirdHitRZPrediction line; }; -} +} // namespace MultiHitGeneratorFromChi2::MultiHitGeneratorFromChi2(const edm::ParameterSet& cfg) - : MultiHitGeneratorFromPairAndLayers(cfg), - useFixedPreFiltering(cfg.getParameter("useFixedPreFiltering")), - extraHitRZtolerance(cfg.getParameter("extraHitRZtolerance")),//extra window in ThirdHitRZPrediction range - extraHitRPhitolerance(cfg.getParameter("extraHitRPhitolerance")),//extra window in ThirdHitPredictionFromCircle range (divide by R to get phi) - extraZKDBox(cfg.getParameter("extraZKDBox")),//extra windown in Z when building the KDTree box (used in barrel) - extraRKDBox(cfg.getParameter("extraRKDBox")),//extra windown in R when building the KDTree box (used in endcap) - extraPhiKDBox(cfg.getParameter("extraPhiKDBox")),//extra windown in Phi when building the KDTree box - fnSigmaRZ(cfg.getParameter("fnSigmaRZ")),//this multiplies the max hit error on the layer when building the KDTree box - chi2VsPtCut(cfg.getParameter("chi2VsPtCut")), - maxChi2(cfg.getParameter("maxChi2")), - refitHits(cfg.getParameter("refitHits")), - filterName_(cfg.getParameter("ClusterShapeHitFilterName")), - builderName_(cfg.existsAs("TTRHBuilder") ? cfg.getParameter("TTRHBuilder") : std::string("WithTrackAngle")), - useSimpleMF_(false), - mfName_("") -{ + : MultiHitGeneratorFromPairAndLayers(cfg), + useFixedPreFiltering(cfg.getParameter("useFixedPreFiltering")), + extraHitRZtolerance( + cfg.getParameter("extraHitRZtolerance")), //extra window in ThirdHitRZPrediction range + extraHitRPhitolerance(cfg.getParameter( + "extraHitRPhitolerance")), //extra window in ThirdHitPredictionFromCircle range (divide by R to get phi) + extraZKDBox( + cfg.getParameter("extraZKDBox")), //extra windown in Z when building the KDTree box (used in barrel) + extraRKDBox( + cfg.getParameter("extraRKDBox")), //extra windown in R when building the KDTree box (used in endcap) + extraPhiKDBox(cfg.getParameter("extraPhiKDBox")), //extra windown in Phi when building the KDTree box + fnSigmaRZ(cfg.getParameter( + "fnSigmaRZ")), //this multiplies the max hit error on the layer when building the KDTree box + chi2VsPtCut(cfg.getParameter("chi2VsPtCut")), + maxChi2(cfg.getParameter("maxChi2")), + refitHits(cfg.getParameter("refitHits")), + filterName_(cfg.getParameter("ClusterShapeHitFilterName")), + builderName_(cfg.existsAs("TTRHBuilder") ? cfg.getParameter("TTRHBuilder") + : std::string("WithTrackAngle")), + useSimpleMF_(false), + mfName_("") { if (useFixedPreFiltering) dphi = cfg.getParameter("phiPreFiltering"); if (chi2VsPtCut) { pt_interv = cfg.getParameter >("pt_interv"); - chi2_cuts = cfg.getParameter >("chi2_cuts"); - } + chi2_cuts = cfg.getParameter >("chi2_cuts"); + } #ifdef EDM_ML_DEBUG detIdsToDebug = cfg.getParameter >("detIdsToDebug"); //if (detIdsToDebug.size()<3) //fixme @@ -99,7 +102,6 @@ MultiHitGeneratorFromChi2::MultiHitGeneratorFromChi2(const edm::ParameterSet& cf MultiHitGeneratorFromChi2::~MultiHitGeneratorFromChi2() {} - void MultiHitGeneratorFromChi2::fillDescriptions(edm::ParameterSetDescription& desc) { MultiHitGeneratorFromPairAndLayers::fillDescriptions(desc); @@ -123,42 +125,37 @@ void MultiHitGeneratorFromChi2::fillDescriptions(edm::ParameterSetDescription& d // chi2 cuts desc.add("maxChi2", 5.0); desc.add("chi2VsPtCut", true); - desc.add >("pt_interv", std::vector{{0.4,0.7,1.0,2.0}}); - desc.add >("chi2_cuts", std::vector{{3.0,4.0,5.0,5.0}}); + desc.add >("pt_interv", std::vector{{0.4, 0.7, 1.0, 2.0}}); + desc.add >("chi2_cuts", std::vector{{3.0, 4.0, 5.0, 5.0}}); // debugging - desc.add >("detIdsToDebug", std::vector{{0,0,0}}); + desc.add >("detIdsToDebug", std::vector{{0, 0, 0}}); } - -void MultiHitGeneratorFromChi2::initES(const edm::EventSetup& es) -{ - +void MultiHitGeneratorFromChi2::initES(const edm::EventSetup& es) { edm::ESHandle bfield_h; - if (useSimpleMF_) es.get().get(mfName_, bfield_h); - else es.get().get(bfield_h); + if (useSimpleMF_) + es.get().get(mfName_, bfield_h); + else + es.get().get(bfield_h); bfield = bfield_h.product(); nomField = bfield->nominalValue(); ufield.set(nomField); // more than enough (never actually used) - if(refitHits) - { - edm::ESHandle filterHandle_; - es.get().get(filterName_, filterHandle_); - filter = filterHandle_.product(); - - edm::ESHandle builderH; - es.get().get(builderName_, builderH); - builder = (TkTransientTrackingRecHitBuilder const *)(builderH.product()); - cloner = (*builder).cloner(); + if (refitHits) { + edm::ESHandle filterHandle_; + es.get().get(filterName_, filterHandle_); + filter = filterHandle_.product(); + + edm::ESHandle builderH; + es.get().get(builderName_, builderH); + builder = (TkTransientTrackingRecHitBuilder const*)(builderH.product()); + cloner = (*builder).cloner(); } } - namespace { - inline - bool intersect(Range &range, const Range &second) - { + inline bool intersect(Range& range, const Range& second) { if (range.first > second.max() || range.second < second.min()) return false; if (range.first < second.min()) @@ -167,21 +164,22 @@ namespace { range.second = second.max(); return range.first < range.second; } -} +} // namespace -void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, - OrderedMultiHits & result, - const edm::Event & ev, - const edm::EventSetup& es, - SeedingLayerSetsHits::SeedingLayerSet pairLayers, - std::vector thirdLayers) -{ - LogDebug("MultiHitGeneratorFromChi2") << "pair: " << thePairGenerator->innerLayer(pairLayers).name() << "+" << thePairGenerator->outerLayer(pairLayers).name() << " 3rd lay size: " << thirdLayers.size(); +void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, + OrderedMultiHits& result, + const edm::Event& ev, + const edm::EventSetup& es, + SeedingLayerSetsHits::SeedingLayerSet pairLayers, + std::vector thirdLayers) { + LogDebug("MultiHitGeneratorFromChi2") << "pair: " << thePairGenerator->innerLayer(pairLayers).name() << "+" + << thePairGenerator->outerLayer(pairLayers).name() + << " 3rd lay size: " << thirdLayers.size(); - auto const & doublets = thePairGenerator->doublets(region,ev,es, pairLayers); + auto const& doublets = thePairGenerator->doublets(region, ev, es, pairLayers); LogTrace("MultiHitGeneratorFromChi2") << ""; if (doublets.empty()) { - // LogDebug("MultiHitGeneratorFromChi2") << "empy pairs"; + // LogDebug("MultiHitGeneratorFromChi2") << "empy pairs"; return; } @@ -189,219 +187,233 @@ void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, hitSets(region, result, ev, es, doublets, thirdLayers, *theLayerCache, cache); } -void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, OrderedMultiHits& result, - const edm::Event& ev, const edm::EventSetup& es, +void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, + OrderedMultiHits& result, + const edm::Event& ev, + const edm::EventSetup& es, const HitDoublets& doublets, const std::vector& thirdLayers, LayerCacheType& layerCache, cacheHits& refittedHitStorage) { int size = thirdLayers.size(); - const RecHitsSortedInPhi * thirdHitMap[size]; - vector thirdLayerDetLayer(size,nullptr); - for (int il=0; il thirdLayerDetLayer(size, nullptr); + for (int il = 0; il < size; ++il) { + thirdHitMap[il] = &layerCache(thirdLayers[il], region, es); - thirdLayerDetLayer[il] = thirdLayers[il].detLayer(); - } + thirdLayerDetLayer[il] = thirdLayers[il].detLayer(); + } hitSets(region, result, es, doublets, thirdHitMap, thirdLayerDetLayer, size, refittedHitStorage); } -void MultiHitGeneratorFromChi2::hitTriplets( - const TrackingRegion& region, - OrderedMultiHits & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers) -{ +void MultiHitGeneratorFromChi2::hitTriplets(const TrackingRegion& region, + OrderedMultiHits& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) { hitSets(region, result, es, doublets, thirdHitMap, thirdLayerDetLayer, nThirdLayers, cache); } -void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, OrderedMultiHits& result, +void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, + OrderedMultiHits& result, const edm::EventSetup& es, const HitDoublets& doublets, - const RecHitsSortedInPhi **thirdHitMap, - const std::vector& thirdLayerDetLayer, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, const int nThirdLayers, cacheHits& refittedHitStorage) { #ifdef EDM_ML_DEBUG unsigned int debug_Id0 = detIdsToDebug[0]; unsigned int debug_Id1 = detIdsToDebug[1]; unsigned int debug_Id2 = detIdsToDebug[2]; -#endif +#endif - std::array bl; - bl[0] = doublets.innerLayer().isBarrel; - bl[1] = doublets.outerLayer().isBarrel; + std::array bl; + bl[0] = doublets.innerLayer().isBarrel; + bl[1] = doublets.outerLayer().isBarrel; //gc: these are all the layers compatible with the layer pairs (as defined in the config file) - //gc: initialize a KDTree per each 3rd layer - std::vector > layerTree; // re-used throughout - std::vector foundNodes; // re-used thoughout + std::vector > layerTree; // re-used throughout + std::vector foundNodes; // re-used thoughout foundNodes.reserve(100); - declareDynArray(KDTreeLinkerAlgo,nThirdLayers, hitTree); + declareDynArray(KDTreeLinkerAlgo, nThirdLayers, hitTree); declareDynArray(LayerRZPredictions, nThirdLayers, mapPred); - float rzError[nThirdLayers]; //save maximum errors - - const float maxDelphi = region.ptMin() < 0.3f ? float(M_PI)/4.f : float(M_PI)/8.f; // FIXME move to config?? - const float maxphi = M_PI+maxDelphi, minphi = -maxphi; // increase to cater for any range - const float safePhi = M_PI-maxDelphi; // sideband + float rzError[nThirdLayers]; //save maximum errors + const float maxDelphi = region.ptMin() < 0.3f ? float(M_PI) / 4.f : float(M_PI) / 8.f; // FIXME move to config?? + const float maxphi = M_PI + maxDelphi, minphi = -maxphi; // increase to cater for any range + const float safePhi = M_PI - maxDelphi; // sideband //gc: loop over each layer - for(int il = 0; il < nThirdLayers; il++) { - LogTrace("MultiHitGeneratorFromChi2") << "considering third layer: with hits: " << thirdHitMap[il]->all().second-thirdHitMap[il]->all().first; - const DetLayer *layer = thirdLayerDetLayer[il]; - LayerRZPredictions &predRZ = mapPred[il]; + for (int il = 0; il < nThirdLayers; il++) { + LogTrace("MultiHitGeneratorFromChi2") + << "considering third layer: with hits: " << thirdHitMap[il]->all().second - thirdHitMap[il]->all().first; + const DetLayer* layer = thirdLayerDetLayer[il]; + LayerRZPredictions& predRZ = mapPred[il]; predRZ.line.initLayer(layer); predRZ.line.initTolerance(extraHitRZtolerance); - //gc: now we take all hits in the layer and fill the KDTree - auto const & layer3 = *thirdHitMap[il]; // Get iterators + //gc: now we take all hits in the layer and fill the KDTree + auto const& layer3 = *thirdHitMap[il]; // Get iterators layerTree.clear(); - float minz=999999.0f, maxz= -minz; // Initialise to extreme values in case no hits - float maxErr=0.0f; - if (!layer3.empty()) - { - minz = layer3.v[0] ; - maxz = minz; //In case there's only one hit on the layer - for (auto i=0U; ihit()->rawId()==debug_Id2, "MultiHitGeneratorFromChi2") << "filling KDTree with hit in id=" << debug_Id2 - << " with pos: " << hi->hit()->globalPosition() - << " phi=" << hi->hit()->globalPosition().phi() - << " z=" << hi->hit()->globalPosition().z() - << " r=" << hi->hit()->globalPosition().perp(); + IfLogTrace(hi->hit()->rawId() == debug_Id2, "MultiHitGeneratorFromChi2") + << "filling KDTree with hit in id=" << debug_Id2 << " with pos: " << hi->hit()->globalPosition() + << " phi=" << hi->hit()->globalPosition().phi() << " z=" << hi->hit()->globalPosition().z() + << " r=" << hi->hit()->globalPosition().perp(); #endif - //use (phi,r) for endcaps rather than (phi,z) - if (myz < minz) { minz = myz;} else { if (myz > maxz) {maxz = myz;}} - auto myerr = layer3.dv[i]; - if (myerr > maxErr) { maxErr = myerr;} - layerTree.push_back(KDTreeNodeInfo(hi, angle, myz)); // save it - // populate side-bands - if (angle>safePhi) layerTree.push_back(KDTreeNodeInfo(hi, float(angle-Geom::twoPi()), float(myz))); - else if (angle<-safePhi) layerTree.push_back(KDTreeNodeInfo(hi, float(angle+Geom::twoPi()), float(myz))); - } + //use (phi,r) for endcaps rather than (phi,z) + if (myz < minz) { + minz = myz; + } else { + if (myz > maxz) { + maxz = myz; + } + } + auto myerr = layer3.dv[i]; + if (myerr > maxErr) { + maxErr = myerr; + } + layerTree.push_back(KDTreeNodeInfo(hi, angle, myz)); // save it + // populate side-bands + if (angle > safePhi) + layerTree.push_back( + KDTreeNodeInfo(hi, float(angle - Geom::twoPi()), float(myz))); + else if (angle < -safePhi) + layerTree.push_back( + KDTreeNodeInfo(hi, float(angle + Geom::twoPi()), float(myz))); } - KDTreeBox phiZ(minphi, maxphi, minz-0.01f, maxz+0.01f); // declare our bounds + } + KDTreeBox phiZ(minphi, maxphi, minz - 0.01f, maxz + 0.01f); // declare our bounds //add fudge factors in case only one hit and also for floating-point inaccuracy - hitTree[il].build(layerTree, phiZ); // make KDtree - rzError[il] = maxErr; //save error + hitTree[il].build(layerTree, phiZ); // make KDtree + rzError[il] = maxErr; //save error } //gc: now we have initialized the KDTrees and we are out of the layer loop - + //gc: this sets the minPt of the triplet auto curv = PixelRecoUtilities::curvature(1. / region.ptMin(), es); LogTrace("MultiHitGeneratorFromChi2") << "doublet size=" << doublets.size() << std::endl; - //fixme add pixels - auto filterHit = [&](TrackingRecHit const * hit, GlobalVector const& dir)->bool { - auto hh = reinterpret_cast(hit); - if (//hh->geographicalId().subdetId() > 2 - hh->geographicalId().subdetId()==SiStripDetId::TIB - || hh->geographicalId().subdetId()==SiStripDetId::TID - //|| hh->geographicalId().subdetId()==SiStripDetId::TOB - //|| hh->geographicalId().subdetId()==SiStripDetId::TEC - ) { - // carefull " for matched and projected local of tsos != local for individual clusters... - if (hh->isMatched()) { - const SiStripMatchedRecHit2D* matchedHit = reinterpret_cast(hh); - if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), dir)==0 || - filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), dir)==0) return false; - } else if (hh->isProjected()) { - const ProjectedSiStripRecHit2D* precHit = reinterpret_cast(hh); - if (filter->isCompatible(precHit->originalHit(), dir)==0) return false; //FIXME?? - } else if (hh->isSingle()) { - const SiStripRecHit2D* recHit = reinterpret_cast(hh); - if (filter->isCompatible(*recHit, dir)==0) return false; - } - } - return true; - }; + //fixme add pixels + auto filterHit = [&](TrackingRecHit const* hit, GlobalVector const& dir) -> bool { + auto hh = reinterpret_cast(hit); + if ( //hh->geographicalId().subdetId() > 2 + hh->geographicalId().subdetId() == SiStripDetId::TIB || hh->geographicalId().subdetId() == SiStripDetId::TID + //|| hh->geographicalId().subdetId()==SiStripDetId::TOB + //|| hh->geographicalId().subdetId()==SiStripDetId::TEC + ) { + // carefull " for matched and projected local of tsos != local for individual clusters... + if (hh->isMatched()) { + const SiStripMatchedRecHit2D* matchedHit = reinterpret_cast(hh); + if (filter->isCompatible(DetId(matchedHit->monoId()), matchedHit->monoCluster(), dir) == 0 || + filter->isCompatible(DetId(matchedHit->stereoId()), matchedHit->stereoCluster(), dir) == 0) + return false; + } else if (hh->isProjected()) { + const ProjectedSiStripRecHit2D* precHit = reinterpret_cast(hh); + if (filter->isCompatible(precHit->originalHit(), dir) == 0) + return false; //FIXME?? + } else if (hh->isSingle()) { + const SiStripRecHit2D* recHit = reinterpret_cast(hh); + if (filter->isCompatible(*recHit, dir) == 0) + return false; + } + } + return true; + }; //gc: now we loop over all pairs - for (std::size_t ip =0; ip!=doublets.size(); ip++) { - + for (std::size_t ip = 0; ip != doublets.size(); ip++) { int foundTripletsFromPair = 0; bool usePair = false; cacheHitPointer bestH2; float minChi2 = std::numeric_limits::max(); - SeedingHitSet::ConstRecHitPointer oriHit0 =doublets.hit(ip,HitDoublets::inner); - SeedingHitSet::ConstRecHitPointer oriHit1 =doublets.hit(ip,HitDoublets::outer); + SeedingHitSet::ConstRecHitPointer oriHit0 = doublets.hit(ip, HitDoublets::inner); + SeedingHitSet::ConstRecHitPointer oriHit1 = doublets.hit(ip, HitDoublets::outer); HitOwnPtr hit0(*oriHit0); HitOwnPtr hit1(*oriHit1); - GlobalPoint gp0 = doublets.gp(ip,HitDoublets::inner); - GlobalPoint gp1 = doublets.gp(ip,HitDoublets::outer); + GlobalPoint gp0 = doublets.gp(ip, HitDoublets::inner); + GlobalPoint gp1 = doublets.gp(ip, HitDoublets::outer); #ifdef EDM_ML_DEBUG - bool debugPair = oriHit0->rawId()==debug_Id0 && oriHit1->rawId()==debug_Id1; + bool debugPair = oriHit0->rawId() == debug_Id0 && oriHit1->rawId() == debug_Id1; #endif - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << endl << endl - << "found new pair with ids "<rawId()<<" "<rawId()<<" with pos: " << gp0 << " " << gp1; + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << endl + << endl + << "found new pair with ids " << oriHit0->rawId() << " " + << oriHit1->rawId() << " with pos: " << gp0 << " " << gp1; if (refitHits) { - TrajectoryStateOnSurface tsos0, tsos1; - assert(!hit0.isOwn()); assert(!hit1.isOwn()); + assert(!hit0.isOwn()); + assert(!hit1.isOwn()); #ifdef EDM_ML_DEBUG - refit2Hits(hit0,hit1,tsos0,tsos1,region,nomField,debugPair); + refit2Hits(hit0, hit1, tsos0, tsos1, region, nomField, debugPair); #else - refit2Hits(hit0,hit1,tsos0,tsos1,region,nomField,false); + refit2Hits(hit0, hit1, tsos0, tsos1, region, nomField, false); #endif - bool passFilterHit0 = filterHit(hit0->hit(),tsos0.globalMomentum()); - IfLogTrace(debugPair&&!passFilterHit0, "MultiHitGeneratorFromChi2") << "hit0 did not pass cluster shape filter"; - if (!passFilterHit0) continue; - bool passFilterHit1 = filterHit(hit1->hit(),tsos1.globalMomentum()); - IfLogTrace(debugPair&&!passFilterHit1, "MultiHitGeneratorFromChi2") << "hit1 did not pass cluster shape filter"; - if (!passFilterHit1) continue; + bool passFilterHit0 = filterHit(hit0->hit(), tsos0.globalMomentum()); + IfLogTrace(debugPair && !passFilterHit0, "MultiHitGeneratorFromChi2") << "hit0 did not pass cluster shape filter"; + if (!passFilterHit0) + continue; + bool passFilterHit1 = filterHit(hit1->hit(), tsos1.globalMomentum()); + IfLogTrace(debugPair && !passFilterHit1, "MultiHitGeneratorFromChi2") << "hit1 did not pass cluster shape filter"; + if (!passFilterHit1) + continue; // refit hits - hit0.reset((SeedingHitSet::RecHitPointer)(cloner(*hit0,tsos0))); - hit1.reset((SeedingHitSet::RecHitPointer)(cloner(*hit1,tsos1))); + hit0.reset((SeedingHitSet::RecHitPointer)(cloner(*hit0, tsos0))); + hit1.reset((SeedingHitSet::RecHitPointer)(cloner(*hit1, tsos1))); #ifdef EDM_ML_DEBUG - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "charge=" << tsos0.charge() << std::endl - << "state1 pt=" << tsos0.globalMomentum().perp() << " eta=" << tsos0.globalMomentum().eta() << " phi=" << tsos0.globalMomentum().phi() << std::endl - << "state2 pt=" << tsos1.globalMomentum().perp() << " eta=" << tsos1.globalMomentum().eta() << " phi=" << tsos1.globalMomentum().phi() << std::endl - << "positions after refitting: " << hit0->globalPosition() << " " << hit1->globalPosition(); -#endif + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") + << "charge=" << tsos0.charge() << std::endl + << "state1 pt=" << tsos0.globalMomentum().perp() << " eta=" << tsos0.globalMomentum().eta() + << " phi=" << tsos0.globalMomentum().phi() << std::endl + << "state2 pt=" << tsos1.globalMomentum().perp() << " eta=" << tsos1.globalMomentum().eta() + << " phi=" << tsos1.globalMomentum().phi() << std::endl + << "positions after refitting: " << hit0->globalPosition() << " " << hit1->globalPosition(); +#endif } else { // not refit clone anyhow - hit0.reset((BaseTrackerRecHit *)hit0->clone()); - hit1.reset((BaseTrackerRecHit *)hit1->clone()); + hit0.reset((BaseTrackerRecHit*)hit0->clone()); + hit1.reset((BaseTrackerRecHit*)hit1->clone()); } - assert(hit0.isOwn()); assert(hit1.isOwn()); - + assert(hit0.isOwn()); + assert(hit1.isOwn()); //gc: create the RZ line for the pair - SimpleLineRZ line(PixelRecoPointRZ(gp0.perp(),gp0.z()), PixelRecoPointRZ(gp1.perp(),gp1.z())); + SimpleLineRZ line(PixelRecoPointRZ(gp0.perp(), gp0.z()), PixelRecoPointRZ(gp1.perp(), gp1.z())); ThirdHitPredictionFromCircle predictionRPhi(gp0, gp1, extraHitRPhitolerance); - auto toPos = std::signbit(gp1.z()-gp0.z()); - + auto toPos = std::signbit(gp1.z() - gp0.z()); //gc: this is the curvature of the two hits assuming the region Range pairCurvature = predictionRPhi.curvature(region.originRBound()); //gc: intersect not only returns a bool but may change pairCurvature to intersection with curv if (!intersect(pairCurvature, Range(-curv, curv))) { - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "curvature cut: curv=" << curv - << " gc=(" << pairCurvature.first << ", " << pairCurvature.second << ")"; + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") + << "curvature cut: curv=" << curv << " gc=(" << pairCurvature.first << ", " << pairCurvature.second << ")"; continue; } - std::array gp; std::array ge; gp[0] = hit0->globalPosition(); @@ -409,197 +421,206 @@ void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, OrderedMul gp[1] = hit1->globalPosition(); ge[1] = hit1->globalPositionError(); - //gc: loop over all third layers compatible with the pair - for(int il = 0; (il < nThirdLayers) & (!usePair); il++) { - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "cosider layer:" << " for this pair. Location: " << thirdLayerDetLayer[il]->location(); + for (int il = 0; (il < nThirdLayers) & (!usePair); il++) { + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") + << "cosider layer:" + << " for this pair. Location: " << thirdLayerDetLayer[il]->location(); if (hitTree[il].empty()) { - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "empty hitTree"; - continue; // Don't bother if no hits + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "empty hitTree"; + continue; // Don't bother if no hits } cacheHitPointer bestL2; float chi2FromThisLayer = std::numeric_limits::max(); - const DetLayer *layer = thirdLayerDetLayer[il]; + const DetLayer* layer = thirdLayerDetLayer[il]; // bool barrelLayer = layer->location() == GeomDetEnumerators::barrel; - auto const & layer3 = *thirdHitMap[il]; + auto const& layer3 = *thirdHitMap[il]; bool barrelLayer = layer3.isBarrel; bl[2] = layer3.isBarrel; - if ( (!barrelLayer) & (toPos != std::signbit(layer->position().z())) ) continue; - + if ((!barrelLayer) & (toPos != std::signbit(layer->position().z()))) + continue; - LayerRZPredictions &predRZ = mapPred[il]; + LayerRZPredictions& predRZ = mapPred[il]; predRZ.line.initPropagator(&line); - - //gc: this takes the z at R-thick/2 and R+thick/2 according to + + //gc: this takes the z at R-thick/2 and R+thick/2 according to // the line from the two points and the adds the extra tolerance Range rzRange = predRZ.line(); if (rzRange.first >= rzRange.second) { - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "rzRange empty"; + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "rzRange empty"; continue; } //gc: check that rzRange is compatible with detector bounds // note that intersect may change rzRange to intersection with bounds - if (!intersect(rzRange, predRZ.line.detSize())) {// theDetSize = Range(-maxZ, maxZ); - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "rzRange and detector do not intersect"; - continue; + if (!intersect(rzRange, predRZ.line.detSize())) { // theDetSize = Range(-maxZ, maxZ); + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "rzRange and detector do not intersect"; + continue; } Range radius = barrelLayer ? predRZ.line.detRange() : rzRange; //gc: define the phi range of the hits Range phiRange; - if (useFixedPreFiltering) { - //gc: in this case it takes as range the phi of the outer - // hit +/- the phiPreFiltering value from cfg + if (useFixedPreFiltering) { + //gc: in this case it takes as range the phi of the outer + // hit +/- the phiPreFiltering value from cfg float phi0 = oriHit0->globalPosition().phi(); phiRange = Range(phi0 - dphi, phi0 + dphi); - } else { - //gc: predictionRPhi uses the cosine rule to find the phi of the 3rd point at radius, assuming the pairCurvature range [-c,+c] - if (pairCurvature.first<0. && pairCurvature.second<0.) { + } else { + //gc: predictionRPhi uses the cosine rule to find the phi of the 3rd point at radius, assuming the pairCurvature range [-c,+c] + if (pairCurvature.first < 0. && pairCurvature.second < 0.) { radius.swap(); - } else if (pairCurvature.first>=0. && pairCurvature.second>=0.) {;} - else { - radius.first=radius.second; + } else if (pairCurvature.first >= 0. && pairCurvature.second >= 0.) { + ; + } else { + radius.first = radius.second; } - auto phi12 = predictionRPhi.phi(pairCurvature.first,radius.first); - auto phi22 = predictionRPhi.phi(pairCurvature.second,radius.second); + auto phi12 = predictionRPhi.phi(pairCurvature.first, radius.first); + auto phi22 = predictionRPhi.phi(pairCurvature.second, radius.second); phi12 = normalizedPhi(phi12); - phi22 = proxim(phi22,phi12); - phiRange = Range(phi12,phi22); phiRange.sort(); + phi22 = proxim(phi22, phi12); + phiRange = Range(phi12, phi22); + phiRange.sort(); } - - float prmin=phiRange.min(), prmax=phiRange.max(); - - if (prmax-prmin>maxDelphi) { + + float prmin = phiRange.min(), prmax = phiRange.max(); + + if (prmax - prmin > maxDelphi) { auto prm = phiRange.mean(); - prmin = prm - 0.5f*maxDelphi; - prmax = prm + 0.5f*maxDelphi; + prmin = prm - 0.5f * maxDelphi; + prmax = prm + 0.5f * maxDelphi; } - //gc: this is the place where hits in the compatible region are put in the foundNodes - using Hit=RecHitsSortedInPhi::Hit; - foundNodes.clear(); // Now recover hits in bounding box... - - + using Hit = RecHitsSortedInPhi::Hit; + foundNodes.clear(); // Now recover hits in bounding box... IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "defining kd tree box"; if (barrelLayer) { - KDTreeBox phiZ(prmin-extraPhiKDBox, prmax+extraPhiKDBox, - float(rzRange.min()-fnSigmaRZ*rzError[il]-extraZKDBox), - float(rzRange.max()+fnSigmaRZ*rzError[il]+extraZKDBox)); - hitTree[il].search(phiZ, foundNodes); - - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "kd tree box bounds, phi: " << prmin-extraPhiKDBox <<","<< prmax+extraPhiKDBox - << " z: "<< rzRange.min()-fnSigmaRZ*rzError[il]-extraZKDBox <<","<::iterator ih = foundNodes.begin(); - ih !=foundNodes.end() && !usePair; ++ih) { - - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << endl << "triplet candidate"; + ih != foundNodes.end() && !usePair; + ++ih) { + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << endl << "triplet candidate"; - const RecHitsSortedInPhi::HitIter KDdata = *ih; + const RecHitsSortedInPhi::HitIter KDdata = *ih; - auto oriHit2 = KDdata->hit(); + auto oriHit2 = KDdata->hit(); auto kk = KDdata - layer3.theHits.begin(); - cacheHitPointer hit2; + cacheHitPointer hit2; auto gp2 = layer3.gp(kk); - if (refitHits) {//fixme - - //fitting all 3 hits takes too much time... do it quickly only for 3rd hit - GlobalVector initMomentum(gp2 - gp1); - initMomentum /= initMomentum.perp(); //set pT=1 - - //fixme add pixels - bool passFilterHit2 = filterHit(oriHit2->hit(),initMomentum); - if (!passFilterHit2) continue; - TrajectoryStateOnSurface state(GlobalTrajectoryParameters(gp2, initMomentum, 1, &ufield),*oriHit2->surface()); - hit2.reset((SeedingHitSet::RecHitPointer)(cloner(*oriHit2,state))); - - } else { - // not refit clone anyhow - hit2.reset((BaseTrackerRecHit*)oriHit2->clone()); - } + if (refitHits) { //fixme + + //fitting all 3 hits takes too much time... do it quickly only for 3rd hit + GlobalVector initMomentum(gp2 - gp1); + initMomentum /= initMomentum.perp(); //set pT=1 + + //fixme add pixels + bool passFilterHit2 = filterHit(oriHit2->hit(), initMomentum); + if (!passFilterHit2) + continue; + TrajectoryStateOnSurface state(GlobalTrajectoryParameters(gp2, initMomentum, 1, &ufield), + *oriHit2->surface()); + hit2.reset((SeedingHitSet::RecHitPointer)(cloner(*oriHit2, state))); + + } else { + // not refit clone anyhow + hit2.reset((BaseTrackerRecHit*)oriHit2->clone()); + } - //gc: add the chi2 cut - gp[2] = hit2->globalPosition(); - ge[2] = hit2->globalPositionError(); - RZLine rzLine(gp,ge,bl); - float chi2 = rzLine.chi2(); + //gc: add the chi2 cut + gp[2] = hit2->globalPosition(); + ge[2] = hit2->globalPositionError(); + RZLine rzLine(gp, ge, bl); + float chi2 = rzLine.chi2(); #ifdef EDM_ML_DEBUG - bool debugTriplet = debugPair && hit2->rawId()==debug_Id2; + bool debugTriplet = debugPair && hit2->rawId() == debug_Id2; #endif - IfLogTrace(debugTriplet, "MultiHitGeneratorFromChi2") << endl << "triplet candidate in debug id" << std::endl - << "hit in id="<rawId()<<" (from KDTree) with pos: " << KDdata->hit()->globalPosition() - << " refitted: " << hit2->globalPosition() - << " chi2: " << chi2; - // should fix nan - if ( (chi2 > maxChi2) | edm::isNotFinite(chi2) ) continue; - - if (chi2VsPtCut) { - - FastCircle theCircle(gp[2],gp[1],gp[0]); - float tesla0 = 0.1f*nomField; - float rho = theCircle.rho(); - float cm2GeV = 0.01f * 0.3f*tesla0; - float pt = cm2GeV * rho; - IfLogTrace(debugTriplet, "MultiHitGeneratorFromChi2") << "triplet pT=" << pt; - if (ptpt_interv[0] && pt<=pt_interv[1] && chi2 > chi2_cuts[0] ) || - ( pt>pt_interv[1] && pt<=pt_interv[2] && chi2 > chi2_cuts[1] ) || - ( pt>pt_interv[2] && pt<=pt_interv[3] && chi2 > chi2_cuts[2] ) || - ( pt>pt_interv[3] && chi2 > chi2_cuts[3] ) ) continue; - } - - // apparently this takes too much time... - // if (chi2_cuts.size()>1) { - // int ncuts = chi2_cuts.size(); - // if ( pt<=pt_interv[0] && chi2 > chi2_cuts[0] ) continue; - // bool pass = true; - // for (int icut=1; icutpt_interv[icut-1] && pt<=pt_interv[icut] && chi2 > chi2_cuts[icut] ) pass=false; - // } - // if (!pass) continue; - // if ( pt>pt_interv[ncuts-2] && chi2 > chi2_cuts[ncuts-1] ) continue; - // if (hit0->rawId()==debug_Id0 && hit1->rawId()==debug_Id1 && hit2->rawId()==debug_Id2) { - // LogTrace("MultiHitGeneratorFromChi2") << "triplet passed chi2 vs pt cut" << std::endl; - // } - // } - - } - - if (theMaxElement!=0 && result.size() >= theMaxElement) { - result.clear(); - edm::LogError("TooManyTriplets")<<" number of triples exceed maximum. no triplets produced."; - return; - } - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "triplet made"; - //result.push_back(SeedingHitSet(hit0, hit1, hit2)); - /* no refit so keep only hit2 + IfLogTrace(debugTriplet, "MultiHitGeneratorFromChi2") + << endl + << "triplet candidate in debug id" << std::endl + << "hit in id=" << hit2->rawId() << " (from KDTree) with pos: " << KDdata->hit()->globalPosition() + << " refitted: " << hit2->globalPosition() << " chi2: " << chi2; + // should fix nan + if ((chi2 > maxChi2) | edm::isNotFinite(chi2)) + continue; + + if (chi2VsPtCut) { + FastCircle theCircle(gp[2], gp[1], gp[0]); + float tesla0 = 0.1f * nomField; + float rho = theCircle.rho(); + float cm2GeV = 0.01f * 0.3f * tesla0; + float pt = cm2GeV * rho; + IfLogTrace(debugTriplet, "MultiHitGeneratorFromChi2") << "triplet pT=" << pt; + if (pt < region.ptMin()) + continue; + + if (chi2_cuts.size() == 4) { + if ((pt > pt_interv[0] && pt <= pt_interv[1] && chi2 > chi2_cuts[0]) || + (pt > pt_interv[1] && pt <= pt_interv[2] && chi2 > chi2_cuts[1]) || + (pt > pt_interv[2] && pt <= pt_interv[3] && chi2 > chi2_cuts[2]) || + (pt > pt_interv[3] && chi2 > chi2_cuts[3])) + continue; + } + + // apparently this takes too much time... + // if (chi2_cuts.size()>1) { + // int ncuts = chi2_cuts.size(); + // if ( pt<=pt_interv[0] && chi2 > chi2_cuts[0] ) continue; + // bool pass = true; + // for (int icut=1; icutpt_interv[icut-1] && pt<=pt_interv[icut] && chi2 > chi2_cuts[icut] ) pass=false; + // } + // if (!pass) continue; + // if ( pt>pt_interv[ncuts-2] && chi2 > chi2_cuts[ncuts-1] ) continue; + // if (hit0->rawId()==debug_Id0 && hit1->rawId()==debug_Id1 && hit2->rawId()==debug_Id2) { + // LogTrace("MultiHitGeneratorFromChi2") << "triplet passed chi2 vs pt cut" << std::endl; + // } + // } + } + + if (theMaxElement != 0 && result.size() >= theMaxElement) { + result.clear(); + edm::LogError("TooManyTriplets") << " number of triples exceed maximum. no triplets produced."; + return; + } + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "triplet made"; + //result.push_back(SeedingHitSet(hit0, hit1, hit2)); + /* no refit so keep only hit2 assert(tripletFromThisLayer.empty()); assert(hit0.isOwn()); assert(hit1.isOwn());assert(hit2.isOwn()); tripletFromThisLayer.emplace_back(std::move(hit0)); @@ -607,24 +628,25 @@ void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, OrderedMul tripletFromThisLayer.emplace_back(std::move(hit2)); assert(hit0.isEmpty()); assert(hit1.isEmpty());assert(hit2.isEmpty()); */ - bestL2 = std::move(hit2); - chi2FromThisLayer = chi2; - foundTripletsFromPair++; - if (foundTripletsFromPair>=2) { - usePair=true; - IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "using pair"; - break; - } - }//loop over hits in KDTree + bestL2 = std::move(hit2); + chi2FromThisLayer = chi2; + foundTripletsFromPair++; + if (foundTripletsFromPair >= 2) { + usePair = true; + IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "using pair"; + break; + } + } //loop over hits in KDTree - if (usePair) break; + if (usePair) + break; else { - //if there is one triplet in more than one layer, try picking the one with best chi2 - if (chi2FromThisLayer0) LogTrace("MultiHitGeneratorFromChi2") << "what?? " << minChi2 << ' ' << chi2FromThisLayer; @@ -632,84 +654,90 @@ void MultiHitGeneratorFromChi2::hitSets(const TrackingRegion& region, OrderedMul */ } - }//loop over layers + } //loop over layers - if (foundTripletsFromPair==0) continue; + if (foundTripletsFromPair == 0) + continue; //push back only (max) once per pair IfLogTrace(debugPair, "MultiHitGeneratorFromChi2") << "Done seed #" << result.size(); - if (usePair) result.push_back(SeedingHitSet(oriHit0, oriHit1)); - else { - assert(1==foundTripletsFromPair); + if (usePair) + result.push_back(SeedingHitSet(oriHit0, oriHit1)); + else { + assert(1 == foundTripletsFromPair); assert(bestH2); - result.emplace_back(&*hit0,&*hit1,&*bestH2); - assert(hit0.isOwn()); assert(hit1.isOwn()); + result.emplace_back(&*hit0, &*hit1, &*bestH2); + assert(hit0.isOwn()); + assert(hit1.isOwn()); refittedHitStorage.emplace_back(const_cast(hit0.release())); refittedHitStorage.emplace_back(const_cast(hit1.release())); refittedHitStorage.emplace_back(std::move(bestH2)); - assert(hit0.empty()); assert(hit1.empty());assert(!bestH2); + assert(hit0.empty()); + assert(hit1.empty()); + assert(!bestH2); } // LogTrace("MultiHitGeneratorFromChi2") << (usePair ? "pair " : "triplet ") << minChi2 <<' ' << refittedHitStorage.size(); - - }//loop over pairs + } //loop over pairs LogTrace("MultiHitGeneratorFromChi2") << "triplet size=" << result.size(); // std::cout << "MultiHitGeneratorFromChi2 " << "triplet size=" << result.size() << std::endl; } -void MultiHitGeneratorFromChi2::refit2Hits(HitOwnPtr & hit1, - HitOwnPtr & hit2, - TrajectoryStateOnSurface& state1, - TrajectoryStateOnSurface& state2, - const TrackingRegion& region, float nomField, bool isDebug) { - +void MultiHitGeneratorFromChi2::refit2Hits(HitOwnPtr& hit1, + HitOwnPtr& hit2, + TrajectoryStateOnSurface& state1, + TrajectoryStateOnSurface& state2, + const TrackingRegion& region, + float nomField, + bool isDebug) { //these need to be sorted in R const GlobalPoint& gp0 = region.origin(); GlobalPoint gp1 = hit1->globalPosition(); GlobalPoint gp2 = hit2->globalPosition(); - IfLogTrace(isDebug, "MultiHitGeneratorFromChi2") << "positions before refitting: " << hit1->globalPosition() << " " << hit2->globalPosition(); + IfLogTrace(isDebug, "MultiHitGeneratorFromChi2") + << "positions before refitting: " << hit1->globalPosition() << " " << hit2->globalPosition(); - FastCircle theCircle(gp2,gp1,gp0); - GlobalPoint cc(theCircle.x0(),theCircle.y0(),0); - float tesla0 = 0.1f*nomField; + FastCircle theCircle(gp2, gp1, gp0); + GlobalPoint cc(theCircle.x0(), theCircle.y0(), 0); + float tesla0 = 0.1f * nomField; float rho = theCircle.rho(); - float cm2GeV = 0.01f * 0.3f*tesla0; + float cm2GeV = 0.01f * 0.3f * tesla0; float pt = cm2GeV * rho; - GlobalVector vec20 = gp2-gp0; + GlobalVector vec20 = gp2 - gp0; //if (isDebug) { cout << "vec20.eta=" << vec20.eta() << endl; } - GlobalVector p0( gp0.y()-cc.y(), -gp0.x()+cc.x(), 0. ); - p0 = p0*pt/p0.perp(); - GlobalVector p1( gp1.y()-cc.y(), -gp1.x()+cc.x(), 0. ); - p1 = p1*pt/p1.perp(); - GlobalVector p2( gp2.y()-cc.y(), -gp2.x()+cc.x(), 0. ); - p2 = p2*pt/p2.perp(); + GlobalVector p0(gp0.y() - cc.y(), -gp0.x() + cc.x(), 0.); + p0 = p0 * pt / p0.perp(); + GlobalVector p1(gp1.y() - cc.y(), -gp1.x() + cc.x(), 0.); + p1 = p1 * pt / p1.perp(); + GlobalVector p2(gp2.y() - cc.y(), -gp2.x() + cc.x(), 0.); + p2 = p2 * pt / p2.perp(); //check sign according to scalar product - if ( (p0.x()*(gp1.x()-gp0.x())+p0.y()*(gp1.y()-gp0.y()) ) < 0 ) { - p0*=-1.; - p1*=-1.; - p2*=-1.; + if ((p0.x() * (gp1.x() - gp0.x()) + p0.y() * (gp1.y() - gp0.y())) < 0) { + p0 *= -1.; + p1 *= -1.; + p2 *= -1.; } //now set z component - auto zv = vec20.z()/vec20.perp(); - p0 = GlobalVector(p0.x(),p0.y(),p0.perp()*zv); - p1 = GlobalVector(p1.x(),p1.y(),p1.perp()*zv); - p2 = GlobalVector(p2.x(),p2.y(),p2.perp()*zv); + auto zv = vec20.z() / vec20.perp(); + p0 = GlobalVector(p0.x(), p0.y(), p0.perp() * zv); + p1 = GlobalVector(p1.x(), p1.y(), p1.perp() * zv); + p2 = GlobalVector(p2.x(), p2.y(), p2.perp() * zv); //get charge from vectorial product TrackCharge q = 1; - if ((gp1-cc).x()*p1.y() - (gp1-cc).y()*p1.x() > 0) q =-q; + if ((gp1 - cc).x() * p1.y() - (gp1 - cc).y() * p1.x() > 0) + q = -q; - TrajectoryStateOnSurface(GlobalTrajectoryParameters(gp1, p1, q, &ufield),*hit1->surface()).swap(state1); + TrajectoryStateOnSurface(GlobalTrajectoryParameters(gp1, p1, q, &ufield), *hit1->surface()).swap(state1); // hit1.reset((SeedingHitSet::RecHitPointer)(cloner(*hit1,state1))); - TrajectoryStateOnSurface(GlobalTrajectoryParameters(gp2, p2, q, &ufield),*hit2->surface()).swap(state2); + TrajectoryStateOnSurface(GlobalTrajectoryParameters(gp2, p2, q, &ufield), *hit2->surface()).swap(state2); // hit2.reset((SeedingHitSet::RecHitPointer)(cloner(*hit2,state2))); - } /* @@ -781,4 +809,3 @@ void MultiHitGeneratorFromChi2::refit3Hits(HitOwnPtr & hit0, << "positions after refitting: " << hit0->globalPosition() << " " << hit1->globalPosition() << " " << hit2->globalPosition(); } */ - diff --git a/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.h b/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.h index db72063b6e047..eb7c907ad10df 100644 --- a/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.h +++ b/RecoTracker/TkSeedGenerator/plugins/MultiHitGeneratorFromChi2.h @@ -20,15 +20,13 @@ #include "MagneticField/UniformEngine/interface/UniformMagneticField.h" - #include #include class HitPairGeneratorFromLayerPair; class dso_hidden MultiHitGeneratorFromChi2 final : public MultiHitGeneratorFromPairAndLayers { - -typedef CombinedMultiHitGenerator::LayerCacheType LayerCacheType; + typedef CombinedMultiHitGenerator::LayerCacheType LayerCacheType; public: MultiHitGeneratorFromChi2(const edm::ParameterSet& cfg); @@ -36,47 +34,53 @@ typedef CombinedMultiHitGenerator::LayerCacheType LayerCacheType; ~MultiHitGeneratorFromChi2() override; static void fillDescriptions(edm::ParameterSetDescription& desc); - static const char *fillDescriptionsLabel() { return "multiHitFromChi2"; } + static const char* fillDescriptionsLabel() { return "multiHitFromChi2"; } + void initES(const edm::EventSetup& es) override; - void initES(const edm::EventSetup& es) override; - - void hitSets( const TrackingRegion& region, OrderedMultiHits & trs, - const edm::Event & ev, const edm::EventSetup& es, - SeedingLayerSetsHits::SeedingLayerSet pairLayers, - std::vector thirdLayers) override; + void hitSets(const TrackingRegion& region, + OrderedMultiHits& trs, + const edm::Event& ev, + const edm::EventSetup& es, + SeedingLayerSetsHits::SeedingLayerSet pairLayers, + std::vector thirdLayers) override; - void hitSets(const TrackingRegion& region, OrderedMultiHits& trs, - const edm::Event& ev, const edm::EventSetup& es, + void hitSets(const TrackingRegion& region, + OrderedMultiHits& trs, + const edm::Event& ev, + const edm::EventSetup& es, const HitDoublets& doublets, const std::vector& thirdLayers, LayerCacheType& layerCache, cacheHits& refittedHitStorage); - void hitTriplets( - const TrackingRegion& region, - OrderedMultiHits & result, - const edm::EventSetup & es, - const HitDoublets & doublets, - const RecHitsSortedInPhi ** thirdHitMap, - const std::vector & thirdLayerDetLayer, - const int nThirdLayers)override; + void hitTriplets(const TrackingRegion& region, + OrderedMultiHits& result, + const edm::EventSetup& es, + const HitDoublets& doublets, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, + const int nThirdLayers) override; - void hitSets(const TrackingRegion& region, OrderedMultiHits& result, + void hitSets(const TrackingRegion& region, + OrderedMultiHits& result, const edm::EventSetup& es, const HitDoublets& doublets, - const RecHitsSortedInPhi **thirdHitMap, - const std::vector& thirdLayerDetLayer, + const RecHitsSortedInPhi** thirdHitMap, + const std::vector& thirdLayerDetLayer, const int nThirdLayers, cacheHits& refittedHitStorage); + private: using HitOwnPtr = mayown_ptr; - void refit2Hits(HitOwnPtr & hit0, - HitOwnPtr & hit1, - TrajectoryStateOnSurface& tsos0, - TrajectoryStateOnSurface& tsos1, - const TrackingRegion& region, float nomField, bool isDebug); + void refit2Hits(HitOwnPtr& hit0, + HitOwnPtr& hit1, + TrajectoryStateOnSurface& tsos0, + TrajectoryStateOnSurface& tsos1, + const TrackingRegion& region, + float nomField, + bool isDebug); /* void refit3Hits(HitOwnPtr & hit0, HitOwnPtr & hit1, @@ -88,7 +92,7 @@ typedef CombinedMultiHitGenerator::LayerCacheType LayerCacheType; */ private: const ClusterShapeHitFilter* filter; - TkTransientTrackingRecHitBuilder const * builder; + TkTransientTrackingRecHitBuilder const* builder; TkClonerImpl cloner; bool useFixedPreFiltering; @@ -114,10 +118,5 @@ typedef CombinedMultiHitGenerator::LayerCacheType LayerCacheType; std::string mfName_; std::vector detIdsToDebug; - - - }; #endif - - diff --git a/RecoTracker/TkSeedGenerator/plugins/SealModules.cc b/RecoTracker/TkSeedGenerator/plugins/SealModules.cc index 2ad71ffae8943..4a64f677fc545 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SealModules.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SealModules.cc @@ -8,30 +8,34 @@ DEFINE_FWK_MODULE(SeedGeneratorFromRegionHitsEDProducer); DEFINE_FWK_MODULE(SeedGeneratorFromProtoTracksEDProducer); DEFINE_FWK_MODULE(SeedCombiner); - #include "RecoTracker/TkSeedGenerator/interface/SeedCreatorFactory.h" #include "SeedFromConsecutiveHitsCreator.h" #include "SeedFromConsecutiveHitsStraightLineCreator.h" #include "SeedFromConsecutiveHitsTripletOnlyCreator.h" DEFINE_EDM_PLUGIN(SeedCreatorFactory, SeedFromConsecutiveHitsCreator, "SeedFromConsecutiveHitsCreator"); -DEFINE_EDM_PLUGIN(SeedCreatorFactory, SeedFromConsecutiveHitsStraightLineCreator, "SeedFromConsecutiveHitsStraightLineCreator"); -DEFINE_EDM_PLUGIN(SeedCreatorFactory, SeedFromConsecutiveHitsTripletOnlyCreator, "SeedFromConsecutiveHitsTripletOnlyCreator"); +DEFINE_EDM_PLUGIN(SeedCreatorFactory, + SeedFromConsecutiveHitsStraightLineCreator, + "SeedFromConsecutiveHitsStraightLineCreator"); +DEFINE_EDM_PLUGIN(SeedCreatorFactory, + SeedFromConsecutiveHitsTripletOnlyCreator, + "SeedFromConsecutiveHitsTripletOnlyCreator"); #include "RecoTracker/TkTrackingRegions/interface/OrderedHitsGeneratorFactory.h" #include "RecoTracker/TkTrackingRegions/interface/OrderedHitsGenerator.h" #include "CombinedMultiHitGenerator.h" DEFINE_EDM_PLUGIN(OrderedHitsGeneratorFactory, CombinedMultiHitGenerator, "StandardMultiHitGenerator"); - #include "MultiHitGeneratorFromChi2.h" #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayers.h" #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h" DEFINE_EDM_PLUGIN(MultiHitGeneratorFromPairAndLayersFactory, MultiHitGeneratorFromChi2, "MultiHitGeneratorFromChi2"); #include "RecoTracker/TkSeedGenerator/interface/SeedCreatorFromRegionHitsEDProducerT.h" -using SeedCreatorFromRegionConsecutiveHitsEDProducer = SeedCreatorFromRegionHitsEDProducerT; +using SeedCreatorFromRegionConsecutiveHitsEDProducer = + SeedCreatorFromRegionHitsEDProducerT; DEFINE_FWK_MODULE(SeedCreatorFromRegionConsecutiveHitsEDProducer); -using SeedCreatorFromRegionConsecutiveHitsTripletOnlyEDProducer = SeedCreatorFromRegionHitsEDProducerT; +using SeedCreatorFromRegionConsecutiveHitsTripletOnlyEDProducer = + SeedCreatorFromRegionHitsEDProducerT; DEFINE_FWK_MODULE(SeedCreatorFromRegionConsecutiveHitsTripletOnlyEDProducer); diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.cc b/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.cc index f231947ffba03..f618e15ebaabc 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.cc @@ -26,72 +26,64 @@ using namespace edm; //using namespace reco; -SeedCombiner::SeedCombiner(const edm::ParameterSet& cfg) -{ - inputCollections_ = edm::vector_transform( - cfg.getParameter >("seedCollections"), - [this](edm::InputTag const & tag) { return consumes(tag); } ); - produces(); - reKeing_=false; - if (cfg.exists("clusterRemovalInfos")){ - clusterRemovalInfos_=cfg.getParameter >("clusterRemovalInfos"); - clusterRemovalTokens_.resize(clusterRemovalInfos_.size()); - for (unsigned int i=0;i(clusterRemovalInfos_[i]); - if (!clusterRemovalInfos_.empty() && clusterRemovalInfos_.size()==inputCollections_.size()) reKeing_=true; - } -} - - -SeedCombiner::~SeedCombiner() -{ +SeedCombiner::SeedCombiner(const edm::ParameterSet& cfg) { + inputCollections_ = + edm::vector_transform(cfg.getParameter >("seedCollections"), + [this](edm::InputTag const& tag) { return consumes(tag); }); + produces(); + reKeing_ = false; + if (cfg.exists("clusterRemovalInfos")) { + clusterRemovalInfos_ = cfg.getParameter >("clusterRemovalInfos"); + clusterRemovalTokens_.resize(clusterRemovalInfos_.size()); + for (unsigned int i = 0; i < clusterRemovalInfos_.size(); ++i) + if (!(clusterRemovalInfos_[i] == edm::InputTag(""))) + clusterRemovalTokens_[i] = consumes(clusterRemovalInfos_[i]); + if (!clusterRemovalInfos_.empty() && clusterRemovalInfos_.size() == inputCollections_.size()) + reKeing_ = true; + } } - -void SeedCombiner::produce(edm::Event& ev, const edm::EventSetup& es) -{ - // Read inputs, and count total seeds - size_t ninputs = inputCollections_.size(); - size_t nseeds = 0; - std::vector > seedCollections(ninputs); - for (size_t i = 0; i < ninputs; ++i) { - ev.getByToken(inputCollections_[i], seedCollections[i]); - nseeds += seedCollections[i]->size(); - } - - // Prepare output collections, with the correct capacity - auto result = std::make_unique(); - result->reserve( nseeds ); - - // Write into output collection - unsigned int iSC=0,iSC_max=seedCollections.size(); - for (;iSC!=iSC_max;++iSC){ - Handle & collection=seedCollections[iSC]; - if (reKeing_ && !(clusterRemovalInfos_[iSC]==edm::InputTag(""))){ - ClusterRemovalRefSetter refSetter(ev, clusterRemovalTokens_[iSC]); - - for (TrajectorySeedCollection::const_iterator iS=collection->begin(); - iS!=collection->end();++iS){ - TrajectorySeed::recHitContainer newRecHitContainer; - newRecHitContainer.reserve(iS->nHits()); - TrajectorySeed::const_iterator iH=iS->recHits().first; - TrajectorySeed::const_iterator iH_end=iS->recHits().second; - //loop seed rechits, copy over and rekey. - for (;iH!=iH_end;++iH){ - newRecHitContainer.push_back(*iH); - refSetter.reKey(&newRecHitContainer.back()); - } - result->push_back(TrajectorySeed(iS->startingState(), - std::move(newRecHitContainer), - iS->direction())); - } - }else{ - //just insert the new seeds as they are - result->insert(result->end(), collection->begin(), collection->end()); +SeedCombiner::~SeedCombiner() {} + +void SeedCombiner::produce(edm::Event& ev, const edm::EventSetup& es) { + // Read inputs, and count total seeds + size_t ninputs = inputCollections_.size(); + size_t nseeds = 0; + std::vector > seedCollections(ninputs); + for (size_t i = 0; i < ninputs; ++i) { + ev.getByToken(inputCollections_[i], seedCollections[i]); + nseeds += seedCollections[i]->size(); + } + + // Prepare output collections, with the correct capacity + auto result = std::make_unique(); + result->reserve(nseeds); + + // Write into output collection + unsigned int iSC = 0, iSC_max = seedCollections.size(); + for (; iSC != iSC_max; ++iSC) { + Handle& collection = seedCollections[iSC]; + if (reKeing_ && !(clusterRemovalInfos_[iSC] == edm::InputTag(""))) { + ClusterRemovalRefSetter refSetter(ev, clusterRemovalTokens_[iSC]); + + for (TrajectorySeedCollection::const_iterator iS = collection->begin(); iS != collection->end(); ++iS) { + TrajectorySeed::recHitContainer newRecHitContainer; + newRecHitContainer.reserve(iS->nHits()); + TrajectorySeed::const_iterator iH = iS->recHits().first; + TrajectorySeed::const_iterator iH_end = iS->recHits().second; + //loop seed rechits, copy over and rekey. + for (; iH != iH_end; ++iH) { + newRecHitContainer.push_back(*iH); + refSetter.reKey(&newRecHitContainer.back()); + } + result->push_back(TrajectorySeed(iS->startingState(), std::move(newRecHitContainer), iS->direction())); } + } else { + //just insert the new seeds as they are + result->insert(result->end(), collection->begin(), collection->end()); } + } - // Save result into the event - ev.put(std::move(result)); + // Save result into the event + ev.put(std::move(result)); } diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.h b/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.h index 729aa3963bcdc..91a5017151bda 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedCombiner.h @@ -7,12 +7,14 @@ #include "DataFormats/TrackerRecHit2D/interface/ClusterRemovalInfo.h" #include "FWCore/Utilities/interface/InputTag.h" -namespace edm { class Event; class EventSetup; class ParameterSet; } - +namespace edm { + class Event; + class EventSetup; + class ParameterSet; +} // namespace edm class dso_hidden SeedCombiner : public edm::stream::EDProducer<> { public: - SeedCombiner(const edm::ParameterSet& cfg); ~SeedCombiner() override; diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.cc b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.cc index 14002e58ae3b3..e37afc5ac829f 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.cc @@ -8,8 +8,8 @@ #include "FWCore/Utilities/interface/ESInputTag.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" -#include "TrackingTools/Records/interface/TrackingComponentsRecord.h" -#include "TrackingTools/Records/interface/TransientRecHitRecord.h" +#include "TrackingTools/Records/interface/TrackingComponentsRecord.h" +#include "TrackingTools/Records/interface/TransientRecHitRecord.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateTransform.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "RecoTracker/TkSeedingLayers/interface/SeedComparitor.h" @@ -17,13 +17,14 @@ namespace { - template - inline - T sqr( T t) {return t*t;} + template + inline T sqr(T t) { + return t * t; + } -} +} // namespace -SeedFromConsecutiveHitsCreator::~SeedFromConsecutiveHitsCreator(){} +SeedFromConsecutiveHitsCreator::~SeedFromConsecutiveHitsCreator() {} void SeedFromConsecutiveHitsCreator::fillDescriptions(edm::ParameterSetDescription& desc) { desc.add("propagator", "PropagatorWithMaterialParabolicMf"); @@ -35,9 +36,9 @@ void SeedFromConsecutiveHitsCreator::fillDescriptions(edm::ParameterSetDescripti desc.add("forceKinematicWithRegionDirection", false); } -void SeedFromConsecutiveHitsCreator::init(const TrackingRegion & iregion, - const edm::EventSetup& es, - const SeedComparitor *ifilter) { +void SeedFromConsecutiveHitsCreator::init(const TrackingRegion& iregion, + const edm::EventSetup& es, + const SeedComparitor* ifilter) { region = &iregion; filter = ifilter; // get tracker @@ -45,172 +46,159 @@ void SeedFromConsecutiveHitsCreator::init(const TrackingRegion & iregion, // get propagator es.get().get(thePropagatorLabel, propagatorHandle); // mag field - es.get().get(mfName_, bfield); + es.get().get(mfName_, bfield); // edm::ESInputTag mfESInputTag(mfName_); - // es.get().get(mfESInputTag, bfield); + // es.get().get(mfESInputTag, bfield); nomField = bfield->nominalValue(); - isBOFF = (0==nomField); + isBOFF = (0 == nomField); edm::ESHandle builderH; es.get().get(TTRHBuilder, builderH); - auto builder = (TkTransientTrackingRecHitBuilder const *)(builderH.product()); + auto builder = (TkTransientTrackingRecHitBuilder const*)(builderH.product()); cloner = (*builder).cloner(); - } -void SeedFromConsecutiveHitsCreator::makeSeed(TrajectorySeedCollection & seedCollection, - const SeedingHitSet & hits) { - if ( hits.size() < 2) return; +void SeedFromConsecutiveHitsCreator::makeSeed(TrajectorySeedCollection& seedCollection, const SeedingHitSet& hits) { + if (hits.size() < 2) + return; GlobalTrajectoryParameters kine; - if (!initialKinematic(kine, hits)) return; + if (!initialKinematic(kine, hits)) + return; - auto sin2Theta = kine.momentum().perp2()/kine.momentum().mag2(); + auto sin2Theta = kine.momentum().perp2() / kine.momentum().mag2(); CurvilinearTrajectoryError error = initialError(sin2Theta); FreeTrajectoryState fts(kine, error); - if(region->direction().x()!=0 && forceKinematicWithRegionDirection_) // a direction was given, check if it is an etaPhi region + if (region->direction().x() != 0 && + forceKinematicWithRegionDirection_) // a direction was given, check if it is an etaPhi region { - const RectangularEtaPhiTrackingRegion * etaPhiRegion = dynamic_cast(region); - if(etaPhiRegion) { - //the following completely reset the kinematics, perhaps it makes no sense and newKine=kine would do better - GlobalVector direction=region->direction()/region->direction().mag(); - GlobalVector momentum=direction*fts.momentum().mag(); - GlobalPoint position=region->origin()+5*direction; - GlobalTrajectoryParameters newKine(position,momentum,fts.charge(),&fts.parameters().magneticField()); - - auto ptMin = region->ptMin(); - CurvilinearTrajectoryError newError; //zeroed - auto & C = newError.matrix(); - constexpr float minC00 = 0.4f; - C[0][0] = std::max(sin2Theta/sqr(ptMin), minC00); - auto zErr = sqr(region->originZBound()); - auto transverseErr = sqr(region->originRBound()); // assume equal cxx cyy - auto twiceDeltaLambda = std::atan(etaPhiRegion->tanLambdaRange().first)-std::atan(etaPhiRegion->tanLambdaRange().second); - auto twiceDeltaPhi = etaPhiRegion->phiMargin().right()+etaPhiRegion->phiMargin().left(); - C[1][1] = twiceDeltaLambda*twiceDeltaLambda; //2 sigma of what given in input - C[2][2] = twiceDeltaPhi*twiceDeltaPhi; - C[3][3] = transverseErr; - C[4][4] = zErr*sin2Theta + transverseErr*(1.f-sin2Theta); - fts = FreeTrajectoryState(newKine,newError); + const RectangularEtaPhiTrackingRegion* etaPhiRegion = dynamic_cast(region); + if (etaPhiRegion) { + //the following completely reset the kinematics, perhaps it makes no sense and newKine=kine would do better + GlobalVector direction = region->direction() / region->direction().mag(); + GlobalVector momentum = direction * fts.momentum().mag(); + GlobalPoint position = region->origin() + 5 * direction; + GlobalTrajectoryParameters newKine(position, momentum, fts.charge(), &fts.parameters().magneticField()); + + auto ptMin = region->ptMin(); + CurvilinearTrajectoryError newError; //zeroed + auto& C = newError.matrix(); + constexpr float minC00 = 0.4f; + C[0][0] = std::max(sin2Theta / sqr(ptMin), minC00); + auto zErr = sqr(region->originZBound()); + auto transverseErr = sqr(region->originRBound()); // assume equal cxx cyy + auto twiceDeltaLambda = + std::atan(etaPhiRegion->tanLambdaRange().first) - std::atan(etaPhiRegion->tanLambdaRange().second); + auto twiceDeltaPhi = etaPhiRegion->phiMargin().right() + etaPhiRegion->phiMargin().left(); + C[1][1] = twiceDeltaLambda * twiceDeltaLambda; //2 sigma of what given in input + C[2][2] = twiceDeltaPhi * twiceDeltaPhi; + C[3][3] = transverseErr; + C[4][4] = zErr * sin2Theta + transverseErr * (1.f - sin2Theta); + fts = FreeTrajectoryState(newKine, newError); } } - - buildSeed(seedCollection,hits,fts); + buildSeed(seedCollection, hits, fts); } - - -bool SeedFromConsecutiveHitsCreator::initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const{ - +bool SeedFromConsecutiveHitsCreator::initialKinematic(GlobalTrajectoryParameters& kine, + const SeedingHitSet& hits) const { SeedingHitSet::ConstRecHitPointer tth1 = hits[0]; SeedingHitSet::ConstRecHitPointer tth2 = hits[1]; - + const GlobalPoint& vertexPos = region->origin(); - FastHelix helix(tth2->globalPosition(), tth1->globalPosition(), vertexPos, nomField,&*bfield); + FastHelix helix(tth2->globalPosition(), tth1->globalPosition(), vertexPos, nomField, &*bfield); if (helix.isValid()) { kine = helix.stateAtVertex(); } else { GlobalVector initMomentum(tth2->globalPosition() - vertexPos); - initMomentum *= (100.f/initMomentum.perp()); + initMomentum *= (100.f / initMomentum.perp()); kine = GlobalTrajectoryParameters(vertexPos, initMomentum, 1, &*bfield); - } - - if UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { - kine = GlobalTrajectoryParameters(kine.position(), - kine.momentum().unit() * theBOFFMomentum, - kine.charge(), - &*bfield); } - return (filter ? filter->compatible(hits, kine, helix) : true); -} - + if + UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { + kine = GlobalTrajectoryParameters( + kine.position(), kine.momentum().unit() * theBOFFMomentum, kine.charge(), &*bfield); + } + return (filter ? filter->compatible(hits, kine, helix) : true); +} -CurvilinearTrajectoryError -SeedFromConsecutiveHitsCreator::initialError(float sin2Theta) const -{ +CurvilinearTrajectoryError SeedFromConsecutiveHitsCreator::initialError(float sin2Theta) const { // Set initial uncertainty on track parameters, using only P.V. constraint and no hit // information. CurvilinearTrajectoryError newError; // zeroed - auto & C = newError.matrix(); + auto& C = newError.matrix(); -// FIXME: minC00. Prevent apriori uncertainty in 1/P from being too small, -// to avoid instabilities. -// N.B. This parameter needs optimising ... + // FIXME: minC00. Prevent apriori uncertainty in 1/P from being too small, + // to avoid instabilities. + // N.B. This parameter needs optimising ... // Probably OK based on quick study: KS 22/11/12. auto sin2th = sin2Theta; auto minC00 = sqr(theMinOneOverPtError); - C[0][0] = std::max(sin2th/sqr(region->ptMin()), minC00); + C[0][0] = std::max(sin2th / sqr(region->ptMin()), minC00); auto zErr = sqr(region->originZBound()); - auto transverseErr = sqr(theOriginTransverseErrorMultiplier*region->originRBound()); + auto transverseErr = sqr(theOriginTransverseErrorMultiplier * region->originRBound()); C[1][1] = C[2][2] = 1.; // no good reason. no bad reason.... C[3][3] = transverseErr; - C[4][4] = zErr*sin2th + transverseErr*(1.f-sin2th); + C[4][4] = zErr * sin2th + transverseErr * (1.f - sin2th); return newError; } -void SeedFromConsecutiveHitsCreator::buildSeed( - TrajectorySeedCollection & seedCollection, - const SeedingHitSet & hits, - const FreeTrajectoryState & fts) const -{ - const Propagator* propagator = &(*propagatorHandle); - +void SeedFromConsecutiveHitsCreator::buildSeed(TrajectorySeedCollection& seedCollection, + const SeedingHitSet& hits, + const FreeTrajectoryState& fts) const { + const Propagator* propagator = &(*propagatorHandle); + // get updator - KFUpdator updator; - + KFUpdator updator; + // Now update initial state track using information from seed hits. - + TrajectoryStateOnSurface updatedState; edm::OwnVector seedHits; - + const TrackingRecHit* hit = nullptr; - for ( unsigned int iHit = 0; iHit < hits.size(); iHit++) { + for (unsigned int iHit = 0; iHit < hits.size(); iHit++) { hit = hits[iHit]->hit(); - TrajectoryStateOnSurface state = (iHit==0) ? - propagator->propagate(fts,tracker->idToDet(hit->geographicalId())->surface()) - : propagator->propagate(updatedState, tracker->idToDet(hit->geographicalId())->surface()); - if (!state.isValid()) return; - - SeedingHitSet::ConstRecHitPointer tth = hits[iHit]; - - std::unique_ptr newtth(refitHit( tth, state)); - - if (!checkHit(state,&*newtth)) return; - - updatedState = updator.update(state, *newtth); - if (!updatedState.isValid()) return; - - seedHits.push_back(newtth.release()); + TrajectoryStateOnSurface state = + (iHit == 0) ? propagator->propagate(fts, tracker->idToDet(hit->geographicalId())->surface()) + : propagator->propagate(updatedState, tracker->idToDet(hit->geographicalId())->surface()); + if (!state.isValid()) + return; - } + SeedingHitSet::ConstRecHitPointer tth = hits[iHit]; - if(!hit) return; - - PTrajectoryStateOnDet const & PTraj = - trajectoryStateTransform::persistentState(updatedState, hit->geographicalId().rawId()); - seedCollection.emplace_back(PTraj,std::move(seedHits),alongMomentum); + std::unique_ptr newtth(refitHit(tth, state)); -} + if (!checkHit(state, &*newtth)) + return; -SeedingHitSet::RecHitPointer -SeedFromConsecutiveHitsCreator::refitHit(SeedingHitSet::ConstRecHitPointer hit, - const TrajectoryStateOnSurface &state) const -{ - return (SeedingHitSet::RecHitPointer)(cloner(*hit,state)); + updatedState = updator.update(state, *newtth); + if (!updatedState.isValid()) + return; + + seedHits.push_back(newtth.release()); + } + + if (!hit) + return; + + PTrajectoryStateOnDet const& PTraj = + trajectoryStateTransform::persistentState(updatedState, hit->geographicalId().rawId()); + seedCollection.emplace_back(PTraj, std::move(seedHits), alongMomentum); } -bool -SeedFromConsecutiveHitsCreator::checkHit( - const TrajectoryStateOnSurface &tsos, - SeedingHitSet::ConstRecHitPointer hit) const -{ - return (filter ? filter->compatible(tsos,hit) : true); +SeedingHitSet::RecHitPointer SeedFromConsecutiveHitsCreator::refitHit(SeedingHitSet::ConstRecHitPointer hit, + const TrajectoryStateOnSurface& state) const { + return (SeedingHitSet::RecHitPointer)(cloner(*hit, state)); } +bool SeedFromConsecutiveHitsCreator::checkHit(const TrajectoryStateOnSurface& tsos, + SeedingHitSet::ConstRecHitPointer hit) const { + return (filter ? filter->compatible(tsos, hit) : true); +} diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.h b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.h index 3c125d12f112e..ad6b4cbf86db8 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsCreator.h @@ -15,71 +15,59 @@ #include "DataFormats/TrackerRecHit2D/interface/BaseTrackerRecHit.h" #include "DataFormats/TrackingRecHit/interface/mayown_ptr.h" -namespace edm { class ParameterSetDescription; } +namespace edm { + class ParameterSetDescription; +} class FreeTrajectoryState; class dso_hidden SeedFromConsecutiveHitsCreator : public SeedCreator { public: - - SeedFromConsecutiveHitsCreator( const edm::ParameterSet & cfg) - : thePropagatorLabel (cfg.getParameter("propagator")) - , theBOFFMomentum (cfg.getParameter("SeedMomentumForBOFF")) - , theOriginTransverseErrorMultiplier(cfg.getParameter("OriginTransverseErrorMultiplier")) - , theMinOneOverPtError (cfg.getParameter("MinOneOverPtError")) - , TTRHBuilder (cfg.getParameter("TTRHBuilder")) - , mfName_(cfg.getParameter("magneticField")) - , forceKinematicWithRegionDirection_(cfg.getParameter("forceKinematicWithRegionDirection")) - {} + SeedFromConsecutiveHitsCreator(const edm::ParameterSet &cfg) + : thePropagatorLabel(cfg.getParameter("propagator")), + theBOFFMomentum(cfg.getParameter("SeedMomentumForBOFF")), + theOriginTransverseErrorMultiplier(cfg.getParameter("OriginTransverseErrorMultiplier")), + theMinOneOverPtError(cfg.getParameter("MinOneOverPtError")), + TTRHBuilder(cfg.getParameter("TTRHBuilder")), + mfName_(cfg.getParameter("magneticField")), + forceKinematicWithRegionDirection_(cfg.getParameter("forceKinematicWithRegionDirection")) {} //dtor ~SeedFromConsecutiveHitsCreator() override; - static void fillDescriptions(edm::ParameterSetDescription& desc); + static void fillDescriptions(edm::ParameterSetDescription &desc); static const char *fillDescriptionsLabel() { return "ConsecutiveHits"; } // initialize the "event dependent state" - void init(const TrackingRegion & region, - const edm::EventSetup& es, - const SeedComparitor *filter) final; + void init(const TrackingRegion ®ion, const edm::EventSetup &es, const SeedComparitor *filter) final; // make job // fill seedCollection with the "TrajectorySeed" - void makeSeed(TrajectorySeedCollection & seedCollection, - const SeedingHitSet & hits) final; - + void makeSeed(TrajectorySeedCollection &seedCollection, const SeedingHitSet &hits) final; private: + virtual bool initialKinematic(GlobalTrajectoryParameters &kine, const SeedingHitSet &hits) const; - virtual bool initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const; - - - bool checkHit( - const TrajectoryStateOnSurface &tsos, - SeedingHitSet::ConstRecHitPointer hit) const dso_hidden; + bool checkHit(const TrajectoryStateOnSurface &tsos, SeedingHitSet::ConstRecHitPointer hit) const dso_hidden; + CurvilinearTrajectoryError initialError(float sin2Theta) const dso_hidden; - CurvilinearTrajectoryError initialError(float sin2Theta) const dso_hidden; + void buildSeed(TrajectorySeedCollection &seedCollection, + const SeedingHitSet &hits, + const FreeTrajectoryState &fts) const dso_hidden; - void buildSeed(TrajectorySeedCollection & seedCollection, - const SeedingHitSet & hits, - const FreeTrajectoryState & fts) const dso_hidden; - - SeedingHitSet::RecHitPointer - refitHit(SeedingHitSet::ConstRecHitPointer hit, - const TrajectoryStateOnSurface & state) const dso_hidden; + SeedingHitSet::RecHitPointer refitHit(SeedingHitSet::ConstRecHitPointer hit, + const TrajectoryStateOnSurface &state) const dso_hidden; protected: - std::string thePropagatorLabel; float theBOFFMomentum; float theOriginTransverseErrorMultiplier; float theMinOneOverPtError; - const TrackingRegion * region = nullptr; + const TrackingRegion *region = nullptr; const SeedComparitor *filter = nullptr; edm::ESHandle tracker; - edm::ESHandle propagatorHandle; + edm::ESHandle propagatorHandle; edm::ESHandle bfield; float nomField; bool isBOFF = false; @@ -88,7 +76,5 @@ class dso_hidden SeedFromConsecutiveHitsCreator : public SeedCreator { bool forceKinematicWithRegionDirection_; TkClonerImpl cloner; - - }; #endif diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.cc b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.cc index db665094c0d4f..f50c8bf7f3e4b 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.cc @@ -1,11 +1,8 @@ #include "SeedFromConsecutiveHitsStraightLineCreator.h" #include "RecoTracker/TkTrackingRegions/interface/TrackingRegion.h" - - -bool SeedFromConsecutiveHitsStraightLineCreator::initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const { - +bool SeedFromConsecutiveHitsStraightLineCreator::initialKinematic(GlobalTrajectoryParameters& kine, + const SeedingHitSet& hits) const { const SeedingHitSet::ConstRecHitPointer& tth1 = hits[0]; const SeedingHitSet::ConstRecHitPointer& tth2 = hits[1]; @@ -14,12 +11,10 @@ bool SeedFromConsecutiveHitsStraightLineCreator::initialKinematic(GlobalTrajecto // Assume initial state is straight line passing through beam spot // with direction given by innermost two seed hits (with big uncertainty) GlobalVector initMomentum(tth2->globalPosition() - tth1->globalPosition()); - double rescale = 1000./initMomentum.perp(); - initMomentum *= rescale; // set to approximately infinite momentum - TrackCharge q = 1; // irrelevant, since infinite momentum + double rescale = 1000. / initMomentum.perp(); + initMomentum *= rescale; // set to approximately infinite momentum + TrackCharge q = 1; // irrelevant, since infinite momentum kine = GlobalTrajectoryParameters(vertexPos, initMomentum, q, &*bfield); return true; - } - diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.h b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.h index ec91f3de3615d..bc38d2e4bae96 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsStraightLineCreator.h @@ -7,18 +7,11 @@ class FreeTrajectoryState; class dso_hidden SeedFromConsecutiveHitsStraightLineCreator final : public SeedFromConsecutiveHitsCreator { public: + SeedFromConsecutiveHitsStraightLineCreator(const edm::ParameterSet& cfg) : SeedFromConsecutiveHitsCreator(cfg) {} - SeedFromConsecutiveHitsStraightLineCreator( const edm::ParameterSet & cfg): - SeedFromConsecutiveHitsCreator(cfg) { } - - ~SeedFromConsecutiveHitsStraightLineCreator() override{} + ~SeedFromConsecutiveHitsStraightLineCreator() override {} private: - - bool initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const override; - - + bool initialKinematic(GlobalTrajectoryParameters& kine, const SeedingHitSet& hits) const override; }; #endif - diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.cc b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.cc index 7ab4ab788f720..3ea0e70787146 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.cc @@ -9,46 +9,46 @@ #include "RecoTracker/TkSeedGenerator/interface/FastHelix.h" #include "DataFormats/SiStripDetId/interface/SiStripDetId.h" -bool SeedFromConsecutiveHitsTripletOnlyCreator::initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const { - +bool SeedFromConsecutiveHitsTripletOnlyCreator::initialKinematic(GlobalTrajectoryParameters& kine, + const SeedingHitSet& hits) const { SeedingHitSet::ConstRecHitPointer tth1 = hits[0]; SeedingHitSet::ConstRecHitPointer tth2 = hits[1]; - - - if (hits.size()==3 && !( trackerHitRTTI::isSingleType(*hits[2]) && (hits[2]->geographicalId().subdetId()==SiStripDetId::TID || - hits[2]->geographicalId().subdetId()==SiStripDetId::TEC ) - ) ) { + if (hits.size() == 3 && + !(trackerHitRTTI::isSingleType(*hits[2]) && (hits[2]->geographicalId().subdetId() == SiStripDetId::TID || + hits[2]->geographicalId().subdetId() == SiStripDetId::TEC))) { //if 3rd hit is mono and endcap pT is not well defined so take initial state from pair SeedingHitSet::ConstRecHitPointer tth3 = hits[2]; - FastHelix helix(tth3->globalPosition(), tth2->globalPosition(), tth1->globalPosition(), nomField, &*bfield, tth1->globalPosition()); + FastHelix helix(tth3->globalPosition(), + tth2->globalPosition(), + tth1->globalPosition(), + nomField, + &*bfield, + tth1->globalPosition()); kine = helix.stateAtVertex(); - if UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { - kine = GlobalTrajectoryParameters(kine.position(), - kine.momentum().unit() * theBOFFMomentum, - kine.charge(), - &*bfield); - } - return (filter ? filter->compatible(hits, kine, helix) : true); - } - + if + UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { + kine = GlobalTrajectoryParameters( + kine.position(), kine.momentum().unit() * theBOFFMomentum, kine.charge(), &*bfield); + } + return (filter ? filter->compatible(hits, kine, helix) : true); + } + const GlobalPoint& vertexPos = region->origin(); - FastHelix helix(tth2->globalPosition(), tth1->globalPosition(), vertexPos, nomField,&*bfield); + FastHelix helix(tth2->globalPosition(), tth1->globalPosition(), vertexPos, nomField, &*bfield); if (helix.isValid()) { kine = helix.stateAtVertex(); } else { GlobalVector initMomentum(tth2->globalPosition() - vertexPos); - initMomentum *= (100./initMomentum.perp()); + initMomentum *= (100. / initMomentum.perp()); kine = GlobalTrajectoryParameters(vertexPos, initMomentum, 1, &*bfield); - } - - if UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { - kine = GlobalTrajectoryParameters(kine.position(), - kine.momentum().unit() * theBOFFMomentum, - kine.charge(), - &*bfield); } + + if + UNLIKELY(isBOFF && (theBOFFMomentum > 0)) { + kine = GlobalTrajectoryParameters( + kine.position(), kine.momentum().unit() * theBOFFMomentum, kine.charge(), &*bfield); + } return (filter ? filter->compatible(hits, kine, helix) : true); } diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.h b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.h index 19b02dd45d1cf..932c518ce8096 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedFromConsecutiveHitsTripletOnlyCreator.h @@ -5,23 +5,16 @@ class dso_hidden SeedFromConsecutiveHitsTripletOnlyCreator final : public SeedFromConsecutiveHitsCreator { public: - - SeedFromConsecutiveHitsTripletOnlyCreator( const edm::ParameterSet & cfg): - SeedFromConsecutiveHitsCreator(cfg) { } + SeedFromConsecutiveHitsTripletOnlyCreator(const edm::ParameterSet& cfg) : SeedFromConsecutiveHitsCreator(cfg) {} static void fillDescriptions(edm::ParameterSetDescription& desc) { SeedFromConsecutiveHitsCreator::fillDescriptions(desc); } - static const char *fillDescriptionsLabel() { return "ConsecutiveHitsTripletOnly"; } + static const char* fillDescriptionsLabel() { return "ConsecutiveHitsTripletOnly"; } - ~SeedFromConsecutiveHitsTripletOnlyCreator() override{} + ~SeedFromConsecutiveHitsTripletOnlyCreator() override {} private: - - bool initialKinematic(GlobalTrajectoryParameters & kine, - const SeedingHitSet & hits) const override; - - + bool initialKinematic(GlobalTrajectoryParameters& kine, const SeedingHitSet& hits) const override; }; #endif - diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.cc b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.cc index 0ff694b083572..56e3aed62672a 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.cc +++ b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.cc @@ -21,17 +21,21 @@ #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" - #include "FWCore/MessageLogger/interface/MessageLogger.h" #include using namespace edm; using namespace reco; -template T sqr( T t) {return t*t;} +template +T sqr(T t) { + return t * t; +} typedef SeedingHitSet::ConstRecHitPointer Hit; -struct HitLessByRadius { bool operator() (const Hit& h1, const Hit & h2) { return h1->globalPosition().perp2() < h2->globalPosition().perp2(); } }; +struct HitLessByRadius { + bool operator()(const Hit& h1, const Hit& h2) { return h1->globalPosition().perp2() < h2->globalPosition().perp2(); } +}; void SeedGeneratorFromProtoTracksEDProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; @@ -45,109 +49,106 @@ void SeedGeneratorFromProtoTracksEDProducer::fillDescriptions(edm::Configuration desc.add("usePV", false); edm::ParameterSetDescription psd0; - psd0.add("ComponentName",std::string("SeedFromConsecutiveHitsCreator")); - psd0.add("propagator",std::string("PropagatorWithMaterial")); - psd0.add("SeedMomentumForBOFF",5.0); - psd0.add("OriginTransverseErrorMultiplier",1.0); - psd0.add("MinOneOverPtError",1.0); - psd0.add("magneticField",std::string("")); - psd0.add("TTRHBuilder",std::string("WithTrackAngle")); - psd0.add("forceKinematicWithRegionDirection",false); - desc.add("SeedCreatorPSet",psd0); - + psd0.add("ComponentName", std::string("SeedFromConsecutiveHitsCreator")); + psd0.add("propagator", std::string("PropagatorWithMaterial")); + psd0.add("SeedMomentumForBOFF", 5.0); + psd0.add("OriginTransverseErrorMultiplier", 1.0); + psd0.add("MinOneOverPtError", 1.0); + psd0.add("magneticField", std::string("")); + psd0.add("TTRHBuilder", std::string("WithTrackAngle")); + psd0.add("forceKinematicWithRegionDirection", false); + desc.add("SeedCreatorPSet", psd0); + descriptions.add("SeedGeneratorFromProtoTracksEDProducer", desc); } - SeedGeneratorFromProtoTracksEDProducer::SeedGeneratorFromProtoTracksEDProducer(const ParameterSet& cfg) - : theConfig(cfg) - , originHalfLength ( cfg.getParameter("originHalfLength") ) - , originRadius ( cfg.getParameter("originRadius") ) - , useProtoTrackKinematics ( cfg.getParameter("useProtoTrackKinematics") ) - , useEventsWithNoVertex ( cfg.getParameter("useEventsWithNoVertex") ) - , builderName ( cfg.getParameter("TTRHBuilder") ) - , usePV_ ( cfg.getParameter( "usePV" ) ) - , theInputCollectionTag ( consumes (cfg.getParameter("InputCollection")) ) - , theInputVertexCollectionTag ( consumes(cfg.getParameter("InputVertexCollection")) ) -{ + : theConfig(cfg), + originHalfLength(cfg.getParameter("originHalfLength")), + originRadius(cfg.getParameter("originRadius")), + useProtoTrackKinematics(cfg.getParameter("useProtoTrackKinematics")), + useEventsWithNoVertex(cfg.getParameter("useEventsWithNoVertex")), + builderName(cfg.getParameter("TTRHBuilder")), + usePV_(cfg.getParameter("usePV")), + theInputCollectionTag(consumes(cfg.getParameter("InputCollection"))), + theInputVertexCollectionTag( + consumes(cfg.getParameter("InputVertexCollection"))) { produces(); - - - } - -void SeedGeneratorFromProtoTracksEDProducer::produce(edm::Event& ev, const edm::EventSetup& es) -{ +void SeedGeneratorFromProtoTracksEDProducer::produce(edm::Event& ev, const edm::EventSetup& es) { auto result = std::make_unique(); Handle trks; ev.getByToken(theInputCollectionTag, trks); - const TrackCollection &protos = *(trks.product()); - + const TrackCollection& protos = *(trks.product()); + edm::Handle vertices; bool foundVertices = ev.getByToken(theInputVertexCollectionTag, vertices); //const reco::VertexCollection & vertices = *(h_vertices.product()); /// /// need optimization: all es stuff should go out of the loop - /// - for (TrackCollection::const_iterator it=protos.begin(); it!= protos.end(); ++it) { - const Track & proto = (*it); + /// + for (TrackCollection::const_iterator it = protos.begin(); it != protos.end(); ++it) { + const Track& proto = (*it); GlobalPoint vtx(proto.vertex().x(), proto.vertex().y(), proto.vertex().z()); // check the compatibility with a primary vertex bool keepTrack = false; - if ( (!foundVertices) || vertices->empty() ) { - if (useEventsWithNoVertex) keepTrack = true; - } - else if (usePV_){ - - GlobalPoint aPV(vertices->begin()->position().x(),vertices->begin()->position().y(),vertices->begin()->position().z()); - double distR2 = sqr(vtx.x()-aPV.x()) +sqr(vtx.y()-aPV.y()); - double distZ = fabs(vtx.z()-aPV.z()); - if ( distR2 < sqr(originRadius) && distZ < originHalfLength ) { + if ((!foundVertices) || vertices->empty()) { + if (useEventsWithNoVertex) + keepTrack = true; + } else if (usePV_) { + GlobalPoint aPV( + vertices->begin()->position().x(), vertices->begin()->position().y(), vertices->begin()->position().z()); + double distR2 = sqr(vtx.x() - aPV.x()) + sqr(vtx.y() - aPV.y()); + double distZ = fabs(vtx.z() - aPV.z()); + if (distR2 < sqr(originRadius) && distZ < originHalfLength) { keepTrack = true; } - } - else { - for (reco::VertexCollection::const_iterator iv=vertices->begin(); iv!= vertices->end(); ++iv) { - GlobalPoint aPV(iv->position().x(),iv->position().y(),iv->position().z()); - double distR2 = sqr(vtx.x()-aPV.x()) +sqr(vtx.y()-aPV.y()); - double distZ = fabs(vtx.z()-aPV.z()); - if ( distR2 < sqr(originRadius) && distZ < originHalfLength ) { - keepTrack = true; - break; + } else { + for (reco::VertexCollection::const_iterator iv = vertices->begin(); iv != vertices->end(); ++iv) { + GlobalPoint aPV(iv->position().x(), iv->position().y(), iv->position().z()); + double distR2 = sqr(vtx.x() - aPV.x()) + sqr(vtx.y() - aPV.y()); + double distZ = fabs(vtx.z() - aPV.z()); + if (distR2 < sqr(originRadius) && distZ < originHalfLength) { + keepTrack = true; + break; } } } - if (!keepTrack) continue; + if (!keepTrack) + continue; - if ( useProtoTrackKinematics ) { - SeedFromProtoTrack seedFromProtoTrack( proto, es); - if (seedFromProtoTrack.isValid()) (*result).push_back( seedFromProtoTrack.trajectorySeed() ); + if (useProtoTrackKinematics) { + SeedFromProtoTrack seedFromProtoTrack(proto, es); + if (seedFromProtoTrack.isValid()) + (*result).push_back(seedFromProtoTrack.trajectorySeed()); } else { edm::ESHandle ttrhbESH; - es.get().get(builderName,ttrhbESH); + es.get().get(builderName, ttrhbESH); std::vector hits; for (unsigned int iHit = 0, nHits = proto.recHitsSize(); iHit < nHits; ++iHit) { TrackingRecHitRef refHit = proto.recHit(iHit); - if(refHit->isValid()) hits.push_back((Hit)&(*refHit)); + if (refHit->isValid()) + hits.push_back((Hit) & (*refHit)); } sort(hits.begin(), hits.end(), HitLessByRadius()); if (hits.size() > 1) { - double mom_perp = sqrt(proto.momentum().x()*proto.momentum().x()+proto.momentum().y()*proto.momentum().y()); - GlobalTrackingRegion region(mom_perp, vtx, 0.2, 0.2); - - edm::ParameterSet seedCreatorPSet = theConfig.getParameter("SeedCreatorPSet"); - SeedFromConsecutiveHitsCreator seedCreator(seedCreatorPSet); - seedCreator.init(region, es, nullptr); - seedCreator.makeSeed(*result, SeedingHitSet(hits[0], hits[1], hits.size() >2 ? hits[2] : SeedingHitSet::nullPtr() )); + double mom_perp = + sqrt(proto.momentum().x() * proto.momentum().x() + proto.momentum().y() * proto.momentum().y()); + GlobalTrackingRegion region(mom_perp, vtx, 0.2, 0.2); + + edm::ParameterSet seedCreatorPSet = theConfig.getParameter("SeedCreatorPSet"); + SeedFromConsecutiveHitsCreator seedCreator(seedCreatorPSet); + seedCreator.init(region, es, nullptr); + seedCreator.makeSeed(*result, + SeedingHitSet(hits[0], hits[1], hits.size() > 2 ? hits[2] : SeedingHitSet::nullPtr())); } } - } + } ev.put(std::move(result)); } - diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.h b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.h index e50a5047ec01a..e69cc43188925 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromProtoTracksEDProducer.h @@ -6,15 +6,17 @@ #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" -namespace edm { class Event; class EventSetup; } - +namespace edm { + class Event; + class EventSetup; +} // namespace edm class dso_hidden SeedGeneratorFromProtoTracksEDProducer : public edm::stream::EDProducer<> { public: SeedGeneratorFromProtoTracksEDProducer(const edm::ParameterSet& cfg); - ~SeedGeneratorFromProtoTracksEDProducer() override{} + ~SeedGeneratorFromProtoTracksEDProducer() override {} void produce(edm::Event& ev, const edm::EventSetup& es) override; - static void fillDescriptions(edm::ConfigurationDescriptions & descriptions); + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: const edm::ParameterSet theConfig; @@ -26,6 +28,5 @@ class dso_hidden SeedGeneratorFromProtoTracksEDProducer : public edm::stream::ED const bool usePV_; const edm::EDGetTokenT theInputCollectionTag; const edm::EDGetTokenT theInputVertexCollectionTag; - }; #endif diff --git a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromRegionHitsEDProducer.h b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromRegionHitsEDProducer.h index 2c19acd9bc6bf..8932b3b3ed365 100644 --- a/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromRegionHitsEDProducer.h +++ b/RecoTracker/TkSeedGenerator/plugins/SeedGeneratorFromRegionHitsEDProducer.h @@ -5,14 +5,16 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "RecoTracker/SpecialSeedGenerators/interface/ClusterChecker.h" -namespace edm { class Event; class EventSetup; } +namespace edm { + class Event; + class EventSetup; +} // namespace edm class SeedGeneratorFromRegionHits; class TrackingRegionProducer; class dso_hidden SeedGeneratorFromRegionHitsEDProducer : public edm::stream::EDProducer<> { public: - SeedGeneratorFromRegionHitsEDProducer(const edm::ParameterSet& cfg); ~SeedGeneratorFromRegionHitsEDProducer() override; diff --git a/RecoTracker/TkSeedGenerator/src/ClusterChecker.cc b/RecoTracker/TkSeedGenerator/src/ClusterChecker.cc index 01a70790773ba..c17e272cb32bc 100644 --- a/RecoTracker/TkSeedGenerator/src/ClusterChecker.cc +++ b/RecoTracker/TkSeedGenerator/src/ClusterChecker.cc @@ -7,105 +7,104 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" -ClusterChecker::ClusterChecker(const edm::ParameterSet & conf, - edm::ConsumesCollector && iC): - ClusterChecker(conf, iC) -{} +ClusterChecker::ClusterChecker(const edm::ParameterSet& conf, edm::ConsumesCollector&& iC) : ClusterChecker(conf, iC) {} -ClusterChecker::ClusterChecker(const edm::ParameterSet & conf, - edm::ConsumesCollector & iC): - doACheck_(conf.getParameter("doClusterCheck")), - selector_(conf.getParameter("doClusterCheck") && conf.existsAs("cut") ? - conf.getParameter("cut") : - "") -{ - if (doACheck_){ - clusterCollectionInputTag_ = conf.getParameter("ClusterCollectionLabel"); - pixelClusterCollectionInputTag_ = conf.getParameter("PixelClusterCollectionLabel"); - token_sc = iC.consumes >(clusterCollectionInputTag_); - token_pc = iC.consumes >(pixelClusterCollectionInputTag_); - maxNrOfCosmicClusters_ = conf.getParameter("MaxNumberOfCosmicClusters"); - maxNrOfPixelClusters_ = conf.getParameter("MaxNumberOfPixelClusters"); - if (conf.existsAs("DontCountDetsAboveNClusters")) { - ignoreDetsAboveNClusters_ = conf.getParameter("DontCountDetsAboveNClusters"); - } else { - ignoreDetsAboveNClusters_ = 0; - } +ClusterChecker::ClusterChecker(const edm::ParameterSet& conf, edm::ConsumesCollector& iC) + : doACheck_(conf.getParameter("doClusterCheck")), + selector_(conf.getParameter("doClusterCheck") && conf.existsAs("cut") + ? conf.getParameter("cut") + : "") { + if (doACheck_) { + clusterCollectionInputTag_ = conf.getParameter("ClusterCollectionLabel"); + pixelClusterCollectionInputTag_ = conf.getParameter("PixelClusterCollectionLabel"); + token_sc = iC.consumes >(clusterCollectionInputTag_); + token_pc = iC.consumes >(pixelClusterCollectionInputTag_); + maxNrOfCosmicClusters_ = conf.getParameter("MaxNumberOfCosmicClusters"); + maxNrOfPixelClusters_ = conf.getParameter("MaxNumberOfPixelClusters"); + if (conf.existsAs("DontCountDetsAboveNClusters")) { + ignoreDetsAboveNClusters_ = conf.getParameter("DontCountDetsAboveNClusters"); + } else { + ignoreDetsAboveNClusters_ = 0; } + } } void ClusterChecker::fillDescriptions(edm::ParameterSetDescription& desc) { desc.add("doClusterCheck", true); - desc.add("MaxNumberOfCosmicClusters", 400000); + desc.add("MaxNumberOfCosmicClusters", 400000); desc.add("ClusterCollectionLabel", edm::InputTag("siStripClusters")); desc.add("MaxNumberOfPixelClusters", 40000); desc.add("PixelClusterCollectionLabel", edm::InputTag("siPixelClusters")); - desc.add("cut", "strip < 400000 && pixel < 40000 && (strip < 50000 + 10*pixel) && (pixel < 5000 + 0.1*strip)"); + desc.add("cut", + "strip < 400000 && pixel < 40000 && (strip < 50000 + 10*pixel) && (pixel < 5000 + 0.1*strip)"); } +ClusterChecker::~ClusterChecker() {} -ClusterChecker::~ClusterChecker() -{ -} - -size_t ClusterChecker::tooManyClusters(const edm::Event & e) const -{ - if (!doACheck_) return 0; +size_t ClusterChecker::tooManyClusters(const edm::Event& e) const { + if (!doACheck_) + return 0; - // get special input for cosmic cluster multiplicity filter - edm::Handle > clusterDSV; - e.getByToken(token_sc, clusterDSV); - reco::utils::ClusterTotals totals; - if (!clusterDSV.failedToGet()) { - const edmNew::DetSetVector & input = *clusterDSV; + // get special input for cosmic cluster multiplicity filter + edm::Handle > clusterDSV; + e.getByToken(token_sc, clusterDSV); + reco::utils::ClusterTotals totals; + if (!clusterDSV.failedToGet()) { + const edmNew::DetSetVector& input = *clusterDSV; - if (ignoreDetsAboveNClusters_ == 0) { - totals.strip = input.dataSize(); - totals.stripdets = input.size(); - } else { - //loop over detectors - totals.strip = 0; - totals.stripdets = 0; - edmNew::DetSetVector::const_iterator DSViter=input.begin(), DSViter_end=input.end(); - for (; DSViter!=DSViter_end; DSViter++ ) { - size_t siz = DSViter->size(); - if (siz > ignoreDetsAboveNClusters_) continue; - totals.strip += siz; - totals.stripdets++; - } - } + if (ignoreDetsAboveNClusters_ == 0) { + totals.strip = input.dataSize(); + totals.stripdets = input.size(); + } else { + //loop over detectors + totals.strip = 0; + totals.stripdets = 0; + edmNew::DetSetVector::const_iterator DSViter = input.begin(), DSViter_end = input.end(); + for (; DSViter != DSViter_end; DSViter++) { + size_t siz = DSViter->size(); + if (siz > ignoreDetsAboveNClusters_) + continue; + totals.strip += siz; + totals.stripdets++; + } } - if (totals.strip > int(maxNrOfCosmicClusters_)) return totals.strip; + } + if (totals.strip > int(maxNrOfCosmicClusters_)) + return totals.strip; - // get special input for pixel cluster multiplicity filter - edm::Handle > pixelClusterDSV; - e.getByToken(token_pc, pixelClusterDSV); - if (!pixelClusterDSV.failedToGet()) { - const edmNew::DetSetVector & input = *pixelClusterDSV; + // get special input for pixel cluster multiplicity filter + edm::Handle > pixelClusterDSV; + e.getByToken(token_pc, pixelClusterDSV); + if (!pixelClusterDSV.failedToGet()) { + const edmNew::DetSetVector& input = *pixelClusterDSV; - if (ignoreDetsAboveNClusters_ == 0) { - totals.pixel = input.dataSize(); - totals.pixeldets = input.size(); - } else { - //loop over detectors - totals.pixel = 0; - totals.pixeldets = 0; - edmNew::DetSetVector::const_iterator DSViter=input.begin(), DSViter_end=input.end(); - for (; DSViter!=DSViter_end; DSViter++ ) { - size_t siz = DSViter->size(); - if (siz > ignoreDetsAboveNClusters_) continue; - totals.pixel += siz; - totals.pixeldets++; - } - } + if (ignoreDetsAboveNClusters_ == 0) { + totals.pixel = input.dataSize(); + totals.pixeldets = input.size(); + } else { + //loop over detectors + totals.pixel = 0; + totals.pixeldets = 0; + edmNew::DetSetVector::const_iterator DSViter = input.begin(), DSViter_end = input.end(); + for (; DSViter != DSViter_end; DSViter++) { + size_t siz = DSViter->size(); + if (siz > ignoreDetsAboveNClusters_) + continue; + totals.pixel += siz; + totals.pixeldets++; + } } - else{ - //say something's wrong. - edm::LogError("ClusterChecker")<<"could not get any SiPixel cluster collections of type edm::DetSetVector with label: "< int(maxNrOfPixelClusters_)) return totals.pixel; + } else { + //say something's wrong. + edm::LogError("ClusterChecker") + << "could not get any SiPixel cluster collections of type edm::DetSetVector with label: " + << pixelClusterCollectionInputTag_; + totals.pixel = 999999; + } + if (totals.pixel > int(maxNrOfPixelClusters_)) + return totals.pixel; - if (!selector_(totals)) return totals.strip; - return 0; + if (!selector_(totals)) + return totals.strip; + return 0; } diff --git a/RecoTracker/TkSeedGenerator/src/FastCircle.cc b/RecoTracker/TkSeedGenerator/src/FastCircle.cc index 399075b3d0287..6cec73b8ac1b6 100644 --- a/RecoTracker/TkSeedGenerator/src/FastCircle.cc +++ b/RecoTracker/TkSeedGenerator/src/FastCircle.cc @@ -1,93 +1,83 @@ #include "RecoTracker/TkSeedGenerator/interface/FastCircle.h" #include "DataFormats/Math/interface/AlgebraicROOTObjects.h" -FastCircle::FastCircle(const GlobalPoint& outerHit, - const GlobalPoint& middleHit, - const GlobalPoint& aVertex) : - theOuterPoint(outerHit), - theInnerPoint(middleHit), - theVertexPoint(aVertex), - theNorm(128.), - theX0(0.), - theY0(0.), - theRho(0.), - theN1(0.), - theN2(0.), - theC(0.), - theValid(true), - theIsLine(false) { - +FastCircle::FastCircle(const GlobalPoint& outerHit, const GlobalPoint& middleHit, const GlobalPoint& aVertex) + : theOuterPoint(outerHit), + theInnerPoint(middleHit), + theVertexPoint(aVertex), + theNorm(128.), + theX0(0.), + theY0(0.), + theRho(0.), + theN1(0.), + theN2(0.), + theC(0.), + theValid(true), + theIsLine(false) { createCircleParameters(); - } FastCircle::FastCircle(const GlobalPoint& outerHit, - const GlobalPoint& middleHit, - const GlobalPoint& aVertex, - double norm) : - theOuterPoint(outerHit), - theInnerPoint(middleHit), - theVertexPoint(aVertex), - theNorm(norm), - theX0(0.), - theY0(0.), - theRho(0.), - theN1(0.), - theN2(0.), - theC(0.), - theValid(true), - theIsLine(false) { - + const GlobalPoint& middleHit, + const GlobalPoint& aVertex, + double norm) + : theOuterPoint(outerHit), + theInnerPoint(middleHit), + theVertexPoint(aVertex), + theNorm(norm), + theX0(0.), + theY0(0.), + theRho(0.), + theN1(0.), + theN2(0.), + theC(0.), + theValid(true), + theIsLine(false) { createCircleParameters(); - } namespace { - inline - AlgebraicVector3 transform(const GlobalPoint& aPoint, float norm) { - + inline AlgebraicVector3 transform(const GlobalPoint& aPoint, float norm) { AlgebraicVector3 riemannPoint; - - auto p = aPoint.basicVector()/norm; + + auto p = aPoint.basicVector() / norm; float R2 = p.perp2(); - float fact = 1.f/(1.f+R2); // let's factorize the common factor out - riemannPoint[0] = fact*p.x(); - riemannPoint[1] = fact*p.y(); - riemannPoint[2] = fact*R2; - + float fact = 1.f / (1.f + R2); // let's factorize the common factor out + riemannPoint[0] = fact * p.x(); + riemannPoint[1] = fact * p.y(); + riemannPoint[2] = fact * R2; + return riemannPoint; } - -} +} // namespace void FastCircle::createCircleParameters() { - - AlgebraicVector3 x = transform(theOuterPoint,theNorm); - AlgebraicVector3 y = transform(theInnerPoint,theNorm); - AlgebraicVector3 z = transform(theVertexPoint,theNorm); + AlgebraicVector3 x = transform(theOuterPoint, theNorm); + AlgebraicVector3 y = transform(theInnerPoint, theNorm); + AlgebraicVector3 z = transform(theVertexPoint, theNorm); AlgebraicVector3 n; - n[0] = x[1]*(y[2] - z[2]) + y[1]*(z[2] - x[2]) + z[1]*(x[2] - y[2]); - n[1] = -(x[0]*(y[2] - z[2]) + y[0]*(z[2] - x[2]) + z[0]*(x[2] - y[2])); - n[2] = x[0]*(y[1] - z[1]) + y[0]*(z[1] - x[1]) + z[0]*(x[1] - y[1]); + n[0] = x[1] * (y[2] - z[2]) + y[1] * (z[2] - x[2]) + z[1] * (x[2] - y[2]); + n[1] = -(x[0] * (y[2] - z[2]) + y[0] * (z[2] - x[2]) + z[0] * (x[2] - y[2])); + n[2] = x[0] * (y[1] - z[1]) + y[0] * (z[1] - x[1]) + z[0] * (x[1] - y[1]); - double mag2 = n[0]*n[0]+n[1]*n[1]+n[2]*n[2]; + double mag2 = n[0] * n[0] + n[1] * n[1] + n[2] * n[2]; if (mag2 < 1.e-20) { theValid = false; return; } - n.Unit(); // reduce n to a unit vector - double c = -(n[0]*x[0] + n[1]*x[1] + n[2]*x[2]); + n.Unit(); // reduce n to a unit vector + double c = -(n[0] * x[0] + n[1] * x[1] + n[2] * x[2]); // c = -(n[0]*y[0] + n[1]*y[1] + n[2]*y[2]); // c = -(n[0]*z[0] + n[1]*z[1] + n[2]*z[2]); - + theN1 = n[0]; theN2 = n[1]; theC = c; - if(fabs(c + n[2]) < 1.e-5) { + if (fabs(c + n[2]) < 1.e-5) { // numeric limit // circle is more a straight line... theValid = false; @@ -95,14 +85,11 @@ void FastCircle::createCircleParameters() { return; } - double x0 = -n[0] / (2.*(c + n[2])); - double y0 = -n[1] / (2.*(c + n[2])); - double rho = - sqrt((n[0]*n[0] + n[1]*n[1] - 4.*c*(c + n[2]))) / fabs(2.*(c + n[2])); - - theX0 = theNorm*x0; - theY0 = theNorm*y0; - theRho = theNorm*rho; + double x0 = -n[0] / (2. * (c + n[2])); + double y0 = -n[1] / (2. * (c + n[2])); + double rho = sqrt((n[0] * n[0] + n[1] * n[1] - 4. * c * (c + n[2]))) / fabs(2. * (c + n[2])); + theX0 = theNorm * x0; + theY0 = theNorm * y0; + theRho = theNorm * rho; } - diff --git a/RecoTracker/TkSeedGenerator/src/FastHelix.cc b/RecoTracker/TkSeedGenerator/src/FastHelix.cc index cecbfd9bf0534..a00d29519becb 100644 --- a/RecoTracker/TkSeedGenerator/src/FastHelix.cc +++ b/RecoTracker/TkSeedGenerator/src/FastHelix.cc @@ -2,98 +2,87 @@ #include "RecoTracker/TkSeedGenerator/interface/FastLine.h" void FastHelix::compute() { - - if(isValid() && (std::abs(tesla0) > 1e-3) && theCircle.rho() 1e-3) && theCircle.rho() < maxRho) helixStateAtVertex(); - else + else straightLineStateAtVertex(); - } void FastHelix::helixStateAtVertex() { - // given the above rho>0. double rho = theCircle.rho(); //remember (radius rho in cm): - //rho = - //100. * pt * + //rho = + //100. * pt * //(10./(3.*MagneticField::inTesla(GlobalPoint(0., 0., 0.)).z())); - + // pt = 0.01 * rho * (0.3*MagneticField::inTesla(GlobalPoint(0.,0.,0.)).z()); - double cm2GeV = 0.01 * 0.3*tesla0; - double pt = cm2GeV * rho; - + double cm2GeV = 0.01 * 0.3 * tesla0; + double pt = cm2GeV * rho; + // verify that rho is not toooo large - double dcphi = ((outerHit().x()-theCircle.x0())*(middleHit().x()-theCircle.x0()) + - (outerHit().y()-theCircle.y0())*(middleHit().y()-theCircle.y0()) - )/(rho*rho); - if (std::abs(dcphi)>=1.f) { straightLineStateAtVertex(); return;} - + double dcphi = ((outerHit().x() - theCircle.x0()) * (middleHit().x() - theCircle.x0()) + + (outerHit().y() - theCircle.y0()) * (middleHit().y() - theCircle.y0())) / + (rho * rho); + if (std::abs(dcphi) >= 1.f) { + straightLineStateAtVertex(); + return; + } + GlobalPoint pMid(middleHit()); GlobalPoint v(vertex()); - + // tangent in v (or the opposite...) - double px = -cm2GeV * (v.y()-theCircle.y0()); - double py = cm2GeV * (v.x()-theCircle.x0()); + double px = -cm2GeV * (v.y() - theCircle.y0()); + double py = cm2GeV * (v.x() - theCircle.x0()); // check sign with scalar product - if(px*(pMid.x() - v.x()) + py*(pMid.y() - v.y()) < 0.) { + if (px * (pMid.x() - v.x()) + py * (pMid.y() - v.y()) < 0.) { px = -px; py = -py; - } + } - - //calculate z0, pz //(z, R*phi) linear relation in a helix //with R, phi defined as radius and angle w.r.t. centre of circle //in transverse plane //pz = pT*(dz/d(R*phi))) - // VI 23/01/2012 double dzdrphi = outerHit().z() - middleHit().z(); - dzdrphi /= rho*acos(dcphi); - double pz = pt*dzdrphi; - + dzdrphi /= rho * acos(dcphi); + double pz = pt * dzdrphi; TrackCharge q = 1; - if (theCircle.x0()*py - theCircle.y0()*px < 0) q =-q; - if (tesla0 < 0.) q =-q; + if (theCircle.x0() * py - theCircle.y0() * px < 0) + q = -q; + if (tesla0 < 0.) + q = -q; //VI - if ( useBasisVertex ) { - atVertex = GlobalTrajectoryParameters(basisVertex, - GlobalVector(px, py, pz), - q, - bField - ); + if (useBasisVertex) { + atVertex = GlobalTrajectoryParameters(basisVertex, GlobalVector(px, py, pz), q, bField); } else { - double z_0 = middleHit().z(); + double z_0 = middleHit().z(); // assume v is before middleHit (opposite to outer) - double ds = ( (v.x()-theCircle.x0())*(middleHit().x()-theCircle.x0()) + - (v.y()-theCircle.y0())*(middleHit().y()-theCircle.y0()) - )/(rho*rho); - if (std::abs(ds)<1.f) { - ds = rho*acos(ds); - z_0 -= ds*dzdrphi; - } else { // line???? - z_0 -= std::sqrt((middleHit()-v).perp2()/(outerHit()-middleHit()).perp2())*(outerHit().z()-middleHit().z()); + double ds = ((v.x() - theCircle.x0()) * (middleHit().x() - theCircle.x0()) + + (v.y() - theCircle.y0()) * (middleHit().y() - theCircle.y0())) / + (rho * rho); + if (std::abs(ds) < 1.f) { + ds = rho * acos(ds); + z_0 -= ds * dzdrphi; + } else { // line???? + z_0 -= std::sqrt((middleHit() - v).perp2() / (outerHit() - middleHit()).perp2()) * + (outerHit().z() - middleHit().z()); } - + //double z_old = -flfit.c()/flfit.n2(); // std::cout << "v:xyz, z,old,new " << v << " " << z_old << " " << z_0 << std::endl; - atVertex = GlobalTrajectoryParameters(GlobalPoint(v.x(),v.y(),z_0), - GlobalVector(px, py, pz), - q, - bField - ); + atVertex = GlobalTrajectoryParameters(GlobalPoint(v.x(), v.y(), z_0), GlobalVector(px, py, pz), q, bField); } - } void FastHelix::straightLineStateAtVertex() { - //calculate GlobalTrajectoryParameters assuming straight line... GlobalPoint pMid(middleHit()); @@ -101,46 +90,38 @@ void FastHelix::straightLineStateAtVertex() { double dydx = 0.; double pt = 0., px = 0., py = 0.; - - if(fabs(theCircle.n1()) > 0. || fabs(theCircle.n2()) > 0.) - pt = maxPt ;// 10 TeV //else no pt - if(fabs(theCircle.n2()) > 0.) { - dydx = -theCircle.n1()/theCircle.n2(); //else px = 0 + + if (fabs(theCircle.n1()) > 0. || fabs(theCircle.n2()) > 0.) + pt = maxPt; // 10 TeV //else no pt + if (fabs(theCircle.n2()) > 0.) { + dydx = -theCircle.n1() / theCircle.n2(); //else px = 0 } - px = pt/sqrt(1. + dydx*dydx); - py = px*dydx; + px = pt / sqrt(1. + dydx * dydx); + py = px * dydx; // check sign with scalar product - if (px*(pMid.x() - v.x()) + py*(pMid.y() - v.y()) < 0.) { + if (px * (pMid.x() - v.x()) + py * (pMid.y() - v.y()) < 0.) { px *= -1.; py *= -1.; - } + } //calculate z_0 and pz at vertex using weighted mean //z = z(r) = z0 + (dz/dr)*r //tan(theta) = dr/dz = (dz/dr)^-1 //theta = atan(1./dzdr) //p = pt/sin(theta) - //pz = p*cos(theta) = pt/tan(theta) + //pz = p*cos(theta) = pt/tan(theta) FastLine flfit(outerHit(), middleHit()); - double dzdr = -flfit.n1()/flfit.n2(); - double pz = pt*dzdr; - + double dzdr = -flfit.n1() / flfit.n2(); + double pz = pt * dzdr; + TrackCharge q = 1; //VI - if ( useBasisVertex ) { - atVertex = GlobalTrajectoryParameters(basisVertex, - GlobalVector(px, py, pz), - q, - bField - ); + if (useBasisVertex) { + atVertex = GlobalTrajectoryParameters(basisVertex, GlobalVector(px, py, pz), q, bField); } else { - double z_0 = -flfit.c()/flfit.n2(); - atVertex = GlobalTrajectoryParameters(GlobalPoint(v.x(), v.y(), z_0), - GlobalVector(px, py, pz), - q, - bField - ); + double z_0 = -flfit.c() / flfit.n2(); + atVertex = GlobalTrajectoryParameters(GlobalPoint(v.x(), v.y(), z_0), GlobalVector(px, py, pz), q, bField); } } diff --git a/RecoTracker/TkSeedGenerator/src/FastLine.cc b/RecoTracker/TkSeedGenerator/src/FastLine.cc index 77ac0392f8da4..f69ee1262b441 100644 --- a/RecoTracker/TkSeedGenerator/src/FastLine.cc +++ b/RecoTracker/TkSeedGenerator/src/FastLine.cc @@ -1,60 +1,37 @@ #include "RecoTracker/TkSeedGenerator/interface/FastLine.h" -FastLine::FastLine(const GlobalPoint& outerHit, - const GlobalPoint& innerHit) : - theOuterHit(outerHit), - theInnerHit(innerHit), - theRho(0.), - theN1(0.), - theN2(0.), - theC(0.), - theValid(true) { - +FastLine::FastLine(const GlobalPoint& outerHit, const GlobalPoint& innerHit) + : theOuterHit(outerHit), theInnerHit(innerHit), theRho(0.), theN1(0.), theN2(0.), theC(0.), theValid(true) { createLineParameters(); - } -FastLine::FastLine(const GlobalPoint& outerHit, - const GlobalPoint& innerHit, - double rho) : - theOuterHit(outerHit), - theInnerHit(innerHit), - theRho(rho), - theN1(0.), - theN2(0.), - theC(0.), - theValid(true) { - +FastLine::FastLine(const GlobalPoint& outerHit, const GlobalPoint& innerHit, double rho) + : theOuterHit(outerHit), theInnerHit(innerHit), theRho(rho), theN1(0.), theN2(0.), theC(0.), theValid(true) { createLineParameters(); - } void FastLine::createLineParameters() { - double rphi0 = 0., rphi1 = 0.; - if(theRho > 0.) { - if (fabs( 1. - theInnerHit.perp2()/(2.*theRho*theRho) ) > 1.) rphi0 = theInnerHit.perp(); - else rphi0 = theRho*acos(1. - theInnerHit.perp2()/(2.*theRho*theRho)); - if (fabs(1. - theOuterHit.perp2()/(2.*theRho*theRho) ) >1.) rphi1 = theOuterHit.perp(); - else rphi1 = theRho*acos(1. - theOuterHit.perp2()/(2.*theRho*theRho)); + if (theRho > 0.) { + if (fabs(1. - theInnerHit.perp2() / (2. * theRho * theRho)) > 1.) + rphi0 = theInnerHit.perp(); + else + rphi0 = theRho * acos(1. - theInnerHit.perp2() / (2. * theRho * theRho)); + if (fabs(1. - theOuterHit.perp2() / (2. * theRho * theRho)) > 1.) + rphi1 = theOuterHit.perp(); + else + rphi1 = theRho * acos(1. - theOuterHit.perp2() / (2. * theRho * theRho)); } else { rphi0 = theInnerHit.perp(); rphi1 = theOuterHit.perp(); - } + } double n1 = theInnerHit.z() - theOuterHit.z(); double n2 = -(rphi0 - rphi1); - double norm = sqrt(n1*n1 + n2*n2); - theN1 = n1/norm; - theN2= n2/norm; - theC = -(theN1*rphi0 + theN2*theInnerHit.z()); + double norm = sqrt(n1 * n1 + n2 * n2); + theN1 = n1 / norm; + theN2 = n2 / norm; + theC = -(theN1 * rphi0 + theN2 * theInnerHit.z()); // theC = -(theN1*rphi1 + theN2*theOuterHit.z()); - } - - - - - - diff --git a/RecoTracker/TkSeedGenerator/src/MultiHitGenerator.cc b/RecoTracker/TkSeedGenerator/src/MultiHitGenerator.cc index 8f17787f7a4ab..f0fb96e0cb20d 100644 --- a/RecoTracker/TkSeedGenerator/src/MultiHitGenerator.cc +++ b/RecoTracker/TkSeedGenerator/src/MultiHitGenerator.cc @@ -1,11 +1,11 @@ #include "RecoTracker/TkSeedGenerator/interface/MultiHitGenerator.h" -#include -#include +#include +#include -const OrderedMultiHits & MultiHitGenerator::run( - const TrackingRegion& region, const edm::Event & ev, const edm::EventSetup& es) -{ - theHitSets.clear(); // called multiple time for the same seed collection +const OrderedMultiHits& MultiHitGenerator::run(const TrackingRegion& region, + const edm::Event& ev, + const edm::EventSetup& es) { + theHitSets.clear(); // called multiple time for the same seed collection theHitSets.reserve(localRA.upper()); hitSets(region, theHitSets, ev, es); theHitSets.shrink_to_fit(); @@ -13,8 +13,7 @@ const OrderedMultiHits & MultiHitGenerator::run( return theHitSets; } -void MultiHitGenerator::clear() -{ - theHitSets.clear(); theHitSets.shrink_to_fit(); +void MultiHitGenerator::clear() { + theHitSets.clear(); + theHitSets.shrink_to_fit(); } - diff --git a/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayers.cc b/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayers.cc index 83d514cfe7281..3762f39577087 100644 --- a/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayers.cc +++ b/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayers.cc @@ -3,10 +3,8 @@ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" -MultiHitGeneratorFromPairAndLayers::MultiHitGeneratorFromPairAndLayers(const edm::ParameterSet& pset): - theLayerCache(nullptr), - theMaxElement(pset.getParameter("maxElement")) -{} +MultiHitGeneratorFromPairAndLayers::MultiHitGeneratorFromPairAndLayers(const edm::ParameterSet& pset) + : theLayerCache(nullptr), theMaxElement(pset.getParameter("maxElement")) {} MultiHitGeneratorFromPairAndLayers::~MultiHitGeneratorFromPairAndLayers() {} @@ -14,11 +12,10 @@ void MultiHitGeneratorFromPairAndLayers::fillDescriptions(edm::ParameterSetDescr desc.add("maxElement", 1000000); } -void MultiHitGeneratorFromPairAndLayers::init(std::unique_ptr&& pairGenerator, LayerCacheType *layerCache) { +void MultiHitGeneratorFromPairAndLayers::init(std::unique_ptr&& pairGenerator, + LayerCacheType* layerCache) { thePairGenerator = std::move(pairGenerator); theLayerCache = layerCache; } -void MultiHitGeneratorFromPairAndLayers::clear() { - cache.clear(); -} +void MultiHitGeneratorFromPairAndLayers::clear() { cache.clear(); } diff --git a/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayersFactory.cc b/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayersFactory.cc index d2c71f0c11f5f..81f3ffa5c541e 100644 --- a/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayersFactory.cc +++ b/RecoTracker/TkSeedGenerator/src/MultiHitGeneratorFromPairAndLayersFactory.cc @@ -1,5 +1,4 @@ #include "RecoTracker/TkSeedGenerator/interface/MultiHitGeneratorFromPairAndLayersFactory.h" #include "FWCore/PluginManager/interface/PluginFactory.h" -EDM_REGISTER_PLUGINFACTORY(MultiHitGeneratorFromPairAndLayersFactory,"MultiHitGeneratorFromPairAndLayersFactory"); - +EDM_REGISTER_PLUGINFACTORY(MultiHitGeneratorFromPairAndLayersFactory, "MultiHitGeneratorFromPairAndLayersFactory"); diff --git a/RecoTracker/TkSeedGenerator/src/SeedFromProtoTrack.cc b/RecoTracker/TkSeedGenerator/src/SeedFromProtoTrack.cc index d2db320d20604..bedc32262cfc9 100644 --- a/RecoTracker/TkSeedGenerator/src/SeedFromProtoTrack.cc +++ b/RecoTracker/TkSeedGenerator/src/SeedFromProtoTrack.cc @@ -18,72 +18,63 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" -SeedFromProtoTrack::SeedFromProtoTrack(const reco::Track & proto, - const SeedingHitSet & hits, const edm::EventSetup& es) - : theValid(true) -{ - for (unsigned int i= 0, n = hits.size(); i< n; ++i) { - const TrackingRecHit * trh = hits[i]->hit(); - theHits.push_back( trh->clone() ); +SeedFromProtoTrack::SeedFromProtoTrack(const reco::Track& proto, const SeedingHitSet& hits, const edm::EventSetup& es) + : theValid(true) { + for (unsigned int i = 0, n = hits.size(); i < n; ++i) { + const TrackingRecHit* trh = hits[i]->hit(); + theHits.push_back(trh->clone()); } init(proto, es); } -SeedFromProtoTrack::SeedFromProtoTrack(const reco::Track & proto, const edm::EventSetup& es) - : theValid(true) -{ +SeedFromProtoTrack::SeedFromProtoTrack(const reco::Track& proto, const edm::EventSetup& es) : theValid(true) { const TrackingRecHit* hit = nullptr; for (unsigned int iHit = 0, nHits = proto.recHitsSize(); iHit < nHits; ++iHit) { TrackingRecHitRef refHit = proto.recHit(iHit); hit = &(*refHit); - theHits.push_back( hit->clone() ); + theHits.push_back(hit->clone()); } - init(proto,es); + init(proto, es); } - -void SeedFromProtoTrack::init(const reco::Track & proto, const edm::EventSetup& es) -{ +void SeedFromProtoTrack::init(const reco::Track& proto, const edm::EventSetup& es) { edm::ESHandle tracker; es.get().get(tracker); - edm::ESHandle propagatorHandle; - es.get().get("PropagatorWithMaterial",propagatorHandle); - const Propagator* propagator = &(*propagatorHandle); + edm::ESHandle propagatorHandle; + es.get().get("PropagatorWithMaterial", propagatorHandle); + const Propagator* propagator = &(*propagatorHandle); edm::ESHandle field; - es.get().get(field);//fixme + es.get().get(field); //fixme - const reco::TrackBase::Point& vtx = proto.referencePoint(); + const reco::TrackBase::Point& vtx = proto.referencePoint(); const reco::TrackBase::Vector& mom = proto.momentum(); - GlobalTrajectoryParameters gtp( - GlobalPoint(vtx.x(),vtx.y(),vtx.z()), - GlobalVector(mom.x(),mom.y(),mom.z()), - proto.charge(), &(*field) ); + GlobalTrajectoryParameters gtp( + GlobalPoint(vtx.x(), vtx.y(), vtx.z()), GlobalVector(mom.x(), mom.y(), mom.z()), proto.charge(), &(*field)); CurvilinearTrajectoryError err = proto.covariance(); - FreeTrajectoryState fts( gtp, err); + FreeTrajectoryState fts(gtp, err); - const TrackingRecHit & lastHit = theHits.back(); + const TrackingRecHit& lastHit = theHits.back(); TrajectoryStateOnSurface outerState = propagator->propagate(fts, tracker->idToDet(lastHit.geographicalId())->surface()); - if (!outerState.isValid()){ - const Surface & surface = tracker->idToDet(lastHit.geographicalId())->surface(); - edm::LogError("SeedFromProtoTrack")<<" was trying to create a seed from:\n"<idToDet(lastHit.geographicalId())->surface(); + edm::LogError("SeedFromProtoTrack") << " was trying to create a seed from:\n" + << fts << "\n propagating to: " << std::hex << lastHit.geographicalId().rawId() + << std::dec << ' ' << surface.position(); theValid = false; - return ; + return; } theValid = true; thePTraj = trajectoryStateTransform::persistentState(outerState, lastHit.geographicalId().rawId()); - - } -TrajectorySeed SeedFromProtoTrack::trajectorySeed() const -{ - return TrajectorySeed( trajectoryState(), hits(), direction()); +TrajectorySeed SeedFromProtoTrack::trajectorySeed() const { + return TrajectorySeed(trajectoryState(), hits(), direction()); } diff --git a/RecoTracker/TkSeedGenerator/src/SeedGeneratorFromRegionHits.cc b/RecoTracker/TkSeedGenerator/src/SeedGeneratorFromRegionHits.cc index 1cae39fde4532..ab7301d79f356 100644 --- a/RecoTracker/TkSeedGenerator/src/SeedGeneratorFromRegionHits.cc +++ b/RecoTracker/TkSeedGenerator/src/SeedGeneratorFromRegionHits.cc @@ -4,27 +4,29 @@ #include "RecoTracker/TkSeedingLayers/interface/SeedComparitor.h" #include "RecoTracker/TkSeedGenerator/interface/SeedCreator.h" -SeedGeneratorFromRegionHits::SeedGeneratorFromRegionHits( - std::unique_ptr ohg, std::unique_ptr asc, std::unique_ptr asp) - : theHitsGenerator{std::move(ohg)}, theComparitor{std::move(asc)}, theSeedCreator{std::move(asp)} -{ } +SeedGeneratorFromRegionHits::SeedGeneratorFromRegionHits(std::unique_ptr ohg, + std::unique_ptr asc, + std::unique_ptr asp) + : theHitsGenerator{std::move(ohg)}, theComparitor{std::move(asc)}, theSeedCreator{std::move(asp)} {} -void SeedGeneratorFromRegionHits::run(TrajectorySeedCollection & seedCollection, - const TrackingRegion & region, const edm::Event& ev, const edm::EventSetup& es) -{ - if (theComparitor) theComparitor->init(ev, es); +void SeedGeneratorFromRegionHits::run(TrajectorySeedCollection& seedCollection, + const TrackingRegion& region, + const edm::Event& ev, + const edm::EventSetup& es) { + if (theComparitor) + theComparitor->init(ev, es); theSeedCreator->init(region, es, theComparitor.get()); - const OrderedSeedingHits & hitss = theHitsGenerator->run(region, ev, es); + const OrderedSeedingHits& hitss = theHitsGenerator->run(region, ev, es); - unsigned int nHitss = hitss.size(); + unsigned int nHitss = hitss.size(); // Modified 10/Jun/2014 Mark Grimes - At 140 pileup this reserve massively overestimates // the amount of memory required. Removing it doesn't appear to slow down the algorithm // noticeably. //if (seedCollection.empty()) seedCollection.reserve(nHitss); // don't do multiple reserves in the case of multiple regions: it would make things even worse // // as it will cause N re-allocations instead of the normal log(N)/log(2) - for (unsigned int iHits = 0; iHits < nHitss; ++iHits) { - const SeedingHitSet & hits = hitss[iHits]; - if (!theComparitor || theComparitor->compatible(hits) ) { + for (unsigned int iHits = 0; iHits < nHitss; ++iHits) { + const SeedingHitSet& hits = hitss[iHits]; + if (!theComparitor || theComparitor->compatible(hits)) { theSeedCreator->makeSeed(seedCollection, hits); } } diff --git a/RecoTracker/TkSeedGenerator/src/classes.h b/RecoTracker/TkSeedGenerator/src/classes.h index 309994c191d42..f0632389c0528 100644 --- a/RecoTracker/TkSeedGenerator/src/classes.h +++ b/RecoTracker/TkSeedGenerator/src/classes.h @@ -1,6 +1,6 @@ #include "RecoTracker/TkSeedGenerator/interface/ClusterChecker.h" namespace RecoTracker_TkSeedGenerator { - struct dictionary { - reco::utils::ClusterTotals totals; - }; -} + struct dictionary { + reco::utils::ClusterTotals totals; + }; +} // namespace RecoTracker_TkSeedGenerator diff --git a/RecoTracker/TkSeedGenerator/test/FastCircleFit_t.cpp b/RecoTracker/TkSeedGenerator/test/FastCircleFit_t.cpp index 6b58355cf7376..6ee622ccb31c4 100644 --- a/RecoTracker/TkSeedGenerator/test/FastCircleFit_t.cpp +++ b/RecoTracker/TkSeedGenerator/test/FastCircleFit_t.cpp @@ -7,105 +7,51 @@ namespace { void test(const std::vector& points, const std::vector& errors) { FastCircleFit c(points, errors); - std::cout << "origin " << c.x0() << " " << c.y0() - << " radius " << c.rho() - << " chi2 " << c.chi2() - << std::endl; + std::cout << "origin " << c.x0() << " " << c.y0() << " radius " << c.rho() << " chi2 " << c.chi2() << std::endl; }; -} +} // namespace int main() { { - std::vector points = {{ - GlobalPoint( 0., -1.,0.), - GlobalPoint(-1., 0.,0.), - GlobalPoint( 0., 1.,0.) - }}; - std::vector errors = {{ - GlobalError(1, - 0, 1, - 0, 0, 1), - GlobalError(1, - 0, 1, - 0, 0, 1), - GlobalError(1, - 0, 1, - 0, 0, 1) - }}; - + std::vector points = {{GlobalPoint(0., -1., 0.), GlobalPoint(-1., 0., 0.), GlobalPoint(0., 1., 0.)}}; + std::vector errors = { + {GlobalError(1, 0, 1, 0, 0, 1), GlobalError(1, 0, 1, 0, 0, 1), GlobalError(1, 0, 1, 0, 0, 1)}}; + test(points, errors); } { - std::vector points = {{ - GlobalPoint( 0.1, 0.,0.), - GlobalPoint(-0.9, 1.,0.), - GlobalPoint( 0.1, 2.,0.) - }}; - std::vector errors = {{ - GlobalError(1, - 0, 1, - 0, 0, 1), - GlobalError(1, - 0, 1, - 0, 0, 1), - GlobalError(1, - 0, 1, - 0, 0, 1) - }}; - + std::vector points = {{GlobalPoint(0.1, 0., 0.), GlobalPoint(-0.9, 1., 0.), GlobalPoint(0.1, 2., 0.)}}; + std::vector errors = { + {GlobalError(1, 0, 1, 0, 0, 1), GlobalError(1, 0, 1, 0, 0, 1), GlobalError(1, 0, 1, 0, 0, 1)}}; + test(points, errors); } { - std::vector points = {{ - GlobalPoint(-3.18318, 0.0479436 ,0.), - GlobalPoint(-6.74696, -0.303678 ,0.), - GlobalPoint(-10.7557, -1.24485 ,0.), - GlobalPoint(-14.6143, -2.79196 ,0.) - }}; - std::vector errors = {{ - GlobalError(2.37751e-07, - 8.873e-07, 3.31145e-06, - 0, 0, 5.22405e-06), - GlobalError(6.10596e-09, - -5.41919e-08, 4.80966e-07, - 0, 0, 7.44661e-06), - GlobalError(6.41271e-09, - -8.96614e-08, 1.25363e-06, - 0, 0, 4.73874e-06), - GlobalError(1.19665e-06, - 2.78201e-07, 2.80112e-07, - 0, 0, 2.78938e-08) - }}; - + std::vector points = {{GlobalPoint(-3.18318, 0.0479436, 0.), + GlobalPoint(-6.74696, -0.303678, 0.), + GlobalPoint(-10.7557, -1.24485, 0.), + GlobalPoint(-14.6143, -2.79196, 0.)}}; + std::vector errors = {{GlobalError(2.37751e-07, 8.873e-07, 3.31145e-06, 0, 0, 5.22405e-06), + GlobalError(6.10596e-09, -5.41919e-08, 4.80966e-07, 0, 0, 7.44661e-06), + GlobalError(6.41271e-09, -8.96614e-08, 1.25363e-06, 0, 0, 4.73874e-06), + GlobalError(1.19665e-06, 2.78201e-07, 2.80112e-07, 0, 0, 2.78938e-08)}}; + test(points, errors); } { - std::vector points = {{ - GlobalPoint(-3.18318, 0.0479436 ,0.), - GlobalPoint(-6.74696, -0.303678 ,0.), - GlobalPoint(-10.7557, -1.24485 ,0.), - GlobalPoint(-14.699, -2.83295 ,0.) - }}; - std::vector errors = {{ - GlobalError(2.37751e-07, - 8.873e-07, 3.31145e-06, - 0, 0, 5.22405e-06), - GlobalError(6.10596e-09, - -5.41919e-08, 4.80966e-07, - 0, 0, 7.44661e-06), - GlobalError(6.41271e-09, - -8.96614e-08, 1.25363e-06, - 0, 0, 4.73874e-06), - GlobalError(3.14525e-06, - 2.64413e-07, 4.33922e-07, - 0, 0, 5.69573e-08) - }}; - + std::vector points = {{GlobalPoint(-3.18318, 0.0479436, 0.), + GlobalPoint(-6.74696, -0.303678, 0.), + GlobalPoint(-10.7557, -1.24485, 0.), + GlobalPoint(-14.699, -2.83295, 0.)}}; + std::vector errors = {{GlobalError(2.37751e-07, 8.873e-07, 3.31145e-06, 0, 0, 5.22405e-06), + GlobalError(6.10596e-09, -5.41919e-08, 4.80966e-07, 0, 0, 7.44661e-06), + GlobalError(6.41271e-09, -8.96614e-08, 1.25363e-06, 0, 0, 4.73874e-06), + GlobalError(3.14525e-06, 2.64413e-07, 4.33922e-07, 0, 0, 5.69573e-08)}}; + test(points, errors); } - return 0; } diff --git a/RecoTracker/TkSeedGenerator/test/FastCircle_t.cpp b/RecoTracker/TkSeedGenerator/test/FastCircle_t.cpp index d7cd13edd353b..7cfd16fe75eff 100644 --- a/RecoTracker/TkSeedGenerator/test/FastCircle_t.cpp +++ b/RecoTracker/TkSeedGenerator/test/FastCircle_t.cpp @@ -1,48 +1,38 @@ #include "RecoTracker/TkSeedGenerator/src/FastCircle.cc" - - int main() { + { + GlobalPoint p1(0., -1., 0.); + GlobalPoint p2(-1., 0., 0.); + GlobalPoint p3(0., 1., 0.); -{ - GlobalPoint p1( 0., -1.,0.); - GlobalPoint p2(-1., 0.,0.); - GlobalPoint p3( 0., 1.,0.); + FastCircle c(p1, p2, p3); - FastCircle c(p1,p2,p3); + std::cout << c.x0() << " " << c.y0() << " " << c.rho() << " " << c.n1() << " " << c.n2() << " " << c.c() + << std::endl; + } - std::cout << c.x0() << " " << c.y0() << " " << c.rho() - << " " << c.n1() << " " << c.n2() << " " << c.c()<< std::endl; - -} + { + GlobalPoint p1(-10., 0., 0.); + GlobalPoint p2(0., 10., 0.); + GlobalPoint p3(10., 0., 0.); -{ + FastCircle c(p1, p2, p3); - GlobalPoint p1( -10., 0.,0.); - GlobalPoint p2( 0., 10.,0.); - GlobalPoint p3( 10., 0.,0.); + std::cout << c.x0() << " " << c.y0() << " " << c.rho() << " " << c.n1() << " " << c.n2() << " " << c.c() + << std::endl; + } - FastCircle c(p1,p2,p3); - - std::cout << c.x0() << " " << c.y0() << " " << c.rho() - << " " << c.n1() << " " << c.n2() << " " << c.c()<< std::endl; - -} - -{ - - GlobalPoint p1( -15., 15.,0.); - GlobalPoint p2( -5., 5.,0.); - GlobalPoint p3( 5., 15.,0.); - - FastCircle c(p1,p2,p3); - - std::cout << c.x0() << " " << c.y0() << " " << c.rho() - << " " << c.n1() << " " << c.n2() << " " << c.c()<< std::endl; - -} + { + GlobalPoint p1(-15., 15., 0.); + GlobalPoint p2(-5., 5., 0.); + GlobalPoint p3(5., 15., 0.); + FastCircle c(p1, p2, p3); - return 0; + std::cout << c.x0() << " " << c.y0() << " " << c.rho() << " " << c.n1() << " " << c.n2() << " " << c.c() + << std::endl; + } + return 0; }