From 5dd8b8df344ed3dc2ffae64a1dc7c11fd7368730 Mon Sep 17 00:00:00 2001 From: Cms Build Date: Fri, 31 May 2019 16:02:50 +0200 Subject: [PATCH] Clang-Format --- .../plugins/SealModules.cc | 1 - .../SiStripProcessedRawDigiProducer.cc | 97 +- .../plugins/SiStripProcessedRawDigiProducer.h | 19 +- .../SUSYBSMObjects/interface/HSCPCaloInfo.h | 93 +- .../SUSYBSMObjects/interface/HSCPDeDxInfo.h | 31 +- .../SUSYBSMObjects/interface/HSCPIsolation.h | 59 +- .../SUSYBSMObjects/interface/HSCParticle.h | 130 +- .../SUSYBSMObjects/interface/MuonSegment.h | 47 +- .../SUSYBSMObjects/src/HSCParticle.cc | 62 +- .../SUSYBSMObjects/src/classes.h | 18 +- .../Skimming/plugins/ZMuMuMuonUserData.cc | 173 +- .../Skimming/plugins/ZMuMuOneTrackUserData.cc | 93 +- .../Skimming/plugins/ZMuMuTrackUserData.cc | 127 +- .../Skimming/plugins/ZMuMuUserData.cc | 157 +- .../WMuNu/src/WMuNuProducer.cc | 149 +- .../WMuNu/src/WMuNuSelector.cc | 645 +- .../WMuNu/src/WMuNuValidator.cc | 992 +- .../interface/BPHBdToJPsiKxBuilder.h | 69 +- .../interface/BPHBsToJPsiPhiBuilder.h | 69 +- .../interface/BPHBuToJPsiKBuilder.h | 73 +- .../SpecificDecay/interface/BPHChi2Select.h | 34 +- .../interface/BPHKx0ToKPiBuilder.h | 41 +- .../SpecificDecay/interface/BPHMassCuts.h | 30 +- .../interface/BPHMassFitSelect.h | 138 +- .../SpecificDecay/interface/BPHMassSelect.h | 24 +- .../interface/BPHMassSymSelect.h | 47 +- .../interface/BPHMuonEtaSelect.h | 26 +- .../SpecificDecay/interface/BPHMuonPtSelect.h | 26 +- .../interface/BPHOniaToMuMuBuilder.h | 92 +- .../interface/BPHParticleEtaSelect.h | 28 +- .../interface/BPHParticleMasses.h | 28 +- .../interface/BPHParticleNeutralVeto.h | 21 +- .../interface/BPHParticlePtSelect.h | 28 +- .../interface/BPHPhiToKKBuilder.h | 41 +- .../plugins/BPHHistoSpecificDecay.cc | 963 +- .../plugins/BPHHistoSpecificDecay.h | 60 +- .../plugins/BPHWriteSpecificDecay.cc | 1053 +- .../plugins/BPHWriteSpecificDecay.h | 168 +- .../SpecificDecay/src/BPHBdToJPsiKxBuilder.cc | 189 +- .../src/BPHBsToJPsiPhiBuilder.cc | 189 +- .../SpecificDecay/src/BPHBuToJPsiKBuilder.cc | 204 +- .../SpecificDecay/src/BPHKx0ToKPiBuilder.cc | 152 +- .../SpecificDecay/src/BPHOniaToMuMuBuilder.cc | 306 +- .../SpecificDecay/src/BPHParticleMasses.cc | 30 +- .../SpecificDecay/src/BPHPhiToKKBuilder.cc | 117 +- .../test/stubs/CheckBPHWriteDecay.cc | 188 +- .../test/stubs/CheckBPHWriteDecay.h | 52 +- .../test/stubs/TestBPHSpecificDecay.cc | 658 +- .../test/stubs/TestBPHSpecificDecay.h | 40 +- .../interface/HeavyChHiggsToTauNuSkim.h | 83 +- .../Skimming/interface/HiggsTo2GammaSkim.h | 9 +- .../interface/HiggsToWW2LeptonsSkim.h | 28 +- .../interface/HiggsToZZ4LeptonsPreFilter.h | 8 +- .../interface/HiggsToZZ4LeptonsSkim.h | 9 +- .../interface/HiggsToZZ4LeptonsSkimEff.h | 8 +- .../Skimming/src/HeavyChHiggsToTauNuSkim.cc | 78 +- .../Skimming/src/HiggsTo2GammaSkim.cc | 53 +- .../Skimming/src/HiggsToWW2LeptonsSkim.cc | 72 +- .../src/HiggsToZZ4LeptonsPreFilter.cc | 116 +- .../Skimming/src/HiggsToZZ4LeptonsSkim.cc | 71 +- .../Skimming/src/HiggsToZZ4LeptonsSkimEff.cc | 185 +- HiggsAnalysis/Skimming/src/SealModule.cc | 3 - .../interface/JetCorrectorImplMakerBase.h | 36 +- .../Algorithms/interface/L1FastjetCorrector.h | 11 +- .../interface/L1FastjetCorrectorImpl.h | 18 +- .../interface/L1JPTOffsetCorrector.h | 56 +- .../interface/L1JPTOffsetCorrectorImpl.h | 39 +- .../Algorithms/interface/L1OffsetCorrector.h | 49 +- .../interface/L1OffsetCorrectorImpl.h | 43 +- .../Algorithms/interface/L6SLBCorrector.h | 43 +- .../Algorithms/interface/L6SLBCorrectorImpl.h | 44 +- .../Algorithms/interface/LXXXCorrector.h | 40 +- .../Algorithms/interface/LXXXCorrectorImpl.h | 38 +- .../src/JetCorrectorImplMakerBase.cc | 28 +- .../Algorithms/src/L1FastjetCorrector.cc | 43 +- .../Algorithms/src/L1FastjetCorrectorImpl.cc | 47 +- .../Algorithms/src/L1JPTOffsetCorrector.cc | 52 +- .../src/L1JPTOffsetCorrectorImpl.cc | 71 +- .../Algorithms/src/L1OffsetCorrector.cc | 50 +- .../Algorithms/src/L1OffsetCorrectorImpl.cc | 65 +- .../Algorithms/src/L6SLBCorrector.cc | 74 +- .../Algorithms/src/L6SLBCorrectorImpl.cc | 100 +- .../Algorithms/src/LXXXCorrector.cc | 44 +- .../Algorithms/src/LXXXCorrectorImpl.cc | 90 +- .../interface/AbsArrayProjector.h | 30 +- .../interface/AbsMultivariateFunctor.h | 26 +- .../interface/AbsVisitor.h | 59 +- .../InterpolationTables/interface/ArrayND.h | 10621 ++++++++-------- .../interface/ArrayNDScanner.h | 88 +- .../interface/ArrayRange.h | 72 +- .../interface/ArrayShape.h | 77 +- .../InterpolationTables/interface/BoxND.h | 878 +- .../interface/CircularMapper1d.h | 75 +- .../interface/ComplexComparesAbs.h | 35 +- .../interface/ComplexComparesFalse.h | 33 +- .../interface/CoordinateSelector.h | 51 +- .../InterpolationTables/interface/DualAxis.h | 162 +- .../interface/DualHistoAxis.h | 217 +- .../interface/EquidistantSequence.h | 41 +- .../InterpolationTables/interface/GridAxis.h | 132 +- .../InterpolationTables/interface/HistoAxis.h | 207 +- .../InterpolationTables/interface/HistoND.h | 6441 +++++----- .../interface/HistoNDFunctorInstances.h | 17 +- .../interface/InterpolationFunctorInstances.h | 23 +- .../InterpolationTables/interface/Interval.h | 460 +- .../interface/LinInterpolatedTableND.h | 2128 ++-- .../interface/LinearMapper1d.h | 85 +- .../interface/NUHistoAxis.h | 199 +- .../interface/NpstatException.h | 69 +- .../interface/PreciseType.h | 80 +- .../interface/ProperDblFromCmpl.h | 60 +- .../interface/SimpleFunctors.h | 659 +- .../interface/StorableHistoNDFunctor.h | 308 +- .../interface/StorableInterpolationFunctor.h | 374 +- .../interface/StorableMultivariateFunctor.h | 87 +- .../StorableMultivariateFunctorReader.h | 24 +- .../interface/UniformAxis.h | 139 +- .../interface/absDifference.h | 136 +- .../interface/allocators.h | 133 +- .../interface/closeWithinTolerance.h | 28 +- .../interface/convertAxis.h | 21 +- .../interface/interpolate.h | 145 +- .../interface/interpolateHistoND.h | 780 +- .../interface/isMonotonous.h | 128 +- .../InterpolationTables/src/ArrayNDScanner.cc | 70 +- .../InterpolationTables/src/ArrayRange.cc | 229 +- .../InterpolationTables/src/ArrayShape.cc | 350 +- .../InterpolationTables/src/DualAxis.cc | 56 +- .../InterpolationTables/src/DualHistoAxis.cc | 56 +- .../src/EquidistantSequence.cc | 106 +- .../InterpolationTables/src/GridAxis.cc | 316 +- .../InterpolationTables/src/HistoAxis.cc | 283 +- .../InterpolationTables/src/NUHistoAxis.cc | 319 +- .../src/StorableMultivariateFunctor.cc | 35 +- .../src/StorableMultivariateFunctorReader.cc | 43 +- .../InterpolationTables/src/UniformAxis.cc | 207 +- .../InterpolationTables/src/convertAxis.cc | 90 +- .../test/TestIsoSimTracks.cc | 356 +- .../IsolatedParticles/test/TestIsoTracks.cc | 345 +- .../JetParton/interface/JetPartonCorrector.h | 27 +- .../JetParton/src/JetPartonCorrector.cc | 360 +- .../interface/JetVertexAssociation.h | 19 +- .../interface/JetVertexMain.h | 27 +- .../src/JetVertexAssociation.cc | 117 +- .../JetVertexAssociation/src/JetVertexMain.cc | 126 +- .../JetVertexAssociation/test/AnalysisJV.cc | 79 +- .../JetVertexAssociation/test/AnalysisJV.h | 33 +- .../JetExamples/test/printGenJetRatio.cc | 66 +- .../JetExamples/test/printJetFlavour.cc | 147 +- .../JetExamples/test/printJetFlavourInfo.cc | 320 +- .../JetExamples/test/printPartonJet.cc | 51 +- .../JetExamples/test/printTrackJet.cc | 52 +- PhysicsTools/JetMCUtils/interface/CandMCTag.h | 4 +- PhysicsTools/JetMCUtils/interface/JetMCTag.h | 8 +- .../JetMCUtils/interface/combination.h | 576 +- PhysicsTools/JetMCUtils/src/CandMCTag.cc | 76 +- PhysicsTools/JetMCUtils/src/JetMCTag.cc | 185 +- .../Skimming/interface/QCDSingleJetFilter.h | 11 +- .../Skimming/src/QCDSingleJetFilter.cc | 72 +- .../interface/AnalysisRootpleProducer.h | 64 +- .../interface/AnalysisRootpleProducerOnlyMC.h | 46 +- .../UEAnalysis/src/AnalysisRootpleProducer.cc | 443 +- .../src/AnalysisRootpleProducerOnlyMC.cc | 210 +- TopQuarkAnalysis/Examples/bin/NiceStyle.cc | 64 +- .../Examples/bin/TopElecFWLiteAnalyzer.cc | 103 +- .../bin/TopHypothesisFWLiteAnalyzer.cc | 157 +- .../Examples/bin/TopJetFWLiteAnalyzer.cc | 103 +- .../Examples/bin/TopMuonFWLiteAnalyzer.cc | 116 +- .../Examples/plugins/HypothesisAnalyzer.cc | 202 +- .../Examples/plugins/HypothesisAnalyzer.h | 10 +- .../Examples/plugins/SealModule.cc | 1 - .../Examples/plugins/TopElecAnalyzer.cc | 79 +- .../Examples/plugins/TopElecAnalyzer.h | 16 +- .../Examples/plugins/TopGenEventAnalyzer.cc | 63 +- .../Examples/plugins/TopGenEventAnalyzer.h | 16 +- .../Examples/plugins/TopJetAnalyzer.cc | 121 +- .../Examples/plugins/TopJetAnalyzer.h | 15 +- .../Examples/plugins/TopMuonAnalyzer.cc | 84 +- .../Examples/plugins/TopMuonAnalyzer.h | 15 +- .../Examples/plugins/TopTauAnalyzer.cc | 45 +- .../Examples/plugins/TopTauAnalyzer.h | 15 +- .../Examples/test/runtestTqafExamples.cpp | 2 +- .../TopKinFitter/interface/CovarianceMatrix.h | 145 +- .../TopKinFitter/interface/StKinFitter.h | 65 +- .../TopKinFitter/interface/TopKinFitter.h | 23 +- .../interface/TtFullHadKinFitter.h | 189 +- .../interface/TtFullLepKinSolver.h | 71 +- .../interface/TtSemiLepKinFitter.h | 136 +- .../TopKinFitter/plugins/SealModule.cc | 4 +- .../plugins/TtFullHadKinFitProducer.cc | 199 +- .../plugins/TtFullHadKinFitProducer.h | 11 +- .../plugins/TtFullLepKinSolutionProducer.h | 476 +- .../plugins/TtSemiLepKinFitProducer.h | 480 +- .../TopKinFitter/src/CovarianceMatrix.cc | 540 +- .../TopKinFitter/src/StKinFitter.cc | 312 +- .../TopKinFitter/src/TopKinFitter.cc | 30 +- .../TopKinFitter/src/TtFullHadKinFitter.cc | 873 +- .../TopKinFitter/src/TtFullLepKinSolver.cc | 530 +- .../TopKinFitter/src/TtSemiLepKinFitter.cc | 431 +- .../test/runtestTqafTopKinFitter.cpp | 2 +- .../TopTools/interface/JetPartonMatching.h | 78 +- .../TopTools/interface/LRHelpFunctions.h | 84 +- .../TopTools/interface/MEzCalculator.h | 24 +- .../TopTools/plugins/GenTtbarCategorizer.cc | 606 +- .../TopTools/plugins/MuonSelectorVertex.cc | 69 +- .../plugins/TtFullHadJetPartonMatch.cc | 2 +- .../plugins/TtFullLepJetPartonMatch.cc | 2 +- .../TopTools/plugins/TtJetPartonMatch.h | 98 +- .../plugins/TtSemiLepJetPartonMatch.cc | 2 +- .../TopTools/src/JetPartonMatching.cc | 416 +- .../TopTools/src/LRHelpFunctions.cc | 733 +- .../TopTools/src/MEzCalculator.cc | 118 +- .../TopTools/test/TestGenTtbarCategories.cc | 142 +- .../TopTools/test/runtestTqafTopTools.cpp | 2 +- TopQuarkAnalysis/TopTools/test/tdrstyle.C | 47 +- 215 files changed, 23614 insertions(+), 25742 deletions(-) mode change 100755 => 100644 ElectroWeakAnalysis/Skimming/plugins/ZMuMuMuonUserData.cc mode change 100755 => 100644 ElectroWeakAnalysis/Skimming/plugins/ZMuMuOneTrackUserData.cc mode change 100755 => 100644 ElectroWeakAnalysis/Skimming/plugins/ZMuMuTrackUserData.cc mode change 100755 => 100644 ElectroWeakAnalysis/Skimming/plugins/ZMuMuUserData.cc mode change 100755 => 100644 ElectroWeakAnalysis/WMuNu/src/WMuNuSelector.cc mode change 100755 => 100644 ElectroWeakAnalysis/WMuNu/src/WMuNuValidator.cc mode change 100755 => 100644 TopQuarkAnalysis/TopTools/test/tdrstyle.C diff --git a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SealModules.cc b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SealModules.cc index 1671a8411e87a..ebe98c1137682 100644 --- a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SealModules.cc +++ b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SealModules.cc @@ -5,5 +5,4 @@ #include "AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.h" - DEFINE_FWK_MODULE(SiStripProcessedRawDigiProducer); diff --git a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.cc b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.cc index dbfd0d12bd243..39772fe1bc7c7 100644 --- a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.cc +++ b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.cc @@ -18,46 +18,47 @@ #include SiStripProcessedRawDigiProducer::SiStripProcessedRawDigiProducer(edm::ParameterSet const& conf) - : inputTags(conf.getParameter >("DigiProducersList")), - inputTokensDigi(edm::vector_transform(inputTags, [this](edm::InputTag const & tag){return consumes >(tag);})), - inputTokensRawDigi(edm::vector_transform(inputTags, [this](edm::InputTag const & tag){return consumes >(tag);})), - subtractorPed(SiStripRawProcessingFactory::create_SubtractorPed(conf)), - subtractorCMN(SiStripRawProcessingFactory::create_SubtractorCMN(conf)){ - - produces< edm::DetSetVector >(""); + : inputTags(conf.getParameter >("DigiProducersList")), + inputTokensDigi(edm::vector_transform( + inputTags, [this](edm::InputTag const& tag) { return consumes >(tag); })), + inputTokensRawDigi(edm::vector_transform( + inputTags, [this](edm::InputTag const& tag) { return consumes >(tag); })), + subtractorPed(SiStripRawProcessingFactory::create_SubtractorPed(conf)), + subtractorCMN(SiStripRawProcessingFactory::create_SubtractorCMN(conf)) { + produces >(""); } -void SiStripProcessedRawDigiProducer:: -produce(edm::Event& e, const edm::EventSetup& es) { - - std::unique_ptr< edm::DetSetVector > output(new edm::DetSetVector()); - edm::Handle< edm::DetSetVector > inputDigis; - edm::Handle< edm::DetSetVector > inputRawdigis; +void SiStripProcessedRawDigiProducer::produce(edm::Event& e, const edm::EventSetup& es) { + std::unique_ptr > output(new edm::DetSetVector()); + edm::Handle > inputDigis; + edm::Handle > inputRawdigis; es.get().get(gainHandle); subtractorPed->init(es); subtractorCMN->init(es); std::string label = findInput(inputRawdigis, inputTokensRawDigi, e); - if( "VirginRaw" == label ) vr_process(*inputRawdigis, *output); - else if( "ProcessedRaw" == label ) pr_process(*inputRawdigis, *output); - else if( "ZeroSuppressed" == findInput(inputDigis, inputTokensDigi, e) ) zs_process(*inputDigis, *output); + if ("VirginRaw" == label) + vr_process(*inputRawdigis, *output); + else if ("ProcessedRaw" == label) + pr_process(*inputRawdigis, *output); + else if ("ZeroSuppressed" == findInput(inputDigis, inputTokensDigi, e)) + zs_process(*inputDigis, *output); else edm::LogError("Input Not Found"); e.put(std::move(output)); } -template -inline -std::string SiStripProcessedRawDigiProducer:: -findInput(edm::Handle& handle, const std::vector >& tokens, const edm::Event& e ) { - - for( typename std::vector >::const_iterator - token = tokens.begin(); token != tokens.end(); ++token ) { +template +inline std::string SiStripProcessedRawDigiProducer::findInput(edm::Handle& handle, + const std::vector >& tokens, + const edm::Event& e) { + for (typename std::vector >::const_iterator token = tokens.begin(); token != tokens.end(); + ++token) { unsigned index(token - tokens.begin()); e.getByToken(*token, handle); - if( handle.isValid() && !handle->empty() ) { + if (handle.isValid() && !handle->empty()) { edm::LogInfo("Input") << inputTags.at(index); return inputTags.at(index).instance(); } @@ -65,50 +66,50 @@ findInput(edm::Handle& handle, const std::vector >& token return "Input Not Found"; } -void SiStripProcessedRawDigiProducer:: -zs_process(const edm::DetSetVector & input, edm::DetSetVector& output) { +void SiStripProcessedRawDigiProducer::zs_process(const edm::DetSetVector& input, + edm::DetSetVector& output) { std::vector digis; - for(edm::DetSetVector::const_iterator detset = input.begin(); detset != input.end(); ++detset ) { + for (edm::DetSetVector::const_iterator detset = input.begin(); detset != input.end(); ++detset) { digis.clear(); - for(edm::DetSet::const_iterator digi = detset->begin(); digi != detset->end(); ++digi) { - digis.resize( digi->strip(), 0); - digis.push_back( digi->adc() ); + for (edm::DetSet::const_iterator digi = detset->begin(); digi != detset->end(); ++digi) { + digis.resize(digi->strip(), 0); + digis.push_back(digi->adc()); } - common_process( detset->id, digis, output); + common_process(detset->id, digis, output); } } -void SiStripProcessedRawDigiProducer:: -pr_process(const edm::DetSetVector & input, edm::DetSetVector& output) { - for(edm::DetSetVector::const_iterator detset=input.begin(); detset!=input.end(); ++detset) { +void SiStripProcessedRawDigiProducer::pr_process(const edm::DetSetVector& input, + edm::DetSetVector& output) { + for (edm::DetSetVector::const_iterator detset = input.begin(); detset != input.end(); ++detset) { std::vector digis; - transform(detset->begin(), detset->end(), back_inserter(digis), boost::bind(&SiStripRawDigi::adc , _1)); + transform(detset->begin(), detset->end(), back_inserter(digis), boost::bind(&SiStripRawDigi::adc, _1)); subtractorCMN->subtract(detset->id, 0, digis); - common_process( detset->id, digis, output); + common_process(detset->id, digis, output); } } -void SiStripProcessedRawDigiProducer:: -vr_process(const edm::DetSetVector & input, edm::DetSetVector& output) { - for(edm::DetSetVector::const_iterator detset=input.begin(); detset!=input.end(); ++detset) { +void SiStripProcessedRawDigiProducer::vr_process(const edm::DetSetVector& input, + edm::DetSetVector& output) { + for (edm::DetSetVector::const_iterator detset = input.begin(); detset != input.end(); ++detset) { std::vector int_digis(detset->size()); - subtractorPed->subtract(*detset,int_digis); + subtractorPed->subtract(*detset, int_digis); std::vector digis(int_digis.begin(), int_digis.end()); subtractorCMN->subtract(detset->id, 0, digis); - common_process( detset->id, digis, output); + common_process(detset->id, digis, output); } } -void SiStripProcessedRawDigiProducer:: -common_process(const uint32_t detId, std::vector & digis, edm::DetSetVector& output) { - +void SiStripProcessedRawDigiProducer::common_process(const uint32_t detId, + std::vector& digis, + edm::DetSetVector& output) { //Apply Gains - SiStripApvGain::Range detGainRange = gainHandle->getRange(detId); - for(std::vector::iterator it=digis.begin(); itgetStripGain(it-digis.begin(), detGainRange)); + SiStripApvGain::Range detGainRange = gainHandle->getRange(detId); + for (std::vector::iterator it = digis.begin(); it < digis.end(); ++it) + (*it) /= (gainHandle->getStripGain(it - digis.begin(), detGainRange)); //Insert as DetSet edm::DetSet ds(detId); - copy(digis.begin(), digis.end(), back_inserter(ds.data) ); + copy(digis.begin(), digis.end(), back_inserter(ds.data)); output.insert(ds); } diff --git a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.h b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.h index 707de78bcdb3b..04cde6e8366ec 100644 --- a/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.h +++ b/AnalysisAlgos/SiStripClusterInfoProducer/plugins/SiStripProcessedRawDigiProducer.h @@ -20,30 +20,25 @@ class SiStripGain; class SiStripProcessedRawDigi; class SiStripProcessedRawDigiProducer : public edm::EDProducer { - - public: - +public: explicit SiStripProcessedRawDigiProducer(edm::ParameterSet const&); - private: - +private: void produce(edm::Event& e, const edm::EventSetup& es) override; - template std::string findInput(edm::Handle& handle, const std::vector >& tokens, const edm::Event& e); + template + std::string findInput(edm::Handle& handle, const std::vector >& tokens, const edm::Event& e); void vr_process(const edm::DetSetVector&, edm::DetSetVector&); void pr_process(const edm::DetSetVector&, edm::DetSetVector&); - void zs_process(const edm::DetSetVector&, edm::DetSetVector&); - void common_process( const uint32_t, std::vector&, edm::DetSetVector&); - + void zs_process(const edm::DetSetVector&, edm::DetSetVector&); + void common_process(const uint32_t, std::vector&, edm::DetSetVector&); std::vector inputTags; std::vector > > inputTokensDigi; std::vector > > inputTokensRawDigi; edm::ESHandle gainHandle; - std::unique_ptr subtractorPed; + std::unique_ptr subtractorPed; std::unique_ptr subtractorCMN; - }; #endif - diff --git a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPCaloInfo.h b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPCaloInfo.h index c2db06dc287b7..247ecd2ecbab3 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPCaloInfo.h +++ b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPCaloInfo.h @@ -10,57 +10,54 @@ namespace susybsm { + class HSCPCaloInfo { + public: + float hcalCrossedEnergy, ecalCrossedEnergy, hoCrossedEnergy; + float ecal3by3dir, ecal5by5dir; + float hcal3by3dir, hcal5by5dir; + float ecalBeta, ecalBetaError; + float ecalDeDx; + float trkIsoDr; + float ecalTime, ecalTimeError; + float ecalInvBetaError; + int ecalCrysCrossed; + std::vector ecalSwissCrossKs; + std::vector ecalE1OverE9s; + std::vector ecalTrackLengths; + std::vector ecalEnergies; + std::vector ecalTimes; + std::vector ecalTimeErrors; + std::vector ecalChi2s; + std::vector ecalOutOfTimeChi2s; + std::vector ecalOutOfTimeEnergies; + std::vector ecalDetIds; + std::vector ecalTrackExitPositions; - class HSCPCaloInfo - { - public: - float hcalCrossedEnergy, ecalCrossedEnergy, hoCrossedEnergy; - float ecal3by3dir, ecal5by5dir; - float hcal3by3dir, hcal5by5dir; - float ecalBeta, ecalBetaError; - float ecalDeDx; - float trkIsoDr; - float ecalTime, ecalTimeError; - float ecalInvBetaError; - int ecalCrysCrossed; - std::vector ecalSwissCrossKs; - std::vector ecalE1OverE9s; - std::vector ecalTrackLengths; - std::vector ecalEnergies; - std::vector ecalTimes; - std::vector ecalTimeErrors; - std::vector ecalChi2s; - std::vector ecalOutOfTimeChi2s; - std::vector ecalOutOfTimeEnergies; - std::vector ecalDetIds; - std::vector ecalTrackExitPositions; - - HSCPCaloInfo() - { - hcalCrossedEnergy = -9999; - ecalCrossedEnergy = -9999; - hoCrossedEnergy = -9999; - ecal3by3dir = -9999; - ecal5by5dir = -9999; - hcal3by3dir = -9999; - hcal5by5dir = -9999; - ecalBeta = -9999; - ecalBetaError = -9999; - ecalDeDx = -9999; - trkIsoDr = -9999; - ecalTime = -9999; - ecalTimeError = -9999; - ecalInvBetaError = -9999; - ecalCrysCrossed = 0; - } + HSCPCaloInfo() { + hcalCrossedEnergy = -9999; + ecalCrossedEnergy = -9999; + hoCrossedEnergy = -9999; + ecal3by3dir = -9999; + ecal5by5dir = -9999; + hcal3by3dir = -9999; + hcal5by5dir = -9999; + ecalBeta = -9999; + ecalBetaError = -9999; + ecalDeDx = -9999; + trkIsoDr = -9999; + ecalTime = -9999; + ecalTimeError = -9999; + ecalInvBetaError = -9999; + ecalCrysCrossed = 0; + } }; - typedef std::vector HSCPCaloInfoCollection; - typedef edm::ValueMap HSCPCaloInfoValueMap; - typedef edm::Ref HSCPCaloInfoRef; - typedef edm::RefProd HSCPCaloInfoRefProd; - typedef edm::RefVector HSCPCaloInfoRefVector; + typedef std::vector HSCPCaloInfoCollection; + typedef edm::ValueMap HSCPCaloInfoValueMap; + typedef edm::Ref HSCPCaloInfoRef; + typedef edm::RefProd HSCPCaloInfoRefProd; + typedef edm::RefVector HSCPCaloInfoRefVector; -} +} // namespace susybsm #endif diff --git a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPDeDxInfo.h b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPDeDxInfo.h index 91d0e08518652..43b2bea700059 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPDeDxInfo.h +++ b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPDeDxInfo.h @@ -10,23 +10,22 @@ namespace susybsm { - class HSCPDeDxInfo - { - public: - std::vector charges; - std::vector pathlengths; - std::vector detIds; - std::vector localPosXs; - std::vector localPosYs; - std::vector clusterIndices; - HSCPDeDxInfo(){} + class HSCPDeDxInfo { + public: + std::vector charges; + std::vector pathlengths; + std::vector detIds; + std::vector localPosXs; + std::vector localPosYs; + std::vector clusterIndices; + HSCPDeDxInfo() {} }; - typedef std::vector HSCPDeDxInfoCollection; - typedef edm::ValueMap HSCPDeDxInfoValueMap; - typedef edm::Ref HSCPDeDxInfoRef; - typedef edm::RefProd HSCPDeDxInfoRefProd; - typedef edm::RefVector HSCPDeDxInfoRefVector; -} + typedef std::vector HSCPDeDxInfoCollection; + typedef edm::ValueMap HSCPDeDxInfoValueMap; + typedef edm::Ref HSCPDeDxInfoRef; + typedef edm::RefProd HSCPDeDxInfoRefProd; + typedef edm::RefVector HSCPDeDxInfoRefVector; +} // namespace susybsm #endif diff --git a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPIsolation.h b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPIsolation.h index e6cc966b22c45..716a2b801238d 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPIsolation.h +++ b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCPIsolation.h @@ -10,40 +10,39 @@ namespace susybsm { - class HSCPIsolation - { - public: - // constructor - HSCPIsolation(){ - TK_CountHighPt = -1; - TK_Count = -1; - TK_SumEt = -1; - ECAL_Energy = -1; - HCAL_Energy = -1; - } + class HSCPIsolation { + public: + // constructor + HSCPIsolation() { + TK_CountHighPt = -1; + TK_Count = -1; + TK_SumEt = -1; + ECAL_Energy = -1; + HCAL_Energy = -1; + } - void Set_TK_CountHighPt(double value){TK_CountHighPt = value;} - void Set_TK_Count (double value){TK_Count = value;} - void Set_TK_SumEt (double value){TK_SumEt = value;} - void Set_ECAL_Energy (double value){ECAL_Energy = value;} - void Set_HCAL_Energy (double value){HCAL_Energy = value;} + void Set_TK_CountHighPt(double value) { TK_CountHighPt = value; } + void Set_TK_Count(double value) { TK_Count = value; } + void Set_TK_SumEt(double value) { TK_SumEt = value; } + void Set_ECAL_Energy(double value) { ECAL_Energy = value; } + void Set_HCAL_Energy(double value) { HCAL_Energy = value; } - double Get_TK_CountHighPt() {return TK_CountHighPt;} - double Get_TK_Count () {return TK_Count ;} - double Get_TK_SumEt () {return TK_SumEt ;} - double Get_ECAL_Energy () {return ECAL_Energy ;} - double Get_HCAL_Energy () {return HCAL_Energy ;} + double Get_TK_CountHighPt() { return TK_CountHighPt; } + double Get_TK_Count() { return TK_Count; } + double Get_TK_SumEt() { return TK_SumEt; } + double Get_ECAL_Energy() { return ECAL_Energy; } + double Get_HCAL_Energy() { return HCAL_Energy; } - public: - double TK_CountHighPt; - double TK_Count; - double TK_SumEt; - double ECAL_Energy; - double HCAL_Energy; + public: + double TK_CountHighPt; + double TK_Count; + double TK_SumEt; + double ECAL_Energy; + double HCAL_Energy; }; - typedef std::vector HSCPIsolationCollection; - typedef edm::ValueMap HSCPIsolationValueMap; -} + typedef std::vector HSCPIsolationCollection; + typedef edm::ValueMap HSCPIsolationValueMap; +} // namespace susybsm #endif diff --git a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCParticle.h b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCParticle.h index 6203e1e2aeb5c..df867db33a4e5 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/interface/HSCParticle.h +++ b/AnalysisDataFormats/SUSYBSMObjects/interface/HSCParticle.h @@ -15,86 +15,78 @@ namespace susybsm { - /// define arbitration schemes - namespace HSCParticleType{ - enum Type {globalMuon, trackerMuon, matchedStandAloneMuon, standAloneMuon, innerTrack, unknown }; - } + /// define arbitration schemes + namespace HSCParticleType { + enum Type { globalMuon, trackerMuon, matchedStandAloneMuon, standAloneMuon, innerTrack, unknown }; + } - class RPCHit4D - { - public: - int id; - int bx; - GlobalPoint gp; - bool operator<(const RPCHit4D& other) const { - return gp.mag() < other.gp.mag(); - } - }; - - - class RPCBetaMeasurement - { - public: - bool isCandidate; - float beta; - - RPCBetaMeasurement(){ - isCandidate = false; - beta = -9999; - } + class RPCHit4D { + public: + int id; + int bx; + GlobalPoint gp; + bool operator<(const RPCHit4D& other) const { return gp.mag() < other.gp.mag(); } }; + class RPCBetaMeasurement { + public: + bool isCandidate; + float beta; - class HSCParticle - { - public: - // constructor - HSCParticle(){ } + RPCBetaMeasurement() { + isCandidate = false; + beta = -9999; + } + }; - // check available infos - bool hasMuonRef() const { return muonRef_.isNonnull(); } - bool hasMTMuonRef() const { return MTMuonRef_.isNonnull(); } - bool hasTrackRef() const { return trackRef_.isNonnull(); } - bool hasTrackIsoRef() const { return trackIsoRef_.isNonnull(); } - bool hasRpcInfo() const { return rpc_.beta!=-9999; } - bool hasCaloInfo() const { return caloInfoRef_.isNonnull(); } + class HSCParticle { + public: + // constructor + HSCParticle() {} - // set infos - void setMuon (const reco::MuonRef& data) {muonRef_ = data;} - void setMTMuon (const reco::MuonRef& data) {MTMuonRef_ = data;} - void setTrack (const reco::TrackRef& data) {trackRef_ = data;} - void setTrackIso (const reco::TrackRef& data) {trackIsoRef_ = data;} - void setRpc (const RPCBetaMeasurement& data) {rpc_ = data;} - void setCaloInfo (const HSCPCaloInfoRef& data) {caloInfoRef_ = data;} + // check available infos + bool hasMuonRef() const { return muonRef_.isNonnull(); } + bool hasMTMuonRef() const { return MTMuonRef_.isNonnull(); } + bool hasTrackRef() const { return trackRef_.isNonnull(); } + bool hasTrackIsoRef() const { return trackIsoRef_.isNonnull(); } + bool hasRpcInfo() const { return rpc_.beta != -9999; } + bool hasCaloInfo() const { return caloInfoRef_.isNonnull(); } + // set infos + void setMuon(const reco::MuonRef& data) { muonRef_ = data; } + void setMTMuon(const reco::MuonRef& data) { MTMuonRef_ = data; } + void setTrack(const reco::TrackRef& data) { trackRef_ = data; } + void setTrackIso(const reco::TrackRef& data) { trackIsoRef_ = data; } + void setRpc(const RPCBetaMeasurement& data) { rpc_ = data; } + void setCaloInfo(const HSCPCaloInfoRef& data) { caloInfoRef_ = data; } - // get infos - reco::TrackRef trackRef () const { return trackRef_; } - reco::TrackRef trackIsoRef () const { return trackIsoRef_; } - reco::MuonRef muonRef () const { return muonRef_; } - reco::MuonRef MTMuonRef () const { return MTMuonRef_; } - HSCPCaloInfoRef caloInfoRef () const { return caloInfoRef_; } - const RPCBetaMeasurement& rpc () const { return rpc_; } + // get infos + reco::TrackRef trackRef() const { return trackRef_; } + reco::TrackRef trackIsoRef() const { return trackIsoRef_; } + reco::MuonRef muonRef() const { return muonRef_; } + reco::MuonRef MTMuonRef() const { return MTMuonRef_; } + HSCPCaloInfoRef caloInfoRef() const { return caloInfoRef_; } + const RPCBetaMeasurement& rpc() const { return rpc_; } - // shortcut of long function - float p () const; - float pt() const; - int type() const; + // shortcut of long function + float p() const; + float pt() const; + int type() const; - private: - reco::TrackRef trackRef_; //TrackRef from refitted track collection (dE/dx purposes) - reco::TrackRef trackIsoRef_; //TrackRef from general track collection (isolation purposes) - reco::MuonRef muonRef_; - reco::MuonRef MTMuonRef_; //Muon reconstructed from MT muon segments. SA only - HSCPCaloInfoRef caloInfoRef_; + private: + reco::TrackRef trackRef_; //TrackRef from refitted track collection (dE/dx purposes) + reco::TrackRef trackIsoRef_; //TrackRef from general track collection (isolation purposes) + reco::MuonRef muonRef_; + reco::MuonRef MTMuonRef_; //Muon reconstructed from MT muon segments. SA only + HSCPCaloInfoRef caloInfoRef_; - RPCBetaMeasurement rpc_; + RPCBetaMeasurement rpc_; }; - typedef std::vector HSCParticleCollection; - typedef edm::Ref HSCParticleRef; - typedef edm::RefProd HSCParticleRefProd; - typedef edm::RefVector HSCParticleRefVector; - typedef edm::AssociationMap > TracksEcalRecHitsMap; -} + typedef std::vector HSCParticleCollection; + typedef edm::Ref HSCParticleRef; + typedef edm::RefProd HSCParticleRefProd; + typedef edm::RefVector HSCParticleRefVector; + typedef edm::AssociationMap > TracksEcalRecHitsMap; +} // namespace susybsm #endif diff --git a/AnalysisDataFormats/SUSYBSMObjects/interface/MuonSegment.h b/AnalysisDataFormats/SUSYBSMObjects/interface/MuonSegment.h index 81a834e9e4c4a..f8bf9dd643c20 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/interface/MuonSegment.h +++ b/AnalysisDataFormats/SUSYBSMObjects/interface/MuonSegment.h @@ -10,37 +10,36 @@ namespace susybsm { - class MuonSegment - { - public: - MuonSegment() {}; - //bool isDT() const { return DT;} - //bool isCSC() const { return CSC;} + class MuonSegment { + public: + MuonSegment(){}; + //bool isDT() const { return DT;} + //bool isCSC() const { return CSC;} - //void setDT(const bool type) {DT = type;} - //void setCSC(const bool type) {CSC = type;} + //void setDT(const bool type) {DT = type;} + //void setCSC(const bool type) {CSC = type;} - void setDTSegmentRef(const DTRecSegment4DRef segment) { DTSegmentRef_ = segment;} - void setCSCSegmentRef(const CSCSegmentRef segment) { CSCSegmentRef_ = segment;} + void setDTSegmentRef(const DTRecSegment4DRef segment) { DTSegmentRef_ = segment; } + void setCSCSegmentRef(const CSCSegmentRef segment) { CSCSegmentRef_ = segment; } - void setGP(const GlobalPoint point) { gp=point;} + void setGP(const GlobalPoint point) { gp = point; } - GlobalPoint getGP() const {return gp;} + GlobalPoint getGP() const { return gp; } - DTRecSegment4DRef getDTSegmentRef() const {return DTSegmentRef_;} - CSCSegmentRef getCSCSegmentRef() const {return CSCSegmentRef_;} + DTRecSegment4DRef getDTSegmentRef() const { return DTSegmentRef_; } + CSCSegmentRef getCSCSegmentRef() const { return CSCSegmentRef_; } - private: - GlobalPoint gp; + private: + GlobalPoint gp; - DTRecSegment4DRef DTSegmentRef_; - CSCSegmentRef CSCSegmentRef_; - }; + DTRecSegment4DRef DTSegmentRef_; + CSCSegmentRef CSCSegmentRef_; + }; - typedef std::vector MuonSegmentCollection; - typedef edm::Ref MuonSegmentRef; - typedef edm::RefProd MuonSegmentRefProd; - typedef edm::RefVector MuonSegmentRefVector; -} + typedef std::vector MuonSegmentCollection; + typedef edm::Ref MuonSegmentRef; + typedef edm::RefProd MuonSegmentRefProd; + typedef edm::RefVector MuonSegmentRefVector; +} // namespace susybsm #endif diff --git a/AnalysisDataFormats/SUSYBSMObjects/src/HSCParticle.cc b/AnalysisDataFormats/SUSYBSMObjects/src/HSCParticle.cc index ff89075ff55b7..ab73745f712a5 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/src/HSCParticle.cc +++ b/AnalysisDataFormats/SUSYBSMObjects/src/HSCParticle.cc @@ -2,29 +2,45 @@ namespace susybsm { -int HSCParticle::type() const { - if ( hasTrackRef() && !hasMuonRef()){ return HSCParticleType::innerTrack; - }else if(!hasTrackRef() && hasMuonRef()){ return HSCParticleType::standAloneMuon; - }else if( hasTrackRef() && hasMuonRef() && muonRef()->isGlobalMuon()){ return HSCParticleType::globalMuon; - }else if( hasTrackRef() && hasMuonRef() && muonRef()->isStandAloneMuon()){ return HSCParticleType::matchedStandAloneMuon; - }else if( hasTrackRef() && hasMuonRef() && muonRef()->isTrackerMuon()){ return HSCParticleType::trackerMuon; - }else return HSCParticleType::unknown; -} + int HSCParticle::type() const { + if (hasTrackRef() && !hasMuonRef()) { + return HSCParticleType::innerTrack; + } else if (!hasTrackRef() && hasMuonRef()) { + return HSCParticleType::standAloneMuon; + } else if (hasTrackRef() && hasMuonRef() && muonRef()->isGlobalMuon()) { + return HSCParticleType::globalMuon; + } else if (hasTrackRef() && hasMuonRef() && muonRef()->isStandAloneMuon()) { + return HSCParticleType::matchedStandAloneMuon; + } else if (hasTrackRef() && hasMuonRef() && muonRef()->isTrackerMuon()) { + return HSCParticleType::trackerMuon; + } else + return HSCParticleType::unknown; + } -float HSCParticle::p() const { - if( hasMuonRef() && muonRef()->combinedMuon() .isNonnull()){ return muonRef()->combinedMuon() ->p(); - }else if(hasMuonRef() && muonRef()->innerTrack() .isNonnull()){ return muonRef()->innerTrack() ->p(); - }else if(hasMuonRef() && muonRef()->standAloneMuon().isNonnull()){ return muonRef()->standAloneMuon()->p(); - }else if(hasTrackRef()&& trackRef() .isNonnull()){ return trackRef() ->p(); - }else return 0.0f; -} + float HSCParticle::p() const { + if (hasMuonRef() && muonRef()->combinedMuon().isNonnull()) { + return muonRef()->combinedMuon()->p(); + } else if (hasMuonRef() && muonRef()->innerTrack().isNonnull()) { + return muonRef()->innerTrack()->p(); + } else if (hasMuonRef() && muonRef()->standAloneMuon().isNonnull()) { + return muonRef()->standAloneMuon()->p(); + } else if (hasTrackRef() && trackRef().isNonnull()) { + return trackRef()->p(); + } else + return 0.0f; + } -float HSCParticle::pt() const { - if( hasMuonRef() && muonRef()->combinedMuon() .isNonnull()){ return muonRef()->combinedMuon() ->pt(); - }else if(hasMuonRef() && muonRef()->innerTrack() .isNonnull()){ return muonRef()->innerTrack() ->pt(); - }else if(hasMuonRef() && muonRef()->standAloneMuon().isNonnull()){ return muonRef()->standAloneMuon()->pt(); - }else if(hasTrackRef()&& trackRef() .isNonnull()){ return trackRef() ->pt(); - }else return 0.0f; -} + float HSCParticle::pt() const { + if (hasMuonRef() && muonRef()->combinedMuon().isNonnull()) { + return muonRef()->combinedMuon()->pt(); + } else if (hasMuonRef() && muonRef()->innerTrack().isNonnull()) { + return muonRef()->innerTrack()->pt(); + } else if (hasMuonRef() && muonRef()->standAloneMuon().isNonnull()) { + return muonRef()->standAloneMuon()->pt(); + } else if (hasTrackRef() && trackRef().isNonnull()) { + return trackRef()->pt(); + } else + return 0.0f; + } -} +} // namespace susybsm diff --git a/AnalysisDataFormats/SUSYBSMObjects/src/classes.h b/AnalysisDataFormats/SUSYBSMObjects/src/classes.h index 848383b68c6ab..f3e5ef27fd98d 100644 --- a/AnalysisDataFormats/SUSYBSMObjects/src/classes.h +++ b/AnalysisDataFormats/SUSYBSMObjects/src/classes.h @@ -6,7 +6,7 @@ namespace AnalysisDataFormats_SUSYBSMObjects { susybsm::HSCParticle pa; -/* susybsm::DriftTubeTOF dtitof; + /* susybsm::DriftTubeTOF dtitof; susybsm::TimeMeasurement tm; std::vector tmv; @@ -19,9 +19,9 @@ namespace AnalysisDataFormats_SUSYBSMObjects { std::vector,reco::Muon,edm::refhelper::FindUsingAdvance,reco::Muon> >,susybsm::DriftTubeTOF> > a; std::vector b; */ -// susybsm::CaloBetaMeasurement calobeta; + // susybsm::CaloBetaMeasurement calobeta; susybsm::RPCBetaMeasurement rpcbeta; -//susybsm::DeDxBeta dedxbeta; + //susybsm::DeDxBeta dedxbeta; susybsm::HSCParticleCollection hc; susybsm::HSCParticleRef hr; susybsm::HSCParticleRefProd hp; @@ -34,15 +34,17 @@ namespace AnalysisDataFormats_SUSYBSMObjects { susybsm::MuonSegmentRefProd msp; susybsm::MuonSegmentRefVector msv; edm::Wrapper mswr1; - + susybsm::TracksEcalRecHitsMap terhm; edm::Wrapper wr2; - edm::helpers::KeyVal >,edm::RefProd > > > hlpr1; + edm::helpers::KeyVal >, + edm::RefProd > > > + hlpr1; susybsm::HSCPIsolation hscpI; susybsm::HSCPIsolationCollection hscpIc; - susybsm::HSCPIsolationValueMap hscpIvm; - edm::Wrapper hscpIW; + susybsm::HSCPIsolationValueMap hscpIvm; + edm::Wrapper hscpIW; edm::Wrapper hscpIcW; edm::Wrapper hscpIvmW; @@ -65,4 +67,4 @@ namespace AnalysisDataFormats_SUSYBSMObjects { edm::Wrapper hscpDEDXW; edm::Wrapper hscpDEDXcW; edm::Wrapper hscpDEDXvmW; -} +} // namespace AnalysisDataFormats_SUSYBSMObjects diff --git a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuMuonUserData.cc b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuMuonUserData.cc old mode 100755 new mode 100644 index 82f910f3d11c7..9c09c1427f8e1 --- a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuMuonUserData.cc +++ b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuMuonUserData.cc @@ -27,45 +27,63 @@ using namespace isodeposit; class ZMuMuMuonUserData : public edm::EDProducer { public: - ZMuMuMuonUserData( const edm::ParameterSet & ); + ZMuMuMuonUserData(const edm::ParameterSet &); + private: - void produce( edm::Event &, const edm::EventSetup & ) override; + void produce(edm::Event &, const edm::EventSetup &) override; EDGetTokenT > srcToken_; EDGetTokenT beamSpotToken_; EDGetTokenT primaryVerticesToken_; double alpha_, beta_; - double ptThreshold_, etEcalThreshold_, etHcalThreshold_ ,dRVetoTrk_, dRTrk_, dREcal_ , dRHcal_; + double ptThreshold_, etEcalThreshold_, etHcalThreshold_, dRVetoTrk_, dRTrk_, dREcal_, dRHcal_; string hltPath_; - template - vector isolation(const T & t, double ptThreshold, double etEcalThreshold, double etHcalThreshold , double dRVetoTrk, double dRTrk, double dREcal , double dRHcal, double alpha, double beta); + template + vector isolation(const T &t, + double ptThreshold, + double etEcalThreshold, + double etHcalThreshold, + double dRVetoTrk, + double dRTrk, + double dREcal, + double dRHcal, + double alpha, + double beta); }; -template -vector ZMuMuMuonUserData::isolation(const T & t, double ptThreshold, double etEcalThreshold, double etHcalThreshold , double dRVetoTrk, double dRTrk, double dREcal , double dRHcal, double alpha, double beta) { - +template +vector ZMuMuMuonUserData::isolation(const T &t, + double ptThreshold, + double etEcalThreshold, + double etHcalThreshold, + double dRVetoTrk, + double dRTrk, + double dREcal, + double dRHcal, + double alpha, + double beta) { vector iso; - const pat::IsoDeposit * trkIso = t.isoDeposit(pat::TrackIso); - const pat::IsoDeposit * ecalIso = t.isoDeposit(pat::EcalIso); - const pat::IsoDeposit * hcalIso = t.isoDeposit(pat::HcalIso); + const pat::IsoDeposit *trkIso = t.isoDeposit(pat::TrackIso); + const pat::IsoDeposit *ecalIso = t.isoDeposit(pat::EcalIso); + const pat::IsoDeposit *hcalIso = t.isoDeposit(pat::HcalIso); Direction dir = Direction(t.eta(), t.phi()); pat::IsoDeposit::AbsVetos vetosTrk; - vetosTrk.push_back(new ConeVeto( dir, dRVetoTrk )); - vetosTrk.push_back(new ThresholdVeto( ptThreshold )); + vetosTrk.push_back(new ConeVeto(dir, dRVetoTrk)); + vetosTrk.push_back(new ThresholdVeto(ptThreshold)); pat::IsoDeposit::AbsVetos vetosEcal; - vetosEcal.push_back(new ConeVeto( dir, 0.)); - vetosEcal.push_back(new ThresholdVeto( etEcalThreshold )); + vetosEcal.push_back(new ConeVeto(dir, 0.)); + vetosEcal.push_back(new ThresholdVeto(etEcalThreshold)); pat::IsoDeposit::AbsVetos vetosHcal; - vetosHcal.push_back(new ConeVeto( dir, 0. )); - vetosHcal.push_back(new ThresholdVeto( etHcalThreshold )); + vetosHcal.push_back(new ConeVeto(dir, 0.)); + vetosHcal.push_back(new ThresholdVeto(etHcalThreshold)); - double isovalueTrk = (trkIso->sumWithin(dRTrk,vetosTrk)); - double isovalueEcal = (ecalIso->sumWithin(dREcal,vetosEcal)); - double isovalueHcal = (hcalIso->sumWithin(dRHcal,vetosHcal)); + double isovalueTrk = (trkIso->sumWithin(dRTrk, vetosTrk)); + double isovalueEcal = (ecalIso->sumWithin(dREcal, vetosEcal)); + double isovalueHcal = (hcalIso->sumWithin(dRHcal, vetosHcal)); iso.push_back(isovalueTrk); //cout<<"isoTrk"< ZMuMuMuonUserData::isolation(const T & t, double ptThreshold, dou //double isovalueHcal = t.hcalIso(); //double iso = isovalueTrk + isovalueEcal + isovalueHcal; - double combIso = alpha*( ((1+beta)/2*isovalueEcal) + ((1-beta)/2*isovalueHcal) ) + ((1-alpha)*isovalueTrk); + double combIso = + alpha * (((1 + beta) / 2 * isovalueEcal) + ((1 - beta) / 2 * isovalueHcal)) + ((1 - alpha) * isovalueTrk); iso.push_back(combIso); //cout<<"combIso"< ZMuMuMuonUserData::isolation(const T & t, double ptThreshold, dou return iso; } -ZMuMuMuonUserData::ZMuMuMuonUserData( const ParameterSet & cfg ): - srcToken_(consumes > ( cfg.getParameter( "src" ) ) ), - beamSpotToken_(consumes (cfg.getParameter( "beamSpot" ) ) ), - primaryVerticesToken_(consumes (cfg.getParameter( "primaryVertices" ) ) ), - alpha_(cfg.getParameter("alpha") ), - beta_(cfg.getParameter("beta") ), - ptThreshold_(cfg.getParameter("ptThreshold") ), - etEcalThreshold_(cfg.getParameter("etEcalThreshold") ), - etHcalThreshold_(cfg.getParameter("etHcalThreshold") ), - dRVetoTrk_(cfg.getParameter("dRVetoTrk") ), - dRTrk_(cfg.getParameter("dRTrk") ), - dREcal_(cfg.getParameter("dREcal") ), - dRHcal_(cfg.getParameter("dRHcal") ), - hltPath_(cfg.getParameter("hltPath") ){ +ZMuMuMuonUserData::ZMuMuMuonUserData(const ParameterSet &cfg) + : srcToken_(consumes >(cfg.getParameter("src"))), + beamSpotToken_(consumes(cfg.getParameter("beamSpot"))), + primaryVerticesToken_(consumes(cfg.getParameter("primaryVertices"))), + alpha_(cfg.getParameter("alpha")), + beta_(cfg.getParameter("beta")), + ptThreshold_(cfg.getParameter("ptThreshold")), + etEcalThreshold_(cfg.getParameter("etEcalThreshold")), + etHcalThreshold_(cfg.getParameter("etHcalThreshold")), + dRVetoTrk_(cfg.getParameter("dRVetoTrk")), + dRTrk_(cfg.getParameter("dRTrk")), + dREcal_(cfg.getParameter("dREcal")), + dRHcal_(cfg.getParameter("dRHcal")), + hltPath_(cfg.getParameter("hltPath")) { produces >(); } -void ZMuMuMuonUserData::produce( Event & evt, const EventSetup & ) { - Handle > muons; - evt.getByToken(srcToken_,muons); +void ZMuMuMuonUserData::produce(Event &evt, const EventSetup &) { + Handle > muons; + evt.getByToken(srcToken_, muons); Handle beamSpotHandle; evt.getByToken(beamSpotToken_, beamSpotHandle); @@ -115,11 +134,12 @@ void ZMuMuMuonUserData::produce( Event & evt, const EventSetup & ) { Handle primaryVertices; // Collection of primary Vertices evt.getByToken(primaryVerticesToken_, primaryVertices); - unique_ptr > muonColl( new vector (*muons) ); - for (unsigned int i = 0; i< muonColl->size();++i){ - pat::Muon & m = (*muonColl)[i]; + unique_ptr > muonColl(new vector(*muons)); + for (unsigned int i = 0; i < muonColl->size(); ++i) { + pat::Muon &m = (*muonColl)[i]; //pat::Muon *mu = new pat::Muon(m); - vector iso = isolation(m,ptThreshold_, etEcalThreshold_, etHcalThreshold_ ,dRVetoTrk_, dRTrk_, dREcal_ , dRHcal_, alpha_, beta_); + vector iso = isolation( + m, ptThreshold_, etEcalThreshold_, etHcalThreshold_, dRVetoTrk_, dRTrk_, dREcal_, dRHcal_, alpha_, beta_); m.setIsolation(pat::User1Iso, iso[0]); //cout<<"muon User1Iso "<dxy(beamSpotHandle->position()); zDaudzFromBS = muGlbRef->dz(beamSpotHandle->position()); - zDaudxyFromPV = muGlbRef->dxy(primaryVertices->begin()->position() ); - zDaudzFromPV = muGlbRef->dz(primaryVertices->begin()->position() ); + zDaudxyFromPV = muGlbRef->dxy(primaryVertices->begin()->position()); + zDaudzFromPV = muGlbRef->dz(primaryVertices->begin()->position()); zDauChi2 = muGlbRef->normalizedChi2(); zDauTrkChi2 = muTrkRef->normalizedChi2(); zDauSaChi2 = muSaRef->normalizedChi2(); @@ -169,60 +186,56 @@ void ZMuMuMuonUserData::produce( Event & evt, const EventSetup & ) { zDauTrkNofStripHits = muTrkRef->hitPattern().numberOfValidStripHits(); zDauNofPixelHits = muGlbRef->hitPattern().numberOfValidPixelHits(); zDauTrkNofPixelHits = muTrkRef->hitPattern().numberOfValidPixelHits(); - } - else if (muSaRef.isNonnull() && m.isStandAloneMuon() == true){ + } else if (muSaRef.isNonnull() && m.isStandAloneMuon() == true) { zDaudxyFromBS = muSaRef->dxy(beamSpotHandle->position()); zDaudzFromBS = muSaRef->dz(beamSpotHandle->position()); - zDaudxyFromPV = muSaRef->dxy(primaryVertices->begin()->position() ); - zDaudzFromPV = muSaRef->dz(primaryVertices->begin()->position() ); + zDaudxyFromPV = muSaRef->dxy(primaryVertices->begin()->position()); + zDaudzFromPV = muSaRef->dz(primaryVertices->begin()->position()); zDauSaChi2 = muSaRef->normalizedChi2(); zDauSaNofMuonHits = muSaRef->hitPattern().numberOfValidMuonHits(); - } - else if (muTrkRef.isNonnull() && m.isTrackerMuon() == true){ + } else if (muTrkRef.isNonnull() && m.isTrackerMuon() == true) { zDaudxyFromBS = muTrkRef->dxy(beamSpotHandle->position()); zDaudzFromBS = muTrkRef->dz(beamSpotHandle->position()); - zDaudxyFromPV = muTrkRef->dxy(primaryVertices->begin()->position() ); - zDaudzFromPV = muTrkRef->dz(primaryVertices->begin()->position() ); + zDaudxyFromPV = muTrkRef->dxy(primaryVertices->begin()->position()); + zDaudzFromPV = muTrkRef->dz(primaryVertices->begin()->position()); zDauTrkChi2 = muTrkRef->normalizedChi2(); zDauTrkNofStripHits = muTrkRef->hitPattern().numberOfValidStripHits(); zDauTrkNofPixelHits = muTrkRef->hitPattern().numberOfValidPixelHits(); - } - const pat::TriggerObjectStandAloneCollection muHLTMatches = m.triggerObjectMatchesByPath( hltPath_); + const pat::TriggerObjectStandAloneCollection muHLTMatches = m.triggerObjectMatchesByPath(hltPath_); float muHLTBit; int dimTrig = muHLTMatches.size(); - if(dimTrig !=0 ){ - muHLTBit = 1; - } else { - muHLTBit = 0; - } + if (dimTrig != 0) { + muHLTBit = 1; + } else { + muHLTBit = 0; + } m.addUserFloat("zDau_dxyFromBS", zDaudxyFromBS); m.addUserFloat("zDau_dzFromBS", zDaudzFromBS); m.addUserFloat("zDau_dxyFromPV", zDaudxyFromPV); m.addUserFloat("zDau_dzFromPV", zDaudzFromPV); - m.addUserFloat("zDau_HLTBit",muHLTBit); + m.addUserFloat("zDau_HLTBit", muHLTBit); m.addUserFloat("zDau_dzFromPV", zDaudzFromPV); m.addUserFloat("zDau_Chi2", zDauChi2); m.addUserFloat("zDau_TrkChi2", zDauTrkChi2); m.addUserFloat("zDau_SaChi2", zDauSaChi2); - m.addUserFloat("zDau_NofMuonHits" , zDauNofMuonHits ); - m.addUserFloat("zDau_SaNofMuonHits" , zDauSaNofMuonHits ); - m.addUserFloat("zDau_NofStripHits" , zDauNofStripHits ); - m.addUserFloat("zDau_TrkNofStripHits" , zDauTrkNofStripHits ); - m.addUserFloat("zDau_NofPixelHits" , zDauNofPixelHits ); - m.addUserFloat("zDau_TrkNofPixelHits" , zDauTrkNofPixelHits ); - m.addUserFloat("zDau_NofMuChambers" , zDauNofMuChambers ); - m.addUserFloat("zDau_NofMuMatches" , zDauNofMuMatches ); - m.addUserFloat("zDau_MuEnergyEm", zDauMuEnergyEm ); - m.addUserFloat("zDau_MuEnergyHad", zDauMuEnergyHad ); - } + m.addUserFloat("zDau_NofMuonHits", zDauNofMuonHits); + m.addUserFloat("zDau_SaNofMuonHits", zDauSaNofMuonHits); + m.addUserFloat("zDau_NofStripHits", zDauNofStripHits); + m.addUserFloat("zDau_TrkNofStripHits", zDauTrkNofStripHits); + m.addUserFloat("zDau_NofPixelHits", zDauNofPixelHits); + m.addUserFloat("zDau_TrkNofPixelHits", zDauTrkNofPixelHits); + m.addUserFloat("zDau_NofMuChambers", zDauNofMuChambers); + m.addUserFloat("zDau_NofMuMatches", zDauNofMuMatches); + m.addUserFloat("zDau_MuEnergyEm", zDauMuEnergyEm); + m.addUserFloat("zDau_MuEnergyHad", zDauMuEnergyHad); + } evt.put(std::move(muonColl)); } #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( ZMuMuMuonUserData ); - +DEFINE_FWK_MODULE(ZMuMuMuonUserData); diff --git a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuOneTrackUserData.cc b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuOneTrackUserData.cc old mode 100755 new mode 100644 index 25ab86c28c997..b91e2261345b5 --- a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuOneTrackUserData.cc +++ b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuOneTrackUserData.cc @@ -28,10 +28,11 @@ using namespace isodeposit; class ZMuMuUserDataOneTrack : public edm::EDProducer { public: - ZMuMuUserDataOneTrack( const edm::ParameterSet & ); + ZMuMuUserDataOneTrack(const edm::ParameterSet &); typedef math::XYZVector Vector; + private: - void produce( edm::Event &, const edm::EventSetup & ) override; + void produce(edm::Event &, const edm::EventSetup &) override; EDGetTokenT > srcToken_; EDGetTokenT beamSpotToken_; @@ -40,83 +41,76 @@ class ZMuMuUserDataOneTrack : public edm::EDProducer { double alpha_, beta_; string hltPath_; int counter; - - }; - - -ZMuMuUserDataOneTrack::ZMuMuUserDataOneTrack( const ParameterSet & cfg ): - srcToken_(consumes > ( cfg.getParameter( "src" ) ) ), - beamSpotToken_(consumes (cfg.getParameter( "beamSpot" ) ) ), - primaryVerticesToken_(consumes (cfg.getParameter( "primaryVertices" ) ) ), - zGenParticlesMatchToken_(consumes (cfg.getParameter( "zGenParticlesMatch" ) ) ), - alpha_(cfg.getParameter("alpha") ), - beta_(cfg.getParameter("beta") ), - hltPath_(cfg.getParameter("hltPath") ){ +ZMuMuUserDataOneTrack::ZMuMuUserDataOneTrack(const ParameterSet &cfg) + : srcToken_(consumes >(cfg.getParameter("src"))), + beamSpotToken_(consumes(cfg.getParameter("beamSpot"))), + primaryVerticesToken_(consumes(cfg.getParameter("primaryVertices"))), + zGenParticlesMatchToken_(consumes(cfg.getParameter("zGenParticlesMatch"))), + alpha_(cfg.getParameter("alpha")), + beta_(cfg.getParameter("beta")), + hltPath_(cfg.getParameter("hltPath")) { produces >(); } -void ZMuMuUserDataOneTrack::produce( Event & evt, const EventSetup & ) { +void ZMuMuUserDataOneTrack::produce(Event &evt, const EventSetup &) { Handle > dimuons; - evt.getByToken(srcToken_,dimuons); + evt.getByToken(srcToken_, dimuons); Handle beamSpotHandle; if (!evt.getByToken(beamSpotToken_, beamSpotHandle)) { - std::cout << ">>> No beam spot found !!!"<>> No beam spot found !!!" << std::endl; } Handle primaryVertices; // Collection of primary Vertices - if (!evt.getByToken(primaryVerticesToken_, primaryVertices)){ - std::cout << ">>> No primary vertices found !!!"<>> No primary vertices found !!!" << std::endl; } - bool isMCMatchTrue=false; + bool isMCMatchTrue = false; Handle zGenParticlesMatch; - if(evt.getByToken( zGenParticlesMatchToken_, zGenParticlesMatch )){ - isMCMatchTrue=true; + if (evt.getByToken(zGenParticlesMatchToken_, zGenParticlesMatch)) { + isMCMatchTrue = true; } //cout<<"isMCMatchTrue"< > dimuonColl( new vector () ); + unique_ptr > dimuonColl(new vector()); - - for (unsigned int i = 0; i< dimuons->size();++i){ - const CompositeCandidate & z = (*dimuons)[i]; + for (unsigned int i = 0; i < dimuons->size(); ++i) { + const CompositeCandidate &z = (*dimuons)[i]; //CandidateBaseRef zRef = dimuons ->refAt(i); edm::Ref > zRef(dimuons, i); pat::CompositeCandidate dimuon(z); - float trueMass,truePt,trueEta,truePhi,trueY; - if (isMCMatchTrue){ - GenParticleRef trueZRef = (*zGenParticlesMatch)[zRef]; + float trueMass, truePt, trueEta, truePhi, trueY; + if (isMCMatchTrue) { + GenParticleRef trueZRef = (*zGenParticlesMatch)[zRef]; //CandidateRef trueZRef = trueZIter->val; - if( trueZRef.isNonnull() ) { - const Candidate & z = * trueZRef; - trueMass = z.mass(); - truePt = z.pt(); - trueEta = z.eta(); - truePhi = z.phi(); - trueY = z.rapidity(); + if (trueZRef.isNonnull()) { + const Candidate &z = *trueZRef; + trueMass = z.mass(); + truePt = z.pt(); + trueEta = z.eta(); + truePhi = z.phi(); + trueY = z.rapidity(); } else { - trueMass = -100; - truePt = -100; - trueEta = -100; - truePhi = -100; - trueY = -100; + trueMass = -100; + truePt = -100; + trueEta = -100; + truePhi = -100; + trueY = -100; } - dimuon.addUserFloat("TrueMass",trueMass); - dimuon.addUserFloat("TruePt",truePt); - dimuon.addUserFloat("TrueEta",trueEta); - dimuon.addUserFloat("TruePhi",truePhi); - dimuon.addUserFloat("TrueY",trueY); - + dimuon.addUserFloat("TrueMass", trueMass); + dimuon.addUserFloat("TruePt", truePt); + dimuon.addUserFloat("TrueEta", trueEta); + dimuon.addUserFloat("TruePhi", truePhi); + dimuon.addUserFloat("TrueY", trueY); } dimuonColl->push_back(dimuon); - } evt.put(std::move(dimuonColl)); @@ -124,5 +118,4 @@ void ZMuMuUserDataOneTrack::produce( Event & evt, const EventSetup & ) { #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( ZMuMuUserDataOneTrack ); - +DEFINE_FWK_MODULE(ZMuMuUserDataOneTrack); diff --git a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuTrackUserData.cc b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuTrackUserData.cc old mode 100755 new mode 100644 index 0c3e2edc5419b..92ea4d597d6dd --- a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuTrackUserData.cc +++ b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuTrackUserData.cc @@ -26,53 +26,70 @@ using namespace isodeposit; class ZMuMuTrackUserData : public edm::EDProducer { public: - ZMuMuTrackUserData( const edm::ParameterSet & ); + ZMuMuTrackUserData(const edm::ParameterSet &); + private: - void produce( edm::Event &, const edm::EventSetup & ) override; + void produce(edm::Event &, const edm::EventSetup &) override; EDGetTokenT > srcToken_; EDGetTokenT beamSpotToken_; EDGetTokenT primaryVerticesToken_; - double ptThreshold_, etEcalThreshold_, etHcalThreshold_ ,dRVetoTrk_, dRTrk_, dREcal_ , dRHcal_; + double ptThreshold_, etEcalThreshold_, etHcalThreshold_, dRVetoTrk_, dRTrk_, dREcal_, dRHcal_; double alpha_, beta_; - template - vector isolation(const T & t, double ptThreshold, double etEcalThreshold, double etHcalThreshold , double dRVetoTrk, double dRTrk, double dREcal , double dRHcal, double alpha, double beta); - + template + vector isolation(const T &t, + double ptThreshold, + double etEcalThreshold, + double etHcalThreshold, + double dRVetoTrk, + double dRTrk, + double dREcal, + double dRHcal, + double alpha, + double beta); }; -template -vector ZMuMuTrackUserData::isolation(const T & t, double ptThreshold, double etEcalThreshold, double etHcalThreshold , double dRVetoTrk, double dRTrk, double dREcal , double dRHcal, double alpha, double beta) { - +template +vector ZMuMuTrackUserData::isolation(const T &t, + double ptThreshold, + double etEcalThreshold, + double etHcalThreshold, + double dRVetoTrk, + double dRTrk, + double dREcal, + double dRHcal, + double alpha, + double beta) { vector iso; - const pat::IsoDeposit * trkIso = t.isoDeposit(pat::TrackIso); - const pat::IsoDeposit * ecalIso = t.isoDeposit(pat::EcalIso); - const pat::IsoDeposit * hcalIso = t.isoDeposit(pat::HcalIso); + const pat::IsoDeposit *trkIso = t.isoDeposit(pat::TrackIso); + const pat::IsoDeposit *ecalIso = t.isoDeposit(pat::EcalIso); + const pat::IsoDeposit *hcalIso = t.isoDeposit(pat::HcalIso); Direction dir = Direction(t.eta(), t.phi()); - pat::IsoDeposit::AbsVetos vetosTrk; - vetosTrk.push_back(new ConeVeto( dir, dRVetoTrk )); - vetosTrk.push_back(new ThresholdVeto( ptThreshold )); + vetosTrk.push_back(new ConeVeto(dir, dRVetoTrk)); + vetosTrk.push_back(new ThresholdVeto(ptThreshold)); pat::IsoDeposit::AbsVetos vetosEcal; - vetosEcal.push_back(new ConeVeto( dir, 0.)); - vetosEcal.push_back(new ThresholdVeto( etEcalThreshold )); + vetosEcal.push_back(new ConeVeto(dir, 0.)); + vetosEcal.push_back(new ThresholdVeto(etEcalThreshold)); pat::IsoDeposit::AbsVetos vetosHcal; - vetosHcal.push_back(new ConeVeto( dir, 0. )); - vetosHcal.push_back(new ThresholdVeto( etHcalThreshold )); + vetosHcal.push_back(new ConeVeto(dir, 0.)); + vetosHcal.push_back(new ThresholdVeto(etHcalThreshold)); - double isovalueTrk = (trkIso->sumWithin(dRTrk,vetosTrk)); - double isovalueEcal = (ecalIso->sumWithin(dREcal,vetosEcal)); - double isovalueHcal = (hcalIso->sumWithin(dRHcal,vetosHcal)); + double isovalueTrk = (trkIso->sumWithin(dRTrk, vetosTrk)); + double isovalueEcal = (ecalIso->sumWithin(dREcal, vetosEcal)); + double isovalueHcal = (hcalIso->sumWithin(dRHcal, vetosHcal)); iso.push_back(isovalueTrk); iso.push_back(isovalueEcal); iso.push_back(isovalueHcal); //double iso = isovalueTrk + isovalueEcal + isovalueHcal; - double combIso = alpha*( ((1+beta)/2*isovalueEcal) + ((1-beta)/2*isovalueHcal) ) + ((1-alpha)*isovalueTrk); + double combIso = + alpha * (((1 + beta) / 2 * isovalueEcal) + ((1 - beta) / 2 * isovalueHcal)) + ((1 - alpha) * isovalueTrk); iso.push_back(combIso); double relIso = combIso /= t.pt(); @@ -80,25 +97,25 @@ vector ZMuMuTrackUserData::isolation(const T & t, double ptThreshold, do return iso; } -ZMuMuTrackUserData::ZMuMuTrackUserData( const ParameterSet & cfg ): - srcToken_(consumes > ( cfg.getParameter( "src" ) ) ), - beamSpotToken_(consumes (cfg.getParameter( "beamSpot" ) ) ), - primaryVerticesToken_(consumes (cfg.getParameter( "primaryVertices" ) ) ), - ptThreshold_(cfg.getParameter("ptThreshold") ), - etEcalThreshold_(cfg.getParameter("etEcalThreshold") ), - etHcalThreshold_(cfg.getParameter("etHcalThreshold") ), - dRVetoTrk_(cfg.getParameter("dRVetoTrk") ), - dRTrk_(cfg.getParameter("dRTrk") ), - dREcal_(cfg.getParameter("dREcal") ), - dRHcal_(cfg.getParameter("dRHcal") ), - alpha_(cfg.getParameter("alpha") ), - beta_(cfg.getParameter("beta") ){ +ZMuMuTrackUserData::ZMuMuTrackUserData(const ParameterSet &cfg) + : srcToken_(consumes >(cfg.getParameter("src"))), + beamSpotToken_(consumes(cfg.getParameter("beamSpot"))), + primaryVerticesToken_(consumes(cfg.getParameter("primaryVertices"))), + ptThreshold_(cfg.getParameter("ptThreshold")), + etEcalThreshold_(cfg.getParameter("etEcalThreshold")), + etHcalThreshold_(cfg.getParameter("etHcalThreshold")), + dRVetoTrk_(cfg.getParameter("dRVetoTrk")), + dRTrk_(cfg.getParameter("dRTrk")), + dREcal_(cfg.getParameter("dREcal")), + dRHcal_(cfg.getParameter("dRHcal")), + alpha_(cfg.getParameter("alpha")), + beta_(cfg.getParameter("beta")) { produces >(); } -void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { - Handle > tracks; - evt.getByToken(srcToken_,tracks); +void ZMuMuTrackUserData::produce(Event &evt, const EventSetup &) { + Handle > tracks; + evt.getByToken(srcToken_, tracks); Handle beamSpotHandle; evt.getByToken(beamSpotToken_, beamSpotHandle); @@ -106,10 +123,11 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { Handle primaryVertices; // Collection of primary Vertices evt.getByToken(primaryVerticesToken_, primaryVertices); - unique_ptr > tkColl( new vector (*tracks) ); - for (unsigned int i = 0; i< tkColl->size();++i){ - pat::GenericParticle & tk = (*tkColl)[i]; - vector iso = isolation(tk,ptThreshold_, etEcalThreshold_, etHcalThreshold_ ,dRVetoTrk_, dRTrk_, dREcal_ , dRHcal_, alpha_, beta_); + unique_ptr > tkColl(new vector(*tracks)); + for (unsigned int i = 0; i < tkColl->size(); ++i) { + pat::GenericParticle &tk = (*tkColl)[i]; + vector iso = isolation( + tk, ptThreshold_, etEcalThreshold_, etHcalThreshold_, dRVetoTrk_, dRTrk_, dREcal_, dRHcal_, alpha_, beta_); tk.setIsolation(pat::User1Iso, iso[0]); // cout << "track User1Iso " << iso[0] << endl; tk.setIsolation(pat::User2Iso, iso[1]); @@ -121,9 +139,7 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { tk.setIsolation(pat::User5Iso, iso[4]); //cout << "track User5Iso " << iso[4] << endl; - - - float zDaudxyFromBS = -1 ; + float zDaudxyFromBS = -1; float zDaudzFromBS = -1; float zDaudxyFromPV = -1; float zDaudzFromPV = -1; @@ -132,18 +148,18 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { float zDauChi2 = -1; float zDauTrkChi2 = -1; float zDauSaChi2 = -1; - float zDauNofMuonHits =- 1; + float zDauNofMuonHits = -1; float zDauNofStripHits = -1; float zDauNofPixelHits = -1; float zDauMuEnergyEm = -1; float zDauMuEnergyHad = -1; TrackRef muTrkRef = tk.track(); - if (muTrkRef.isNonnull()){ + if (muTrkRef.isNonnull()) { zDaudxyFromBS = muTrkRef->dxy(beamSpotHandle->position()); zDaudzFromBS = muTrkRef->dz(beamSpotHandle->position()); - zDaudxyFromPV = muTrkRef->dxy(primaryVertices->begin()->position() ); - zDaudzFromPV = muTrkRef->dz(primaryVertices->begin()->position() ); + zDaudxyFromPV = muTrkRef->dxy(primaryVertices->begin()->position()); + zDaudzFromPV = muTrkRef->dz(primaryVertices->begin()->position()); zDauChi2 = muTrkRef->normalizedChi2(); zDauTrkChi2 = muTrkRef->normalizedChi2(); zDauNofStripHits = muTrkRef->hitPattern().numberOfValidStripHits(); @@ -153,9 +169,9 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { tk.addUserFloat("zDau_dzFromBS", zDaudzFromBS); tk.addUserFloat("zDau_dxyFromPV", zDaudxyFromPV); tk.addUserFloat("zDau_dzFromPV", zDaudzFromPV); - tk.addUserFloat("zDau_NofMuonHits" , zDauNofMuonHits ); - tk.addUserFloat("zDau_TrkNofStripHits" , zDauNofStripHits ); - tk.addUserFloat("zDau_TrkNofPixelHits" , zDauNofPixelHits ); + tk.addUserFloat("zDau_NofMuonHits", zDauNofMuonHits); + tk.addUserFloat("zDau_TrkNofStripHits", zDauNofStripHits); + tk.addUserFloat("zDau_TrkNofPixelHits", zDauNofPixelHits); tk.addUserFloat("zDau_NofMuChambers", zDauNofMuChambers); tk.addUserFloat("zDau_NofMuMatches", zDauNofMuMatches); tk.addUserFloat("zDau_Chi2", zDauChi2); @@ -163,8 +179,6 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { tk.addUserFloat("zDau_SaChi2", zDauSaChi2); tk.addUserFloat("zDau_MuEnergyEm", zDauMuEnergyEm); tk.addUserFloat("zDau_MuEnergyHad", zDauMuEnergyHad); - - } evt.put(std::move(tkColl)); @@ -172,5 +186,4 @@ void ZMuMuTrackUserData::produce( Event & evt, const EventSetup & ) { #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( ZMuMuTrackUserData ); - +DEFINE_FWK_MODULE(ZMuMuTrackUserData); diff --git a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuUserData.cc b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuUserData.cc old mode 100755 new mode 100644 index 706b61c8454ca..b48cd92719a76 --- a/ElectroWeakAnalysis/Skimming/plugins/ZMuMuUserData.cc +++ b/ElectroWeakAnalysis/Skimming/plugins/ZMuMuUserData.cc @@ -28,10 +28,11 @@ using namespace isodeposit; class ZMuMuUserData : public edm::EDProducer { public: - ZMuMuUserData( const edm::ParameterSet & ); + ZMuMuUserData(const edm::ParameterSet &); typedef math::XYZVector Vector; + private: - void produce( edm::Event &, const edm::EventSetup & ) override; + void produce(edm::Event &, const edm::EventSetup &) override; EDGetTokenT > srcToken_; EDGetTokenT beamSpotToken_; @@ -40,26 +41,22 @@ class ZMuMuUserData : public edm::EDProducer { double alpha_, beta_; string hltPath_; int counter; - - }; - - -ZMuMuUserData::ZMuMuUserData( const ParameterSet & cfg ): - srcToken_(consumes > ( cfg.getParameter( "src" ) ) ), - beamSpotToken_(consumes (cfg.getParameter( "beamSpot" ) ) ), - primaryVerticesToken_(consumes (cfg.getParameter( "primaryVertices" ) ) ), - zGenParticlesMatchToken_(consumes (cfg.getParameter( "zGenParticlesMatch" ) ) ), - alpha_(cfg.getParameter("alpha") ), - beta_(cfg.getParameter("beta") ), - hltPath_(cfg.getParameter("hltPath") ){ +ZMuMuUserData::ZMuMuUserData(const ParameterSet &cfg) + : srcToken_(consumes >(cfg.getParameter("src"))), + beamSpotToken_(consumes(cfg.getParameter("beamSpot"))), + primaryVerticesToken_(consumes(cfg.getParameter("primaryVertices"))), + zGenParticlesMatchToken_(consumes(cfg.getParameter("zGenParticlesMatch"))), + alpha_(cfg.getParameter("alpha")), + beta_(cfg.getParameter("beta")), + hltPath_(cfg.getParameter("hltPath")) { produces >(); } -void ZMuMuUserData::produce( Event & evt, const EventSetup & ) { +void ZMuMuUserData::produce(Event &evt, const EventSetup &) { Handle > dimuons; - evt.getByToken(srcToken_,dimuons); + evt.getByToken(srcToken_, dimuons); Handle beamSpotHandle; evt.getByToken(beamSpotToken_, beamSpotHandle); @@ -67,54 +64,51 @@ void ZMuMuUserData::produce( Event & evt, const EventSetup & ) { Handle primaryVertices; // Collection of primary Vertices evt.getByToken(primaryVerticesToken_, primaryVertices); - - bool isMCMatchTrue=false; + bool isMCMatchTrue = false; Handle zGenParticlesMatch; - if(evt.getByToken( zGenParticlesMatchToken_, zGenParticlesMatch )){ - isMCMatchTrue=true; + if (evt.getByToken(zGenParticlesMatchToken_, zGenParticlesMatch)) { + isMCMatchTrue = true; } //cout<<"isMCMatchTrue"< > dimuonColl( new vector () ); - + unique_ptr > dimuonColl(new vector()); - for (unsigned int i = 0; i< dimuons->size();++i){ - const CompositeCandidate & z = (*dimuons)[i]; + for (unsigned int i = 0; i < dimuons->size(); ++i) { + const CompositeCandidate &z = (*dimuons)[i]; //CandidateBaseRef zRef = dimuons ->refAt(i); edm::Ref > zRef(dimuons, i); pat::CompositeCandidate dimuon(z); - float trueMass,truePt,trueEta,truePhi,trueY; - if (isMCMatchTrue){ - GenParticleRef trueZRef = (*zGenParticlesMatch)[zRef]; - //CandidateRef trueZRef = trueZIter->val; - if( trueZRef.isNonnull() ) { - const Candidate & z = * trueZRef; - trueMass = z.mass(); - truePt = z.pt(); - trueEta = z.eta(); - truePhi = z.phi(); - trueY = z.rapidity(); - } else { - trueMass = -100; - truePt = -100; - trueEta = -100; - truePhi = -100; - trueY = -100; - } - - dimuon.addUserFloat("TrueMass",trueMass); - dimuon.addUserFloat("TruePt",truePt); - dimuon.addUserFloat("TrueEta",trueEta); - dimuon.addUserFloat("TruePhi",truePhi); - dimuon.addUserFloat("TrueY",trueY); + float trueMass, truePt, trueEta, truePhi, trueY; + if (isMCMatchTrue) { + GenParticleRef trueZRef = (*zGenParticlesMatch)[zRef]; + //CandidateRef trueZRef = trueZIter->val; + if (trueZRef.isNonnull()) { + const Candidate &z = *trueZRef; + trueMass = z.mass(); + truePt = z.pt(); + trueEta = z.eta(); + truePhi = z.phi(); + trueY = z.rapidity(); + } else { + trueMass = -100; + truePt = -100; + trueEta = -100; + truePhi = -100; + trueY = -100; + } + dimuon.addUserFloat("TrueMass", trueMass); + dimuon.addUserFloat("TruePt", truePt); + dimuon.addUserFloat("TrueEta", trueEta); + dimuon.addUserFloat("TruePhi", truePhi); + dimuon.addUserFloat("TrueY", trueY); } - const Candidate * dau1 = z.daughter(0); - const Candidate * dau2 = z.daughter(1); - const pat::Muon & mu1 = dynamic_cast(*dau1->masterClone()); - const pat::Muon & mu2 = dynamic_cast(*dau2->masterClone()); + const Candidate *dau1 = z.daughter(0); + const Candidate *dau2 = z.daughter(1); + const pat::Muon &mu1 = dynamic_cast(*dau1->masterClone()); + const pat::Muon &mu2 = dynamic_cast(*dau2->masterClone()); /*cout<<"mu1 is null? "<get(); - stAloneTrack2 = dau2->get(); + stAloneTrack1 = dau1->get(); + stAloneTrack2 = dau2->get(); float zDau1SaEta = stAloneTrack1->eta(); float zDau2SaEta = stAloneTrack2->eta(); float zDau1SaPhi = stAloneTrack1->phi(); float zDau2SaPhi = stAloneTrack2->phi(); - float zDau1SaPt,zDau2SaPt; - if(counter % 2 == 0) { - momentum = stAloneTrack1->momentum(); - p4_1 = dau2->polarP4(); - mu_mass = dau1->mass(); - /// I fill the dau1 with positive and dau2 with negatove values for the pt, in order to flag the muons used for building zMassSa - zDau1SaPt = stAloneTrack1->pt(); - zDau2SaPt = - stAloneTrack2->pt(); - }else{ - momentum = stAloneTrack2->momentum(); - p4_1= dau1->polarP4(); - mu_mass = dau2->mass(); - /// I fill the dau1 with negatove and dau2 with positive values for the pt - zDau1SaPt = - stAloneTrack1->pt(); - zDau2SaPt = stAloneTrack2->pt(); + float zDau1SaPt, zDau2SaPt; + if (counter % 2 == 0) { + momentum = stAloneTrack1->momentum(); + p4_1 = dau2->polarP4(); + mu_mass = dau1->mass(); + /// I fill the dau1 with positive and dau2 with negatove values for the pt, in order to flag the muons used for building zMassSa + zDau1SaPt = stAloneTrack1->pt(); + zDau2SaPt = -stAloneTrack2->pt(); + } else { + momentum = stAloneTrack2->momentum(); + p4_1 = dau1->polarP4(); + mu_mass = dau2->mass(); + /// I fill the dau1 with negatove and dau2 with positive values for the pt + zDau1SaPt = -stAloneTrack1->pt(); + zDau2SaPt = stAloneTrack2->pt(); } - Candidate::PolarLorentzVector p4_2(momentum.rho(), momentum.eta(),momentum.phi(), mu_mass); - double mass = (p4_1+p4_2).mass(); + Candidate::PolarLorentzVector p4_2(momentum.rho(), momentum.eta(), momentum.phi(), mu_mass); + double mass = (p4_1 + p4_2).mass(); float zMassSa = mass; //cout<<"zMassSa "<push_back(dimuon); - } - evt.put(std::move(dimuonColl)); } #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( ZMuMuUserData ); - +DEFINE_FWK_MODULE(ZMuMuUserData); diff --git a/ElectroWeakAnalysis/WMuNu/src/WMuNuProducer.cc b/ElectroWeakAnalysis/WMuNu/src/WMuNuProducer.cc index f3dbf23065e5b..1141ab486e563 100644 --- a/ElectroWeakAnalysis/WMuNu/src/WMuNuProducer.cc +++ b/ElectroWeakAnalysis/WMuNu/src/WMuNuProducer.cc @@ -13,8 +13,6 @@ // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" @@ -30,15 +28,12 @@ #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/METReco/interface/MET.h" - class WMuNuProducer : public edm::EDProducer { public: WMuNuProducer(const edm::ParameterSet&); ~WMuNuProducer() override; - private: - void produce(edm::Event&, const edm::EventSetup&) override; void beginJob() override; void endJob() override; @@ -47,17 +42,15 @@ class WMuNuProducer : public edm::EDProducer { edm::EDGetTokenT > metToken_; struct ComparePt { - bool operator()(reco::WMuNuCandidate w1, reco::WMuNuCandidate w2 ) const { - double pt1 = w1.getMuon().pt(); - double pt2 = w2.getMuon().pt(); - return (pt1> pt2); - } - }; + bool operator()(reco::WMuNuCandidate w1, reco::WMuNuCandidate w2) const { + double pt1 = w1.getMuon().pt(); + double pt2 = w2.getMuon().pt(); + return (pt1 > pt2); + } + }; ComparePt ptComparator; unsigned int nall; - - }; #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -78,86 +71,76 @@ class WMuNuProducer : public edm::EDProducer { #include "DataFormats/Common/interface/View.h" - - - using namespace edm; using namespace std; using namespace reco; -WMuNuProducer::WMuNuProducer( const ParameterSet & cfg ) : - // Input collections - muonToken_(consumes >(cfg.getUntrackedParameter ("MuonTag", edm::InputTag("muons")))), - metToken_(consumes >(cfg.getUntrackedParameter ("METTag", edm::InputTag("met")))) -{ - produces< WMuNuCandidateCollection >(); -} - -void WMuNuProducer::beginJob() { -} - -void WMuNuProducer::endJob() { - LogTrace("")<<"WMuNuCandidateCollection Stored in the Event"; +WMuNuProducer::WMuNuProducer(const ParameterSet& cfg) + : // Input collections + muonToken_(consumes >(cfg.getUntrackedParameter("MuonTag", edm::InputTag("muons")))), + metToken_(consumes >(cfg.getUntrackedParameter("METTag", edm::InputTag("met")))) { + produces(); } +void WMuNuProducer::beginJob() {} -WMuNuProducer::~WMuNuProducer() -{ - - // do anything here that needs to be done at desctruction time - // (e.g. close files, deallocate resources etc.) +void WMuNuProducer::endJob() { LogTrace("") << "WMuNuCandidateCollection Stored in the Event"; } +WMuNuProducer::~WMuNuProducer() { + // do anything here that needs to be done at desctruction time + // (e.g. close files, deallocate resources etc.) } - -void WMuNuProducer::produce (Event & ev, const EventSetup &) { - - // Muon collection - Handle > muonCollection; - if (!ev.getByToken(muonToken_, muonCollection)) { - LogError("") << ">>> Muon collection does not exist !!!"; - return; - } - int muonCollectionSize = muonCollection->size(); - - // MET - Handle > metCollection; - if (!ev.getByToken(metToken_, metCollection)) { - LogError("") << ">>> MET collection does not exist !!!"; - return; - } - //const MET& Met = metCollection->at(0); - edm::Ptr met(metCollection,0); - - - if (muonCollectionSize<1) return; - - unique_ptr< WMuNuCandidateCollection > WMuNuCandidates(new WMuNuCandidateCollection ); - - - // Fill Collection with n muons --> n W Candidates ordered by pt - - for (int indx=0; indx muon(muonCollection,indx); - if (!muon->isGlobalMuon()) continue; - if (muon->globalTrack().isNull()) continue; - if (muon->innerTrack().isNull()) continue; - - // Build WMuNuCandidate - LogTrace("")<<"Building WMuNu Candidate!"; - WMuNuCandidate* WCand = new WMuNuCandidate(muon,met); - LogTrace("") << "\t... W mass, W_et: "<massT()<<", "<eT()<<"[GeV]"; - LogTrace("") << "\t... W_px, W_py: "<px()<<", "<< WCand->py() <<"[GeV]"; - LogTrace("") << "\t... acop: " << WCand->acop(); - LogTrace("") << "\t... Muon pt, px, py, pz: "<getMuon().pt()<<", "<getMuon().px()<<", "<getMuon().py()<<", "<< WCand->getMuon().pz()<<" [GeV]"; - LogTrace("") << "\t... Met met_et, met_px, met_py : "<getNeutrino().pt()<<", "<getNeutrino().px()<<", "<getNeutrino().py()<<" [GeV]"; - WMuNuCandidates->push_back(*WCand); - } - - std::sort(WMuNuCandidates->begin(),WMuNuCandidates->end(),ptComparator); - - ev.put(std::move(WMuNuCandidates)); - +void WMuNuProducer::produce(Event& ev, const EventSetup&) { + // Muon collection + Handle > muonCollection; + if (!ev.getByToken(muonToken_, muonCollection)) { + LogError("") << ">>> Muon collection does not exist !!!"; + return; + } + int muonCollectionSize = muonCollection->size(); + + // MET + Handle > metCollection; + if (!ev.getByToken(metToken_, metCollection)) { + LogError("") << ">>> MET collection does not exist !!!"; + return; + } + //const MET& Met = metCollection->at(0); + edm::Ptr met(metCollection, 0); + + if (muonCollectionSize < 1) + return; + + unique_ptr WMuNuCandidates(new WMuNuCandidateCollection); + + // Fill Collection with n muons --> n W Candidates ordered by pt + + for (int indx = 0; indx < muonCollectionSize; indx++) { + edm::Ptr muon(muonCollection, indx); + if (!muon->isGlobalMuon()) + continue; + if (muon->globalTrack().isNull()) + continue; + if (muon->innerTrack().isNull()) + continue; + + // Build WMuNuCandidate + LogTrace("") << "Building WMuNu Candidate!"; + WMuNuCandidate* WCand = new WMuNuCandidate(muon, met); + LogTrace("") << "\t... W mass, W_et: " << WCand->massT() << ", " << WCand->eT() << "[GeV]"; + LogTrace("") << "\t... W_px, W_py: " << WCand->px() << ", " << WCand->py() << "[GeV]"; + LogTrace("") << "\t... acop: " << WCand->acop(); + LogTrace("") << "\t... Muon pt, px, py, pz: " << WCand->getMuon().pt() << ", " << WCand->getMuon().px() << ", " + << WCand->getMuon().py() << ", " << WCand->getMuon().pz() << " [GeV]"; + LogTrace("") << "\t... Met met_et, met_px, met_py : " << WCand->getNeutrino().pt() << ", " + << WCand->getNeutrino().px() << ", " << WCand->getNeutrino().py() << " [GeV]"; + WMuNuCandidates->push_back(*WCand); + } + + std::sort(WMuNuCandidates->begin(), WMuNuCandidates->end(), ptComparator); + + ev.put(std::move(WMuNuCandidates)); } DEFINE_FWK_MODULE(WMuNuProducer); diff --git a/ElectroWeakAnalysis/WMuNu/src/WMuNuSelector.cc b/ElectroWeakAnalysis/WMuNu/src/WMuNuSelector.cc old mode 100755 new mode 100644 index 26e79ac613317..f0b911d0e6695 --- a/ElectroWeakAnalysis/WMuNu/src/WMuNuSelector.cc +++ b/ElectroWeakAnalysis/WMuNu/src/WMuNuSelector.cc @@ -34,11 +34,12 @@ class WMuNuSelector : public edm::EDFilter { public: - WMuNuSelector (const edm::ParameterSet &); + WMuNuSelector(const edm::ParameterSet&); bool filter(edm::Event&, const edm::EventSetup&) override; void beginJob() override; void endJob() override; void init_histograms(); + private: bool plotHistograms_; edm::EDGetTokenT trigToken_; @@ -73,13 +74,10 @@ class WMuNuSelector : public edm::EDFilter { double ntrig, npresel; double nsel; double ncharge; - double nkin, nid,nacop,niso,nmass; - - - - std::map h1_; - std::map h2_; + double nkin, nid, nacop, niso, nmass; + std::map h1_; + std::map h2_; }; #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/Common/interface/Handle.h" @@ -97,22 +95,23 @@ class WMuNuSelector : public edm::EDFilter { #include "FWCore/Common/interface/TriggerNames.h" - using namespace edm; using namespace std; using namespace reco; -WMuNuSelector::WMuNuSelector( const ParameterSet & cfg ) : - // Fast selection (no histograms) - plotHistograms_(cfg.getUntrackedParameter ("plotHistograms", true)), +WMuNuSelector::WMuNuSelector(const ParameterSet& cfg) + : // Fast selection (no histograms) + plotHistograms_(cfg.getUntrackedParameter("plotHistograms", true)), // Input collections - trigToken_(consumes(cfg.getUntrackedParameter ("TrigTag", edm::InputTag("TriggerResults::HLT")))), - muonToken_(consumes >(cfg.getUntrackedParameter ("MuonTag", edm::InputTag("muons")))), - jetToken_(consumes >(cfg.getUntrackedParameter ("JetTag", edm::InputTag("sisCone5CaloJets")))), + trigToken_(consumes( + cfg.getUntrackedParameter("TrigTag", edm::InputTag("TriggerResults::HLT")))), + muonToken_(consumes >(cfg.getUntrackedParameter("MuonTag", edm::InputTag("muons")))), + jetToken_( + consumes >(cfg.getUntrackedParameter("JetTag", edm::InputTag("sisCone5CaloJets")))), beamSpotToken_(consumes(edm::InputTag("offlineBeamSpot"))), - WMuNuCollectionToken_(consumes(cfg.getUntrackedParameter ("WMuNuCollectionTag", edm::InputTag("WMuNus")))), - + WMuNuCollectionToken_(consumes( + cfg.getUntrackedParameter("WMuNuCollectionTag", edm::InputTag("WMuNus")))), // Preselection cuts muonTrig_(cfg.getUntrackedParameter("MuonTrig", "HLT_Mu9")), @@ -121,7 +120,6 @@ WMuNuSelector::WMuNuSelector( const ParameterSet & cfg ) : eJetMin_(cfg.getUntrackedParameter("EJetMin", 999999.)), nJetMax_(cfg.getUntrackedParameter("NJetMax", 999999)), - // Main cuts ptCut_(cfg.getUntrackedParameter("PtCut", 25.)), etaCut_(cfg.getUntrackedParameter("EtaCut", 2.1)), @@ -141,288 +139,351 @@ WMuNuSelector::WMuNuSelector( const ParameterSet & cfg ) : isAlsoTrackerMuon_(cfg.getUntrackedParameter("IsAlsoTrackerMuon", true)), // W+/W- Selection - selectByCharge_(cfg.getUntrackedParameter("SelectByCharge", 0)) -{ -} + selectByCharge_(cfg.getUntrackedParameter("SelectByCharge", 0)) {} void WMuNuSelector::beginJob() { - nall = 0; - ntrig=0; - npresel=0; - ncharge = 0; - nkin=0; - nid=0; - nacop=0; - niso=0; - nsel = 0; - - if(plotHistograms_){ - edm::Service fs; - h1_["hNWCand_sel"] =fs->make("NWCand_sel","Nb. of WCandidates passing pre-selection (ordered by pt)",10,0.,10.); - h1_["hPtMu_sel"] =fs->make("ptMu_sel","Pt mu",100,0.,100.); - h1_["hEtaMu_sel"] =fs->make("etaMu_sel","Eta mu",50,-2.5,2.5); - h1_["hd0_sel"] =fs->make("d0_sel","Impact parameter",1000,-1.,1.); - h1_["hNHits_sel"] =fs->make("NumberOfValidHits_sel","Number of Hits in Silicon",100,0.,100.); - h1_["hNormChi2_sel"] =fs->make("NormChi2_sel","Chi2/ndof of global track",1000,0.,50.); - h1_["hTracker_sel"] =fs->make("isTrackerMuon_sel","is Tracker Muon?",2,0.,2.); - h1_["hMET_sel"] =fs->make("MET_sel","Missing Transverse Energy (GeV)", 300,0.,300.); - h1_["hTMass_sel"] =fs->make("TMass_sel","Rec. Transverse Mass (GeV)",300,0.,300.); - h1_["hAcop_sel"] =fs->make("Acop_sel","Mu-MET acoplanarity",50,0.,M_PI); - h1_["hPtSum_sel"] =fs->make("ptSum_sel","Track Isolation, Sum pT (GeV)",200,0.,100.); - h1_["hPtSumN_sel"] =fs->make("ptSumN_sel","Track Isolation, Sum pT/pT",1000,0.,10.); - h1_["hCal_sel"] =fs->make("Cal_sel","Calorimetric isolation, HCAL+ECAL (GeV)",200,0.,100.); - h1_["hIsoTotN_sel"] =fs->make("isoTotN_sel","(Sum pT + Cal)/pT",1000,0.,10.); - h1_["hIsoTot_sel"] =fs->make("isoTot_sel","(Sum pT + Cal)",200,0.,100.); - h2_["hTMass_PtSum_inclusive"] =fs->make("TMass_PtSum_inclusive","Rec. Transverse Mass (GeV) vs Sum pT (GeV)",200,0.,100.,300,0.,300.); - h2_["hTMass_PtSumNorm_inclusive"] =fs->make("TMass_PtSumNorm_inclusive","Rec. Transverse Mass (GeV) vs Sum Pt / Pt", 1000,0,10,300,0,300); - h2_["hTMass_TotIsoNorm_inclusive"]=fs->make("TMass_TotIsoNorm_inclusive","Rec. Transverse Mass (GeV) vs (Sum Pt + Cal)/Pt", 10000,0,10,200,0,200); - h2_["hMET_PtSum_inclusive"] =fs->make("MET_PtSum_inclusive","Missing Transverse Energy (GeV) vs Sum Pt (GeV)",200,0.,100.,300,0.,300.); - h2_["hMET_PtSumNorm_inclusive"] =fs->make("MET_PtSumNorm_inclusive","Missing Transverse Energy (GeV) vs Sum Pt/Pt",1000,0,10,300,0,300); - h2_["hMET_TotIsoNorm_inclusive"]=fs->make("MET_TotIsoNorm_inclusive","Missing Transverse Energy (GeV) vs (SumPt + Cal)/Pt",10000,0,10,200,0,200); - } + nall = 0; + ntrig = 0; + npresel = 0; + ncharge = 0; + nkin = 0; + nid = 0; + nacop = 0; + niso = 0; + nsel = 0; + + if (plotHistograms_) { + edm::Service fs; + h1_["hNWCand_sel"] = + fs->make("NWCand_sel", "Nb. of WCandidates passing pre-selection (ordered by pt)", 10, 0., 10.); + h1_["hPtMu_sel"] = fs->make("ptMu_sel", "Pt mu", 100, 0., 100.); + h1_["hEtaMu_sel"] = fs->make("etaMu_sel", "Eta mu", 50, -2.5, 2.5); + h1_["hd0_sel"] = fs->make("d0_sel", "Impact parameter", 1000, -1., 1.); + h1_["hNHits_sel"] = fs->make("NumberOfValidHits_sel", "Number of Hits in Silicon", 100, 0., 100.); + h1_["hNormChi2_sel"] = fs->make("NormChi2_sel", "Chi2/ndof of global track", 1000, 0., 50.); + h1_["hTracker_sel"] = fs->make("isTrackerMuon_sel", "is Tracker Muon?", 2, 0., 2.); + h1_["hMET_sel"] = fs->make("MET_sel", "Missing Transverse Energy (GeV)", 300, 0., 300.); + h1_["hTMass_sel"] = fs->make("TMass_sel", "Rec. Transverse Mass (GeV)", 300, 0., 300.); + h1_["hAcop_sel"] = fs->make("Acop_sel", "Mu-MET acoplanarity", 50, 0., M_PI); + h1_["hPtSum_sel"] = fs->make("ptSum_sel", "Track Isolation, Sum pT (GeV)", 200, 0., 100.); + h1_["hPtSumN_sel"] = fs->make("ptSumN_sel", "Track Isolation, Sum pT/pT", 1000, 0., 10.); + h1_["hCal_sel"] = fs->make("Cal_sel", "Calorimetric isolation, HCAL+ECAL (GeV)", 200, 0., 100.); + h1_["hIsoTotN_sel"] = fs->make("isoTotN_sel", "(Sum pT + Cal)/pT", 1000, 0., 10.); + h1_["hIsoTot_sel"] = fs->make("isoTot_sel", "(Sum pT + Cal)", 200, 0., 100.); + h2_["hTMass_PtSum_inclusive"] = fs->make( + "TMass_PtSum_inclusive", "Rec. Transverse Mass (GeV) vs Sum pT (GeV)", 200, 0., 100., 300, 0., 300.); + h2_["hTMass_PtSumNorm_inclusive"] = fs->make( + "TMass_PtSumNorm_inclusive", "Rec. Transverse Mass (GeV) vs Sum Pt / Pt", 1000, 0, 10, 300, 0, 300); + h2_["hTMass_TotIsoNorm_inclusive"] = fs->make( + "TMass_TotIsoNorm_inclusive", "Rec. Transverse Mass (GeV) vs (Sum Pt + Cal)/Pt", 10000, 0, 10, 200, 0, 200); + h2_["hMET_PtSum_inclusive"] = fs->make( + "MET_PtSum_inclusive", "Missing Transverse Energy (GeV) vs Sum Pt (GeV)", 200, 0., 100., 300, 0., 300.); + h2_["hMET_PtSumNorm_inclusive"] = fs->make( + "MET_PtSumNorm_inclusive", "Missing Transverse Energy (GeV) vs Sum Pt/Pt", 1000, 0, 10, 300, 0, 300); + h2_["hMET_TotIsoNorm_inclusive"] = fs->make( + "MET_TotIsoNorm_inclusive", "Missing Transverse Energy (GeV) vs (SumPt + Cal)/Pt", 10000, 0, 10, 200, 0, 200); + } } - void WMuNuSelector::endJob() { - double all = nall; - double epresel = npresel/all; - double etrig = ntrig/all; - double ekin = nkin/all; - double eid = nid/all; - double eacop = nacop/all; - double eiso = niso/all; - double esel = nsel/all; - - LogVerbatim("") << "\n>>>>>> W SELECTION SUMMARY BEGIN >>>>>>>>>>>>>>>"; - LogVerbatim("") << "Total number of events analyzed: " << nall << " [events]"; - LogVerbatim("") << "Total number of events triggered: " << ntrig << " [events]"; - LogVerbatim("") << "Total number of events pre-selected: " << npresel << " [events]"; - LogVerbatim("") << "Total number of events after kinematic cuts: " << nkin << " [events]"; - LogVerbatim("") << "Total number of events after Muon ID cuts: " << nid << " [events]"; - LogVerbatim("") << "Total number of events after Acop cut: " << nacop << " [events]"; - LogVerbatim("") << "Total number of events after iso cut: " << niso << " [events]"; - LogVerbatim("") << "Total number of events selected: " << nsel << " [events]"; - LogVerbatim("") << "Efficiencies:"; - LogVerbatim("") << "Trigger Efficiency: " << "(" << setprecision(4) << etrig*100. <<" +/- "<< setprecision(2) << sqrt(etrig*(1-etrig)/all)*100. << ")%"; - LogVerbatim("") << "Pre-Selection Efficiency: " << "(" << setprecision(4) << epresel*100. <<" +/- "<< setprecision(2) << sqrt(epresel*(1-epresel)/all)*100. << ")%"; - LogVerbatim("") << "Pt, Eta Selection Efficiency: " << "(" << setprecision(4) << ekin*100. <<" +/- "<< setprecision(2) << sqrt(ekin*(1-ekin)/all)*100. << ")%"; - LogVerbatim("") << "MuonID Efficiency: " << "(" << setprecision(4) << eid*100. <<" +/- "<< setprecision(2) << sqrt(eid*(1-eid)/all)*100. << ")%"; - LogVerbatim("") << "Acop Efficiency: " << "(" << setprecision(4) << eacop*100. <<" +/- "<< setprecision(2) << sqrt(eacop*(1-eacop)/all)*100. << ")%"; - LogVerbatim("") << "Iso Efficiency: " << "(" << setprecision(4) << eiso*100. <<" +/- "<< setprecision(2) << sqrt(eiso*(1-eiso)/all)*100. << ")%"; - LogVerbatim("") << "Selection Efficiency: " << "(" << setprecision(4) << esel*100. <<" +/- "<< setprecision(2) << sqrt(esel*(1-esel)/nall)*100. << ")%"; - - if ( fabs(selectByCharge_)==1 ){ - esel = nsel/ncharge; - LogVerbatim("") << "\n>>>>>> W+(-) SELECTION >>>>>>>>>>>>>>>"; - LogVerbatim("") << "Total number of W+(-) events pre-selected: " << ncharge << " [events]"; - LogVerbatim("") << "Total number of events selected: " << nsel << " [events]"; - LogVerbatim("") << "Selection Efficiency only W+(-): " << "(" << setprecision(4) << esel*100. <<" +/- "<< setprecision(2) << sqrt(esel*(1-esel)/ncharge)*100. << ")%"; - } - LogVerbatim("") << ">>>>>> W SELECTION SUMMARY END >>>>>>>>>>>>>>>\n"; + double all = nall; + double epresel = npresel / all; + double etrig = ntrig / all; + double ekin = nkin / all; + double eid = nid / all; + double eacop = nacop / all; + double eiso = niso / all; + double esel = nsel / all; + + LogVerbatim("") << "\n>>>>>> W SELECTION SUMMARY BEGIN >>>>>>>>>>>>>>>"; + LogVerbatim("") << "Total number of events analyzed: " << nall << " [events]"; + LogVerbatim("") << "Total number of events triggered: " << ntrig << " [events]"; + LogVerbatim("") << "Total number of events pre-selected: " << npresel << " [events]"; + LogVerbatim("") << "Total number of events after kinematic cuts: " << nkin << " [events]"; + LogVerbatim("") << "Total number of events after Muon ID cuts: " << nid << " [events]"; + LogVerbatim("") << "Total number of events after Acop cut: " << nacop << " [events]"; + LogVerbatim("") << "Total number of events after iso cut: " << niso << " [events]"; + LogVerbatim("") << "Total number of events selected: " << nsel << " [events]"; + LogVerbatim("") << "Efficiencies:"; + LogVerbatim("") << "Trigger Efficiency: " + << "(" << setprecision(4) << etrig * 100. << " +/- " << setprecision(2) + << sqrt(etrig * (1 - etrig) / all) * 100. << ")%"; + LogVerbatim("") << "Pre-Selection Efficiency: " + << "(" << setprecision(4) << epresel * 100. << " +/- " << setprecision(2) + << sqrt(epresel * (1 - epresel) / all) * 100. << ")%"; + LogVerbatim("") << "Pt, Eta Selection Efficiency: " + << "(" << setprecision(4) << ekin * 100. << " +/- " << setprecision(2) + << sqrt(ekin * (1 - ekin) / all) * 100. << ")%"; + LogVerbatim("") << "MuonID Efficiency: " + << "(" << setprecision(4) << eid * 100. << " +/- " << setprecision(2) + << sqrt(eid * (1 - eid) / all) * 100. << ")%"; + LogVerbatim("") << "Acop Efficiency: " + << "(" << setprecision(4) << eacop * 100. << " +/- " << setprecision(2) + << sqrt(eacop * (1 - eacop) / all) * 100. << ")%"; + LogVerbatim("") << "Iso Efficiency: " + << "(" << setprecision(4) << eiso * 100. << " +/- " << setprecision(2) + << sqrt(eiso * (1 - eiso) / all) * 100. << ")%"; + LogVerbatim("") << "Selection Efficiency: " + << "(" << setprecision(4) << esel * 100. << " +/- " << setprecision(2) + << sqrt(esel * (1 - esel) / nall) * 100. << ")%"; + + if (fabs(selectByCharge_) == 1) { + esel = nsel / ncharge; + LogVerbatim("") << "\n>>>>>> W+(-) SELECTION >>>>>>>>>>>>>>>"; + LogVerbatim("") << "Total number of W+(-) events pre-selected: " << ncharge << " [events]"; + LogVerbatim("") << "Total number of events selected: " << nsel << " [events]"; + LogVerbatim("") << "Selection Efficiency only W+(-): " + << "(" << setprecision(4) << esel * 100. << " +/- " << setprecision(2) + << sqrt(esel * (1 - esel) / ncharge) * 100. << ")%"; + } + LogVerbatim("") << ">>>>>> W SELECTION SUMMARY END >>>>>>>>>>>>>>>\n"; } -bool WMuNuSelector::filter (Event & ev, const EventSetup &) { - nall++; - - // Repeat Pre-Selection Cuts just in case... - // Muon collection - Handle > muonCollection; - if (!ev.getByToken(muonToken_, muonCollection)) { - LogError("") << ">>> Muon collection does not exist !!!"; - return false; - } - unsigned int muonCollectionSize = muonCollection->size(); - - // Trigger - Handle triggerResults; - if (!ev.getByToken(trigToken_, triggerResults)) { - LogError("") << ">>> TRIGGER collection does not exist !!!"; - return false; - } - const edm::TriggerNames & triggerNames = ev.triggerNames(*triggerResults); - bool trigger_fired = false; - int itrig1 = triggerNames.triggerIndex(muonTrig_); - if (triggerResults->accept(itrig1)) trigger_fired = true; - LogTrace("") << ">>> Trigger bit: " << trigger_fired << " (" << muonTrig_ << ")"; - - // Loop to reject/control Z->mumu is done separately - unsigned int nmuonsForZ1 = 0; - unsigned int nmuonsForZ2 = 0; - for (unsigned int i=0; iat(i); - if (!mu.isGlobalMuon()) continue; - double pt = mu.pt(); - if (pt>ptThrForZ1_) nmuonsForZ1++; - if (pt>ptThrForZ2_) nmuonsForZ2++; - } - LogTrace("") << "> Z rejection: muons above " << ptThrForZ1_ << " [GeV]: " << nmuonsForZ1; - LogTrace("") << "> Z rejection: muons above " << ptThrForZ2_ << " [GeV]: " << nmuonsForZ2; - - // Jet collection - Handle > jetCollection; - if (!ev.getByToken(jetToken_, jetCollection)) { - LogError("") << ">>> JET collection does not exist !!!"; - return false; - } - unsigned int jetCollectionSize = jetCollection->size(); - int njets = 0; - for (unsigned int i=0; iat(i); - if (jet.et()>eJetMin_) njets++; - } - LogTrace("") << ">>> Total number of jets: " << jetCollectionSize; - LogTrace("") << ">>> Number of jets above " << eJetMin_ << " [GeV]: " << njets; - - - // Beam spot - Handle beamSpotHandle; - if (!ev.getByToken(beamSpotToken_, beamSpotHandle)) { - LogTrace("") << ">>> No beam spot found !!!"; - return false; - } - - - - // Get WMuNu candidates from file: - - Handle WMuNuCollection; - if (!ev.getByToken(WMuNuCollectionToken_,WMuNuCollection) ) { - LogTrace("") << ">>> WMuNu not found !!!"; - return false; - } - - if(WMuNuCollection->empty()) {LogTrace("")<<"No WMuNu Candidates in the Event!"; return false;} - if(WMuNuCollection->size() > 1) {LogTrace("")<<"This event contains more than one W Candidate";} - - // W->mu nu selection criteria - - LogTrace("") << "> WMuNu Candidate with: "; - const WMuNuCandidate& WMuNu = WMuNuCollection->at(0); - // WMuNuCandidates are ordered by Pt! - // The Inclusive Selection WMuNu Candidate is the first one - - const reco::Muon & mu = WMuNu.getMuon(); - const reco::MET & met =WMuNu.getNeutrino(); - if(plotHistograms_){ - h1_["hNWCand_sel"]->Fill(WMuNuCollection->size()); - } - - - // Preselection cuts: - - if (!trigger_fired) {LogTrace("")<<"Event did not fire the Trigger"; return false;} - ntrig++; - - if (nmuonsForZ1>=1 && nmuonsForZ2>=2) {LogTrace("")<<"Z Candidate!!"; return false;} - if (njets>nJetMax_) {LogTrace("")<<"NJets > threshold"; return false;} - - npresel++; - - // Select Ws by charge: - - if (selectByCharge_*WMuNu.charge()==-1){ ncharge++;} - - - // W->mu nu selection criteria - - if (!mu.isGlobalMuon()) return false; - - reco::TrackRef gm = mu.globalTrack(); - //reco::TrackRef tk = mu.innerTrack(); - - // Pt,eta cuts - double pt = mu.pt(); - double eta = mu.eta(); - LogTrace("") << "\t... Muon pt, eta: " << pt << " [GeV], " << eta; - if(plotHistograms_){ h1_["hPtMu_sel"]->Fill(pt);} - if (ptFill(eta);} - if (fabs(eta)>etaCut_) return false; - - nkin++; - - - // d0, chi2, nhits quality cuts - double dxy = gm->dxy(beamSpotHandle->position()); - double normalizedChi2 = gm->normalizedChi2(); LogTrace("")<<"Im here"<hitPattern().numberOfValidTrackerHits(); - LogTrace("") << "\t... Muon dxy, normalizedChi2, trackerHits, isTrackerMuon?: " << dxy << " [cm], "<Fill(dxy);} - if (!muon::isGoodMuon(mu,muon::GlobalMuonPromptTight) ) return false; - if(plotHistograms_){ h1_["hNormChi2_sel"]->Fill(normalizedChi2);} - if (normalizedChi2>normalizedChi2Cut_) return false; - if(plotHistograms_){ h1_["hNHits_sel"]->Fill(trackerHits);} - if (trackerHitsFill(mu.isTrackerMuon());} - if (!mu.isTrackerMuon()) return false; - - nid++; - - // Acoplanarity cuts - double acop = WMuNu.acop(); - LogTrace("") << "\t... acoplanarity: " << acop; - - // Isolation cuts - double SumPt = mu.isolationR03().sumPt; double isovar=SumPt; - double Cal = mu.isolationR03().emEt + mu.isolationR03().hadEt; if(isCombinedIso_)isovar+=Cal; - if(plotHistograms_){ - h1_["hPtSum_sel"]->Fill(SumPt); - h1_["hPtSumN_sel"]->Fill(SumPt/pt); - h1_["hCal_sel"]->Fill(Cal); - h1_["hIsoTot_sel"]->Fill( (SumPt+Cal)); - h1_["hIsoTotN_sel"]->Fill( (SumPt+Cal) / pt ); - } - - if (isRelativeIso_) isovar /= pt; - bool iso = (isovar<=isoCut03_); - LogTrace("") << "\t... isolation value" << isovar <<", isolated? " <Fill(SumPt,massT); - h2_["hTMass_PtSumNorm_inclusive"]->Fill(SumPt/pt,massT); - h2_["hTMass_TotIsoNorm_inclusive"]->Fill((SumPt+Cal)/pt,massT); - h2_["hMET_PtSum_inclusive"]->Fill(SumPt,met_et); - h2_["hMET_PtSumNorm_inclusive"]->Fill(SumPt/pt,met_et); - h2_["hMET_TotIsoNorm_inclusive"]->Fill((SumPt+Cal)/pt,met_et); - } - - if (!iso) return false; - - niso++; - - if(plotHistograms_){ h1_["hAcop_sel"]->Fill(acop);} - if (acop>=acopCut_) return false; - - nacop++; - - if(plotHistograms_){ - h1_["hMET_sel"]->Fill(met_et); - h1_["hTMass_sel"]->Fill(massT); - } - - - if (massT<=mtMin_ || massT>=mtMax_) return false; - if (met_et<=metMin_ || met_et>=metMax_) return false; - - LogTrace("") << ">>>> Event ACCEPTED"; - nsel++; - - - // (To be continued ;-) ) - - return true; +bool WMuNuSelector::filter(Event& ev, const EventSetup&) { + nall++; + + // Repeat Pre-Selection Cuts just in case... + // Muon collection + Handle > muonCollection; + if (!ev.getByToken(muonToken_, muonCollection)) { + LogError("") << ">>> Muon collection does not exist !!!"; + return false; + } + unsigned int muonCollectionSize = muonCollection->size(); + + // Trigger + Handle triggerResults; + if (!ev.getByToken(trigToken_, triggerResults)) { + LogError("") << ">>> TRIGGER collection does not exist !!!"; + return false; + } + const edm::TriggerNames& triggerNames = ev.triggerNames(*triggerResults); + bool trigger_fired = false; + int itrig1 = triggerNames.triggerIndex(muonTrig_); + if (triggerResults->accept(itrig1)) + trigger_fired = true; + LogTrace("") << ">>> Trigger bit: " << trigger_fired << " (" << muonTrig_ << ")"; + + // Loop to reject/control Z->mumu is done separately + unsigned int nmuonsForZ1 = 0; + unsigned int nmuonsForZ2 = 0; + for (unsigned int i = 0; i < muonCollectionSize; i++) { + const Muon& mu = muonCollection->at(i); + if (!mu.isGlobalMuon()) + continue; + double pt = mu.pt(); + if (pt > ptThrForZ1_) + nmuonsForZ1++; + if (pt > ptThrForZ2_) + nmuonsForZ2++; + } + LogTrace("") << "> Z rejection: muons above " << ptThrForZ1_ << " [GeV]: " << nmuonsForZ1; + LogTrace("") << "> Z rejection: muons above " << ptThrForZ2_ << " [GeV]: " << nmuonsForZ2; + + // Jet collection + Handle > jetCollection; + if (!ev.getByToken(jetToken_, jetCollection)) { + LogError("") << ">>> JET collection does not exist !!!"; + return false; + } + unsigned int jetCollectionSize = jetCollection->size(); + int njets = 0; + for (unsigned int i = 0; i < jetCollectionSize; i++) { + const Jet& jet = jetCollection->at(i); + if (jet.et() > eJetMin_) + njets++; + } + LogTrace("") << ">>> Total number of jets: " << jetCollectionSize; + LogTrace("") << ">>> Number of jets above " << eJetMin_ << " [GeV]: " << njets; + + // Beam spot + Handle beamSpotHandle; + if (!ev.getByToken(beamSpotToken_, beamSpotHandle)) { + LogTrace("") << ">>> No beam spot found !!!"; + return false; + } + + // Get WMuNu candidates from file: + + Handle WMuNuCollection; + if (!ev.getByToken(WMuNuCollectionToken_, WMuNuCollection)) { + LogTrace("") << ">>> WMuNu not found !!!"; + return false; + } + + if (WMuNuCollection->empty()) { + LogTrace("") << "No WMuNu Candidates in the Event!"; + return false; + } + if (WMuNuCollection->size() > 1) { + LogTrace("") << "This event contains more than one W Candidate"; + } + + // W->mu nu selection criteria + + LogTrace("") << "> WMuNu Candidate with: "; + const WMuNuCandidate& WMuNu = WMuNuCollection->at(0); + // WMuNuCandidates are ordered by Pt! + // The Inclusive Selection WMuNu Candidate is the first one + + const reco::Muon& mu = WMuNu.getMuon(); + const reco::MET& met = WMuNu.getNeutrino(); + if (plotHistograms_) { + h1_["hNWCand_sel"]->Fill(WMuNuCollection->size()); + } + + // Preselection cuts: + + if (!trigger_fired) { + LogTrace("") << "Event did not fire the Trigger"; + return false; + } + ntrig++; + + if (nmuonsForZ1 >= 1 && nmuonsForZ2 >= 2) { + LogTrace("") << "Z Candidate!!"; + return false; + } + if (njets > nJetMax_) { + LogTrace("") << "NJets > threshold"; + return false; + } + + npresel++; + + // Select Ws by charge: + + if (selectByCharge_ * WMuNu.charge() == -1) { + ncharge++; + } + + // W->mu nu selection criteria + + if (!mu.isGlobalMuon()) + return false; + + reco::TrackRef gm = mu.globalTrack(); + //reco::TrackRef tk = mu.innerTrack(); + + // Pt,eta cuts + double pt = mu.pt(); + double eta = mu.eta(); + LogTrace("") << "\t... Muon pt, eta: " << pt << " [GeV], " << eta; + if (plotHistograms_) { + h1_["hPtMu_sel"]->Fill(pt); + } + if (pt < ptCut_) + return false; + if (plotHistograms_) { + h1_["hEtaMu_sel"]->Fill(eta); + } + if (fabs(eta) > etaCut_) + return false; + + nkin++; + + // d0, chi2, nhits quality cuts + double dxy = gm->dxy(beamSpotHandle->position()); + double normalizedChi2 = gm->normalizedChi2(); + LogTrace("") << "Im here" << endl; + double trackerHits = gm->hitPattern().numberOfValidTrackerHits(); + LogTrace("") << "\t... Muon dxy, normalizedChi2, trackerHits, isTrackerMuon?: " << dxy << " [cm], " << normalizedChi2 + << ", " << trackerHits << ", " << mu.isTrackerMuon(); + + if (plotHistograms_) { + h1_["hd0_sel"]->Fill(dxy); + } + if (!muon::isGoodMuon(mu, muon::GlobalMuonPromptTight)) + return false; + if (plotHistograms_) { + h1_["hNormChi2_sel"]->Fill(normalizedChi2); + } + if (normalizedChi2 > normalizedChi2Cut_) + return false; + if (plotHistograms_) { + h1_["hNHits_sel"]->Fill(trackerHits); + } + if (trackerHits < trackerHitsCut_) + return false; + if (plotHistograms_) { + h1_["hTracker_sel"]->Fill(mu.isTrackerMuon()); + } + if (!mu.isTrackerMuon()) + return false; + + nid++; + + // Acoplanarity cuts + double acop = WMuNu.acop(); + LogTrace("") << "\t... acoplanarity: " << acop; + + // Isolation cuts + double SumPt = mu.isolationR03().sumPt; + double isovar = SumPt; + double Cal = mu.isolationR03().emEt + mu.isolationR03().hadEt; + if (isCombinedIso_) + isovar += Cal; + if (plotHistograms_) { + h1_["hPtSum_sel"]->Fill(SumPt); + h1_["hPtSumN_sel"]->Fill(SumPt / pt); + h1_["hCal_sel"]->Fill(Cal); + h1_["hIsoTot_sel"]->Fill((SumPt + Cal)); + h1_["hIsoTotN_sel"]->Fill((SumPt + Cal) / pt); + } + + if (isRelativeIso_) + isovar /= pt; + bool iso = (isovar <= isoCut03_); + LogTrace("") << "\t... isolation value" << isovar << ", isolated? " << iso; + + double met_et = met.pt(); + LogTrace("") << "\t... Met pt: " << WMuNu.getNeutrino().pt() << "[GeV]"; + + double massT = WMuNu.massT(); + double w_et = WMuNu.eT(); + + LogTrace("") << "\t... W mass, W_et, W_px, W_py: " << massT << ", " << w_et << ", " << WMuNu.px() << ", " + << WMuNu.py() << " [GeV]"; + + // Plot 2D Histograms before final cuts + if (plotHistograms_ && acop < acopCut_) { + h2_["hTMass_PtSum_inclusive"]->Fill(SumPt, massT); + h2_["hTMass_PtSumNorm_inclusive"]->Fill(SumPt / pt, massT); + h2_["hTMass_TotIsoNorm_inclusive"]->Fill((SumPt + Cal) / pt, massT); + h2_["hMET_PtSum_inclusive"]->Fill(SumPt, met_et); + h2_["hMET_PtSumNorm_inclusive"]->Fill(SumPt / pt, met_et); + h2_["hMET_TotIsoNorm_inclusive"]->Fill((SumPt + Cal) / pt, met_et); + } + + if (!iso) + return false; + + niso++; + + if (plotHistograms_) { + h1_["hAcop_sel"]->Fill(acop); + } + if (acop >= acopCut_) + return false; + + nacop++; + + if (plotHistograms_) { + h1_["hMET_sel"]->Fill(met_et); + h1_["hTMass_sel"]->Fill(massT); + } + + if (massT <= mtMin_ || massT >= mtMax_) + return false; + if (met_et <= metMin_ || met_et >= metMax_) + return false; + + LogTrace("") << ">>>> Event ACCEPTED"; + nsel++; + + // (To be continued ;-) ) + + return true; } #include "FWCore/Framework/interface/MakerMacros.h" diff --git a/ElectroWeakAnalysis/WMuNu/src/WMuNuValidator.cc b/ElectroWeakAnalysis/WMuNu/src/WMuNuValidator.cc old mode 100755 new mode 100644 index c184409cb4ae3..b523e13bdabb1 --- a/ElectroWeakAnalysis/WMuNu/src/WMuNuValidator.cc +++ b/ElectroWeakAnalysis/WMuNu/src/WMuNuValidator.cc @@ -11,7 +11,6 @@ // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - #include "FWCore/Framework/interface/EDFilter.h" #include "FWCore/Utilities/interface/InputTag.h" #include "FWCore/Framework/interface/Event.h" @@ -25,12 +24,13 @@ class WMuNuValidator : public edm::EDFilter { public: - WMuNuValidator (const edm::ParameterSet &); + WMuNuValidator(const edm::ParameterSet&); bool filter(edm::Event&, const edm::EventSetup&) override; void beginJob() override; void endJob() override; void init_histograms(); void fill_histogram(const char*, const double&); + private: bool fastOption_; edm::EDGetTokenT trigToken_; @@ -71,7 +71,7 @@ class WMuNuValidator : public edm::EDFilter { unsigned int nmet; unsigned int nsel; - std::map h1_; + std::map h1_; }; #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -94,22 +94,23 @@ using namespace edm; using namespace std; using namespace reco; -WMuNuValidator::WMuNuValidator( const ParameterSet & cfg ) : - // Fast selection (no histograms or book-keeping) - fastOption_(cfg.getUntrackedParameter ("FastOption", false)), +WMuNuValidator::WMuNuValidator(const ParameterSet& cfg) + : // Fast selection (no histograms or book-keeping) + fastOption_(cfg.getUntrackedParameter("FastOption", false)), // Input collections - trigToken_(consumes(cfg.getUntrackedParameter ("TrigTag", edm::InputTag("TriggerResults::HLT")))), - muonToken_(consumes >(cfg.getUntrackedParameter ("MuonTag", edm::InputTag("muons")))), - metTag_(cfg.getUntrackedParameter ("METTag", edm::InputTag("met"))), + trigToken_(consumes( + cfg.getUntrackedParameter("TrigTag", edm::InputTag("TriggerResults::HLT")))), + muonToken_(consumes >(cfg.getUntrackedParameter("MuonTag", edm::InputTag("muons")))), + metTag_(cfg.getUntrackedParameter("METTag", edm::InputTag("met"))), metToken_(consumes >(metTag_)), - metIncludesMuons_(cfg.getUntrackedParameter ("METIncludesMuons", false)), - jetTag_(cfg.getUntrackedParameter ("JetTag", edm::InputTag("sisCone5CaloJets"))), + metIncludesMuons_(cfg.getUntrackedParameter("METIncludesMuons", false)), + jetTag_(cfg.getUntrackedParameter("JetTag", edm::InputTag("sisCone5CaloJets"))), jetToken_(consumes >(jetTag_)), beamSpotToken_(consumes(edm::InputTag("offlineBeamSpot"))), // Main cuts - muonTrig_(cfg.getUntrackedParameter ("MuonTrig", "HLT_Mu9")), + muonTrig_(cfg.getUntrackedParameter("MuonTrig", "HLT_Mu9")), ptCut_(cfg.getUntrackedParameter("PtCut", 25.)), etaCut_(cfg.getUntrackedParameter("EtaCut", 2.1)), isRelativeIso_(cfg.getUntrackedParameter("IsRelativeIso", true)), @@ -133,477 +134,562 @@ WMuNuValidator::WMuNuValidator( const ParameterSet & cfg ) : // Top rejection eJetMin_(cfg.getUntrackedParameter("EJetMin", 999999.)), - nJetMax_(cfg.getUntrackedParameter("NJetMax", 999999)) -{ -} + nJetMax_(cfg.getUntrackedParameter("NJetMax", 999999)) {} void WMuNuValidator::beginJob() { - nall = 0; - nsel = 0; - - if (!fastOption_) { - nrec = 0; - niso = 0; - nhlt = 0; - nmet = 0; - init_histograms(); - } + nall = 0; + nsel = 0; + + if (!fastOption_) { + nrec = 0; + niso = 0; + nhlt = 0; + nmet = 0; + init_histograms(); + } } void WMuNuValidator::init_histograms() { - edm::Service fs; - TFileDirectory subDir0 = fs->mkdir("BeforeCuts"); - TFileDirectory subDir1 = fs->mkdir("LastCut"); - TFileDirectory* subDir[2]; subDir[0] = &subDir0; subDir[1] = &subDir1; - - char chname[256] = ""; - char chtitle[256] = ""; - std::string chsuffix[2] = { "_BEFORECUTS", "_LASTCUT" }; - - for (int i=0; i<2; ++i) { - snprintf(chname, 255, "PT%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Muon transverse momentum [GeV]"); - h1_[chname] = subDir[i]->make(chname,chtitle,100,0.,100.); - - snprintf(chname, 255, "ETA%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Muon pseudo-rapidity"); - h1_[chname] = subDir[i]->make(chname,chtitle,50,-2.5,2.5); - - snprintf(chname, 255, "DXY%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Muon transverse distance to beam spot [cm]"); - h1_[chname] = subDir[i]->make(chname,chtitle,100,-0.5,0.5); - - snprintf(chname, 255, "CHI2%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Normalized Chi2, inner track fit"); - h1_[chname] = subDir[i]->make(chname,chtitle,100,0.,100.); - - snprintf(chname, 255, "NHITS%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Number of hits, inner track"); - h1_[chname] = subDir[i]->make(chname,chtitle,40,-0.5,39.5); - - snprintf(chname, 255, "ValidMuonHits%s", chsuffix[i].data()); - snprintf(chtitle, 255, "number Of Valid Muon Hits"); - h1_[chname] = subDir[i]->make(chname,chtitle,40,-0.5,39.5); - - snprintf(chname, 255, "TKMU%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Tracker-muon flag (for global muons)"); - h1_[chname] = subDir[i]->make(chname,chtitle,2,-0.5,1.5); - - snprintf(chname, 255, "ISO%s", chsuffix[i].data()); - if (isRelativeIso_) { - if (isCombinedIso_) { - snprintf(chtitle, 255, "Relative (combined) isolation variable"); - } else { - snprintf(chtitle, 255, "Relative (tracker) isolation variable"); - } - h1_[chname] = subDir[i]->make(chname,chtitle, 100, 0., 1.); - } else { - if (isCombinedIso_) { - snprintf(chtitle, 255, "Absolute (combined) isolation variable [GeV]"); - } else { - snprintf(chtitle, 255, "Absolute (tracker) isolation variable [GeV]"); - } - h1_[chname] = subDir[i]->make(chname,chtitle, 100, 0., 20.); - } - - snprintf(chname, 255, "TRIG%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Trigger response (bit %s)", muonTrig_.data()); - h1_[chname] = subDir[i]->make(chname,chtitle,2,-0.5,1.5); + edm::Service fs; + TFileDirectory subDir0 = fs->mkdir("BeforeCuts"); + TFileDirectory subDir1 = fs->mkdir("LastCut"); + TFileDirectory* subDir[2]; + subDir[0] = &subDir0; + subDir[1] = &subDir1; + + char chname[256] = ""; + char chtitle[256] = ""; + std::string chsuffix[2] = {"_BEFORECUTS", "_LASTCUT"}; + + for (int i = 0; i < 2; ++i) { + snprintf(chname, 255, "PT%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Muon transverse momentum [GeV]"); + h1_[chname] = subDir[i]->make(chname, chtitle, 100, 0., 100.); + + snprintf(chname, 255, "ETA%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Muon pseudo-rapidity"); + h1_[chname] = subDir[i]->make(chname, chtitle, 50, -2.5, 2.5); + + snprintf(chname, 255, "DXY%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Muon transverse distance to beam spot [cm]"); + h1_[chname] = subDir[i]->make(chname, chtitle, 100, -0.5, 0.5); + + snprintf(chname, 255, "CHI2%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Normalized Chi2, inner track fit"); + h1_[chname] = subDir[i]->make(chname, chtitle, 100, 0., 100.); + + snprintf(chname, 255, "NHITS%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Number of hits, inner track"); + h1_[chname] = subDir[i]->make(chname, chtitle, 40, -0.5, 39.5); + + snprintf(chname, 255, "ValidMuonHits%s", chsuffix[i].data()); + snprintf(chtitle, 255, "number Of Valid Muon Hits"); + h1_[chname] = subDir[i]->make(chname, chtitle, 40, -0.5, 39.5); + + snprintf(chname, 255, "TKMU%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Tracker-muon flag (for global muons)"); + h1_[chname] = subDir[i]->make(chname, chtitle, 2, -0.5, 1.5); + + snprintf(chname, 255, "ISO%s", chsuffix[i].data()); + if (isRelativeIso_) { + if (isCombinedIso_) { + snprintf(chtitle, 255, "Relative (combined) isolation variable"); + } else { + snprintf(chtitle, 255, "Relative (tracker) isolation variable"); + } + h1_[chname] = subDir[i]->make(chname, chtitle, 100, 0., 1.); + } else { + if (isCombinedIso_) { + snprintf(chtitle, 255, "Absolute (combined) isolation variable [GeV]"); + } else { + snprintf(chtitle, 255, "Absolute (tracker) isolation variable [GeV]"); + } + h1_[chname] = subDir[i]->make(chname, chtitle, 100, 0., 20.); + } - snprintf(chname, 255, "MT%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Transverse mass (%s) [GeV]", metTag_.label().data()); - h1_[chname] = subDir[i]->make(chname,chtitle,150,0.,300.); + snprintf(chname, 255, "TRIG%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Trigger response (bit %s)", muonTrig_.data()); + h1_[chname] = subDir[i]->make(chname, chtitle, 2, -0.5, 1.5); - snprintf(chname, 255, "MET%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Missing transverse energy (%s) [GeV]", metTag_.label().data()); - h1_[chname] = subDir[i]->make(chname,chtitle,100,0.,200.); + snprintf(chname, 255, "MT%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Transverse mass (%s) [GeV]", metTag_.label().data()); + h1_[chname] = subDir[i]->make(chname, chtitle, 150, 0., 300.); - snprintf(chname, 255, "ACOP%s", chsuffix[i].data()); - snprintf(chtitle, 255, "MU-MET (%s) acoplanarity", metTag_.label().data()); - h1_[chname] = subDir[i]->make(chname,chtitle,50,0.,M_PI); + snprintf(chname, 255, "MET%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Missing transverse energy (%s) [GeV]", metTag_.label().data()); + h1_[chname] = subDir[i]->make(chname, chtitle, 100, 0., 200.); - snprintf(chname, 255, "NZ1%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Z rejection: number of muons above %.2f GeV", ptThrForZ1_); - h1_[chname] = subDir[i]->make(chname,chtitle, 10, -0.5, 9.5); + snprintf(chname, 255, "ACOP%s", chsuffix[i].data()); + snprintf(chtitle, 255, "MU-MET (%s) acoplanarity", metTag_.label().data()); + h1_[chname] = subDir[i]->make(chname, chtitle, 50, 0., M_PI); - snprintf(chname, 255, "NZ2%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Z rejection: number of muons above %.2f GeV", ptThrForZ2_); - h1_[chname] = subDir[i]->make(chname,chtitle, 10, -0.5, 9.5); + snprintf(chname, 255, "NZ1%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Z rejection: number of muons above %.2f GeV", ptThrForZ1_); + h1_[chname] = subDir[i]->make(chname, chtitle, 10, -0.5, 9.5); - snprintf(chname, 255, "NJETS%s", chsuffix[i].data()); - snprintf(chtitle, 255, "Number of jets (%s) above %.2f GeV", jetTag_.label().data(), eJetMin_); - h1_[chname] = subDir[i]->make(chname,chtitle,10,-0.5,9.5); + snprintf(chname, 255, "NZ2%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Z rejection: number of muons above %.2f GeV", ptThrForZ2_); + h1_[chname] = subDir[i]->make(chname, chtitle, 10, -0.5, 9.5); - } + snprintf(chname, 255, "NJETS%s", chsuffix[i].data()); + snprintf(chtitle, 255, "Number of jets (%s) above %.2f GeV", jetTag_.label().data(), eJetMin_); + h1_[chname] = subDir[i]->make(chname, chtitle, 10, -0.5, 9.5); + } } void WMuNuValidator::fill_histogram(const char* name, const double& var) { - if (fastOption_) return; - h1_[name]->Fill(var); + if (fastOption_) + return; + h1_[name]->Fill(var); } void WMuNuValidator::endJob() { - double all = nall; - double esel = nsel/all; - LogVerbatim("") << "\n>>>>>> W SELECTION SUMMARY BEGIN >>>>>>>>>>>>>>>"; - LogVerbatim("") << "Total numer of events analyzed: " << nall << " [events]"; - LogVerbatim("") << "Total numer of events selected: " << nsel << " [events]"; - LogVerbatim("") << "Overall efficiency: " << "(" << setprecision(4) << esel*100. <<" +/- "<< setprecision(2) << sqrt(esel*(1-esel)/all)*100. << ")%"; - - if (!fastOption_) { - double erec = nrec/all; - double eiso = niso/all; - double ehlt = nhlt/all; - double emet = nmet/all; - - double num = nrec; - double eff = erec; - double err = sqrt(eff*(1-eff)/all); - LogVerbatim("") << "Passing Pt/Eta/Quality cuts: " << num << " [events], (" << setprecision(4) << eff*100. <<" +/- "<< setprecision(2) << err*100. << ")%"; - - num = niso; - eff = eiso; - err = sqrt(eff*(1-eff)/all); - double effstep = 0.; - double errstep = 0.; - if (nrec>0) effstep = eiso/erec; - if (nrec>0) errstep = sqrt(effstep*(1-effstep)/nrec); - LogVerbatim("") << "Passing isolation cuts: " << num << " [events], (" << setprecision(4) << eff*100. <<" +/- "<< setprecision(2) << err*100. << ")%, to previous step: (" << setprecision(4) << effstep*100. << " +/- "<< setprecision(2) << errstep*100. <<")%"; - - num = nhlt; - eff = ehlt; - err = sqrt(eff*(1-eff)/all); - effstep = 0.; - errstep = 0.; - if (niso>0) effstep = ehlt/eiso; - if (niso>0) errstep = sqrt(effstep*(1-effstep)/niso); - LogVerbatim("") << "Passing HLT criteria: " << num << " [events], (" << setprecision(4) << eff*100. <<" +/- "<< setprecision(2) << err*100. << ")%, to previous step: (" << setprecision(4) << effstep*100. << " +/- "<< setprecision(2) << errstep*100. <<")%"; - - num = nmet; - eff = emet; - err = sqrt(eff*(1-eff)/all); - effstep = 0.; - errstep = 0.; - if (nhlt>0) effstep = emet/ehlt; - if (nhlt>0) errstep = sqrt(effstep*(1-effstep)/nhlt); - LogVerbatim("") << "Passing MET/acoplanarity cuts: " << num << " [events], (" << setprecision(4) << eff*100. <<" +/- "<< setprecision(2) << err*100. << ")%, to previous step: (" << setprecision(4) << effstep*100. << " +/- "<< setprecision(2) << errstep*100. <<")%"; - - num = nsel; - eff = esel; - err = sqrt(eff*(1-eff)/all); - effstep = 0.; - errstep = 0.; - if (nmet>0) effstep = esel/emet; - if (nmet>0) errstep = sqrt(effstep*(1-effstep)/nmet); - LogVerbatim("") << "Passing Z/top rejection cuts: " << num << " [events], (" << setprecision(4) << eff*100. <<" +/- "<< setprecision(2) << err*100. << ")%, to previous step: (" << setprecision(4) << effstep*100. << " +/- "<< setprecision(2) << errstep*100. <<")%"; - } - - LogVerbatim("") << ">>>>>> W SELECTION SUMMARY END >>>>>>>>>>>>>>>\n"; + double all = nall; + double esel = nsel / all; + LogVerbatim("") << "\n>>>>>> W SELECTION SUMMARY BEGIN >>>>>>>>>>>>>>>"; + LogVerbatim("") << "Total numer of events analyzed: " << nall << " [events]"; + LogVerbatim("") << "Total numer of events selected: " << nsel << " [events]"; + LogVerbatim("") << "Overall efficiency: " + << "(" << setprecision(4) << esel * 100. << " +/- " << setprecision(2) + << sqrt(esel * (1 - esel) / all) * 100. << ")%"; + + if (!fastOption_) { + double erec = nrec / all; + double eiso = niso / all; + double ehlt = nhlt / all; + double emet = nmet / all; + + double num = nrec; + double eff = erec; + double err = sqrt(eff * (1 - eff) / all); + LogVerbatim("") << "Passing Pt/Eta/Quality cuts: " << num << " [events], (" << setprecision(4) << eff * 100. + << " +/- " << setprecision(2) << err * 100. << ")%"; + + num = niso; + eff = eiso; + err = sqrt(eff * (1 - eff) / all); + double effstep = 0.; + double errstep = 0.; + if (nrec > 0) + effstep = eiso / erec; + if (nrec > 0) + errstep = sqrt(effstep * (1 - effstep) / nrec); + LogVerbatim("") << "Passing isolation cuts: " << num << " [events], (" << setprecision(4) << eff * 100. + << " +/- " << setprecision(2) << err * 100. << ")%, to previous step: (" << setprecision(4) + << effstep * 100. << " +/- " << setprecision(2) << errstep * 100. << ")%"; + + num = nhlt; + eff = ehlt; + err = sqrt(eff * (1 - eff) / all); + effstep = 0.; + errstep = 0.; + if (niso > 0) + effstep = ehlt / eiso; + if (niso > 0) + errstep = sqrt(effstep * (1 - effstep) / niso); + LogVerbatim("") << "Passing HLT criteria: " << num << " [events], (" << setprecision(4) << eff * 100. + << " +/- " << setprecision(2) << err * 100. << ")%, to previous step: (" << setprecision(4) + << effstep * 100. << " +/- " << setprecision(2) << errstep * 100. << ")%"; + + num = nmet; + eff = emet; + err = sqrt(eff * (1 - eff) / all); + effstep = 0.; + errstep = 0.; + if (nhlt > 0) + effstep = emet / ehlt; + if (nhlt > 0) + errstep = sqrt(effstep * (1 - effstep) / nhlt); + LogVerbatim("") << "Passing MET/acoplanarity cuts: " << num << " [events], (" << setprecision(4) << eff * 100. + << " +/- " << setprecision(2) << err * 100. << ")%, to previous step: (" << setprecision(4) + << effstep * 100. << " +/- " << setprecision(2) << errstep * 100. << ")%"; + + num = nsel; + eff = esel; + err = sqrt(eff * (1 - eff) / all); + effstep = 0.; + errstep = 0.; + if (nmet > 0) + effstep = esel / emet; + if (nmet > 0) + errstep = sqrt(effstep * (1 - effstep) / nmet); + LogVerbatim("") << "Passing Z/top rejection cuts: " << num << " [events], (" << setprecision(4) << eff * 100. + << " +/- " << setprecision(2) << err * 100. << ")%, to previous step: (" << setprecision(4) + << effstep * 100. << " +/- " << setprecision(2) << errstep * 100. << ")%"; + } + + LogVerbatim("") << ">>>>>> W SELECTION SUMMARY END >>>>>>>>>>>>>>>\n"; } -bool WMuNuValidator::filter (Event & ev, const EventSetup &) { - - // Reset global event selection flags - bool rec_sel = false; - bool iso_sel = false; - bool hlt_sel = false; - bool met_sel = false; - bool all_sel = false; - - // Muon collection - Handle > muonCollection; - if (!ev.getByToken(muonToken_, muonCollection)) { - LogError("") << ">>> Muon collection does not exist !!!"; - return false; - } - unsigned int muonCollectionSize = muonCollection->size(); - - // Beam spot - Handle beamSpotHandle; - if (!ev.getByToken(beamSpotToken_, beamSpotHandle)) { - LogTrace("") << ">>> No beam spot found !!!"; - return false; - } - - // MET - double met_px = 0.; - double met_py = 0.; - Handle > metCollection; - if (!ev.getByToken(metToken_, metCollection)) { - LogError("") << ">>> MET collection does not exist !!!"; - return false; - } - const MET& met = metCollection->at(0); - met_px = met.px(); - met_py = met.py(); - if (!metIncludesMuons_) { - for (unsigned int i=0; iat(i); - if (!mu.isGlobalMuon()) continue; - met_px -= mu.px(); - met_py -= mu.py(); - } - } - double met_et = sqrt(met_px*met_px+met_py*met_py); - LogTrace("") << ">>> MET, MET_px, MET_py: " << met_et << ", " << met_px << ", " << met_py << " [GeV]"; - fill_histogram("MET_BEFORECUTS",met_et); - - // Trigger - Handle triggerResults; - if (!ev.getByToken(trigToken_, triggerResults)) { - LogError("") << ">>> TRIGGER collection does not exist !!!"; - return false; - } - const edm::TriggerNames & triggerNames = ev.triggerNames(*triggerResults); - /* +bool WMuNuValidator::filter(Event& ev, const EventSetup&) { + // Reset global event selection flags + bool rec_sel = false; + bool iso_sel = false; + bool hlt_sel = false; + bool met_sel = false; + bool all_sel = false; + + // Muon collection + Handle > muonCollection; + if (!ev.getByToken(muonToken_, muonCollection)) { + LogError("") << ">>> Muon collection does not exist !!!"; + return false; + } + unsigned int muonCollectionSize = muonCollection->size(); + + // Beam spot + Handle beamSpotHandle; + if (!ev.getByToken(beamSpotToken_, beamSpotHandle)) { + LogTrace("") << ">>> No beam spot found !!!"; + return false; + } + + // MET + double met_px = 0.; + double met_py = 0.; + Handle > metCollection; + if (!ev.getByToken(metToken_, metCollection)) { + LogError("") << ">>> MET collection does not exist !!!"; + return false; + } + const MET& met = metCollection->at(0); + met_px = met.px(); + met_py = met.py(); + if (!metIncludesMuons_) { + for (unsigned int i = 0; i < muonCollectionSize; i++) { + const Muon& mu = muonCollection->at(i); + if (!mu.isGlobalMuon()) + continue; + met_px -= mu.px(); + met_py -= mu.py(); + } + } + double met_et = sqrt(met_px * met_px + met_py * met_py); + LogTrace("") << ">>> MET, MET_px, MET_py: " << met_et << ", " << met_px << ", " << met_py << " [GeV]"; + fill_histogram("MET_BEFORECUTS", met_et); + + // Trigger + Handle triggerResults; + if (!ev.getByToken(trigToken_, triggerResults)) { + LogError("") << ">>> TRIGGER collection does not exist !!!"; + return false; + } + const edm::TriggerNames& triggerNames = ev.triggerNames(*triggerResults); + /* for (unsigned int i=0; isize(); i++) { if (triggerResults->accept(i)) { LogTrace("") << "Accept by: " << i << ", Trigger: " << triggerNames.triggerName(i); } } */ - bool trigger_fired = false; - int itrig1 = triggerNames.triggerIndex(muonTrig_); - if (triggerResults->accept(itrig1)) trigger_fired = true; - LogTrace("") << ">>> Trigger bit: " << trigger_fired << " (" << muonTrig_ << ")"; - fill_histogram("TRIG_BEFORECUTS",trigger_fired); - - // Loop to reject/control Z->mumu is done separately - unsigned int nmuonsForZ1 = 0; - unsigned int nmuonsForZ2 = 0; - for (unsigned int i=0; iat(i); - if (!mu.isGlobalMuon()) continue; - double pt = mu.pt(); - if (pt>ptThrForZ1_) nmuonsForZ1++; - if (pt>ptThrForZ2_) nmuonsForZ2++; - } - LogTrace("") << "> Z rejection: muons above " << ptThrForZ1_ << " [GeV]: " << nmuonsForZ1; - LogTrace("") << "> Z rejection: muons above " << ptThrForZ2_ << " [GeV]: " << nmuonsForZ2; - fill_histogram("NZ1_BEFORECUTS",nmuonsForZ1); - fill_histogram("NZ2_BEFORECUTS",nmuonsForZ2); - - // Jet collection - Handle > jetCollection; - if (!ev.getByToken(jetToken_, jetCollection)) { - LogError("") << ">>> JET collection does not exist !!!"; - return false; - } - unsigned int jetCollectionSize = jetCollection->size(); - int njets = 0; - for (unsigned int i=0; iat(i); - if (jet.et()>eJetMin_) njets++; - } - LogTrace("") << ">>> Total number of jets: " << jetCollectionSize; - LogTrace("") << ">>> Number of jets above " << eJetMin_ << " [GeV]: " << njets; - fill_histogram("NJETS_BEFORECUTS",njets); - - // Start counting, reject already events if possible (under FastOption flag) - nall++; - if (fastOption_ && !trigger_fired) return false; - if (fastOption_ && nmuonsForZ1>=1 && nmuonsForZ2>=2) return false; - if (fastOption_ && njets>nJetMax_) return false; - - // Histograms per event shouldbe done only once, so keep track of them - bool hlt_hist_done = false; - bool met_hist_done = false; - bool nz1_hist_done = false; - bool nz2_hist_done = false; - bool njets_hist_done = false; - - // Central W->mu nu selection criteria - const int NFLAGS = 13; - bool muon_sel[NFLAGS]; - for (unsigned int i=0; iat(i); - if (!mu.isGlobalMuon()) continue; - if (mu.globalTrack().isNull()) continue; - if (mu.innerTrack().isNull()) continue; - - LogTrace("") << "> Wsel: processing muon number " << i << "..."; - reco::TrackRef gm = mu.globalTrack(); - //reco::TrackRef tk = mu.innerTrack(); - - // Pt,eta cuts - double pt = mu.pt(); - double eta = mu.eta(); - LogTrace("") << "\t... pt, eta: " << pt << " [GeV], " << eta;; - if (pt>ptCut_) muon_sel[0] = true; - else if (fastOption_) continue; - if (fabs(eta)dxy(beamSpotHandle->position()); - double normalizedChi2 = gm->normalizedChi2(); - double validmuonhits=gm->hitPattern().numberOfValidMuonHits(); - //double standalonehits=mu.outerTrack()->numberOfValidHits(); - double trackerHits = gm->hitPattern().numberOfValidTrackerHits(); - LogTrace("") << "\t... dxy, normalizedChi2, trackerHits, isTrackerMuon?: " << dxy << " [cm], " << normalizedChi2 << ", " << trackerHits << ", " << mu.isTrackerMuon(); - if (fabs(dxy)=trackerHitsCut_) muon_sel[4] = true; - else if (fastOption_) continue; - if (mu.isTrackerMuon()) muon_sel[5] = true; - else if (fastOption_) continue; - - fill_histogram("PT_BEFORECUTS",pt); - fill_histogram("ETA_BEFORECUTS",eta); - fill_histogram("DXY_BEFORECUTS",dxy); - fill_histogram("CHI2_BEFORECUTS",normalizedChi2); - fill_histogram("NHITS_BEFORECUTS",trackerHits); - fill_histogram("ValidMuonHits_BEFORECUTS",validmuonhits); - fill_histogram("TKMU_BEFORECUTS",mu.isTrackerMuon()); - - // Isolation cuts - double isovar = mu.isolationR03().sumPt; - if (isCombinedIso_) { - isovar += mu.isolationR03().emEt; - isovar += mu.isolationR03().hadEt; - } - if (isRelativeIso_) isovar /= pt; - if (isovar0) ? sqrt(massT) : 0; - - LogTrace("") << "\t... W mass, W_et, W_px, W_py: " << massT << ", " << w_et << ", " << w_px << ", " << w_py << " [GeV]"; - if (massT>mtMin_ && massTmetMin_ && met_et deltaphi(mu.phi()-atan2(met_py,met_px)); - double acop = deltaphi.value(); - if (acop<0) acop = - acop; - acop = M_PI - acop; - LogTrace("") << "\t... acoplanarity: " << acop; - if (acop pt,eta and quality cuts are satisfied - if (rec_sel_this) rec_sel = true; - // "iso" => "rec" AND "muon is isolated" - if (iso_sel_this) iso_sel = true; - // "hlt" => "iso" AND "event is triggered" - if (hlt_sel_this) hlt_sel = true; - // "met" => "hlt" AND "MET/MT and acoplanarity cuts" - if (met_sel_this) met_sel = true; - // "all" => "met" AND "Z/top rejection cuts" - if (all_sel_this) all_sel = true; - - // Do N-1 histograms now (and only once for global event quantities) - if (flags_passed >= (NFLAGS-1)) { - if (!muon_sel[0] || flags_passed==NFLAGS) - fill_histogram("PT_LASTCUT",pt); - if (!muon_sel[1] || flags_passed==NFLAGS) - fill_histogram("ETA_LASTCUT",eta); - if (!muon_sel[2] || flags_passed==NFLAGS) - fill_histogram("DXY_LASTCUT",dxy); - if (!muon_sel[3] || flags_passed==NFLAGS) { - fill_histogram("CHI2_LASTCUT",normalizedChi2); - fill_histogram("ValidMuonHits_LASTCUT",validmuonhits); } - if (!muon_sel[4] || flags_passed==NFLAGS) - fill_histogram("NHITS_LASTCUT",trackerHits); - if (!muon_sel[5] || flags_passed==NFLAGS) - fill_histogram("TKMU_LASTCUT",mu.isTrackerMuon()); - if (!muon_sel[6] || flags_passed==NFLAGS) - fill_histogram("ISO_LASTCUT",isovar); - if (!muon_sel[7] || flags_passed==NFLAGS) { - if (!hlt_hist_done) { fill_histogram("TRIG_LASTCUT",trigger_fired); - hlt_hist_done = true;} - } - if (!muon_sel[8] || flags_passed==NFLAGS) - fill_histogram("MT_LASTCUT",massT); - if (!muon_sel[9] || flags_passed==NFLAGS) { - if (!met_hist_done) { fill_histogram("MET_LASTCUT",met_et); - met_hist_done = true;} - } - if (!muon_sel[10] || flags_passed==NFLAGS) - fill_histogram("ACOP_LASTCUT",acop); - if (!muon_sel[11] || flags_passed==NFLAGS) { - if (!nz1_hist_done) { fill_histogram("NZ1_LASTCUT",nmuonsForZ1); - nz1_hist_done = true;} - } - if (!muon_sel[11] || flags_passed==NFLAGS) { - if (!nz2_hist_done) { fill_histogram("NZ2_LASTCUT",nmuonsForZ2); - nz2_hist_done = true; } - } - if (!muon_sel[12] || flags_passed==NFLAGS) { - if (!njets_hist_done) { fill_histogram("NJETS_LASTCUT",njets); - njets_hist_done = true;} - } - } - } - + bool trigger_fired = false; + int itrig1 = triggerNames.triggerIndex(muonTrig_); + if (triggerResults->accept(itrig1)) + trigger_fired = true; + LogTrace("") << ">>> Trigger bit: " << trigger_fired << " (" << muonTrig_ << ")"; + fill_histogram("TRIG_BEFORECUTS", trigger_fired); + + // Loop to reject/control Z->mumu is done separately + unsigned int nmuonsForZ1 = 0; + unsigned int nmuonsForZ2 = 0; + for (unsigned int i = 0; i < muonCollectionSize; i++) { + const Muon& mu = muonCollection->at(i); + if (!mu.isGlobalMuon()) + continue; + double pt = mu.pt(); + if (pt > ptThrForZ1_) + nmuonsForZ1++; + if (pt > ptThrForZ2_) + nmuonsForZ2++; + } + LogTrace("") << "> Z rejection: muons above " << ptThrForZ1_ << " [GeV]: " << nmuonsForZ1; + LogTrace("") << "> Z rejection: muons above " << ptThrForZ2_ << " [GeV]: " << nmuonsForZ2; + fill_histogram("NZ1_BEFORECUTS", nmuonsForZ1); + fill_histogram("NZ2_BEFORECUTS", nmuonsForZ2); + + // Jet collection + Handle > jetCollection; + if (!ev.getByToken(jetToken_, jetCollection)) { + LogError("") << ">>> JET collection does not exist !!!"; + return false; + } + unsigned int jetCollectionSize = jetCollection->size(); + int njets = 0; + for (unsigned int i = 0; i < jetCollectionSize; i++) { + const Jet& jet = jetCollection->at(i); + if (jet.et() > eJetMin_) + njets++; + } + LogTrace("") << ">>> Total number of jets: " << jetCollectionSize; + LogTrace("") << ">>> Number of jets above " << eJetMin_ << " [GeV]: " << njets; + fill_histogram("NJETS_BEFORECUTS", njets); + + // Start counting, reject already events if possible (under FastOption flag) + nall++; + if (fastOption_ && !trigger_fired) + return false; + if (fastOption_ && nmuonsForZ1 >= 1 && nmuonsForZ2 >= 2) + return false; + if (fastOption_ && njets > nJetMax_) + return false; + + // Histograms per event shouldbe done only once, so keep track of them + bool hlt_hist_done = false; + bool met_hist_done = false; + bool nz1_hist_done = false; + bool nz2_hist_done = false; + bool njets_hist_done = false; + + // Central W->mu nu selection criteria + const int NFLAGS = 13; + bool muon_sel[NFLAGS]; + for (unsigned int i = 0; i < muonCollectionSize; i++) { + for (int j = 0; j < NFLAGS; ++j) { + muon_sel[j] = false; + } + + const Muon& mu = muonCollection->at(i); + if (!mu.isGlobalMuon()) + continue; + if (mu.globalTrack().isNull()) + continue; + if (mu.innerTrack().isNull()) + continue; + + LogTrace("") << "> Wsel: processing muon number " << i << "..."; + reco::TrackRef gm = mu.globalTrack(); + //reco::TrackRef tk = mu.innerTrack(); + + // Pt,eta cuts + double pt = mu.pt(); + double eta = mu.eta(); + LogTrace("") << "\t... pt, eta: " << pt << " [GeV], " << eta; + ; + if (pt > ptCut_) + muon_sel[0] = true; + else if (fastOption_) + continue; + if (fabs(eta) < etaCut_) + muon_sel[1] = true; + else if (fastOption_) + continue; + + // d0, chi2, nhits quality cuts + double dxy = gm->dxy(beamSpotHandle->position()); + double normalizedChi2 = gm->normalizedChi2(); + double validmuonhits = gm->hitPattern().numberOfValidMuonHits(); + //double standalonehits=mu.outerTrack()->numberOfValidHits(); + double trackerHits = gm->hitPattern().numberOfValidTrackerHits(); + LogTrace("") << "\t... dxy, normalizedChi2, trackerHits, isTrackerMuon?: " << dxy << " [cm], " << normalizedChi2 + << ", " << trackerHits << ", " << mu.isTrackerMuon(); + if (fabs(dxy) < dxyCut_) + muon_sel[2] = true; + else if (fastOption_) + continue; + if (muon::isGoodMuon(mu, muon::GlobalMuonPromptTight)) + muon_sel[3] = true; + else if (fastOption_) + continue; + if (trackerHits >= trackerHitsCut_) + muon_sel[4] = true; + else if (fastOption_) + continue; + if (mu.isTrackerMuon()) + muon_sel[5] = true; + else if (fastOption_) + continue; + + fill_histogram("PT_BEFORECUTS", pt); + fill_histogram("ETA_BEFORECUTS", eta); + fill_histogram("DXY_BEFORECUTS", dxy); + fill_histogram("CHI2_BEFORECUTS", normalizedChi2); + fill_histogram("NHITS_BEFORECUTS", trackerHits); + fill_histogram("ValidMuonHits_BEFORECUTS", validmuonhits); + fill_histogram("TKMU_BEFORECUTS", mu.isTrackerMuon()); + + // Isolation cuts + double isovar = mu.isolationR03().sumPt; + if (isCombinedIso_) { + isovar += mu.isolationR03().emEt; + isovar += mu.isolationR03().hadEt; + } + if (isRelativeIso_) + isovar /= pt; + if (isovar < isoCut03_) + muon_sel[6] = true; + else if (fastOption_) + continue; + LogTrace("") << "\t... isolation value" << isovar << ", isolated? " << muon_sel[6]; + fill_histogram("ISO_BEFORECUTS", isovar); + + // HLT (not mtched to muon for the time being) + if (trigger_fired) + muon_sel[7] = true; + else if (fastOption_) + continue; + + // MET/MT cuts + double w_et = met_et + mu.pt(); + double w_px = met_px + mu.px(); + double w_py = met_py + mu.py(); + double massT = w_et * w_et - w_px * w_px - w_py * w_py; + massT = (massT > 0) ? sqrt(massT) : 0; + + LogTrace("") << "\t... W mass, W_et, W_px, W_py: " << massT << ", " << w_et << ", " << w_px << ", " << w_py + << " [GeV]"; + if (massT > mtMin_ && massT < mtMax_) + muon_sel[8] = true; + else if (fastOption_) + continue; + fill_histogram("MT_BEFORECUTS", massT); + if (met_et > metMin_ && met_et < metMax_) + muon_sel[9] = true; + else if (fastOption_) + continue; + + // Acoplanarity cuts + Geom::Phi deltaphi(mu.phi() - atan2(met_py, met_px)); + double acop = deltaphi.value(); + if (acop < 0) + acop = -acop; + acop = M_PI - acop; + LogTrace("") << "\t... acoplanarity: " << acop; + if (acop < acopCut_) + muon_sel[10] = true; + else if (fastOption_) + continue; + fill_histogram("ACOP_BEFORECUTS", acop); + + // Remaining flags (from global event information) + if (nmuonsForZ1 < 1 || nmuonsForZ2 < 2) + muon_sel[11] = true; + else if (fastOption_) + continue; + if (njets <= nJetMax_) + muon_sel[12] = true; + else if (fastOption_) + continue; + + if (fastOption_) { + all_sel = true; + break; + } else { + // Collect necessary flags "per muon" + int flags_passed = 0; + bool rec_sel_this = true; + bool iso_sel_this = true; + bool hlt_sel_this = true; + bool met_sel_this = true; + bool all_sel_this = true; + for (int j = 0; j < NFLAGS; ++j) { + if (muon_sel[j]) + flags_passed += 1; + if (j < 6 && !muon_sel[j]) + rec_sel_this = false; + if (j < 7 && !muon_sel[j]) + iso_sel_this = false; + if (j < 8 && !muon_sel[j]) + hlt_sel_this = false; + if (j < 11 && !muon_sel[j]) + met_sel_this = false; + if (!muon_sel[j]) + all_sel_this = false; } - // Collect final flags - if (!fastOption_) { - if (rec_sel) nrec++; - if (iso_sel) niso++; - if (hlt_sel) nhlt++; - if (met_sel) nmet++; + // "rec" => pt,eta and quality cuts are satisfied + if (rec_sel_this) + rec_sel = true; + // "iso" => "rec" AND "muon is isolated" + if (iso_sel_this) + iso_sel = true; + // "hlt" => "iso" AND "event is triggered" + if (hlt_sel_this) + hlt_sel = true; + // "met" => "hlt" AND "MET/MT and acoplanarity cuts" + if (met_sel_this) + met_sel = true; + // "all" => "met" AND "Z/top rejection cuts" + if (all_sel_this) + all_sel = true; + + // Do N-1 histograms now (and only once for global event quantities) + if (flags_passed >= (NFLAGS - 1)) { + if (!muon_sel[0] || flags_passed == NFLAGS) + fill_histogram("PT_LASTCUT", pt); + if (!muon_sel[1] || flags_passed == NFLAGS) + fill_histogram("ETA_LASTCUT", eta); + if (!muon_sel[2] || flags_passed == NFLAGS) + fill_histogram("DXY_LASTCUT", dxy); + if (!muon_sel[3] || flags_passed == NFLAGS) { + fill_histogram("CHI2_LASTCUT", normalizedChi2); + fill_histogram("ValidMuonHits_LASTCUT", validmuonhits); + } + if (!muon_sel[4] || flags_passed == NFLAGS) + fill_histogram("NHITS_LASTCUT", trackerHits); + if (!muon_sel[5] || flags_passed == NFLAGS) + fill_histogram("TKMU_LASTCUT", mu.isTrackerMuon()); + if (!muon_sel[6] || flags_passed == NFLAGS) + fill_histogram("ISO_LASTCUT", isovar); + if (!muon_sel[7] || flags_passed == NFLAGS) { + if (!hlt_hist_done) { + fill_histogram("TRIG_LASTCUT", trigger_fired); + hlt_hist_done = true; + } + } + if (!muon_sel[8] || flags_passed == NFLAGS) + fill_histogram("MT_LASTCUT", massT); + if (!muon_sel[9] || flags_passed == NFLAGS) { + if (!met_hist_done) { + fill_histogram("MET_LASTCUT", met_et); + met_hist_done = true; + } + } + if (!muon_sel[10] || flags_passed == NFLAGS) + fill_histogram("ACOP_LASTCUT", acop); + if (!muon_sel[11] || flags_passed == NFLAGS) { + if (!nz1_hist_done) { + fill_histogram("NZ1_LASTCUT", nmuonsForZ1); + nz1_hist_done = true; + } + } + if (!muon_sel[11] || flags_passed == NFLAGS) { + if (!nz2_hist_done) { + fill_histogram("NZ2_LASTCUT", nmuonsForZ2); + nz2_hist_done = true; + } + } + if (!muon_sel[12] || flags_passed == NFLAGS) { + if (!njets_hist_done) { + fill_histogram("NJETS_LASTCUT", njets); + njets_hist_done = true; + } + } } - - if (all_sel) { - nsel++; - LogTrace("") << ">>>> Event ACCEPTED"; - } else { - LogTrace("") << ">>>> Event REJECTED"; - } - - return all_sel; - + } + } + + // Collect final flags + if (!fastOption_) { + if (rec_sel) + nrec++; + if (iso_sel) + niso++; + if (hlt_sel) + nhlt++; + if (met_sel) + nmet++; + } + + if (all_sel) { + nsel++; + LogTrace("") << ">>>> Event ACCEPTED"; + } else { + LogTrace("") << ">>>> Event REJECTED"; + } + + return all_sel; } #include "FWCore/Framework/interface/MakerMacros.h" - DEFINE_FWK_MODULE( WMuNuValidator ); +DEFINE_FWK_MODULE(WMuNuValidator); diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBdToJPsiKxBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBdToJPsiKxBuilder.h index 1a3efcbdef508..0435ee075e84a 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBdToJPsiKxBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBdToJPsiKxBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -38,14 +37,12 @@ class BPHMassFitSelect; // --------------------- class BPHBdToJPsiKxBuilder { - - public: - +public: /** Constructor */ - BPHBdToJPsiKxBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const std::vector& kx0Collection ); + BPHBdToJPsiKxBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const std::vector& kx0Collection); /** Destructor */ @@ -57,47 +54,46 @@ class BPHBdToJPsiKxBuilder { std::vector build(); /// set cuts - void setJPsiMassMin( double m ); - void setJPsiMassMax( double m ); - void setKxMassMin ( double m ); - void setKxMassMax ( double m ); - void setMassMin ( double m ); - void setMassMax ( double m ); - void setProbMin ( double p ); - void setMassFitMin ( double m ); - void setMassFitMax ( double m ); - void setConstr ( bool flag ); + void setJPsiMassMin(double m); + void setJPsiMassMax(double m); + void setKxMassMin(double m); + void setKxMassMax(double m); + void setMassMin(double m); + void setMassMax(double m); + void setProbMin(double p); + void setMassFitMin(double m); + void setMassFitMax(double m); + void setConstr(bool flag); /// get current cuts double getJPsiMassMin() const; double getJPsiMassMax() const; - double getKxMassMin () const; - double getKxMassMax () const; - double getMassMin () const; - double getMassMax () const; - double getProbMin () const; - double getMassFitMin () const; - double getMassFitMax () const; - bool getConstr () const; - - private: - + double getKxMassMin() const; + double getKxMassMax() const; + double getMassMin() const; + double getMassMax() const; + double getProbMin() const; + double getMassFitMin() const; + double getMassFitMax() const; + bool getConstr() const; + +private: // private copy and assigment constructors - BPHBdToJPsiKxBuilder ( const BPHBdToJPsiKxBuilder& x ) = delete; - BPHBdToJPsiKxBuilder& operator=( const BPHBdToJPsiKxBuilder& x ) = delete; + BPHBdToJPsiKxBuilder(const BPHBdToJPsiKxBuilder& x) = delete; + BPHBdToJPsiKxBuilder& operator=(const BPHBdToJPsiKxBuilder& x) = delete; std::string jPsiName; - std::string kx0Name; + std::string kx0Name; const edm::EventSetup* evSetup; const std::vector* jCollection; const std::vector* kCollection; - BPHMassSelect * jpsiSel; - BPHMassSelect * mkx0Sel; + BPHMassSelect* jpsiSel; + BPHMassSelect* mkx0Sel; - BPHMassSelect * massSel; - BPHChi2Select * chi2Sel; + BPHMassSelect* massSel; + BPHChi2Select* chi2Sel; BPHMassFitSelect* mFitSel; bool massConstr; @@ -105,9 +101,6 @@ class BPHBdToJPsiKxBuilder { bool updated; std::vector bdList; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBsToJPsiPhiBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBsToJPsiPhiBuilder.h index eef7ecc28bfc2..b9b210e44d236 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBsToJPsiPhiBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBsToJPsiPhiBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -38,14 +37,12 @@ class BPHMassFitSelect; // --------------------- class BPHBsToJPsiPhiBuilder { - - public: - +public: /** Constructor */ - BPHBsToJPsiPhiBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const std::vector& phiCollection ); + BPHBsToJPsiPhiBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const std::vector& phiCollection); /** Destructor */ @@ -57,47 +54,46 @@ class BPHBsToJPsiPhiBuilder { std::vector build(); /// set cuts - void setJPsiMassMin( double m ); - void setJPsiMassMax( double m ); - void setPhiMassMin ( double m ); - void setPhiMassMax ( double m ); - void setMassMin ( double m ); - void setMassMax ( double m ); - void setProbMin ( double p ); - void setMassFitMin ( double m ); - void setMassFitMax ( double m ); - void setConstr ( bool flag ); + void setJPsiMassMin(double m); + void setJPsiMassMax(double m); + void setPhiMassMin(double m); + void setPhiMassMax(double m); + void setMassMin(double m); + void setMassMax(double m); + void setProbMin(double p); + void setMassFitMin(double m); + void setMassFitMax(double m); + void setConstr(bool flag); /// get current cuts double getJPsiMassMin() const; double getJPsiMassMax() const; - double getPhiMassMin () const; - double getPhiMassMax () const; - double getMassMin () const; - double getMassMax () const; - double getProbMin () const; - double getMassFitMin () const; - double getMassFitMax () const; - bool getConstr () const; - - private: - + double getPhiMassMin() const; + double getPhiMassMax() const; + double getMassMin() const; + double getMassMax() const; + double getProbMin() const; + double getMassFitMin() const; + double getMassFitMax() const; + bool getConstr() const; + +private: // private copy and assigment constructors - BPHBsToJPsiPhiBuilder ( const BPHBsToJPsiPhiBuilder& x ) = delete; - BPHBsToJPsiPhiBuilder& operator=( const BPHBsToJPsiPhiBuilder& x ) = delete; + BPHBsToJPsiPhiBuilder(const BPHBsToJPsiPhiBuilder& x) = delete; + BPHBsToJPsiPhiBuilder& operator=(const BPHBsToJPsiPhiBuilder& x) = delete; std::string jPsiName; - std::string phiName; + std::string phiName; const edm::EventSetup* evSetup; const std::vector* jCollection; const std::vector* pCollection; - BPHMassSelect * jpsiSel; - BPHMassSelect * mphiSel; + BPHMassSelect* jpsiSel; + BPHMassSelect* mphiSel; - BPHMassSelect * massSel; - BPHChi2Select * chi2Sel; + BPHMassSelect* massSel; + BPHChi2Select* chi2Sel; BPHMassFitSelect* mFitSel; bool massConstr; @@ -105,9 +101,6 @@ class BPHBsToJPsiPhiBuilder { bool updated; std::vector bsList; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBuToJPsiKBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBuToJPsiKBuilder.h index 400cd09cb1f04..9923bca323e3e 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBuToJPsiKBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHBuToJPsiKBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -41,14 +40,12 @@ class BPHMassFitSelect; // --------------------- class BPHBuToJPsiKBuilder { - - public: - +public: /** Constructor */ - BPHBuToJPsiKBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const BPHRecoBuilder::BPHGenericCollection* kaonCollection ); + BPHBuToJPsiKBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const BPHRecoBuilder::BPHGenericCollection* kaonCollection); /** Destructor */ @@ -60,59 +57,55 @@ class BPHBuToJPsiKBuilder { std::vector build(); /// set cuts - void setKPtMin ( double pt ); - void setKEtaMax ( double eta ); - void setJPsiMassMin( double m ); - void setJPsiMassMax( double m ); - void setMassMin ( double m ); - void setMassMax ( double m ); - void setProbMin ( double p ); - void setMassFitMin ( double m ); - void setMassFitMax ( double m ); - void setConstr ( bool flag ); + void setKPtMin(double pt); + void setKEtaMax(double eta); + void setJPsiMassMin(double m); + void setJPsiMassMax(double m); + void setMassMin(double m); + void setMassMax(double m); + void setProbMin(double p); + void setMassFitMin(double m); + void setMassFitMax(double m); + void setConstr(bool flag); /// get current cuts - double getKPtMin () const; - double getKEtaMax () const; + double getKPtMin() const; + double getKEtaMax() const; double getJPsiMassMin() const; double getJPsiMassMax() const; - double getMassMin () const; - double getMassMax () const; - double getProbMin () const; - double getMassFitMin () const; - double getMassFitMax () const; - bool getConstr () const; - - private: - + double getMassMin() const; + double getMassMax() const; + double getProbMin() const; + double getMassFitMin() const; + double getMassFitMax() const; + bool getConstr() const; + +private: // private copy and assigment constructors - BPHBuToJPsiKBuilder ( const BPHBuToJPsiKBuilder& x ) = delete; - BPHBuToJPsiKBuilder& operator=( const BPHBuToJPsiKBuilder& x ) = delete; + BPHBuToJPsiKBuilder(const BPHBuToJPsiKBuilder& x) = delete; + BPHBuToJPsiKBuilder& operator=(const BPHBuToJPsiKBuilder& x) = delete; std::string jPsiName; std::string kaonName; const edm::EventSetup* evSetup; const std::vector* jCollection; - const BPHRecoBuilder::BPHGenericCollection* kCollection; + const BPHRecoBuilder::BPHGenericCollection* kCollection; - BPHMassSelect * jpsiSel; + BPHMassSelect* jpsiSel; BPHParticleNeutralVeto* knVeto; - BPHParticlePtSelect * ptSel; - BPHParticleEtaSelect * etaSel; + BPHParticlePtSelect* ptSel; + BPHParticleEtaSelect* etaSel; - BPHMassSelect * massSel; - BPHChi2Select * chi2Sel; - BPHMassFitSelect * mFitSel; + BPHMassSelect* massSel; + BPHChi2Select* chi2Sel; + BPHMassFitSelect* mFitSel; bool massConstr; float minPDiff; bool updated; std::vector buList; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHChi2Select.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHChi2Select.h index 1ec05b881ab2f..609039bafcb80 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHChi2Select.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHChi2Select.h @@ -24,18 +24,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHChi2Select: public BPHVertexSelect { - - public: - +class BPHChi2Select : public BPHVertexSelect { +public: /** Constructor */ - BPHChi2Select( double prob ): probMin( prob ) {} + BPHChi2Select(double prob) : probMin(prob) {} /** Destructor */ @@ -44,29 +41,30 @@ class BPHChi2Select: public BPHVertexSelect { /** Operations */ /// select vertex - bool accept( const BPHDecayVertex& cand ) const override { + bool accept(const BPHDecayVertex& cand) const override { const reco::Vertex& v = cand.vertex(); - if ( v.isFake() ) return false; - if ( !v.isValid() ) return false; - return ( TMath::Prob( v.chi2(), lround( v.ndof() ) ) > probMin ); + if (v.isFake()) + return false; + if (!v.isValid()) + return false; + return (TMath::Prob(v.chi2(), lround(v.ndof())) > probMin); } /// set prob min - void setProbMin( double p ) { probMin = p; return; } + void setProbMin(double p) { + probMin = p; + return; + } /// get current prob min double getProbMin() const { return probMin; } - private: - +private: // private copy and assigment constructors - BPHChi2Select ( const BPHChi2Select& x ) = delete; - BPHChi2Select& operator=( const BPHChi2Select& x ) = delete; + BPHChi2Select(const BPHChi2Select& x) = delete; + BPHChi2Select& operator=(const BPHChi2Select& x) = delete; double probMin; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHKx0ToKPiBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHKx0ToKPiBuilder.h index 5ae30ff4db2fc..eb1150e4a61f2 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHKx0ToKPiBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHKx0ToKPiBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -39,14 +38,12 @@ class BPHMassSelect; // --------------------- class BPHKx0ToKPiBuilder { - - public: - +public: /** Constructor */ - BPHKx0ToKPiBuilder( const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* posCollection, - const BPHRecoBuilder::BPHGenericCollection* negCollection ); + BPHKx0ToKPiBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* posCollection, + const BPHRecoBuilder::BPHGenericCollection* negCollection); /** Destructor */ @@ -58,27 +55,26 @@ class BPHKx0ToKPiBuilder { std::vector build(); /// set cuts - void setPtMin ( double pt ); - void setEtaMax ( double eta ); - void setMassMin( double m ); - void setMassMax( double m ); - void setProbMin( double p ); - void setConstr ( double mass, double sigma ); + void setPtMin(double pt); + void setEtaMax(double eta); + void setMassMin(double m); + void setMassMax(double m); + void setProbMin(double p); + void setConstr(double mass, double sigma); /// get current cuts - double getPtMin () const; - double getEtaMax () const; + double getPtMin() const; + double getEtaMax() const; double getMassMin() const; double getMassMax() const; double getProbMin() const; - double getConstrMass () const; + double getConstrMass() const; double getConstrSigma() const; - private: - +private: // private copy and assigment constructors - BPHKx0ToKPiBuilder ( const BPHKx0ToKPiBuilder& x ) = delete; - BPHKx0ToKPiBuilder& operator=( const BPHKx0ToKPiBuilder& x ) = delete; + BPHKx0ToKPiBuilder(const BPHKx0ToKPiBuilder& x) = delete; + BPHKx0ToKPiBuilder& operator=(const BPHKx0ToKPiBuilder& x) = delete; std::string kaonName; std::string pionName; @@ -87,7 +83,7 @@ class BPHKx0ToKPiBuilder { const BPHRecoBuilder::BPHGenericCollection* pCollection; const BPHRecoBuilder::BPHGenericCollection* nCollection; - BPHParticlePtSelect * ptSel; + BPHParticlePtSelect* ptSel; BPHParticleEtaSelect* etaSel; BPHMassSelect* massSel; BPHChi2Select* chi2Sel; @@ -96,9 +92,6 @@ class BPHKx0ToKPiBuilder { bool updated; std::vector kx0List; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassCuts.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassCuts.h index be7ca117672d8..e0b79d7e5dbaa 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassCuts.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassCuts.h @@ -16,29 +16,23 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ - //--------------- // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- class BPHMassCuts { - - public: - +public: /** Constructor */ - BPHMassCuts( double minMass, double maxMass ): mMin( minMass ), - mMax( maxMass ) {} + BPHMassCuts(double minMass, double maxMass) : mMin(minMass), mMax(maxMass) {} /** Destructor */ @@ -47,24 +41,26 @@ class BPHMassCuts { /** Operations */ /// set mass cuts - void setMassMin( double m ) { mMin = m; return; } - void setMassMax( double m ) { mMax = m; return; } + void setMassMin(double m) { + mMin = m; + return; + } + void setMassMax(double m) { + mMax = m; + return; + } /// get current mass cuts double getMassMin() const { return mMin; } double getMassMax() const { return mMax; } - protected: - +protected: // private copy and assigment constructors - BPHMassCuts ( const BPHMassCuts& x ); - BPHMassCuts& operator=( const BPHMassCuts& x ); + BPHMassCuts(const BPHMassCuts& x); + BPHMassCuts& operator=(const BPHMassCuts& x); double mMin; double mMax; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassFitSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassFitSelect.h index df2e74526f67c..1036161ebe127 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassFitSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassFitSelect.h @@ -31,107 +31,114 @@ // -- Class Interface -- // --------------------- -class BPHMassFitSelect: public BPHFitSelect, public BPHMassCuts { - - public: - +class BPHMassFitSelect : public BPHFitSelect, public BPHMassCuts { +public: /** Constructor */ - BPHMassFitSelect( double minMass, double maxMass ): - BPHMassCuts( minMass, maxMass ) { setFitConstraint(); } + BPHMassFitSelect(double minMass, double maxMass) : BPHMassCuts(minMass, maxMass) { setFitConstraint(); } - BPHMassFitSelect( const std::string& name, double mass, double sigma, - double minMass, double maxMass ): - BPHMassCuts( minMass, maxMass ) { setFitConstraint( name, mass, sigma ); } + BPHMassFitSelect(const std::string& name, double mass, double sigma, double minMass, double maxMass) + : BPHMassCuts(minMass, maxMass) { + setFitConstraint(name, mass, sigma); + } - BPHMassFitSelect( const std::string& name, double mass, - double minMass, double maxMass ): - BPHMassCuts( minMass, maxMass ) { setFitConstraint( name, mass ); } + BPHMassFitSelect(const std::string& name, double mass, double minMass, double maxMass) + : BPHMassCuts(minMass, maxMass) { + setFitConstraint(name, mass); + } - BPHMassFitSelect( const std::string& name, KinematicConstraint* c, - double minMass, double maxMass ): - BPHMassCuts( minMass, maxMass ) { setFitConstraint( name, c ); } + BPHMassFitSelect(const std::string& name, KinematicConstraint* c, double minMass, double maxMass) + : BPHMassCuts(minMass, maxMass) { + setFitConstraint(name, c); + } - BPHMassFitSelect( const std::string& name, MultiTrackKinematicConstraint* c, - double minMass, double maxMass ): - BPHMassCuts( minMass, maxMass ) { setFitConstraint( name, c ); } + BPHMassFitSelect(const std::string& name, MultiTrackKinematicConstraint* c, double minMass, double maxMass) + : BPHMassCuts(minMass, maxMass) { + setFitConstraint(name, c); + } /** Destructor */ - ~BPHMassFitSelect() override { - } + ~BPHMassFitSelect() override {} /** Operations */ /// select particle - bool accept( const BPHKinematicFit& cand ) const override { - switch ( type ) { - default: - case none: break; - case mcss: cand.kinematicTree( cName, cMass, cSigma ); break; - case mcst: cand.kinematicTree( cName, cMass ) ; break; - case kf: cand.kinematicTree( cName, kc ); break; - case mtkf: cand.kinematicTree( cName, mtkc ); break; + bool accept(const BPHKinematicFit& cand) const override { + switch (type) { + default: + case none: + break; + case mcss: + cand.kinematicTree(cName, cMass, cSigma); + break; + case mcst: + cand.kinematicTree(cName, cMass); + break; + case kf: + cand.kinematicTree(cName, kc); + break; + case mtkf: + cand.kinematicTree(cName, mtkc); + break; } double mass = cand.p4().mass(); - return ( ( mass > mMin ) && ( mass < mMax ) ); + return ((mass > mMin) && (mass < mMax)); } /// set fit constraint void setFitConstraint() { type = none; - cName = "" ; - cMass = -1.0; + cName = ""; + cMass = -1.0; cSigma = -1.0; - kc = nullptr ; - mtkc = nullptr ; + kc = nullptr; + mtkc = nullptr; } - void setFitConstraint( const std::string& name, double mass ) { + void setFitConstraint(const std::string& name, double mass) { type = mcst; - cName = name ; - cMass = mass ; - cSigma = -1.0 ; - kc = nullptr ; - mtkc = nullptr ; + cName = name; + cMass = mass; + cSigma = -1.0; + kc = nullptr; + mtkc = nullptr; } - void setFitConstraint( const std::string& name, double mass, double sigma ) { + void setFitConstraint(const std::string& name, double mass, double sigma) { type = mcss; - cName = name ; - cMass = mass ; + cName = name; + cMass = mass; cSigma = sigma; - kc = nullptr ; - mtkc = nullptr ; + kc = nullptr; + mtkc = nullptr; } - void setFitConstraint( const std::string& name, KinematicConstraint* c ) { + void setFitConstraint(const std::string& name, KinematicConstraint* c) { type = kf; - cName = name ; - cMass = -1.0 ; - cSigma = -1.0 ; - kc = c ; - mtkc = nullptr ; + cName = name; + cMass = -1.0; + cSigma = -1.0; + kc = c; + mtkc = nullptr; } - void setFitConstraint( const std::string& name, - MultiTrackKinematicConstraint* c ) { + void setFitConstraint(const std::string& name, MultiTrackKinematicConstraint* c) { type = mtkf; - cName = name ; - cMass = -1.0 ; - cSigma = -1.0 ; - kc = nullptr ; - mtkc = c ; + cName = name; + cMass = -1.0; + cSigma = -1.0; + kc = nullptr; + mtkc = c; } /// get fit constraint const std::string& getConstrainedName() const { return cName; } - double getMass () const { return cMass; } + double getMass() const { return cMass; } double getSigma() const { return cSigma; } - KinematicConstraint* getKC () const { return kc; } + KinematicConstraint* getKC() const { return kc; } MultiTrackKinematicConstraint* getMultiTrackKC() const { return mtkc; } - private: - +private: // private copy and assigment constructors - BPHMassFitSelect ( const BPHMassFitSelect& x ) = delete; - BPHMassFitSelect& operator=( const BPHMassFitSelect& x ) = delete; + BPHMassFitSelect(const BPHMassFitSelect& x) = delete; + BPHMassFitSelect& operator=(const BPHMassFitSelect& x) = delete; enum fit_type { none, mcss, mcst, kf, mtkf }; @@ -139,11 +146,8 @@ class BPHMassFitSelect: public BPHFitSelect, public BPHMassCuts { std::string cName; double cMass; double cSigma; - KinematicConstraint* kc; + KinematicConstraint* kc; MultiTrackKinematicConstraint* mtkc; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSelect.h index e4ef4d9d7fee2..ea7f783055aab 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSelect.h @@ -24,19 +24,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHMassSelect: public BPHMomentumSelect, public BPHMassCuts { - - public: - +class BPHMassSelect : public BPHMomentumSelect, public BPHMassCuts { +public: /** Constructor */ - BPHMassSelect( double minMass, double maxMass ): BPHMassCuts( minMass, - maxMass ) {} + BPHMassSelect(double minMass, double maxMass) : BPHMassCuts(minMass, maxMass) {} /** Destructor */ @@ -45,19 +41,15 @@ class BPHMassSelect: public BPHMomentumSelect, public BPHMassCuts { /** Operations */ /// select particle - bool accept( const BPHDecayMomentum& cand ) const override { + bool accept(const BPHDecayMomentum& cand) const override { double mass = cand.composite().mass(); - return ( ( mass > mMin ) && ( mass < mMax ) ); + return ((mass > mMin) && (mass < mMax)); } - private: - +private: // private copy and assigment constructors - BPHMassSelect ( const BPHMassSelect& x ) = delete; - BPHMassSelect& operator=( const BPHMassSelect& x ) = delete; - + BPHMassSelect(const BPHMassSelect& x) = delete; + BPHMassSelect& operator=(const BPHMassSelect& x) = delete; }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSymSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSymSelect.h index 760d34d178539..89e013deacded 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSymSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMassSymSelect.h @@ -30,15 +30,12 @@ // -- Class Interface -- // --------------------- -class BPHMassSymSelect: public BPHMomentumSelect { - - public: - +class BPHMassSymSelect : public BPHMomentumSelect { +public: /** Constructor */ - BPHMassSymSelect( const std::string& np, const std::string& nn, - const BPHMassSelect* ms ): nPos( np ), nNeg( nn ), - mSel( ms ) {} + BPHMassSymSelect(const std::string& np, const std::string& nn, const BPHMassSelect* ms) + : nPos(np), nNeg(nn), mSel(ms) {} /** Destructor */ @@ -47,42 +44,34 @@ class BPHMassSymSelect: public BPHMomentumSelect { /** Operations */ /// select particle - bool accept( const BPHDecayMomentum& cand ) const override { + bool accept(const BPHDecayMomentum& cand) const override { + if (mSel->accept(cand)) + return true; - if ( mSel->accept( cand ) ) return true; + const reco::Candidate* pp = cand.getDaug(nPos); + const reco::Candidate* np = cand.getDaug(nNeg); - const - reco::Candidate* pp = cand.getDaug( nPos ); - const - reco::Candidate* np = cand.getDaug( nNeg ); + reco::Candidate* pc = cand.originalReco(pp)->clone(); + reco::Candidate* nc = cand.originalReco(np)->clone(); - reco::Candidate* pc = cand.originalReco( pp )->clone(); - reco::Candidate* nc = cand.originalReco( np )->clone(); - - pc->setMass( np->p4().mass() ); - nc->setMass( pp->p4().mass() ); - const reco::Candidate::LorentzVector s4 = pc->p4() + nc->p4(); + pc->setMass(np->p4().mass()); + nc->setMass(pp->p4().mass()); + const reco::Candidate::LorentzVector s4 = pc->p4() + nc->p4(); double mass = s4.mass(); delete pc; delete nc; - return ( ( mass > mSel->getMassMin() ) && - ( mass < mSel->getMassMax() ) ); - + return ((mass > mSel->getMassMin()) && (mass < mSel->getMassMax())); } - private: - +private: // private copy and assigment constructors - BPHMassSymSelect ( const BPHMassSymSelect& x ) = delete; - BPHMassSymSelect& operator=( const BPHMassSymSelect& x ) = delete; + BPHMassSymSelect(const BPHMassSymSelect& x) = delete; + BPHMassSymSelect& operator=(const BPHMassSymSelect& x) = delete; std::string nPos; std::string nNeg; const BPHMassSelect* mSel; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonEtaSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonEtaSelect.h index 7447d4bcf95cc..05159992d2ccd 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonEtaSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonEtaSelect.h @@ -23,18 +23,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHMuonEtaSelect: public BPHParticleEtaSelect { - - public: - +class BPHMuonEtaSelect : public BPHParticleEtaSelect { +public: /** Constructor */ - BPHMuonEtaSelect( double eta ): BPHParticleEtaSelect( eta ) {} + BPHMuonEtaSelect(double eta) : BPHParticleEtaSelect(eta) {} /** Destructor */ @@ -43,19 +40,16 @@ class BPHMuonEtaSelect: public BPHParticleEtaSelect { /** Operations */ /// select muon - bool accept( const reco::Candidate& cand ) const override { - if ( dynamic_cast( &cand ) == nullptr ) return false; - return BPHParticleEtaSelect::accept( cand ); + bool accept(const reco::Candidate& cand) const override { + if (dynamic_cast(&cand) == nullptr) + return false; + return BPHParticleEtaSelect::accept(cand); } - private: - +private: // private copy and assigment constructors - BPHMuonEtaSelect ( const BPHMuonEtaSelect& x ) = delete; - BPHMuonEtaSelect& operator=( const BPHMuonEtaSelect& x ) = delete; - + BPHMuonEtaSelect(const BPHMuonEtaSelect& x) = delete; + BPHMuonEtaSelect& operator=(const BPHMuonEtaSelect& x) = delete; }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonPtSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonPtSelect.h index c27e8665f7489..39f69941fd03f 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonPtSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHMuonPtSelect.h @@ -23,18 +23,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHMuonPtSelect: public BPHParticlePtSelect { - - public: - +class BPHMuonPtSelect : public BPHParticlePtSelect { +public: /** Constructor */ - BPHMuonPtSelect( double pt ): BPHParticlePtSelect( pt ) {} + BPHMuonPtSelect(double pt) : BPHParticlePtSelect(pt) {} /** Destructor */ @@ -43,19 +40,16 @@ class BPHMuonPtSelect: public BPHParticlePtSelect { /** Operations */ /// select muon - bool accept( const reco::Candidate& cand ) const override { - if ( dynamic_cast( &cand ) == nullptr ) return false; - return BPHParticlePtSelect::accept( cand ); + bool accept(const reco::Candidate& cand) const override { + if (dynamic_cast(&cand) == nullptr) + return false; + return BPHParticlePtSelect::accept(cand); } - private: - +private: // private copy and assigment constructors - BPHMuonPtSelect ( const BPHMuonPtSelect& x ) = delete; - BPHMuonPtSelect& operator=( const BPHMuonPtSelect& x ) = delete; - + BPHMuonPtSelect(const BPHMuonPtSelect& x) = delete; + BPHMuonPtSelect& operator=(const BPHMuonPtSelect& x) = delete; }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHOniaToMuMuBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHOniaToMuMuBuilder.h index dd038a4b312de..404a914973781 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHOniaToMuMuBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHOniaToMuMuBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -43,17 +42,14 @@ class BPHVertexSelect; // --------------------- class BPHOniaToMuMuBuilder { - - public: - - enum oniaType { Phi , Psi1, Psi2, Ups , Ups1, Ups2, Ups3 }; +public: + enum oniaType { Phi, Psi1, Psi2, Ups, Ups1, Ups2, Ups3 }; /** Constructor */ - BPHOniaToMuMuBuilder( - const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* muPosCollection, - const BPHRecoBuilder::BPHGenericCollection* muNegCollection ); + BPHOniaToMuMuBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* muPosCollection, + const BPHRecoBuilder::BPHGenericCollection* muNegCollection); /** Destructor */ @@ -66,39 +62,37 @@ class BPHOniaToMuMuBuilder { /// extract list of candidates of specific type /// candidates are rebuilt applying corresponding mass constraint - std::vector getList( oniaType type, - BPHRecoSelect * dSel = nullptr, - BPHMomentumSelect* mSel = nullptr, - BPHVertexSelect * vSel = nullptr, - BPHFitSelect * kSel = nullptr ); + std::vector getList(oniaType type, + BPHRecoSelect* dSel = nullptr, + BPHMomentumSelect* mSel = nullptr, + BPHVertexSelect* vSel = nullptr, + BPHFitSelect* kSel = nullptr); /// retrieve original candidate from a copy with the same daughters /// obtained through "getList" - BPHPlusMinusConstCandPtr getOriginalCandidate( - const BPHRecoCandidate& cand ); + BPHPlusMinusConstCandPtr getOriginalCandidate(const BPHRecoCandidate& cand); /// set cuts - void setPtMin ( oniaType type, double pt ); - void setEtaMax ( oniaType type, double eta ); - void setMassMin( oniaType type, double m ); - void setMassMax( oniaType type, double m ); - void setProbMin( oniaType type, double p ); - void setConstr ( oniaType type, double mass, double sigma ); + void setPtMin(oniaType type, double pt); + void setEtaMax(oniaType type, double eta); + void setMassMin(oniaType type, double m); + void setMassMax(oniaType type, double m); + void setProbMin(oniaType type, double p); + void setConstr(oniaType type, double mass, double sigma); /// get current cuts - double getPtMin ( oniaType type ) const; - double getEtaMax ( oniaType type ) const; - double getMassMin( oniaType type ) const; - double getMassMax( oniaType type ) const; - double getProbMin( oniaType type ) const; - double getConstrMass ( oniaType type ) const; - double getConstrSigma( oniaType type ) const; - - private: - + double getPtMin(oniaType type) const; + double getEtaMax(oniaType type) const; + double getMassMin(oniaType type) const; + double getMassMax(oniaType type) const; + double getProbMin(oniaType type) const; + double getConstrMass(oniaType type) const; + double getConstrSigma(oniaType type) const; + +private: // private copy and assigment constructors - BPHOniaToMuMuBuilder ( const BPHOniaToMuMuBuilder& x ) = delete; - BPHOniaToMuMuBuilder& operator=( const BPHOniaToMuMuBuilder& x ) = delete; + BPHOniaToMuMuBuilder(const BPHOniaToMuMuBuilder& x) = delete; + BPHOniaToMuMuBuilder& operator=(const BPHOniaToMuMuBuilder& x) = delete; std::string muPosName; std::string muNegName; @@ -108,30 +102,30 @@ class BPHOniaToMuMuBuilder { const BPHRecoBuilder::BPHGenericCollection* negCollection; struct OniaParameters { - BPHMuonPtSelect * ptSel; - BPHMuonEtaSelect* etaSel; - BPHMassSelect * massSel; - BPHChi2Select * chi2Sel; + BPHMuonPtSelect* ptSel; + BPHMuonEtaSelect* etaSel; + BPHMassSelect* massSel; + BPHChi2Select* chi2Sel; double mass; double sigma; bool updated; }; bool updated; - std::map< oniaType, OniaParameters > oniaPar; - std::map< oniaType, std::vector > oniaList; + std::map oniaPar; + std::map > oniaList; std::vector fullList; void setNotUpdated(); - void setParameters( oniaType type, - double ptMin, double etaMax, - double massMin, double massMax, - double probMin, - double mass, double sigma ); - void extractList( oniaType type ); - + void setParameters(oniaType type, + double ptMin, + double etaMax, + double massMin, + double massMax, + double probMin, + double mass, + double sigma); + void extractList(oniaType type); }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleEtaSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleEtaSelect.h index 8b8eefcb87200..677f061c4e469 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleEtaSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleEtaSelect.h @@ -23,18 +23,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHParticleEtaSelect: public BPHRecoSelect { - - public: - +class BPHParticleEtaSelect : public BPHRecoSelect { +public: /** Constructor */ - BPHParticleEtaSelect( double eta ): etaMax( eta ) {} + BPHParticleEtaSelect(double eta) : etaMax(eta) {} /** Destructor */ @@ -43,26 +40,23 @@ class BPHParticleEtaSelect: public BPHRecoSelect { /** Operations */ /// select particle - bool accept( const reco::Candidate& cand ) const override { - return ( fabs( cand.p4().eta() ) < etaMax ); - } + bool accept(const reco::Candidate& cand) const override { return (fabs(cand.p4().eta()) < etaMax); } /// set eta max - void setEtaMax( double eta ) { etaMax = eta; return; } + void setEtaMax(double eta) { + etaMax = eta; + return; + } /// get current eta max double getEtaMax() const { return etaMax; } - private: - +private: // private copy and assigment constructors - BPHParticleEtaSelect ( const BPHParticleEtaSelect& x ) = delete; - BPHParticleEtaSelect& operator=( const BPHParticleEtaSelect& x ) = delete; + BPHParticleEtaSelect(const BPHParticleEtaSelect& x) = delete; + BPHParticleEtaSelect& operator=(const BPHParticleEtaSelect& x) = delete; double etaMax; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleMasses.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleMasses.h index 8b5de22b178b5..9a829890c4509 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleMasses.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleMasses.h @@ -13,54 +13,46 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ - //--------------- // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- class BPHParticleMasses { - - public: - - static const double elMass; +public: + static const double elMass; static const double muonMass; - static const double tauMass; + static const double tauMass; static const double pionMass; static const double kaonMass; - static const double kx0Mass; - static const double phiMass; + static const double kx0Mass; + static const double phiMass; static const double jPsiMass; static const double psi2Mass; static const double ups1Mass; static const double ups2Mass; static const double ups3Mass; - static const double elMSigma; + static const double elMSigma; static const double muonMSigma; - static const double tauMSigma; + static const double tauMSigma; static const double pionMSigma; static const double kaonMSigma; - static const double kx0MWidth; - static const double phiMWidth; + static const double kx0MWidth; + static const double phiMWidth; static const double jPsiMWidth; static const double psi2MWidth; static const double ups1MWidth; static const double ups2MWidth; static const double ups3MWidth; - private: - +private: }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleNeutralVeto.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleNeutralVeto.h index db03e8ea8f7e4..e75be62e7dfd5 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleNeutralVeto.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticleNeutralVeto.h @@ -23,15 +23,12 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHParticleNeutralVeto: public BPHRecoSelect { - - public: - +class BPHParticleNeutralVeto : public BPHRecoSelect { +public: /** Constructor */ BPHParticleNeutralVeto() {} @@ -43,18 +40,12 @@ class BPHParticleNeutralVeto: public BPHRecoSelect { /** Operations */ /// select charged particles - bool accept( const reco::Candidate& cand ) const override { - return ( cand.charge() != 0 ); - } - - private: + bool accept(const reco::Candidate& cand) const override { return (cand.charge() != 0); } +private: // private copy and assigment constructors - BPHParticleNeutralVeto ( const BPHParticleNeutralVeto& x ) = delete; - BPHParticleNeutralVeto& operator=( const BPHParticleNeutralVeto& x ) = delete; - + BPHParticleNeutralVeto(const BPHParticleNeutralVeto& x) = delete; + BPHParticleNeutralVeto& operator=(const BPHParticleNeutralVeto& x) = delete; }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticlePtSelect.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticlePtSelect.h index ad1fd0098588e..abb4170c729a2 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticlePtSelect.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHParticlePtSelect.h @@ -23,18 +23,15 @@ // C++ Headers -- //--------------- - // --------------------- // -- Class Interface -- // --------------------- -class BPHParticlePtSelect: public BPHRecoSelect { - - public: - +class BPHParticlePtSelect : public BPHRecoSelect { +public: /** Constructor */ - BPHParticlePtSelect( double pt ): ptMin( pt ) {} + BPHParticlePtSelect(double pt) : ptMin(pt) {} /** Destructor */ @@ -43,26 +40,23 @@ class BPHParticlePtSelect: public BPHRecoSelect { /** Operations */ /// select particle - bool accept( const reco::Candidate& cand ) const override { - return ( cand.p4().pt() > ptMin ); - } + bool accept(const reco::Candidate& cand) const override { return (cand.p4().pt() > ptMin); } /// set pt min - void setPtMin( double pt ) { ptMin = pt; return; } + void setPtMin(double pt) { + ptMin = pt; + return; + } /// get current pt min double getPtMin() const { return ptMin; } - private: - +private: // private copy and assigment constructors - BPHParticlePtSelect ( const BPHParticlePtSelect& x ) = delete; - BPHParticlePtSelect& operator=( const BPHParticlePtSelect& x ) = delete; + BPHParticlePtSelect(const BPHParticlePtSelect& x) = delete; + BPHParticlePtSelect& operator=(const BPHParticlePtSelect& x) = delete; double ptMin; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHPhiToKKBuilder.h b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHPhiToKKBuilder.h index cd78400a65543..8d67a4658251a 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/interface/BPHPhiToKKBuilder.h +++ b/HeavyFlavorAnalysis/SpecificDecay/interface/BPHPhiToKKBuilder.h @@ -13,7 +13,6 @@ // Base Class Headers -- //---------------------- - //------------------------------------ // Collaborating Class Declarations -- //------------------------------------ @@ -39,14 +38,12 @@ class BPHMassSelect; // --------------------- class BPHPhiToKKBuilder { - - public: - +public: /** Constructor */ - BPHPhiToKKBuilder( const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* kPosCollection, - const BPHRecoBuilder::BPHGenericCollection* kNegCollection ); + BPHPhiToKKBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* kPosCollection, + const BPHRecoBuilder::BPHGenericCollection* kNegCollection); /** Destructor */ @@ -58,27 +55,26 @@ class BPHPhiToKKBuilder { std::vector build(); /// set cuts - void setPtMin ( double pt ); - void setEtaMax ( double eta ); - void setMassMin( double m ); - void setMassMax( double m ); - void setProbMin( double p ); - void setConstr ( double mass, double sigma ); + void setPtMin(double pt); + void setEtaMax(double eta); + void setMassMin(double m); + void setMassMax(double m); + void setProbMin(double p); + void setConstr(double mass, double sigma); /// get current cuts - double getPtMin () const; - double getEtaMax () const; + double getPtMin() const; + double getEtaMax() const; double getMassMin() const; double getMassMax() const; double getProbMin() const; - double getConstrMass () const; + double getConstrMass() const; double getConstrSigma() const; - private: - +private: // private copy and assigment constructors - BPHPhiToKKBuilder ( const BPHPhiToKKBuilder& x ) = delete; - BPHPhiToKKBuilder& operator=( const BPHPhiToKKBuilder& x ) = delete; + BPHPhiToKKBuilder(const BPHPhiToKKBuilder& x) = delete; + BPHPhiToKKBuilder& operator=(const BPHPhiToKKBuilder& x) = delete; std::string kPosName; std::string kNegName; @@ -87,7 +83,7 @@ class BPHPhiToKKBuilder { const BPHRecoBuilder::BPHGenericCollection* posCollection; const BPHRecoBuilder::BPHGenericCollection* negCollection; - BPHParticlePtSelect * ptSel; + BPHParticlePtSelect* ptSel; BPHParticleEtaSelect* etaSel; BPHMassSelect* massSel; BPHChi2Select* chi2Sel; @@ -96,9 +92,6 @@ class BPHPhiToKKBuilder { bool updated; std::vector phiList; - }; - #endif - diff --git a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.cc b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.cc index 1e7032913b934..36ce727faf468 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.cc @@ -30,88 +30,83 @@ using namespace std; -#define SET_LABEL(NAME,PSET) ( NAME = PSET.getParameter( #NAME ) ) +#define SET_LABEL(NAME, PSET) (NAME = PSET.getParameter(#NAME)) // SET_LABEL(xyz,ps); // is equivalent to // xyz = ps.getParameter( "xyx" ) class BPHUserData { - public: - template - static const T* get( const pat::CompositeCandidate& cand, - const string& name ) { - if ( cand.hasUserData( name ) ) return cand.userData( name ); +public: + template + static const T* get(const pat::CompositeCandidate& cand, const string& name) { + if (cand.hasUserData(name)) + return cand.userData(name); return nullptr; } - template - static const T* getByRef( const pat::CompositeCandidate& cand, - const string& name ) { - if ( cand.hasUserData( name ) ) { - typedef edm::Ref< std::vector > objRef; - const objRef* ref = cand.userData( name ); - if ( ref == nullptr ) return nullptr; - if ( ref->isNull() ) return nullptr; + template + static const T* getByRef(const pat::CompositeCandidate& cand, const string& name) { + if (cand.hasUserData(name)) { + typedef edm::Ref > objRef; + const objRef* ref = cand.userData(name); + if (ref == nullptr) + return nullptr; + if (ref->isNull()) + return nullptr; return ref->get(); } return nullptr; } }; - class BPHDaughters { - public: - static vector get( - const pat::CompositeCandidate& cand, float massMin, float massMax ) { +public: + static vector get(const pat::CompositeCandidate& cand, float massMin, float massMax) { int i; int n = cand.numberOfDaughters(); vector v; - v.reserve( n ); - for ( i = 0; i < n; ++i ) { - const reco::Candidate* dptr = cand.daughter( i ); + v.reserve(n); + for (i = 0; i < n; ++i) { + const reco::Candidate* dptr = cand.daughter(i); float mass = dptr->mass(); - if ( ( mass > massMin ) && ( mass < massMax ) ) v.push_back( dptr ); + if ((mass > massMin) && (mass < massMax)) + v.push_back(dptr); } return v; } }; - class BPHSoftMuonSelect { - public: - BPHSoftMuonSelect( int cutTrackerLayers = 5, - int cutPixelLayers = 0, - float maxDxy = 0.3, - float maxDz = 20.0, - bool goodMuon = true , - bool highPurity = true ): - cutTL ( cutTrackerLayers ), - cutPL ( cutPixelLayers ), - maxXY ( maxDxy ), - maxZ ( maxDz ), - gM ( goodMuon ), - hP ( highPurity ) {} - bool accept( const reco::Candidate& cand, - const reco::Vertex* pv ) const { - const pat::Muon* p = reinterpret_cast( &cand ); - if ( p == nullptr ) return false; - if ( gM && - !muon::isGoodMuon( *p, muon::TMOneStationTight ) ) return false; - if ( p->innerTrack()->hitPattern().trackerLayersWithMeasurement() <= cutTL ) - return false; - if ( p->innerTrack()->hitPattern(). pixelLayersWithMeasurement() <= cutPL ) - return false; - if ( hP && - !p->innerTrack()->quality( reco::TrackBase::highPurity ) ) - return false; - if ( pv == nullptr ) return true; +public: + BPHSoftMuonSelect(int cutTrackerLayers = 5, + int cutPixelLayers = 0, + float maxDxy = 0.3, + float maxDz = 20.0, + bool goodMuon = true, + bool highPurity = true) + : cutTL(cutTrackerLayers), cutPL(cutPixelLayers), maxXY(maxDxy), maxZ(maxDz), gM(goodMuon), hP(highPurity) {} + bool accept(const reco::Candidate& cand, const reco::Vertex* pv) const { + const pat::Muon* p = reinterpret_cast(&cand); + if (p == nullptr) + return false; + if (gM && !muon::isGoodMuon(*p, muon::TMOneStationTight)) + return false; + if (p->innerTrack()->hitPattern().trackerLayersWithMeasurement() <= cutTL) + return false; + if (p->innerTrack()->hitPattern().pixelLayersWithMeasurement() <= cutPL) + return false; + if (hP && !p->innerTrack()->quality(reco::TrackBase::highPurity)) + return false; + if (pv == nullptr) + return true; const reco::Vertex::Point& pos = pv->position(); - if ( fabs( p->innerTrack()->dxy( pos ) ) >= maxXY ) - return false; - if ( fabs( p->innerTrack()->dz ( pos ) ) >= maxZ ) - return false; + if (fabs(p->innerTrack()->dxy(pos)) >= maxXY) + return false; + if (fabs(p->innerTrack()->dz(pos)) >= maxZ) + return false; return true; } - private: + +private: const reco::Vertex* pv; int cutTL; int cutPL; @@ -121,46 +116,46 @@ class BPHSoftMuonSelect { bool hP; }; - -class BPHDaughterSelect: public BPHHistoSpecificDecay::CandidateSelect { - public: - BPHDaughterSelect( float ptMinLoose, - float ptMinTight, - float etaMaxLoose, - float etaMaxTight, - const BPHSoftMuonSelect* - softMuonselector = nullptr ): pLMin( ptMinLoose ), - pTMin( ptMinTight ), - eLMax( etaMaxLoose ), - eTMax( etaMaxTight ), - sms( softMuonselector ) { - } - bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pv = nullptr ) const override { - const reco::Candidate* dptr0 = cand.daughter( 0 ); - const reco::Candidate* dptr1 = cand.daughter( 1 ); - if ( dptr0 == nullptr ) return false; - if ( dptr1 == nullptr ) return false; +class BPHDaughterSelect : public BPHHistoSpecificDecay::CandidateSelect { +public: + BPHDaughterSelect(float ptMinLoose, + float ptMinTight, + float etaMaxLoose, + float etaMaxTight, + const BPHSoftMuonSelect* softMuonselector = nullptr) + : pLMin(ptMinLoose), pTMin(ptMinTight), eLMax(etaMaxLoose), eTMax(etaMaxTight), sms(softMuonselector) {} + bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pv = nullptr) const override { + const reco::Candidate* dptr0 = cand.daughter(0); + const reco::Candidate* dptr1 = cand.daughter(1); + if (dptr0 == nullptr) + return false; + if (dptr1 == nullptr) + return false; float pt0 = dptr0->pt(); float pt1 = dptr1->pt(); - if ( ( pt0 < pLMin ) || ( pt1 < pLMin ) ) return false; - if ( ( pt0 < pTMin ) && ( pt1 < pTMin ) ) return false; - float eta0 = fabs( dptr0->eta() ); - float eta1 = fabs( dptr1->eta() ); - if ( ( eLMax > 0 ) && - ( ( eta0 > eLMax ) || ( eta1 > eLMax ) ) ) return false; - if ( ( eTMax > 0 ) && - ( ( eta0 > eTMax ) && ( eta1 > eTMax ) ) ) return false; - if ( sms != nullptr ) { - const reco::Vertex* pvtx = BPHUserData::getByRef - ( cand, "primaryVertex" ); - if ( pvtx == nullptr ) return false; - if ( !sms->accept( *dptr0, pvtx ) ) return false; - if ( !sms->accept( *dptr1, pvtx ) ) return false; - } + if ((pt0 < pLMin) || (pt1 < pLMin)) + return false; + if ((pt0 < pTMin) && (pt1 < pTMin)) + return false; + float eta0 = fabs(dptr0->eta()); + float eta1 = fabs(dptr1->eta()); + if ((eLMax > 0) && ((eta0 > eLMax) || (eta1 > eLMax))) + return false; + if ((eTMax > 0) && ((eta0 > eTMax) && (eta1 > eTMax))) + return false; + if (sms != nullptr) { + const reco::Vertex* pvtx = BPHUserData::getByRef(cand, "primaryVertex"); + if (pvtx == nullptr) + return false; + if (!sms->accept(*dptr0, pvtx)) + return false; + if (!sms->accept(*dptr1, pvtx)) + return false; + } return true; } - private: + +private: float pLMin; float pTMin; float eLMax; @@ -168,38 +163,29 @@ class BPHDaughterSelect: public BPHHistoSpecificDecay::CandidateSelect { const BPHSoftMuonSelect* sms; }; - -class BPHCompositeBasicSelect: public BPHHistoSpecificDecay::CandidateSelect { - public: - BPHCompositeBasicSelect( float massMin, - float massMax, - float ptMin = -1.0, - float etaMax = -1.0, - float rapidityMax = -1.0 ): mMin( massMin ), - mMax( massMax ), - pMin( ptMin ), - eMax( etaMax ), - yMax( rapidityMax ) { - } - bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pv = nullptr ) const override { - if ( ( ( mMin > 0 ) && ( mMax < 0 ) ) || - ( ( mMin < 0 ) && ( mMax > 0 ) ) || - ( ( mMin > 0 ) && ( mMax > 0 ) && ( mMin < mMax ) ) ) { +class BPHCompositeBasicSelect : public BPHHistoSpecificDecay::CandidateSelect { +public: + BPHCompositeBasicSelect( + float massMin, float massMax, float ptMin = -1.0, float etaMax = -1.0, float rapidityMax = -1.0) + : mMin(massMin), mMax(massMax), pMin(ptMin), eMax(etaMax), yMax(rapidityMax) {} + bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pv = nullptr) const override { + if (((mMin > 0) && (mMax < 0)) || ((mMin < 0) && (mMax > 0)) || ((mMin > 0) && (mMax > 0) && (mMin < mMax))) { float mass = cand.mass(); - if ( mass < mMin ) return false; - if ( ( mMax > 0 ) && - ( mass > mMax ) ) return false; + if (mass < mMin) + return false; + if ((mMax > 0) && (mass > mMax)) + return false; } - if ( cand. pt() < pMin ) return false; - if ( ( eMax > 0 ) && - ( fabs( cand. eta() ) > eMax ) ) return false; - if ( ( yMax > 0 ) && - ( fabs( cand.rapidity() ) > yMax ) ) return false; + if (cand.pt() < pMin) + return false; + if ((eMax > 0) && (fabs(cand.eta()) > eMax)) + return false; + if ((yMax > 0) && (fabs(cand.rapidity()) > yMax)) + return false; return true; } - private: +private: float mMin; float mMax; float pMin; @@ -207,51 +193,44 @@ class BPHCompositeBasicSelect: public BPHHistoSpecificDecay::CandidateSelect { float yMax; }; - -class BPHFittedBasicSelect: public BPHHistoSpecificDecay::CandidateSelect { - public: - BPHFittedBasicSelect( float massMin, - float massMax, - float ptMin = -1.0, - float etaMax = -1.0, - float rapidityMax = -1.0 ): mMin( massMin ), - mMax( massMax ), - pMin( ptMin ), - eMax( etaMax ), - rMax( rapidityMax ) { - } - bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pv = nullptr ) const override { - if ( !cand.hasUserFloat( "fitMass" ) ) return false; - float mass = cand.userFloat( "fitMass" ); - if ( ( ( mMin > 0 ) && ( mMax < 0 ) ) || - ( ( mMin < 0 ) && ( mMax > 0 ) ) || - ( ( mMin > 0 ) && ( mMax > 0 ) && ( mMin < mMax ) ) ) { - if ( mass < mMin ) return false; - if ( ( mMax > 0 ) && - ( mass > mMax ) ) return false; +class BPHFittedBasicSelect : public BPHHistoSpecificDecay::CandidateSelect { +public: + BPHFittedBasicSelect(float massMin, float massMax, float ptMin = -1.0, float etaMax = -1.0, float rapidityMax = -1.0) + : mMin(massMin), mMax(massMax), pMin(ptMin), eMax(etaMax), rMax(rapidityMax) {} + bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pv = nullptr) const override { + if (!cand.hasUserFloat("fitMass")) + return false; + float mass = cand.userFloat("fitMass"); + if (((mMin > 0) && (mMax < 0)) || ((mMin < 0) && (mMax > 0)) || ((mMin > 0) && (mMax > 0) && (mMin < mMax))) { + if (mass < mMin) + return false; + if ((mMax > 0) && (mass > mMax)) + return false; } - const Vector3DBase* fmom = BPHUserData::get - < Vector3DBase >( cand, "fitMomentum" ); - if ( fmom == nullptr ) return false; - if ( pMin > 0 ) { - if ( fmom->transverse() < pMin ) return false; + const Vector3DBase* fmom = BPHUserData::get >(cand, "fitMomentum"); + if (fmom == nullptr) + return false; + if (pMin > 0) { + if (fmom->transverse() < pMin) + return false; } - if ( eMax > 0 ) { - if ( fabs( fmom->eta() ) > eMax ) return false; + if (eMax > 0) { + if (fabs(fmom->eta()) > eMax) + return false; } - if ( rMax > 0 ) { + if (rMax > 0) { float x = fmom->x(); float y = fmom->y(); float z = fmom->z(); - float e = sqrt( ( x * x ) + ( y * y ) + ( z * z ) + ( mass * mass ) ); - float r = log( ( e + z ) / ( e - z ) ) / 2; - if ( fabs( r ) > rMax ) return false; + float e = sqrt((x * x) + (y * y) + (z * z) + (mass * mass)); + float r = log((e + z) / (e - z)) / 2; + if (fabs(r) > rMax) + return false; } return true; } - private: +private: float mMin; float mMax; float pMin; @@ -259,269 +238,226 @@ class BPHFittedBasicSelect: public BPHHistoSpecificDecay::CandidateSelect { float rMax; }; - -class BPHCompositeVertexSelect: public BPHHistoSpecificDecay::CandidateSelect { - public: - BPHCompositeVertexSelect( float probMin, - float cosMin = -1.0, - float sigMin = -1.0 ): pMin( probMin ), - cMin( cosMin ), - sMin( sigMin ) { - } - bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pvtx = nullptr ) const override { - const reco::Vertex* svtx = BPHUserData::get - ( cand, "vertex" ); - if ( svtx == nullptr ) return false; - if ( pvtx == nullptr ) return false; - if ( pMin > 0 ) { - if ( ChiSquaredProbability( svtx->chi2(), - svtx->ndof() ) < pMin ) return false; +class BPHCompositeVertexSelect : public BPHHistoSpecificDecay::CandidateSelect { +public: + BPHCompositeVertexSelect(float probMin, float cosMin = -1.0, float sigMin = -1.0) + : pMin(probMin), cMin(cosMin), sMin(sigMin) {} + bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pvtx = nullptr) const override { + const reco::Vertex* svtx = BPHUserData::get(cand, "vertex"); + if (svtx == nullptr) + return false; + if (pvtx == nullptr) + return false; + if (pMin > 0) { + if (ChiSquaredProbability(svtx->chi2(), svtx->ndof()) < pMin) + return false; } - if ( ( cMin > 0 ) || ( sMin > 0 ) ) { - TVector3 disp( svtx->x() - pvtx->x(), - svtx->y() - pvtx->y(), - 0 ); - TVector3 cmom( cand.px(), cand.py(), 0 ); - float cosAlpha = disp.Dot( cmom ) / ( disp.Perp() * cmom.Perp() ); - if ( cosAlpha < cMin ) return false; - if ( sMin < 0 ) return true; + if ((cMin > 0) || (sMin > 0)) { + TVector3 disp(svtx->x() - pvtx->x(), svtx->y() - pvtx->y(), 0); + TVector3 cmom(cand.px(), cand.py(), 0); + float cosAlpha = disp.Dot(cmom) / (disp.Perp() * cmom.Perp()); + if (cosAlpha < cMin) + return false; + if (sMin < 0) + return true; float mass = cand.mass(); - AlgebraicVector3 vmom( cand.px(), cand.py(), 0 ); + AlgebraicVector3 vmom(cand.px(), cand.py(), 0); VertexDistanceXY vdistXY; - Measurement1D distXY = vdistXY.distance( *svtx, *pvtx ); + Measurement1D distXY = vdistXY.distance(*svtx, *pvtx); double ctauPV = distXY.value() * cosAlpha * mass / cmom.Perp(); GlobalError sve = svtx->error(); GlobalError pve = pvtx->error(); AlgebraicSymMatrix33 vXYe = sve.matrix() + pve.matrix(); - double ctauErrPV = sqrt( ROOT::Math::Similarity( vmom, vXYe ) ) * mass / - cmom.Perp2(); - if ( ( ctauPV / ctauErrPV ) < sMin ) return false; + double ctauErrPV = sqrt(ROOT::Math::Similarity(vmom, vXYe)) * mass / cmom.Perp2(); + if ((ctauPV / ctauErrPV) < sMin) + return false; } return true; } - private: +private: float pMin; float cMin; float sMin; }; - -class BPHFittedVertexSelect: public BPHHistoSpecificDecay::CandidateSelect { - public: - BPHFittedVertexSelect( float probMin, - float cosMin = -1.0, - float sigMin = -1.0 ): pMin( probMin ), - cMin( cosMin ), - sMin( sigMin ) { - } - bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pvtx ) const override { - const reco::Vertex* svtx = BPHUserData::get - ( cand, "fitVertex" ); - if ( svtx == nullptr ) return false; - if ( pMin > 0 ) { - if ( ChiSquaredProbability( svtx->chi2(), - svtx->ndof() ) < pMin ) return false; +class BPHFittedVertexSelect : public BPHHistoSpecificDecay::CandidateSelect { +public: + BPHFittedVertexSelect(float probMin, float cosMin = -1.0, float sigMin = -1.0) + : pMin(probMin), cMin(cosMin), sMin(sigMin) {} + bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pvtx) const override { + const reco::Vertex* svtx = BPHUserData::get(cand, "fitVertex"); + if (svtx == nullptr) + return false; + if (pMin > 0) { + if (ChiSquaredProbability(svtx->chi2(), svtx->ndof()) < pMin) + return false; } - if ( ( cMin > 0 ) || ( sMin > 0 ) ) { - TVector3 disp( svtx->x() - pvtx->x(), - svtx->y() - pvtx->y(), - 0 ); - const Vector3DBase* fmom = BPHUserData::get - < Vector3DBase >( cand, "fitMomentum" ); - if ( fmom == nullptr ) return false; - TVector3 cmom( fmom->x(), fmom->y(), 0 ); - float cosAlpha = disp.Dot( cmom ) / ( disp.Perp() * cmom.Perp() ); - if ( cosAlpha < cMin ) return false; - if ( sMin < 0 ) return true; - if ( !cand.hasUserFloat( "fitMass" ) ) return false; - float mass = cand.userFloat( "fitMass" ); - AlgebraicVector3 vmom( fmom->x(), fmom->y(), 0 ); + if ((cMin > 0) || (sMin > 0)) { + TVector3 disp(svtx->x() - pvtx->x(), svtx->y() - pvtx->y(), 0); + const Vector3DBase* fmom = + BPHUserData::get >(cand, "fitMomentum"); + if (fmom == nullptr) + return false; + TVector3 cmom(fmom->x(), fmom->y(), 0); + float cosAlpha = disp.Dot(cmom) / (disp.Perp() * cmom.Perp()); + if (cosAlpha < cMin) + return false; + if (sMin < 0) + return true; + if (!cand.hasUserFloat("fitMass")) + return false; + float mass = cand.userFloat("fitMass"); + AlgebraicVector3 vmom(fmom->x(), fmom->y(), 0); VertexDistanceXY vdistXY; - Measurement1D distXY = vdistXY.distance( *svtx, *pvtx ); + Measurement1D distXY = vdistXY.distance(*svtx, *pvtx); double ctauPV = distXY.value() * cosAlpha * mass / cmom.Perp(); GlobalError sve = svtx->error(); GlobalError pve = pvtx->error(); AlgebraicSymMatrix33 vXYe = sve.matrix() + pve.matrix(); - double ctauErrPV = sqrt( ROOT::Math::Similarity( vmom, vXYe ) ) * mass / - cmom.Perp2(); - if ( ( ctauPV / ctauErrPV ) < sMin ) return false; + double ctauErrPV = sqrt(ROOT::Math::Similarity(vmom, vXYe)) * mass / cmom.Perp2(); + if ((ctauPV / ctauErrPV) < sMin) + return false; } return true; } - private: +private: float pMin; float cMin; float sMin; }; - -BPHHistoSpecificDecay::BPHHistoSpecificDecay( const edm::ParameterSet& ps ) { - - useOnia = ( ! SET_LABEL( oniaCandsLabel, ps ).empty() ); - useSd = ( ! SET_LABEL( sdCandsLabel, ps ).empty() ); - useSs = ( ! SET_LABEL( ssCandsLabel, ps ).empty() ); - useBu = ( ! SET_LABEL( buCandsLabel, ps ).empty() ); - useBd = ( ! SET_LABEL( bdCandsLabel, ps ).empty() ); - useBs = ( ! SET_LABEL( bsCandsLabel, ps ).empty() ); - if ( useOnia ) consume< vector >( oniaCandsToken, - oniaCandsLabel ); - if ( useSd ) consume< vector >( sdCandsToken, - sdCandsLabel ); - if ( useSs ) consume< vector >( ssCandsToken, - ssCandsLabel ); - if ( useBu ) consume< vector >( buCandsToken, - buCandsLabel ); - if ( useBd ) consume< vector >( bdCandsToken, - bdCandsLabel ); - if ( useBs ) consume< vector >( bsCandsToken, - bsCandsLabel ); +BPHHistoSpecificDecay::BPHHistoSpecificDecay(const edm::ParameterSet& ps) { + useOnia = (!SET_LABEL(oniaCandsLabel, ps).empty()); + useSd = (!SET_LABEL(sdCandsLabel, ps).empty()); + useSs = (!SET_LABEL(ssCandsLabel, ps).empty()); + useBu = (!SET_LABEL(buCandsLabel, ps).empty()); + useBd = (!SET_LABEL(bdCandsLabel, ps).empty()); + useBs = (!SET_LABEL(bsCandsLabel, ps).empty()); + if (useOnia) + consume >(oniaCandsToken, oniaCandsLabel); + if (useSd) + consume >(sdCandsToken, sdCandsLabel); + if (useSs) + consume >(ssCandsToken, ssCandsLabel); + if (useBu) + consume >(buCandsToken, buCandsLabel); + if (useBd) + consume >(bdCandsToken, bdCandsLabel); + if (useBs) + consume >(bsCandsToken, bsCandsLabel); static const BPHSoftMuonSelect sms; - double phiMassMin = 0.85; - double phiMassMax = 3.30; - double phiPtMin = 16.0; - double phiEtaMax = -1.0; - double phiRMax = -1.0; - double jPsiMassMin = 2.95; - double jPsiMassMax = 3.30; - double jPsiPtMin = 16.0; - double jPsiEtaMax = -1.0; - double jPsiRMax = -1.0; - double psi2MassMin = 3.40; - double psi2MassMax = 4.00; - double psi2PtMin = 13.0; - double psi2EtaMax = -1.0; - double psi2RMax = -1.0; - double upsMassMin = 8.50; - double upsMassMax = 11.0; - double upsPtMin = 13.0; - double upsEtaMax = -1.0; - double upsRMax = -1.0; - - double oniaProbMin = 0.005; - double oniaCosMin = -1.0; - double oniaSigMin = -1.0; - - double oniaMuPtMinLoose = -1.0; - double oniaMuPtMinTight = -1.0; + double phiMassMin = 0.85; + double phiMassMax = 3.30; + double phiPtMin = 16.0; + double phiEtaMax = -1.0; + double phiRMax = -1.0; + double jPsiMassMin = 2.95; + double jPsiMassMax = 3.30; + double jPsiPtMin = 16.0; + double jPsiEtaMax = -1.0; + double jPsiRMax = -1.0; + double psi2MassMin = 3.40; + double psi2MassMax = 4.00; + double psi2PtMin = 13.0; + double psi2EtaMax = -1.0; + double psi2RMax = -1.0; + double upsMassMin = 8.50; + double upsMassMax = 11.0; + double upsPtMin = 13.0; + double upsEtaMax = -1.0; + double upsRMax = -1.0; + + double oniaProbMin = 0.005; + double oniaCosMin = -1.0; + double oniaSigMin = -1.0; + + double oniaMuPtMinLoose = -1.0; + double oniaMuPtMinTight = -1.0; double oniaMuEtaMaxLoose = -1.0; double oniaMuEtaMaxTight = -1.0; - phiBasicSelect = new BPHCompositeBasicSelect( - phiMassMin, phiMassMax, - phiPtMin , phiEtaMax , phiRMax ); - jPsiBasicSelect = new BPHCompositeBasicSelect( - jPsiMassMin, jPsiMassMax, - jPsiPtMin , jPsiEtaMax , jPsiRMax ); - psi2BasicSelect = new BPHCompositeBasicSelect( - psi2MassMin, psi2MassMax, - psi2PtMin , psi2EtaMax , psi2RMax ); - upsBasicSelect = new BPHCompositeBasicSelect( - upsMassMin, upsMassMax, - upsPtMin , upsEtaMax , upsRMax ); - oniaVertexSelect = new BPHCompositeVertexSelect( - oniaProbMin, oniaCosMin, oniaSigMin ); - oniaDaughterSelect = new BPHDaughterSelect( - oniaMuPtMinLoose , oniaMuPtMinTight , - oniaMuEtaMaxLoose, oniaMuEtaMaxTight, &sms ); - - double buJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; - double buJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; - double buJPsiPtMin = 8.0; - double buJPsiEtaMax = -1.0; - double buJPsiRMax = -1.0; - double buProbMin = 0.10; - double buCosMin = 0.99; - double buSigMin = 3.0; - double buMuPtMinLoose = 4.0; - double buMuPtMinTight = 4.0; - double buMuEtaMaxLoose = 2.2; - double buMuEtaMaxTight = 2.2; + phiBasicSelect = new BPHCompositeBasicSelect(phiMassMin, phiMassMax, phiPtMin, phiEtaMax, phiRMax); + jPsiBasicSelect = new BPHCompositeBasicSelect(jPsiMassMin, jPsiMassMax, jPsiPtMin, jPsiEtaMax, jPsiRMax); + psi2BasicSelect = new BPHCompositeBasicSelect(psi2MassMin, psi2MassMax, psi2PtMin, psi2EtaMax, psi2RMax); + upsBasicSelect = new BPHCompositeBasicSelect(upsMassMin, upsMassMax, upsPtMin, upsEtaMax, upsRMax); + oniaVertexSelect = new BPHCompositeVertexSelect(oniaProbMin, oniaCosMin, oniaSigMin); + oniaDaughterSelect = + new BPHDaughterSelect(oniaMuPtMinLoose, oniaMuPtMinTight, oniaMuEtaMaxLoose, oniaMuEtaMaxTight, &sms); + + double buJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; + double buJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; + double buJPsiPtMin = 8.0; + double buJPsiEtaMax = -1.0; + double buJPsiRMax = -1.0; + double buProbMin = 0.10; + double buCosMin = 0.99; + double buSigMin = 3.0; + double buMuPtMinLoose = 4.0; + double buMuPtMinTight = 4.0; + double buMuEtaMaxLoose = 2.2; + double buMuEtaMaxTight = 2.2; buKPtMin = 1.6; - buJPsiBasicSelect = new BPHCompositeBasicSelect( - buJPsiMassMin, buJPsiMassMax, - buJPsiPtMin , buJPsiEtaMax , buJPsiRMax ); - buVertexSelect = new BPHFittedVertexSelect( - buProbMin, buCosMin, buSigMin ); - buJPsiDaughterSelect = new BPHDaughterSelect( - buMuPtMinLoose , buMuPtMinTight , - buMuEtaMaxLoose, buMuEtaMaxTight, &sms ); - - double bdJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; - double bdJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; - double bdJPsiPtMin = 8.0; - double bdJPsiEtaMax = -1.0; - double bdJPsiRMax = -1.0; - double bdKx0MassMin = BPHParticleMasses::kx0Mass - 0.075; - double bdKx0MassMax = BPHParticleMasses::kx0Mass + 0.075; - double bdKx0PtMin = -1.0; - double bdKx0EtaMax = -1.0; - double bdKx0RMax = -1.0; - double bdProbMin = 0.10; - double bdCosMin = 0.99; - double bdSigMin = 3.0; - double bdMuPtMinLoose = 4.0; - double bdMuPtMinTight = 4.0; - double bdMuEtaMaxLoose = 2.2; - double bdMuEtaMaxTight = 2.2; - - bdJPsiBasicSelect = new BPHCompositeBasicSelect( - bdJPsiMassMin, bdJPsiMassMax, - bdJPsiPtMin , bdJPsiEtaMax , bdJPsiRMax ); - bdKx0BasicSelect = new BPHCompositeBasicSelect( - bdKx0MassMin, bdKx0MassMax, - bdKx0PtMin , bdKx0EtaMax , bdKx0RMax ); - bdVertexSelect = new BPHFittedVertexSelect( - bdProbMin, bdCosMin, bdSigMin ); - bdJPsiDaughterSelect = new BPHDaughterSelect( - bdMuPtMinLoose , bdMuPtMinTight , - bdMuEtaMaxLoose, bdMuEtaMaxTight, &sms ); - - double bsJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; - double bsJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; - double bsJPsiPtMin = 8.0; - double bsJPsiEtaMax = -1.0; - double bsJPsiRMax = -1.0; - double bsPhiMassMin = BPHParticleMasses::phiMass - 0.010; - double bsPhiMassMax = BPHParticleMasses::phiMass + 0.010; - double bsPhiPtMin = -1.0; - double bsPhiEtaMax = -1.0; - double bsPhiRMax = -1.0; - double bsProbMin = 0.10; - double bsCosMin = 0.99; - double bsSigMin = 3.0; - double bsMuPtMinLoose = 4.0; - double bsMuPtMinTight = 4.0; - double bsMuEtaMaxLoose = 2.2; - double bsMuEtaMaxTight = 2.2; - bsJPsiBasicSelect = new BPHCompositeBasicSelect( - bsJPsiMassMin, bsJPsiMassMax, - bsJPsiPtMin , bsJPsiEtaMax , bsJPsiRMax ); - bsPhiBasicSelect = new BPHCompositeBasicSelect( - bsPhiMassMin, bsPhiMassMax, - bsPhiPtMin , bsPhiEtaMax , bsPhiRMax ); - bsVertexSelect = new BPHFittedVertexSelect( - bsProbMin, bsCosMin, bsSigMin ); - bsJPsiDaughterSelect = new BPHDaughterSelect( - bsMuPtMinLoose , bsMuPtMinTight , - bsMuEtaMaxLoose, bsMuEtaMaxTight, &sms ); - + buJPsiBasicSelect = new BPHCompositeBasicSelect(buJPsiMassMin, buJPsiMassMax, buJPsiPtMin, buJPsiEtaMax, buJPsiRMax); + buVertexSelect = new BPHFittedVertexSelect(buProbMin, buCosMin, buSigMin); + buJPsiDaughterSelect = new BPHDaughterSelect(buMuPtMinLoose, buMuPtMinTight, buMuEtaMaxLoose, buMuEtaMaxTight, &sms); + + double bdJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; + double bdJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; + double bdJPsiPtMin = 8.0; + double bdJPsiEtaMax = -1.0; + double bdJPsiRMax = -1.0; + double bdKx0MassMin = BPHParticleMasses::kx0Mass - 0.075; + double bdKx0MassMax = BPHParticleMasses::kx0Mass + 0.075; + double bdKx0PtMin = -1.0; + double bdKx0EtaMax = -1.0; + double bdKx0RMax = -1.0; + double bdProbMin = 0.10; + double bdCosMin = 0.99; + double bdSigMin = 3.0; + double bdMuPtMinLoose = 4.0; + double bdMuPtMinTight = 4.0; + double bdMuEtaMaxLoose = 2.2; + double bdMuEtaMaxTight = 2.2; + + bdJPsiBasicSelect = new BPHCompositeBasicSelect(bdJPsiMassMin, bdJPsiMassMax, bdJPsiPtMin, bdJPsiEtaMax, bdJPsiRMax); + bdKx0BasicSelect = new BPHCompositeBasicSelect(bdKx0MassMin, bdKx0MassMax, bdKx0PtMin, bdKx0EtaMax, bdKx0RMax); + bdVertexSelect = new BPHFittedVertexSelect(bdProbMin, bdCosMin, bdSigMin); + bdJPsiDaughterSelect = new BPHDaughterSelect(bdMuPtMinLoose, bdMuPtMinTight, bdMuEtaMaxLoose, bdMuEtaMaxTight, &sms); + + double bsJPsiMassMin = BPHParticleMasses::jPsiMass - 0.150; + double bsJPsiMassMax = BPHParticleMasses::jPsiMass + 0.150; + double bsJPsiPtMin = 8.0; + double bsJPsiEtaMax = -1.0; + double bsJPsiRMax = -1.0; + double bsPhiMassMin = BPHParticleMasses::phiMass - 0.010; + double bsPhiMassMax = BPHParticleMasses::phiMass + 0.010; + double bsPhiPtMin = -1.0; + double bsPhiEtaMax = -1.0; + double bsPhiRMax = -1.0; + double bsProbMin = 0.10; + double bsCosMin = 0.99; + double bsSigMin = 3.0; + double bsMuPtMinLoose = 4.0; + double bsMuPtMinTight = 4.0; + double bsMuEtaMaxLoose = 2.2; + double bsMuEtaMaxTight = 2.2; + bsJPsiBasicSelect = new BPHCompositeBasicSelect(bsJPsiMassMin, bsJPsiMassMax, bsJPsiPtMin, bsJPsiEtaMax, bsJPsiRMax); + bsPhiBasicSelect = new BPHCompositeBasicSelect(bsPhiMassMin, bsPhiMassMax, bsPhiPtMin, bsPhiEtaMax, bsPhiRMax); + bsVertexSelect = new BPHFittedVertexSelect(bsProbMin, bsCosMin, bsSigMin); + bsJPsiDaughterSelect = new BPHDaughterSelect(bsMuPtMinLoose, bsMuPtMinTight, bsMuEtaMaxLoose, bsMuEtaMaxTight, &sms); } - BPHHistoSpecificDecay::~BPHHistoSpecificDecay() { - - delete phiBasicSelect; + delete phiBasicSelect; delete jPsiBasicSelect; delete psi2BasicSelect; - delete upsBasicSelect; + delete upsBasicSelect; delete oniaVertexSelect; delete oniaDaughterSelect; @@ -538,52 +474,46 @@ BPHHistoSpecificDecay::~BPHHistoSpecificDecay() { delete bsPhiBasicSelect; delete bsVertexSelect; delete bsJPsiDaughterSelect; - } - -void BPHHistoSpecificDecay::fillDescriptions( - edm::ConfigurationDescriptions& descriptions ) { - edm::ParameterSetDescription desc; - desc.add( "oniaCandsLabel", "" ); - desc.add( "sdCandsLabel", "" ); - desc.add( "ssCandsLabel", "" ); - desc.add( "buCandsLabel", "" ); - desc.add( "bdCandsLabel", "" ); - desc.add( "bsCandsLabel", "" ); - descriptions.add( "bphHistoSpecificDecay", desc ); - return; +void BPHHistoSpecificDecay::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("oniaCandsLabel", ""); + desc.add("sdCandsLabel", ""); + desc.add("ssCandsLabel", ""); + desc.add("buCandsLabel", ""); + desc.add("bdCandsLabel", ""); + desc.add("bsCandsLabel", ""); + descriptions.add("bphHistoSpecificDecay", desc); + return; } - void BPHHistoSpecificDecay::beginJob() { - createHisto( "massPhi" , 35, 0.85, 1.20 ); // Phi mass - createHisto( "massJPsi" , 35, 2.95, 3.30 ); // JPsi mass - createHisto( "massPsi2" , 60, 3.40, 4.00 ); // Psi2 mass - createHisto( "massUps123" , 125, 8.50, 11.0 ); // Ups mass - createHisto( "massBu" , 50, 5.00, 6.00 ); // Bu mass - createHisto( "massBd" , 50, 5.00, 6.00 ); // Bd mass - createHisto( "massBs" , 50, 5.00, 6.00 ); // Bs mass - createHisto( "mfitBu" , 50, 5.00, 6.00 ); // Bu mass, with constraint - createHisto( "mfitBd" , 50, 5.00, 6.00 ); // Bd mass, with constraint - createHisto( "mfitBs" , 50, 5.00, 6.00 ); // Bs mass, with constraint - createHisto( "massBuJPsi" , 35, 2.95, 3.30 ); // JPsi mass in Bu decay - createHisto( "massBdJPsi" , 35, 2.95, 3.30 ); // JPsi mass in Bd decay - createHisto( "massBsJPsi" , 35, 2.95, 3.30 ); // JPsi mass in Bs decay - createHisto( "massBsPhi" , 50, 1.01, 1.03 ); // Phi mass in Bs decay - createHisto( "massBdKx0" , 50, 0.80, 1.05 ); // Kx0 mass in Bd decay - - createHisto( "massFull" , 200, 2.00, 12.0 ); // Full onia mass + createHisto("massPhi", 35, 0.85, 1.20); // Phi mass + createHisto("massJPsi", 35, 2.95, 3.30); // JPsi mass + createHisto("massPsi2", 60, 3.40, 4.00); // Psi2 mass + createHisto("massUps123", 125, 8.50, 11.0); // Ups mass + createHisto("massBu", 50, 5.00, 6.00); // Bu mass + createHisto("massBd", 50, 5.00, 6.00); // Bd mass + createHisto("massBs", 50, 5.00, 6.00); // Bs mass + createHisto("mfitBu", 50, 5.00, 6.00); // Bu mass, with constraint + createHisto("mfitBd", 50, 5.00, 6.00); // Bd mass, with constraint + createHisto("mfitBs", 50, 5.00, 6.00); // Bs mass, with constraint + createHisto("massBuJPsi", 35, 2.95, 3.30); // JPsi mass in Bu decay + createHisto("massBdJPsi", 35, 2.95, 3.30); // JPsi mass in Bd decay + createHisto("massBsJPsi", 35, 2.95, 3.30); // JPsi mass in Bs decay + createHisto("massBsPhi", 50, 1.01, 1.03); // Phi mass in Bs decay + createHisto("massBdKx0", 50, 0.80, 1.05); // Kx0 mass in Bd decay + + createHisto("massFull", 200, 2.00, 12.0); // Full onia mass return; } -void BPHHistoSpecificDecay::analyze( const edm::Event& ev, - const edm::EventSetup& es ) { - +void BPHHistoSpecificDecay::analyze(const edm::Event& ev, const edm::EventSetup& es) { // get magnetic field edm::ESHandle magneticField; - es.get().get( magneticField ); + es.get().get(magneticField); // get object collections // collections are got through "BPHTokenWrapper" interface to allow @@ -591,167 +521,158 @@ void BPHHistoSpecificDecay::analyze( const edm::Event& ev, //////////// quarkonia //////////// - edm::Handle< vector > oniaCands; + edm::Handle > oniaCands; int iqo; int nqo = 0; - if ( useOnia ) { - oniaCandsToken.get( ev, oniaCands ); + if (useOnia) { + oniaCandsToken.get(ev, oniaCands); nqo = oniaCands->size(); } - for ( iqo = 0; iqo < nqo; ++ iqo ) { - LogTrace( "DataDump" ) - << "*********** quarkonium " << iqo << "/" << nqo << " ***********"; - const pat::CompositeCandidate& cand = oniaCands->at( iqo ); - if ( !oniaVertexSelect->accept( cand, - BPHUserData::getByRef( cand, - "primaryVertex" ) ) ) continue; - if ( !oniaDaughterSelect->accept( cand ) ) continue; - fillHisto( "Full", cand ); - if ( phiBasicSelect->accept( cand ) ) fillHisto( "Phi" , cand ); - if ( jPsiBasicSelect->accept( cand ) ) fillHisto( "JPsi" , cand ); - if ( psi2BasicSelect->accept( cand ) ) fillHisto( "Psi2" , cand ); - if ( upsBasicSelect->accept( cand ) ) fillHisto( "Ups123", cand ); + for (iqo = 0; iqo < nqo; ++iqo) { + LogTrace("DataDump") << "*********** quarkonium " << iqo << "/" << nqo << " ***********"; + const pat::CompositeCandidate& cand = oniaCands->at(iqo); + if (!oniaVertexSelect->accept(cand, BPHUserData::getByRef(cand, "primaryVertex"))) + continue; + if (!oniaDaughterSelect->accept(cand)) + continue; + fillHisto("Full", cand); + if (phiBasicSelect->accept(cand)) + fillHisto("Phi", cand); + if (jPsiBasicSelect->accept(cand)) + fillHisto("JPsi", cand); + if (psi2BasicSelect->accept(cand)) + fillHisto("Psi2", cand); + if (upsBasicSelect->accept(cand)) + fillHisto("Ups123", cand); } //////////// Bu //////////// - edm::Handle< vector > buCands; + edm::Handle > buCands; int ibu; int nbu = 0; - if ( useBu ) { - buCandsToken.get( ev, buCands ); + if (useBu) { + buCandsToken.get(ev, buCands); nbu = buCands->size(); } - for ( ibu = 0; ibu < nbu; ++ ibu ) { - LogTrace( "DataDump" ) - << "*********** Bu " << ibu << "/" << nbu << " ***********"; - const pat::CompositeCandidate& cand = buCands->at( ibu ); - const pat::CompositeCandidate* jPsi = BPHUserData::getByRef - ( cand, "refToJPsi" ); - LogTrace( "DataDump" ) - << "JPsi: " << jPsi; - if ( jPsi == nullptr ) continue; - if ( !buJPsiBasicSelect ->accept( *jPsi ) ) continue; - if ( !buJPsiDaughterSelect->accept( *jPsi ) ) continue; - if ( !buVertexSelect->accept( cand, - BPHUserData::getByRef( *jPsi, - "primaryVertex" ) ) ) continue; - const reco::Candidate* kptr = BPHDaughters::get( cand, 0.49, 0.50 ).front(); - if ( kptr == nullptr ) continue; - if ( kptr->pt() < buKPtMin ) continue; - fillHisto( "Bu" , cand ); - fillHisto( "BuJPsi", *jPsi ); + for (ibu = 0; ibu < nbu; ++ibu) { + LogTrace("DataDump") << "*********** Bu " << ibu << "/" << nbu << " ***********"; + const pat::CompositeCandidate& cand = buCands->at(ibu); + const pat::CompositeCandidate* jPsi = BPHUserData::getByRef(cand, "refToJPsi"); + LogTrace("DataDump") << "JPsi: " << jPsi; + if (jPsi == nullptr) + continue; + if (!buJPsiBasicSelect->accept(*jPsi)) + continue; + if (!buJPsiDaughterSelect->accept(*jPsi)) + continue; + if (!buVertexSelect->accept(cand, BPHUserData::getByRef(*jPsi, "primaryVertex"))) + continue; + const reco::Candidate* kptr = BPHDaughters::get(cand, 0.49, 0.50).front(); + if (kptr == nullptr) + continue; + if (kptr->pt() < buKPtMin) + continue; + fillHisto("Bu", cand); + fillHisto("BuJPsi", *jPsi); } //////////// Bd //////////// - edm::Handle< vector > bdCands; + edm::Handle > bdCands; int ibd; int nbd = 0; - if ( useBd ) { - bdCandsToken.get( ev, bdCands ); + if (useBd) { + bdCandsToken.get(ev, bdCands); nbd = bdCands->size(); } - for ( ibd = 0; ibd < nbd; ++ ibd ) { - LogTrace( "DataDump" ) - << "*********** Bd " << ibd << "/" << nbd << " ***********"; - const pat::CompositeCandidate& cand = bdCands->at( ibd ); - const pat::CompositeCandidate* jPsi = BPHUserData::getByRef - ( cand, "refToJPsi" ); - LogTrace( "DataDump" ) - << "JPsi: " << jPsi; - if ( jPsi == nullptr ) continue; - const pat::CompositeCandidate* kx0 = BPHUserData::getByRef - ( cand, "refToKx0" ); - LogTrace( "DataDump" ) - << "Kx0: " << kx0; - if ( kx0 == nullptr ) continue; - if ( !bdJPsiBasicSelect ->accept( *jPsi ) ) continue; - if ( !bdKx0BasicSelect ->accept( * kx0 ) ) continue; - if ( !bdJPsiDaughterSelect->accept( *jPsi ) ) continue; - if ( !bdVertexSelect->accept( cand, - BPHUserData::getByRef( *jPsi, - "primaryVertex" ) ) ) continue; - fillHisto( "Bd" , cand ); - fillHisto( "BdJPsi", *jPsi ); - fillHisto( "BdKx0" , *kx0 ); + for (ibd = 0; ibd < nbd; ++ibd) { + LogTrace("DataDump") << "*********** Bd " << ibd << "/" << nbd << " ***********"; + const pat::CompositeCandidate& cand = bdCands->at(ibd); + const pat::CompositeCandidate* jPsi = BPHUserData::getByRef(cand, "refToJPsi"); + LogTrace("DataDump") << "JPsi: " << jPsi; + if (jPsi == nullptr) + continue; + const pat::CompositeCandidate* kx0 = BPHUserData::getByRef(cand, "refToKx0"); + LogTrace("DataDump") << "Kx0: " << kx0; + if (kx0 == nullptr) + continue; + if (!bdJPsiBasicSelect->accept(*jPsi)) + continue; + if (!bdKx0BasicSelect->accept(*kx0)) + continue; + if (!bdJPsiDaughterSelect->accept(*jPsi)) + continue; + if (!bdVertexSelect->accept(cand, BPHUserData::getByRef(*jPsi, "primaryVertex"))) + continue; + fillHisto("Bd", cand); + fillHisto("BdJPsi", *jPsi); + fillHisto("BdKx0", *kx0); } //////////// Bs //////////// - edm::Handle< vector > bsCands; + edm::Handle > bsCands; int ibs; int nbs = 0; - if ( useBs ) { - bsCandsToken.get( ev, bsCands ); + if (useBs) { + bsCandsToken.get(ev, bsCands); nbs = bsCands->size(); } - for ( ibs = 0; ibs < nbs; ++ ibs ) { - LogTrace( "DataDump" ) - << "*********** Bs " << ibs << "/" << nbs << " ***********"; - const pat::CompositeCandidate& cand = bsCands->at( ibs ); - const pat::CompositeCandidate* jPsi = BPHUserData::getByRef - ( cand, "refToJPsi" ); - LogTrace( "DataDump" ) - << "JPsi: " << jPsi; - if ( jPsi == nullptr ) continue; - const pat::CompositeCandidate* phi = BPHUserData::getByRef - ( cand, "refToPhi" ); - LogTrace( "DataDump" ) - << "Phi: " << phi; - if ( phi == nullptr ) continue; - if ( !bsJPsiBasicSelect ->accept( *jPsi ) ) continue; - if ( !bsPhiBasicSelect ->accept( * phi ) ) continue; - if ( !bsJPsiDaughterSelect->accept( *jPsi ) ) continue; - if ( !bsVertexSelect->accept( cand, - BPHUserData::getByRef( *jPsi, - "primaryVertex" ) ) ) continue; - fillHisto( "Bs" , cand ); - fillHisto( "BsJPsi", *jPsi ); - fillHisto( "BsPhi" , *phi ); + for (ibs = 0; ibs < nbs; ++ibs) { + LogTrace("DataDump") << "*********** Bs " << ibs << "/" << nbs << " ***********"; + const pat::CompositeCandidate& cand = bsCands->at(ibs); + const pat::CompositeCandidate* jPsi = BPHUserData::getByRef(cand, "refToJPsi"); + LogTrace("DataDump") << "JPsi: " << jPsi; + if (jPsi == nullptr) + continue; + const pat::CompositeCandidate* phi = BPHUserData::getByRef(cand, "refToPhi"); + LogTrace("DataDump") << "Phi: " << phi; + if (phi == nullptr) + continue; + if (!bsJPsiBasicSelect->accept(*jPsi)) + continue; + if (!bsPhiBasicSelect->accept(*phi)) + continue; + if (!bsJPsiDaughterSelect->accept(*jPsi)) + continue; + if (!bsVertexSelect->accept(cand, BPHUserData::getByRef(*jPsi, "primaryVertex"))) + continue; + fillHisto("Bs", cand); + fillHisto("BsJPsi", *jPsi); + fillHisto("BsPhi", *phi); } - - return; - -} - - -void BPHHistoSpecificDecay::endJob() { return; } +void BPHHistoSpecificDecay::endJob() { return; } -void BPHHistoSpecificDecay::fillHisto( const string& name, - const pat::CompositeCandidate& cand ) { - float mass = ( cand.hasUserFloat( "fitMass" ) ? - cand. userFloat( "fitMass" ) : -1 ); - fillHisto( "mass" + name, cand.mass() ); - fillHisto( "mfit" + name, mass ); +void BPHHistoSpecificDecay::fillHisto(const string& name, const pat::CompositeCandidate& cand) { + float mass = (cand.hasUserFloat("fitMass") ? cand.userFloat("fitMass") : -1); + fillHisto("mass" + name, cand.mass()); + fillHisto("mfit" + name, mass); return; } - -void BPHHistoSpecificDecay::fillHisto( const string& name, float x ) { - map::iterator iter = histoMap.find( name ); - map::iterator iend = histoMap.end(); - if ( iter == iend ) return; - iter->second->Fill( x ); +void BPHHistoSpecificDecay::fillHisto(const string& name, float x) { + map::iterator iter = histoMap.find(name); + map::iterator iend = histoMap.end(); + if (iter == iend) + return; + iter->second->Fill(x); return; } - -void BPHHistoSpecificDecay::createHisto( const string& name, - int nbin, float hmin, float hmax ) { - histoMap[name] = fs->make( name.c_str(), name.c_str(), - nbin, hmin, hmax ); +void BPHHistoSpecificDecay::createHisto(const string& name, int nbin, float hmin, float hmax) { + histoMap[name] = fs->make(name.c_str(), name.c_str(), nbin, hmin, hmax); return; } #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( BPHHistoSpecificDecay ); +DEFINE_FWK_MODULE(BPHHistoSpecificDecay); diff --git a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.h b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.h index 71f2c01ef6310..0b999d8fde0e8 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.h +++ b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHHistoSpecificDecay.h @@ -20,43 +20,38 @@ class TVector3; namespace reco { class Candidate; class Vertex; -} +} // namespace reco -class BPHHistoSpecificDecay: - public BPHAnalyzerWrapper { - - public: - - explicit BPHHistoSpecificDecay( const edm::ParameterSet& ps ); +class BPHHistoSpecificDecay : public BPHAnalyzerWrapper { +public: + explicit BPHHistoSpecificDecay(const edm::ParameterSet& ps); ~BPHHistoSpecificDecay() override; - static void fillDescriptions( edm::ConfigurationDescriptions& descriptions ); + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); void beginJob() override; - void analyze( const edm::Event& ev, const edm::EventSetup& es ) override; + void analyze(const edm::Event& ev, const edm::EventSetup& es) override; void endJob() override; class CandidateSelect { - public: + public: virtual ~CandidateSelect() {} - virtual bool accept( const pat::CompositeCandidate& cand, - const reco::Vertex* pv = nullptr ) const = 0 ; + virtual bool accept(const pat::CompositeCandidate& cand, const reco::Vertex* pv = nullptr) const = 0; }; - private: - +private: std::string oniaCandsLabel; - std::string sdCandsLabel; - std::string ssCandsLabel; - std::string buCandsLabel; - std::string bdCandsLabel; - std::string bsCandsLabel; - BPHTokenWrapper< std::vector > oniaCandsToken; - BPHTokenWrapper< std::vector > sdCandsToken; - BPHTokenWrapper< std::vector > ssCandsToken; - BPHTokenWrapper< std::vector > buCandsToken; - BPHTokenWrapper< std::vector > bdCandsToken; - BPHTokenWrapper< std::vector > bsCandsToken; + std::string sdCandsLabel; + std::string ssCandsLabel; + std::string buCandsLabel; + std::string bdCandsLabel; + std::string bsCandsLabel; + BPHTokenWrapper > oniaCandsToken; + BPHTokenWrapper > sdCandsToken; + BPHTokenWrapper > ssCandsToken; + BPHTokenWrapper > buCandsToken; + BPHTokenWrapper > bdCandsToken; + BPHTokenWrapper > bsCandsToken; bool useOnia; bool useSd; bool useSs; @@ -65,12 +60,12 @@ class BPHHistoSpecificDecay: bool useBs; edm::Service fs; - std::map histoMap; + std::map histoMap; - CandidateSelect* phiBasicSelect; + CandidateSelect* phiBasicSelect; CandidateSelect* jPsiBasicSelect; CandidateSelect* psi2BasicSelect; - CandidateSelect* upsBasicSelect; + CandidateSelect* upsBasicSelect; CandidateSelect* oniaVertexSelect; CandidateSelect* oniaDaughterSelect; @@ -90,12 +85,9 @@ class BPHHistoSpecificDecay: double buKPtMin; - void fillHisto ( const std::string& name, - const pat::CompositeCandidate& cand ); - void fillHisto ( const std::string& name, float x ); - void createHisto ( const std::string& name, - int nbin, float hmin, float hmax ); - + void fillHisto(const std::string& name, const pat::CompositeCandidate& cand); + void fillHisto(const std::string& name, float x); + void createHisto(const std::string& name, int nbin, float hmin, float hmax); }; #endif diff --git a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.cc b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.cc index 411620532aad2..4f93005ab122d 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.cc @@ -44,175 +44,175 @@ using namespace std; -#define SET_PAR(TYPE,NAME,PSET) ( NAME = PSET.getParameter< TYPE >( #NAME ) ) +#define SET_PAR(TYPE, NAME, PSET) (NAME = PSET.getParameter(#NAME)) // SET_PAR(string,xyz,ps); // is equivalent to // ( xyz = ps.getParameter< string >( "xyx" ) ) -BPHWriteSpecificDecay::BPHWriteSpecificDecay( const edm::ParameterSet& ps ) { - - usePV = ( ! SET_PAR( string, pVertexLabel, ps ).empty() ); - usePM = ( ! SET_PAR( string, patMuonLabel, ps ).empty() ); - useCC = ( ! SET_PAR( string, ccCandsLabel, ps ).empty() ); - usePF = ( ! SET_PAR( string, pfCandsLabel, ps ).empty() ); - usePC = ( ! SET_PAR( string, pcCandsLabel, ps ).empty() ); - useGP = ( ! SET_PAR( string, gpCandsLabel, ps ).empty() ); - SET_PAR( string, oniaName, ps ); - SET_PAR( string, sdName, ps ); - SET_PAR( string, ssName, ps ); - SET_PAR( string, buName, ps ); - SET_PAR( string, bdName, ps ); - SET_PAR( string, bsName, ps ); - - SET_PAR( bool, writeMomentum, ps ); - SET_PAR( bool, writeVertex , ps ); - - rMap["Onia" ] = Onia; +BPHWriteSpecificDecay::BPHWriteSpecificDecay(const edm::ParameterSet& ps) { + usePV = (!SET_PAR(string, pVertexLabel, ps).empty()); + usePM = (!SET_PAR(string, patMuonLabel, ps).empty()); + useCC = (!SET_PAR(string, ccCandsLabel, ps).empty()); + usePF = (!SET_PAR(string, pfCandsLabel, ps).empty()); + usePC = (!SET_PAR(string, pcCandsLabel, ps).empty()); + useGP = (!SET_PAR(string, gpCandsLabel, ps).empty()); + SET_PAR(string, oniaName, ps); + SET_PAR(string, sdName, ps); + SET_PAR(string, ssName, ps); + SET_PAR(string, buName, ps); + SET_PAR(string, bdName, ps); + SET_PAR(string, bsName, ps); + + SET_PAR(bool, writeMomentum, ps); + SET_PAR(bool, writeVertex, ps); + + rMap["Onia"] = Onia; rMap["PHiMuMu"] = Pmm; - rMap["Psi1" ] = Psi1; - rMap["Psi2" ] = Psi2; - rMap["Ups" ] = Ups; - rMap["Ups1" ] = Ups1; - rMap["Ups2" ] = Ups2; - rMap["Ups3" ] = Ups3; - rMap["Kx0" ] = Kx0; - rMap["PhiKK" ] = Pkk; - rMap["Bu" ] = Bu; - rMap["Bd" ] = Bd; - rMap["Bs" ] = Bs; - - pMap["ptMin" ] = ptMin; - pMap["etaMax" ] = etaMax; - pMap["mJPsiMin" ] = mPsiMin; - pMap["mJPsiMax" ] = mPsiMax; - pMap["mKx0Min" ] = mKx0Min; - pMap["mKx0Max" ] = mKx0Max; - pMap["mPhiMin" ] = mPhiMin; - pMap["mPhiMax" ] = mPhiMax; - pMap["massMin" ] = massMin; - pMap["massMax" ] = massMax; - pMap["probMin" ] = probMin; - pMap["massFitMin" ] = mFitMin; - pMap["massFitMax" ] = mFitMax; - pMap["constrMass" ] = constrMass; + rMap["Psi1"] = Psi1; + rMap["Psi2"] = Psi2; + rMap["Ups"] = Ups; + rMap["Ups1"] = Ups1; + rMap["Ups2"] = Ups2; + rMap["Ups3"] = Ups3; + rMap["Kx0"] = Kx0; + rMap["PhiKK"] = Pkk; + rMap["Bu"] = Bu; + rMap["Bd"] = Bd; + rMap["Bs"] = Bs; + + pMap["ptMin"] = ptMin; + pMap["etaMax"] = etaMax; + pMap["mJPsiMin"] = mPsiMin; + pMap["mJPsiMax"] = mPsiMax; + pMap["mKx0Min"] = mKx0Min; + pMap["mKx0Max"] = mKx0Max; + pMap["mPhiMin"] = mPhiMin; + pMap["mPhiMax"] = mPhiMax; + pMap["massMin"] = massMin; + pMap["massMax"] = massMax; + pMap["probMin"] = probMin; + pMap["massFitMin"] = mFitMin; + pMap["massFitMax"] = mFitMax; + pMap["constrMass"] = constrMass; pMap["constrSigma"] = constrSigma; - fMap["constrMJPsi" ] = constrMJPsi; + fMap["constrMJPsi"] = constrMJPsi; fMap["writeCandidate"] = writeCandidate; - recoOnia = - recoKx0 = writeKx0 = - recoPkk = writePkk = - recoBu = writeBu = - recoBd = writeBd = - recoBs = writeBs = false; + recoOnia = recoKx0 = writeKx0 = recoPkk = writePkk = recoBu = writeBu = recoBd = writeBd = recoBs = writeBs = false; writeOnia = true; - const vector recoSelect = - ps.getParameter< vector >( "recoSelect" ); + const vector recoSelect = ps.getParameter >("recoSelect"); int iSel; int nSel = recoSelect.size(); - for ( iSel = 0; iSel < nSel; ++iSel ) setRecoParameters( recoSelect[iSel] ); - if ( !recoOnia ) writeOnia = false; - - if ( recoBu ) recoOnia = true; - if ( recoBd ) recoOnia = recoKx0 = true; - if ( recoBs ) recoOnia = recoPkk = true; - if ( writeBu ) writeOnia = true; - if ( writeBd ) writeOnia = writeKx0 = true; - if ( writeBs ) writeOnia = writePkk = true; - - if ( usePV ) consume< vector >( pVertexToken, - pVertexLabel ); - if ( usePM ) consume< pat::MuonCollection >( patMuonToken, - patMuonLabel ); - if ( useCC ) consume< vector >( ccCandsToken, - ccCandsLabel ); - if ( usePF ) consume< vector >( pfCandsToken, - pfCandsLabel ); - if ( usePC ) consume< vector >( pcCandsToken, - pcCandsLabel ); - if ( useGP ) consume< vector >( gpCandsToken, - gpCandsLabel ); - - if ( writeOnia ) produces( oniaName ); - if ( writeKx0 ) produces( sdName ); - if ( writePkk ) produces( ssName ); - if ( writeBu ) produces( buName ); - if ( writeBd ) produces( bdName ); - if ( writeBs ) produces( bsName ); - -} - - -BPHWriteSpecificDecay::~BPHWriteSpecificDecay() { -} - - -void BPHWriteSpecificDecay::fillDescriptions( - edm::ConfigurationDescriptions& descriptions ) { - edm::ParameterSetDescription desc; - desc.add( "pVertexLabel", "" ); - desc.add( "patMuonLabel", "" ); - desc.add( "ccCandsLabel", "" ); - desc.add( "pfCandsLabel", "" ); - desc.add( "pcCandsLabel", "" ); - desc.add( "gpCandsLabel", "" ); - desc.add( "oniaName", "oniaCand" ); - desc.add( "sdName", "kx0Cand" ); - desc.add( "ssName", "phiCand" ); - desc.add( "buName", "buFitted" ); - desc.add( "bdName", "bdFitted" ); - desc.add( "bsName", "bsFitted" ); - desc.add( "writeVertex" , true ); - desc.add( "writeMomentum", true ); - edm::ParameterSetDescription dpar; - dpar.add( "name" ); - dpar.add( "ptMin", -2.0e35 ); - dpar.add( "etaMax", -2.0e35 ); - dpar.add( "mJPsiMin", -2.0e35 ); - dpar.add( "mJPsiMax", -2.0e35 ); - dpar.add( "mKx0Min", -2.0e35 ); - dpar.add( "mKx0Max", -2.0e35 ); - dpar.add( "mPhiMin", -2.0e35 ); - dpar.add( "mPhiMax", -2.0e35 ); - dpar.add( "massMin", -2.0e35 ); - dpar.add( "massMax", -2.0e35 ); - dpar.add( "probMin", -2.0e35 ); - dpar.add( "massFitMin", -2.0e35 ); - dpar.add( "massFitMax", -2.0e35 ); - dpar.add( "constrMass", -2.0e35 ); - dpar.add( "constrSigma", -2.0e35 ); - dpar.add( "constrMJPsi", true ); - dpar.add( "writeCandidate", true ); - vector rpar; - desc.addVPSet( "recoSelect", dpar, rpar ); - descriptions.add( "bphWriteSpecificDecay", desc ); - return; + for (iSel = 0; iSel < nSel; ++iSel) + setRecoParameters(recoSelect[iSel]); + if (!recoOnia) + writeOnia = false; + + if (recoBu) + recoOnia = true; + if (recoBd) + recoOnia = recoKx0 = true; + if (recoBs) + recoOnia = recoPkk = true; + if (writeBu) + writeOnia = true; + if (writeBd) + writeOnia = writeKx0 = true; + if (writeBs) + writeOnia = writePkk = true; + + if (usePV) + consume >(pVertexToken, pVertexLabel); + if (usePM) + consume(patMuonToken, patMuonLabel); + if (useCC) + consume >(ccCandsToken, ccCandsLabel); + if (usePF) + consume >(pfCandsToken, pfCandsLabel); + if (usePC) + consume >(pcCandsToken, pcCandsLabel); + if (useGP) + consume >(gpCandsToken, gpCandsLabel); + + if (writeOnia) + produces(oniaName); + if (writeKx0) + produces(sdName); + if (writePkk) + produces(ssName); + if (writeBu) + produces(buName); + if (writeBd) + produces(bdName); + if (writeBs) + produces(bsName); } - -void BPHWriteSpecificDecay::beginJob() { +BPHWriteSpecificDecay::~BPHWriteSpecificDecay() {} + +void BPHWriteSpecificDecay::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("pVertexLabel", ""); + desc.add("patMuonLabel", ""); + desc.add("ccCandsLabel", ""); + desc.add("pfCandsLabel", ""); + desc.add("pcCandsLabel", ""); + desc.add("gpCandsLabel", ""); + desc.add("oniaName", "oniaCand"); + desc.add("sdName", "kx0Cand"); + desc.add("ssName", "phiCand"); + desc.add("buName", "buFitted"); + desc.add("bdName", "bdFitted"); + desc.add("bsName", "bsFitted"); + desc.add("writeVertex", true); + desc.add("writeMomentum", true); + edm::ParameterSetDescription dpar; + dpar.add("name"); + dpar.add("ptMin", -2.0e35); + dpar.add("etaMax", -2.0e35); + dpar.add("mJPsiMin", -2.0e35); + dpar.add("mJPsiMax", -2.0e35); + dpar.add("mKx0Min", -2.0e35); + dpar.add("mKx0Max", -2.0e35); + dpar.add("mPhiMin", -2.0e35); + dpar.add("mPhiMax", -2.0e35); + dpar.add("massMin", -2.0e35); + dpar.add("massMax", -2.0e35); + dpar.add("probMin", -2.0e35); + dpar.add("massFitMin", -2.0e35); + dpar.add("massFitMax", -2.0e35); + dpar.add("constrMass", -2.0e35); + dpar.add("constrSigma", -2.0e35); + dpar.add("constrMJPsi", true); + dpar.add("writeCandidate", true); + vector rpar; + desc.addVPSet("recoSelect", dpar, rpar); + descriptions.add("bphWriteSpecificDecay", desc); return; } - -void BPHWriteSpecificDecay::produce( edm::Event& ev, - const edm::EventSetup& es ) { - fill( ev, es ); - if ( writeOnia ) write( ev, lFull, oniaName ); - if ( writeKx0 ) write( ev, lSd , sdName ); - if ( writePkk ) write( ev, lSs , ssName ); - if ( writeBu ) write( ev, lBu , buName ); - if ( writeBd ) write( ev, lBd , bdName ); - if ( writeBs ) write( ev, lBs , bsName ); +void BPHWriteSpecificDecay::beginJob() { return; } + +void BPHWriteSpecificDecay::produce(edm::Event& ev, const edm::EventSetup& es) { + fill(ev, es); + if (writeOnia) + write(ev, lFull, oniaName); + if (writeKx0) + write(ev, lSd, sdName); + if (writePkk) + write(ev, lSs, ssName); + if (writeBu) + write(ev, lBu, buName); + if (writeBd) + write(ev, lBd, bdName); + if (writeBs) + write(ev, lBs, bsName); return; } - -void BPHWriteSpecificDecay::fill( edm::Event& ev, - const edm::EventSetup& es ) { - +void BPHWriteSpecificDecay::fill(edm::Event& ev, const edm::EventSetup& es) { lFull.clear(); lJPsi.clear(); lSd.clear(); @@ -226,139 +226,166 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, // get magnetic field edm::ESHandle magneticField; - es.get().get( magneticField ); + es.get().get(magneticField); // get object collections // collections are got through "BPHTokenWrapper" interface to allow // uniform access in different CMSSW versions - edm::Handle< std::vector > pVertices; - pVertexToken.get( ev, pVertices ); + edm::Handle > pVertices; + pVertexToken.get(ev, pVertices); int npv = pVertices->size(); int nrc = 0; // get reco::PFCandidate collection (in full AOD ) - edm::Handle< vector > pfCands; - if ( usePF ) { - pfCandsToken.get( ev, pfCands ); + edm::Handle > pfCands; + if (usePF) { + pfCandsToken.get(ev, pfCands); nrc = pfCands->size(); } // get pat::PackedCandidate collection (in MiniAOD) // pat::PackedCandidate is not defined in CMSSW_5XY, so a - // typedef (BPHTrackReference::candidate) is used, actually referring + // typedef (BPHTrackReference::candidate) is used, actually referring // to pat::PackedCandidate only for CMSSW versions where it's defined - edm::Handle< vector > pcCands; - if ( usePC ) { - pcCandsToken.get( ev, pcCands ); + edm::Handle > pcCands; + if (usePC) { + pcCandsToken.get(ev, pcCands); nrc = pcCands->size(); } // get pat::GenericParticle collection (in skimmed data) - edm::Handle< vector > gpCands; - if ( useGP ) { - gpCandsToken.get( ev, gpCands ); + edm::Handle > gpCands; + if (useGP) { + gpCandsToken.get(ev, gpCands); nrc = gpCands->size(); } // get pat::Muon collection (in full AOD and MiniAOD) edm::Handle patMuon; - if ( usePM ) { - patMuonToken.get( ev, patMuon ); + if (usePM) { + patMuonToken.get(ev, patMuon); } // get muons from pat::CompositeCandidate objects describing onia; // muons from all composite objects are copied to an unique std::vector vector muDaugs; set muonSet; - typedef multimap mu_cc_map; + typedef multimap mu_cc_map; mu_cc_map muCCMap; - if ( useCC ) { - edm::Handle< vector > ccCands; - ccCandsToken.get( ev, ccCands ); + if (useCC) { + edm::Handle > ccCands; + ccCandsToken.get(ev, ccCands); int n = ccCands->size(); muDaugs.clear(); - muDaugs.reserve( n ); + muDaugs.reserve(n); muonSet.clear(); set::const_iterator iter; set::const_iterator iend; int i; - for ( i = 0; i < n; ++i ) { - const pat::CompositeCandidate& cc = ccCands->at( i ); + for (i = 0; i < n; ++i) { + const pat::CompositeCandidate& cc = ccCands->at(i); int j; int m = cc.numberOfDaughters(); - for ( j = 0; j < m; ++j ) { - const reco::Candidate* dp = cc.daughter( j ); - const pat::Muon* mp = dynamic_cast( dp ); + for (j = 0; j < m; ++j) { + const reco::Candidate* dp = cc.daughter(j); + const pat::Muon* mp = dynamic_cast(dp); iter = muonSet.begin(); iend = muonSet.end(); - bool add = ( mp != nullptr ) && ( muonSet.find( mp ) == iend ); - while ( add && ( iter != iend ) ) { - if ( BPHRecoBuilder::sameTrack( mp, *iter++, 1.0e-5 ) ) add = false; + bool add = (mp != nullptr) && (muonSet.find(mp) == iend); + while (add && (iter != iend)) { + if (BPHRecoBuilder::sameTrack(mp, *iter++, 1.0e-5)) + add = false; } - if ( add ) muonSet.insert( mp ); + if (add) + muonSet.insert(mp); // associate muon to the CompositeCandidate containing it - muCCMap.insert( pair( dp, &cc ) ); + muCCMap.insert(pair(dp, &cc)); } } iter = muonSet.begin(); iend = muonSet.end(); - while ( iter != iend ) muDaugs.push_back( *iter++ ); + while (iter != iend) + muDaugs.push_back(*iter++); } - map< recoType, map >::const_iterator rIter = parMap.begin(); - map< recoType, map >::const_iterator rIend = parMap.end(); + map >::const_iterator rIter = parMap.begin(); + map >::const_iterator rIend = parMap.end(); // reconstruct quarkonia BPHOniaToMuMuBuilder* onia = nullptr; - if ( recoOnia ) { - if ( usePM ) onia = new BPHOniaToMuMuBuilder( es, - BPHRecoBuilder::createCollection( patMuon, "cfmig" ), - BPHRecoBuilder::createCollection( patMuon, "cfmig" ) ); - else - if ( useCC ) onia = new BPHOniaToMuMuBuilder( es, - BPHRecoBuilder::createCollection( muDaugs, "cfmig" ), - BPHRecoBuilder::createCollection( muDaugs, "cfmig" ) ); + if (recoOnia) { + if (usePM) + onia = new BPHOniaToMuMuBuilder( + es, BPHRecoBuilder::createCollection(patMuon, "cfmig"), BPHRecoBuilder::createCollection(patMuon, "cfmig")); + else if (useCC) + onia = new BPHOniaToMuMuBuilder( + es, BPHRecoBuilder::createCollection(muDaugs, "cfmig"), BPHRecoBuilder::createCollection(muDaugs, "cfmig")); } - if ( onia != nullptr ) { - while ( rIter != rIend ) { - const map< recoType, map >::value_type& rEntry = *rIter++; - recoType rType = rEntry.first; - const map& pMap = rEntry.second; + if (onia != nullptr) { + while (rIter != rIend) { + const map >::value_type& rEntry = *rIter++; + recoType rType = rEntry.first; + const map& pMap = rEntry.second; BPHOniaToMuMuBuilder::oniaType type; - switch( rType ) { - case Pmm : type = BPHOniaToMuMuBuilder::Phi ; break; - case Psi1: type = BPHOniaToMuMuBuilder::Psi1; break; - case Psi2: type = BPHOniaToMuMuBuilder::Psi2; break; - case Ups : type = BPHOniaToMuMuBuilder::Ups ; break; - case Ups1: type = BPHOniaToMuMuBuilder::Ups1; break; - case Ups2: type = BPHOniaToMuMuBuilder::Ups2; break; - case Ups3: type = BPHOniaToMuMuBuilder::Ups3; break; - default: continue; + switch (rType) { + case Pmm: + type = BPHOniaToMuMuBuilder::Phi; + break; + case Psi1: + type = BPHOniaToMuMuBuilder::Psi1; + break; + case Psi2: + type = BPHOniaToMuMuBuilder::Psi2; + break; + case Ups: + type = BPHOniaToMuMuBuilder::Ups; + break; + case Ups1: + type = BPHOniaToMuMuBuilder::Ups1; + break; + case Ups2: + type = BPHOniaToMuMuBuilder::Ups2; + break; + case Ups3: + type = BPHOniaToMuMuBuilder::Ups3; + break; + default: + continue; } - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case ptMin : onia->setPtMin ( type, pv ); break; - case etaMax : onia->setEtaMax ( type, pv ); break; - case massMin : onia->setMassMin( type, pv ); break; - case massMax : onia->setMassMax( type, pv ); break; - case probMin : onia->setProbMin( type, pv ); break; - case constrMass : onia->setConstr ( type, pv, - onia->getConstrSigma( type ) - ); break; - case constrSigma: onia->setConstr ( type, onia->getConstrMass ( type ), - pv ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case ptMin: + onia->setPtMin(type, pv); + break; + case etaMax: + onia->setEtaMax(type, pv); + break; + case massMin: + onia->setMassMin(type, pv); + break; + case massMax: + onia->setMassMax(type, pv); + break; + case probMin: + onia->setProbMin(type, pv); + break; + case constrMass: + onia->setConstr(type, pv, onia->getConstrSigma(type)); + break; + case constrSigma: + onia->setConstr(type, onia->getConstrMass(type), pv); + break; + default: + break; } } } @@ -369,11 +396,10 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, int iFull; int nFull = lFull.size(); - map oniaVtxMap; + map oniaVtxMap; typedef mu_cc_map::const_iterator mu_cc_iter; - for ( iFull = 0; iFull < nFull; ++iFull ) { - + for (iFull = 0; iFull < nFull; ++iFull) { const reco::Vertex* pVtx = nullptr; int pvId = 0; const BPHPlusMinusCandidate* ptr = lFull[iFull].get(); @@ -381,31 +407,28 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, // try to recover primary vertex association in skim data: // get the CompositeCandidate containing both muons - pair cc0 = muCCMap.equal_range( - ptr->originalReco( daugs[0] ) ); - pair cc1 = muCCMap.equal_range( - ptr->originalReco( daugs[1] ) ); + pair cc0 = muCCMap.equal_range(ptr->originalReco(daugs[0])); + pair cc1 = muCCMap.equal_range(ptr->originalReco(daugs[1])); mu_cc_iter iter0 = cc0.first; mu_cc_iter iend0 = cc0.second; mu_cc_iter iter1 = cc1.first; mu_cc_iter iend1 = cc1.second; - while ( ( iter0 != iend0 ) && ( pVtx == nullptr ) ) { + while ((iter0 != iend0) && (pVtx == nullptr)) { const pat::CompositeCandidate* ccp = iter0++->second; - while ( iter1 != iend1 ) { - if ( ccp != iter1++->second ) continue; - pVtx = ccp->userData( "PVwithmuons" ); + while (iter1 != iend1) { + if (ccp != iter1++->second) + continue; + pVtx = ccp->userData("PVwithmuons"); const reco::Vertex* sVtx = nullptr; const reco::Vertex::Point& pPos = pVtx->position(); float dMin = 999999.; int ipv; - for ( ipv = 0; ipv < npv; ++ipv ) { - const reco::Vertex* tVtx = &pVertices->at( ipv ); + for (ipv = 0; ipv < npv; ++ipv) { + const reco::Vertex* tVtx = &pVertices->at(ipv); const reco::Vertex::Point& tPos = tVtx->position(); - float dist = pow( pPos.x() - tPos.x(), 2 ) + - pow( pPos.y() - tPos.y(), 2 ) + - pow( pPos.z() - tPos.z(), 2 ); - if ( dist < dMin ) { - dMin = dist; + float dist = pow(pPos.x() - tPos.x(), 2) + pow(pPos.y() - tPos.y(), 2) + pow(pPos.z() - tPos.z(), 2); + if (dist < dMin) { + dMin = dist; sVtx = tVtx; pvId = ipv; } @@ -415,28 +438,26 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, } } - // if not found, as ofr other type of inut data, + // if not found, as ofr other type of inut data, // try to get the nearest primary vertex in z direction - if ( pVtx == nullptr ) { + if (pVtx == nullptr) { const reco::Vertex::Point& sVtp = ptr->vertex().position(); - GlobalPoint cPos( sVtp.x(), sVtp.y(), sVtp.z() ); + GlobalPoint cPos(sVtp.x(), sVtp.y(), sVtp.z()); const pat::CompositeCandidate& sCC = ptr->composite(); - GlobalVector cDir( sCC.px(), sCC.py(), sCC.pz() ); - GlobalPoint bPos( 0.0, 0.0, 0.0 ); - GlobalVector bDir( 0.0, 0.0, 1.0 ); + GlobalVector cDir(sCC.px(), sCC.py(), sCC.pz()); + GlobalPoint bPos(0.0, 0.0, 0.0); + GlobalVector bDir(0.0, 0.0, 1.0); TwoTrackMinimumDistance ttmd; - bool state = ttmd.calculate( GlobalTrajectoryParameters( cPos, cDir, - TrackCharge( 0 ), &( *magneticField ) ), - GlobalTrajectoryParameters( bPos, bDir, - TrackCharge( 0 ), &( *magneticField ) ) ); + bool state = ttmd.calculate(GlobalTrajectoryParameters(cPos, cDir, TrackCharge(0), &(*magneticField)), + GlobalTrajectoryParameters(bPos, bDir, TrackCharge(0), &(*magneticField))); float minDz = 999999.; - float extrapZ = ( state ? ttmd.points().first.z() : -9e20 ); + float extrapZ = (state ? ttmd.points().first.z() : -9e20); int ipv; - for ( ipv = 0; ipv < npv; ++ipv ) { - const reco::Vertex& tVtx = pVertices->at( ipv ); - float deltaZ = fabs( extrapZ - tVtx.position().z() ) ; - if ( deltaZ < minDz ) { - minDz = deltaZ; + for (ipv = 0; ipv < npv; ++ipv) { + const reco::Vertex& tVtx = pVertices->at(ipv); + float deltaZ = fabs(extrapZ - tVtx.position().z()); + if (deltaZ < minDz) { + minDz = deltaZ; pVtx = &tVtx; pvId = ipv; } @@ -444,33 +465,33 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, } oniaVtxMap[ptr] = pVtx; - pvRefMap[ptr] = vertex_ref( pVertices, pvId ); - + pvRefMap[ptr] = vertex_ref(pVertices, pvId); } - pVertexToken.get( ev, pVertices ); + pVertexToken.get(ev, pVertices); - // get JPsi subsample and associate JPsi candidate to original + // get JPsi subsample and associate JPsi candidate to original // generic onia candidate - if ( nFull ) lJPsi = onia->getList( BPHOniaToMuMuBuilder::Psi1 ); + if (nFull) + lJPsi = onia->getList(BPHOniaToMuMuBuilder::Psi1); int nJPsi = lJPsi.size(); delete onia; - if ( !nJPsi ) return; - if ( !nrc ) return; + if (!nJPsi) + return; + if (!nrc) + return; int ij; int io; int nj = lJPsi.size(); int no = lFull.size(); - for ( ij = 0; ij < nj; ++ij ) { + for (ij = 0; ij < nj; ++ij) { const BPHRecoCandidate* jp = lJPsi[ij].get(); - for ( io = 0; io < no; ++io ) { + for (io = 0; io < no; ++io) { const BPHRecoCandidate* oc = lFull[io].get(); - if ( ( jp->originalReco( jp->getDaug( "MuPos" ) ) == - oc->originalReco( oc->getDaug( "MuPos" ) ) ) && - ( jp->originalReco( jp->getDaug( "MuNeg" ) ) == - oc->originalReco( oc->getDaug( "MuNeg" ) ) ) ) { + if ((jp->originalReco(jp->getDaug("MuPos")) == oc->originalReco(oc->getDaug("MuPos"))) && + (jp->originalReco(jp->getDaug("MuNeg")) == oc->originalReco(oc->getDaug("MuNeg")))) { jPsiOMap[jp] = oc; break; } @@ -480,40 +501,61 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, // build and dump Bu BPHBuToJPsiKBuilder* bu = nullptr; - if ( recoBu ) { - if ( usePF ) bu = new BPHBuToJPsiKBuilder( es, lJPsi, - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) bu = new BPHBuToJPsiKBuilder( es, lJPsi, - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) bu = new BPHBuToJPsiKBuilder( es, lJPsi, - BPHRecoBuilder::createCollection( gpCands ) ); + if (recoBu) { + if (usePF) + bu = new BPHBuToJPsiKBuilder(es, lJPsi, BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + bu = new BPHBuToJPsiKBuilder(es, lJPsi, BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + bu = new BPHBuToJPsiKBuilder(es, lJPsi, BPHRecoBuilder::createCollection(gpCands)); } - if ( bu != nullptr ) { - rIter = parMap.find( Bu ); - if ( rIter != rIend ) { - const map& pMap = rIter->second; - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + if (bu != nullptr) { + rIter = parMap.find(Bu); + if (rIter != rIend) { + const map& pMap = rIter->second; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case ptMin : bu->setKPtMin ( pv ); break; - case etaMax : bu->setKEtaMax ( pv ); break; - case mPsiMin : bu->setJPsiMassMin( pv ); break; - case mPsiMax : bu->setJPsiMassMax( pv ); break; - case massMin : bu->setMassMin ( pv ); break; - case massMax : bu->setMassMax ( pv ); break; - case probMin : bu->setProbMin ( pv ); break; - case mFitMin : bu->setMassFitMin ( pv ); break; - case mFitMax : bu->setMassFitMax ( pv ); break; - case constrMJPsi: bu->setConstr ( pv > 0 ); break; - case writeCandidate: writeBu = ( pv > 0 ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case ptMin: + bu->setKPtMin(pv); + break; + case etaMax: + bu->setKEtaMax(pv); + break; + case mPsiMin: + bu->setJPsiMassMin(pv); + break; + case mPsiMax: + bu->setJPsiMassMax(pv); + break; + case massMin: + bu->setMassMin(pv); + break; + case massMax: + bu->setMassMax(pv); + break; + case probMin: + bu->setProbMin(pv); + break; + case mFitMin: + bu->setMassFitMin(pv); + break; + case mFitMax: + bu->setMassFitMax(pv); + break; + case constrMJPsi: + bu->setConstr(pv > 0); + break; + case writeCandidate: + writeBu = (pv > 0); + break; + default: + break; } } } @@ -525,40 +567,55 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, vector lKx0; BPHKx0ToKPiBuilder* kx0 = nullptr; - if ( recoKx0 ) { - if ( usePF ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( pfCands ), - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( pcCands ), - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( gpCands ), - BPHRecoBuilder::createCollection( gpCands ) ); + if (recoKx0) { + if (usePF) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(pfCands), BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(pcCands), BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(gpCands), BPHRecoBuilder::createCollection(gpCands)); } - if ( kx0 != nullptr ) { - rIter = parMap.find( Kx0 ); - if ( rIter != rIend ) { - const map& pMap = rIter->second; - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + if (kx0 != nullptr) { + rIter = parMap.find(Kx0); + if (rIter != rIend) { + const map& pMap = rIter->second; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case ptMin : kx0->setPtMin ( pv ); break; - case etaMax : kx0->setEtaMax ( pv ); break; - case massMin : kx0->setMassMin( pv ); break; - case massMax : kx0->setMassMax( pv ); break; - case probMin : kx0->setProbMin( pv ); break; - case constrMass : kx0->setConstr ( pv, kx0->getConstrSigma() ); break; - case constrSigma: kx0->setConstr ( kx0->getConstrMass() , pv ); break; - case writeCandidate: writeKx0 = ( pv > 0 ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case ptMin: + kx0->setPtMin(pv); + break; + case etaMax: + kx0->setEtaMax(pv); + break; + case massMin: + kx0->setMassMin(pv); + break; + case massMax: + kx0->setMassMax(pv); + break; + case probMin: + kx0->setProbMin(pv); + break; + case constrMass: + kx0->setConstr(pv, kx0->getConstrSigma()); + break; + case constrSigma: + kx0->setConstr(kx0->getConstrMass(), pv); + break; + case writeCandidate: + writeKx0 = (pv > 0); + break; + default: + break; } } } @@ -570,31 +627,53 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, // build and dump Bd - if ( recoBd && nKx0 ) { - - BPHBdToJPsiKxBuilder* bd = new BPHBdToJPsiKxBuilder( es, lJPsi, lKx0 ); - rIter = parMap.find( Bd ); - if ( rIter != rIend ) { - const map& pMap = rIter->second; - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + if (recoBd && nKx0) { + BPHBdToJPsiKxBuilder* bd = new BPHBdToJPsiKxBuilder(es, lJPsi, lKx0); + rIter = parMap.find(Bd); + if (rIter != rIend) { + const map& pMap = rIter->second; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case mPsiMin : bd->setJPsiMassMin( pv ); break; - case mPsiMax : bd->setJPsiMassMax( pv ); break; - case mKx0Min : bd->setKxMassMin ( pv ); break; - case mKx0Max : bd->setKxMassMax ( pv ); break; - case massMin : bd->setMassMin ( pv ); break; - case massMax : bd->setMassMax ( pv ); break; - case probMin : bd->setProbMin ( pv ); break; - case mFitMin : bd->setMassFitMin ( pv ); break; - case mFitMax : bd->setMassFitMax ( pv ); break; - case constrMJPsi: bd->setConstr ( pv > 0 ); break; - case writeCandidate: writeBd = ( pv > 0 ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case mPsiMin: + bd->setJPsiMassMin(pv); + break; + case mPsiMax: + bd->setJPsiMassMax(pv); + break; + case mKx0Min: + bd->setKxMassMin(pv); + break; + case mKx0Max: + bd->setKxMassMax(pv); + break; + case massMin: + bd->setMassMin(pv); + break; + case massMax: + bd->setMassMax(pv); + break; + case probMin: + bd->setProbMin(pv); + break; + case mFitMin: + bd->setMassFitMin(pv); + break; + case mFitMax: + bd->setMassFitMax(pv); + break; + case constrMJPsi: + bd->setConstr(pv > 0); + break; + case writeCandidate: + writeBd = (pv > 0); + break; + default: + break; } } } @@ -605,51 +684,67 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, set sKx0; int iBd; int nBd = lBd.size(); - for ( iBd = 0; iBd < nBd; ++iBd ) sKx0.insert( lBd[iBd]->getComp( "Kx0" ) ); + for (iBd = 0; iBd < nBd; ++iBd) + sKx0.insert(lBd[iBd]->getComp("Kx0")); set::const_iterator iter = sKx0.begin(); set::const_iterator iend = sKx0.end(); - while ( iter != iend ) lSd.push_back( *iter++ ); - + while (iter != iend) + lSd.push_back(*iter++); } // build and dump Phi vector lPhi; BPHPhiToKKBuilder* phi = nullptr; - if ( recoPkk ) { - if ( usePF ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( pfCands ), - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( pcCands ), - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( gpCands ), - BPHRecoBuilder::createCollection( gpCands ) ); + if (recoPkk) { + if (usePF) + phi = new BPHPhiToKKBuilder( + es, BPHRecoBuilder::createCollection(pfCands), BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + phi = new BPHPhiToKKBuilder( + es, BPHRecoBuilder::createCollection(pcCands), BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + phi = new BPHPhiToKKBuilder( + es, BPHRecoBuilder::createCollection(gpCands), BPHRecoBuilder::createCollection(gpCands)); } - if ( phi != nullptr ) { - rIter = parMap.find( Pkk ); - if ( rIter != rIend ) { - const map& pMap = rIter->second; - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + if (phi != nullptr) { + rIter = parMap.find(Pkk); + if (rIter != rIend) { + const map& pMap = rIter->second; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case ptMin : phi->setPtMin ( pv ); break; - case etaMax : phi->setEtaMax ( pv ); break; - case massMin : phi->setMassMin( pv ); break; - case massMax : phi->setMassMax( pv ); break; - case probMin : phi->setProbMin( pv ); break; - case constrMass : phi->setConstr ( pv, phi->getConstrSigma() ); break; - case constrSigma: phi->setConstr ( phi->getConstrMass() , pv ); break; - case writeCandidate: writePkk = ( pv > 0 ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case ptMin: + phi->setPtMin(pv); + break; + case etaMax: + phi->setEtaMax(pv); + break; + case massMin: + phi->setMassMin(pv); + break; + case massMax: + phi->setMassMax(pv); + break; + case probMin: + phi->setProbMin(pv); + break; + case constrMass: + phi->setConstr(pv, phi->getConstrSigma()); + break; + case constrSigma: + phi->setConstr(phi->getConstrMass(), pv); + break; + case writeCandidate: + writePkk = (pv > 0); + break; + default: + break; } } } @@ -661,31 +756,53 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, // build and dump Bs - if ( recoBs && nPhi ) { - - BPHBsToJPsiPhiBuilder* bs = new BPHBsToJPsiPhiBuilder( es, lJPsi, lPhi ); - rIter = parMap.find( Bs ); - if ( rIter != rIend ) { - const map& pMap = rIter->second; - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& pEntry = *pIter++; + if (recoBs && nPhi) { + BPHBsToJPsiPhiBuilder* bs = new BPHBsToJPsiPhiBuilder(es, lJPsi, lPhi); + rIter = parMap.find(Bs); + if (rIter != rIend) { + const map& pMap = rIter->second; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& pEntry = *pIter++; parType id = pEntry.first; - double pv = pEntry.second; - switch( id ) { - case mPsiMin : bs->setJPsiMassMin( pv ); break; - case mPsiMax : bs->setJPsiMassMax( pv ); break; - case mPhiMin : bs->setPhiMassMin ( pv ); break; - case mPhiMax : bs->setPhiMassMax ( pv ); break; - case massMin : bs->setMassMin ( pv ); break; - case massMax : bs->setMassMax ( pv ); break; - case probMin : bs->setProbMin ( pv ); break; - case mFitMin : bs->setMassFitMin ( pv ); break; - case mFitMax : bs->setMassFitMax ( pv ); break; - case constrMJPsi: bs->setConstr ( pv > 0 ); break; - case writeCandidate: writeBs = ( pv > 0 ); break; - default: break; + double pv = pEntry.second; + switch (id) { + case mPsiMin: + bs->setJPsiMassMin(pv); + break; + case mPsiMax: + bs->setJPsiMassMax(pv); + break; + case mPhiMin: + bs->setPhiMassMin(pv); + break; + case mPhiMax: + bs->setPhiMassMax(pv); + break; + case massMin: + bs->setMassMin(pv); + break; + case massMax: + bs->setMassMax(pv); + break; + case probMin: + bs->setProbMin(pv); + break; + case mFitMin: + bs->setMassFitMin(pv); + break; + case mFitMax: + bs->setMassFitMax(pv); + break; + case constrMJPsi: + bs->setConstr(pv > 0); + break; + case writeCandidate: + writeBs = (pv > 0); + break; + default: + break; } } } @@ -696,71 +813,81 @@ void BPHWriteSpecificDecay::fill( edm::Event& ev, set sPhi; int iBs; int nBs = lBs.size(); - for ( iBs = 0; iBs < nBs; ++iBs ) sPhi.insert( lBs[iBs]->getComp( "Phi" ) ); + for (iBs = 0; iBs < nBs; ++iBs) + sPhi.insert(lBs[iBs]->getComp("Phi")); set::const_iterator iter = sPhi.begin(); set::const_iterator iend = sPhi.end(); - while ( iter != iend ) lSs.push_back( *iter++ ); - + while (iter != iend) + lSs.push_back(*iter++); } return; - -} - - -void BPHWriteSpecificDecay::endJob() { - return; } - -void BPHWriteSpecificDecay::setRecoParameters( const edm::ParameterSet& ps ) { - - const string& name = ps.getParameter( "name" ); - bool writeCandidate = ps.getParameter( "writeCandidate" ); - switch( rMap[name] ) { - case Onia: recoOnia = true; writeOnia = writeCandidate; break; - case Pmm: - case Psi1: - case Psi2: - case Ups: - case Ups1: - case Ups2: - case Ups3: recoOnia = true; break; - case Kx0 : recoKx0 = true; writeKx0 = writeCandidate; break; - case Pkk : recoPkk = true; writePkk = writeCandidate; break; - case Bu : recoBu = true; writeBu = writeCandidate; break; - case Bd : recoBd = true; writeBd = writeCandidate; break; - case Bs : recoBs = true; writeBs = writeCandidate; break; +void BPHWriteSpecificDecay::endJob() { return; } + +void BPHWriteSpecificDecay::setRecoParameters(const edm::ParameterSet& ps) { + const string& name = ps.getParameter("name"); + bool writeCandidate = ps.getParameter("writeCandidate"); + switch (rMap[name]) { + case Onia: + recoOnia = true; + writeOnia = writeCandidate; + break; + case Pmm: + case Psi1: + case Psi2: + case Ups: + case Ups1: + case Ups2: + case Ups3: + recoOnia = true; + break; + case Kx0: + recoKx0 = true; + writeKx0 = writeCandidate; + break; + case Pkk: + recoPkk = true; + writePkk = writeCandidate; + break; + case Bu: + recoBu = true; + writeBu = writeCandidate; + break; + case Bd: + recoBd = true; + writeBd = writeCandidate; + break; + case Bs: + recoBs = true; + writeBs = writeCandidate; + break; } - map::const_iterator pIter = pMap.begin(); - map::const_iterator pIend = pMap.end(); - while ( pIter != pIend ) { - const map::value_type& entry = *pIter++; + map::const_iterator pIter = pMap.begin(); + map::const_iterator pIend = pMap.end(); + while (pIter != pIend) { + const map::value_type& entry = *pIter++; const string& pn = entry.first; - parType id = entry.second; - double pv = ps.getParameter( pn ); - if ( pv > -1.0e35 ) edm::LogVerbatim( "Configuration" ) - << "BPHWriteSpecificDecay::setRecoParameters: set " << pn - << " for " << name << " : " - << ( parMap[rMap[name]][id] = pv ); + parType id = entry.second; + double pv = ps.getParameter(pn); + if (pv > -1.0e35) + edm::LogVerbatim("Configuration") << "BPHWriteSpecificDecay::setRecoParameters: set " << pn << " for " << name + << " : " << (parMap[rMap[name]][id] = pv); } - map::const_iterator fIter = fMap.begin(); - map::const_iterator fIend = fMap.end(); - while ( fIter != fIend ) { - const map::value_type& entry = *fIter++; + map::const_iterator fIter = fMap.begin(); + map::const_iterator fIend = fMap.end(); + while (fIter != fIend) { + const map::value_type& entry = *fIter++; const string& fn = entry.first; - parType id = entry.second; - edm::LogVerbatim( "Configuration" ) - << "BPHWriteSpecificDecay::setRecoParameters: set " << fn - << " for " << name << " : " - << ( parMap[rMap[name]][id] = - ( ps.getParameter( fn ) ? 1 : -1 ) ); + parType id = entry.second; + edm::LogVerbatim("Configuration") << "BPHWriteSpecificDecay::setRecoParameters: set " << fn << " for " << name + << " : " << (parMap[rMap[name]][id] = (ps.getParameter(fn) ? 1 : -1)); } - } #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( BPHWriteSpecificDecay ); +DEFINE_FWK_MODULE(BPHWriteSpecificDecay); diff --git a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.h b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.h index c358029c70950..d3bc8d79a5036 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.h +++ b/HeavyFlavorAnalysis/SpecificDecay/plugins/BPHWriteSpecificDecay.h @@ -30,23 +30,19 @@ class TH1F; class BPHRecoCandidate; -class BPHWriteSpecificDecay: - public BPHAnalyzerWrapper { - - public: - - explicit BPHWriteSpecificDecay( const edm::ParameterSet& ps ); +class BPHWriteSpecificDecay : public BPHAnalyzerWrapper { +public: + explicit BPHWriteSpecificDecay(const edm::ParameterSet& ps); ~BPHWriteSpecificDecay() override; - static void fillDescriptions( edm::ConfigurationDescriptions& descriptions ); + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); void beginJob() override; - void produce( edm::Event& ev, const edm::EventSetup& es ) override; - virtual void fill( edm::Event& ev, const edm::EventSetup& es ); + void produce(edm::Event& ev, const edm::EventSetup& es) override; + virtual void fill(edm::Event& ev, const edm::EventSetup& es); void endJob() override; - private: - +private: std::string pVertexLabel; std::string patMuonLabel; std::string ccCandsLabel; @@ -55,12 +51,12 @@ class BPHWriteSpecificDecay: std::string gpCandsLabel; // token wrappers to allow running both on "old" and "new" CMSSW versions - BPHTokenWrapper< std::vector > pVertexToken; - BPHTokenWrapper< pat::MuonCollection > patMuonToken; - BPHTokenWrapper< std::vector > ccCandsToken; - BPHTokenWrapper< std::vector > pfCandsToken; - BPHTokenWrapper< std::vector > pcCandsToken; - BPHTokenWrapper< std::vector > gpCandsToken; + BPHTokenWrapper > pVertexToken; + BPHTokenWrapper patMuonToken; + BPHTokenWrapper > ccCandsToken; + BPHTokenWrapper > pfCandsToken; + BPHTokenWrapper > pcCandsToken; + BPHTokenWrapper > gpCandsToken; bool usePV; bool usePM; @@ -70,22 +66,36 @@ class BPHWriteSpecificDecay: bool useGP; std::string oniaName; - std::string sdName; - std::string ssName; - std::string buName; - std::string bdName; - std::string bsName; - - enum recoType { Onia, Pmm , Psi1, Psi2, Ups , Ups1, Ups2, Ups3, - Kx0, Pkk, Bu, Bd, Bs }; - enum parType { ptMin, etaMax, - mPsiMin, mPsiMax, mKx0Min, mKx0Max, mPhiMin, mPhiMax, - massMin, massMax, probMin, mFitMin, mFitMax, - constrMass, constrSigma, constrMJPsi, writeCandidate }; - std::map rMap; + std::string sdName; + std::string ssName; + std::string buName; + std::string bdName; + std::string bsName; + + enum recoType { Onia, Pmm, Psi1, Psi2, Ups, Ups1, Ups2, Ups3, Kx0, Pkk, Bu, Bd, Bs }; + enum parType { + ptMin, + etaMax, + mPsiMin, + mPsiMax, + mKx0Min, + mKx0Max, + mPhiMin, + mPhiMax, + massMin, + massMax, + probMin, + mFitMin, + mFitMax, + constrMass, + constrSigma, + constrMJPsi, + writeCandidate + }; + std::map rMap; std::map pMap; std::map fMap; - std::map< recoType, std::map > parMap; + std::map > parMap; bool recoOnia; bool recoKx0; @@ -112,82 +122,78 @@ class BPHWriteSpecificDecay: std::vector lBd; std::vector lBs; - std::map jPsiOMap; - typedef edm::Ref< std::vector > vertex_ref; - std::map pvRefMap; - typedef edm::Ref< pat::CompositeCandidateCollection > compcc_ref; - std::map ccRefMap; + std::map jPsiOMap; + typedef edm::Ref > vertex_ref; + std::map pvRefMap; + typedef edm::Ref compcc_ref; + std::map ccRefMap; - void setRecoParameters( const edm::ParameterSet& ps ); + void setRecoParameters(const edm::ParameterSet& ps); template - edm::OrphanHandle write( edm::Event& ev, - const std::vector& list, const std::string& name ) { - pat::CompositeCandidateCollection* ccList = - new pat::CompositeCandidateCollection; + edm::OrphanHandle write(edm::Event& ev, + const std::vector& list, + const std::string& name) { + pat::CompositeCandidateCollection* ccList = new pat::CompositeCandidateCollection; int i; int n = list.size(); - std::map::const_iterator jpoIter; - std::map::const_iterator jpoIend = jPsiOMap.end(); - std::map::const_iterator pvrIter; - std::map::const_iterator pvrIend = - pvRefMap.end(); - std::map::const_iterator ccrIter; - std::map::const_iterator ccrIend = - ccRefMap.end(); - for ( i = 0; i < n; ++i ) { + std::map::const_iterator jpoIter; + std::map::const_iterator jpoIend = jPsiOMap.end(); + std::map::const_iterator pvrIter; + std::map::const_iterator pvrIend = pvRefMap.end(); + std::map::const_iterator ccrIter; + std::map::const_iterator ccrIend = ccRefMap.end(); + for (i = 0; i < n; ++i) { const T& ptr = list[i]; - ccList->push_back( ptr->composite() ); + ccList->push_back(ptr->composite()); pat::CompositeCandidate& cc = ccList->back(); - if ( ( pvrIter = pvRefMap.find( ptr.get() ) ) != pvrIend ) - cc.addUserData ( "primaryVertex", pvrIter->second ); + if ((pvrIter = pvRefMap.find(ptr.get())) != pvrIend) + cc.addUserData("primaryVertex", pvrIter->second); const std::vector& cNames = ptr->compNames(); int j = 0; int m = cNames.size(); - while ( j < m ) { + while (j < m) { const std::string& compName = cNames[j++]; - const BPHRecoCandidate* cptr = ptr->getComp( compName ).get(); - if ( ( ccrIter = ccRefMap.find( cptr ) ) == ccrIend ) { - if ( ( jpoIter = jPsiOMap.find( cptr ) ) != jpoIend ) - cptr = jpoIter->second; - else cptr = nullptr; + const BPHRecoCandidate* cptr = ptr->getComp(compName).get(); + if ((ccrIter = ccRefMap.find(cptr)) == ccrIend) { + if ((jpoIter = jPsiOMap.find(cptr)) != jpoIend) + cptr = jpoIter->second; + else + cptr = nullptr; } - if ( ( ccrIter = ccRefMap.find( cptr ) ) != ccrIend ) { + if ((ccrIter = ccRefMap.find(cptr)) != ccrIend) { compcc_ref cref = ccrIter->second; - if ( cref.isNonnull() ) cc.addUserData ( "refTo" + compName, cref ); + if (cref.isNonnull()) + cc.addUserData("refTo" + compName, cref); } } - const BPHPlusMinusCandidate* pmp = - dynamic_cast( ptr.get() ); - if ( pmp != nullptr ) cc.addUserData( "cowboy", pmp->isCowboy() ); - if ( ptr->isEmpty() ) { - if ( writeVertex ) cc.addUserData( "vertex" , ptr->vertex() ); + const BPHPlusMinusCandidate* pmp = dynamic_cast(ptr.get()); + if (pmp != nullptr) + cc.addUserData("cowboy", pmp->isCowboy()); + if (ptr->isEmpty()) { + if (writeVertex) + cc.addUserData("vertex", ptr->vertex()); continue; } - if ( writeVertex ) cc.addUserData( "fitVertex", - reco::Vertex( *ptr->currentDecayVertex() ) ); - if ( ptr->isValidFit() ) { + if (writeVertex) + cc.addUserData("fitVertex", reco::Vertex(*ptr->currentDecayVertex())); + if (ptr->isValidFit()) { const RefCountedKinematicParticle kinPart = ptr->currentParticle(); - const KinematicState kinStat = kinPart->currentState(); - cc.addUserFloat( "fitMass", kinStat.mass() ); - if ( writeMomentum ) cc.addUserData ( "fitMomentum", - kinStat.kinematicParameters().momentum() ); + const KinematicState kinStat = kinPart->currentState(); + cc.addUserFloat("fitMass", kinStat.mass()); + if (writeMomentum) + cc.addUserData("fitMomentum", kinStat.kinematicParameters().momentum()); } - } typedef std::unique_ptr ccc_pointer; - edm::OrphanHandle ccHandle = - ev.put( ccc_pointer( ccList ), name ); - for ( i = 0; i < n; ++i ) { + edm::OrphanHandle ccHandle = ev.put(ccc_pointer(ccList), name); + for (i = 0; i < n; ++i) { const BPHRecoCandidate* ptr = list[i].get(); - edm::Ref ccRef( ccHandle, i ); + edm::Ref ccRef(ccHandle, i); ccRefMap[ptr] = ccRef; } return ccHandle; } - }; #endif diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToJPsiKxBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToJPsiKxBuilder.cc index ab0c5a13ca3a0..f9bf7fec1070e 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToJPsiKxBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBdToJPsiKxBuilder.cc @@ -30,26 +30,18 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHBdToJPsiKxBuilder::BPHBdToJPsiKxBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const std::vector& kx0Collection ): - jPsiName( "JPsi" ), - kx0Name( "Kx0" ), - evSetup( &es ), - jCollection( &jpsiCollection ), - kCollection( & kx0Collection ) { - jpsiSel = new BPHMassSelect ( 2.80, 3.40 ); - mkx0Sel = new BPHMassSelect ( 0.80, 1.00 ); - massSel = new BPHMassSelect ( 3.50, 8.00 ); - chi2Sel = new BPHChi2Select ( 0.02 ); - mFitSel = new BPHMassFitSelect( jPsiName, - BPHParticleMasses::jPsiMass, - BPHParticleMasses::jPsiMWidth, - 5.00, 6.00 ); +BPHBdToJPsiKxBuilder::BPHBdToJPsiKxBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const std::vector& kx0Collection) + : jPsiName("JPsi"), kx0Name("Kx0"), evSetup(&es), jCollection(&jpsiCollection), kCollection(&kx0Collection) { + jpsiSel = new BPHMassSelect(2.80, 3.40); + mkx0Sel = new BPHMassSelect(0.80, 1.00); + massSel = new BPHMassSelect(3.50, 8.00); + chi2Sel = new BPHChi2Select(0.02); + mFitSel = new BPHMassFitSelect(jPsiName, BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth, 5.00, 6.00); massConstr = true; minPDiff = 1.0e-4; updated = false; @@ -70,161 +62,122 @@ BPHBdToJPsiKxBuilder::~BPHBdToJPsiKxBuilder() { // Operations -- //-------------- vector BPHBdToJPsiKxBuilder::build() { - - if ( updated ) return bdList; - - BPHRecoBuilder bBd( *evSetup ); - bBd.setMinPDiffererence( minPDiff ); - bBd.add( jPsiName, *jCollection ); - bBd.add( kx0Name, *kCollection ); - bBd.filter( jPsiName, *jpsiSel ); - bBd.filter( kx0Name, *mkx0Sel ); - - bBd.filter( *massSel ); - bBd.filter( *chi2Sel ); - if ( massConstr ) bBd.filter( *mFitSel ); - - bdList = BPHRecoCandidate::build( bBd ); -// -// Apply kinematic constraint on the JPsi mass. -// The operation is already performed when apply the mass selection, -// so it's not repeated. The following code is left as example -// for similar operations -// -// int iBd; -// int nBd = ( massConstr ? bdList.size() : 0 ); -// for ( iBd = 0; iBd < nBd; ++iBd ) { -// BPHRecoCandidate* cptr( const_cast( -// bdList[iBd].get() ) ); -// BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); -// double jMass = jpsi->constrMass(); -// if ( jMass < 0 ) continue; -// double sigma = jpsi->constrSigma(); -// cptr->kinematicTree( jPsiName, jMass, sigma ); -// } + if (updated) + return bdList; + + BPHRecoBuilder bBd(*evSetup); + bBd.setMinPDiffererence(minPDiff); + bBd.add(jPsiName, *jCollection); + bBd.add(kx0Name, *kCollection); + bBd.filter(jPsiName, *jpsiSel); + bBd.filter(kx0Name, *mkx0Sel); + + bBd.filter(*massSel); + bBd.filter(*chi2Sel); + if (massConstr) + bBd.filter(*mFitSel); + + bdList = BPHRecoCandidate::build(bBd); + // + // Apply kinematic constraint on the JPsi mass. + // The operation is already performed when apply the mass selection, + // so it's not repeated. The following code is left as example + // for similar operations + // + // int iBd; + // int nBd = ( massConstr ? bdList.size() : 0 ); + // for ( iBd = 0; iBd < nBd; ++iBd ) { + // BPHRecoCandidate* cptr( const_cast( + // bdList[iBd].get() ) ); + // BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); + // double jMass = jpsi->constrMass(); + // if ( jMass < 0 ) continue; + // double sigma = jpsi->constrSigma(); + // cptr->kinematicTree( jPsiName, jMass, sigma ); + // } updated = true; return bdList; - } /// set cuts -void BPHBdToJPsiKxBuilder::setJPsiMassMin( double m ) { +void BPHBdToJPsiKxBuilder::setJPsiMassMin(double m) { updated = false; - jpsiSel->setMassMin( m ); + jpsiSel->setMassMin(m); return; } - -void BPHBdToJPsiKxBuilder::setJPsiMassMax( double m ) { +void BPHBdToJPsiKxBuilder::setJPsiMassMax(double m) { updated = false; - jpsiSel->setMassMax( m ); + jpsiSel->setMassMax(m); return; } - -void BPHBdToJPsiKxBuilder::setKxMassMin( double m ) { +void BPHBdToJPsiKxBuilder::setKxMassMin(double m) { updated = false; - mkx0Sel->setMassMin( m ); + mkx0Sel->setMassMin(m); return; } - -void BPHBdToJPsiKxBuilder::setKxMassMax( double m ) { +void BPHBdToJPsiKxBuilder::setKxMassMax(double m) { updated = false; - mkx0Sel->setMassMax( m ); + mkx0Sel->setMassMax(m); return; } - -void BPHBdToJPsiKxBuilder::setMassMin( double m ) { +void BPHBdToJPsiKxBuilder::setMassMin(double m) { updated = false; - massSel->setMassMin( m ); + massSel->setMassMin(m); return; } - -void BPHBdToJPsiKxBuilder::setMassMax( double m ) { +void BPHBdToJPsiKxBuilder::setMassMax(double m) { updated = false; - massSel->setMassMax( m ); + massSel->setMassMax(m); return; } - -void BPHBdToJPsiKxBuilder::setProbMin( double p ) { +void BPHBdToJPsiKxBuilder::setProbMin(double p) { updated = false; - chi2Sel->setProbMin( p ); + chi2Sel->setProbMin(p); return; } - -void BPHBdToJPsiKxBuilder::setMassFitMin( double m ) { +void BPHBdToJPsiKxBuilder::setMassFitMin(double m) { updated = false; - mFitSel->setMassMin( m ); + mFitSel->setMassMin(m); return; } - -void BPHBdToJPsiKxBuilder::setMassFitMax( double m ) { +void BPHBdToJPsiKxBuilder::setMassFitMax(double m) { updated = false; - mFitSel->setMassMax( m ); + mFitSel->setMassMax(m); return; } - -void BPHBdToJPsiKxBuilder::setConstr( bool flag ) { +void BPHBdToJPsiKxBuilder::setConstr(bool flag) { updated = false; massConstr = flag; return; } /// get current cuts -double BPHBdToJPsiKxBuilder::getJPsiMassMin() const { - return jpsiSel->getMassMin(); -} - - -double BPHBdToJPsiKxBuilder::getJPsiMassMax() const { - return jpsiSel->getMassMax(); -} +double BPHBdToJPsiKxBuilder::getJPsiMassMin() const { return jpsiSel->getMassMin(); } +double BPHBdToJPsiKxBuilder::getJPsiMassMax() const { return jpsiSel->getMassMax(); } -double BPHBdToJPsiKxBuilder::getKxMassMin() const { - return mkx0Sel->getMassMin(); -} - - -double BPHBdToJPsiKxBuilder::getKxMassMax() const { - return mkx0Sel->getMassMax(); -} - - -double BPHBdToJPsiKxBuilder::getMassMin() const { - return massSel->getMassMin(); -} - +double BPHBdToJPsiKxBuilder::getKxMassMin() const { return mkx0Sel->getMassMin(); } -double BPHBdToJPsiKxBuilder::getMassMax() const { - return massSel->getMassMax(); -} - - -double BPHBdToJPsiKxBuilder::getProbMin() const { - return chi2Sel->getProbMin(); -} +double BPHBdToJPsiKxBuilder::getKxMassMax() const { return mkx0Sel->getMassMax(); } +double BPHBdToJPsiKxBuilder::getMassMin() const { return massSel->getMassMin(); } -double BPHBdToJPsiKxBuilder::getMassFitMin() const { - return mFitSel->getMassMin(); -} - +double BPHBdToJPsiKxBuilder::getMassMax() const { return massSel->getMassMax(); } -double BPHBdToJPsiKxBuilder::getMassFitMax() const { - return mFitSel->getMassMax(); -} +double BPHBdToJPsiKxBuilder::getProbMin() const { return chi2Sel->getProbMin(); } +double BPHBdToJPsiKxBuilder::getMassFitMin() const { return mFitSel->getMassMin(); } -bool BPHBdToJPsiKxBuilder::getConstr() const { - return massConstr; -} +double BPHBdToJPsiKxBuilder::getMassFitMax() const { return mFitSel->getMassMax(); } +bool BPHBdToJPsiKxBuilder::getConstr() const { return massConstr; } diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBsToJPsiPhiBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBsToJPsiPhiBuilder.cc index 8a05736f3b8be..1f146a3b6a0a0 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBsToJPsiPhiBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBsToJPsiPhiBuilder.cc @@ -30,26 +30,18 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHBsToJPsiPhiBuilder::BPHBsToJPsiPhiBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const std::vector& phiCollection ): - jPsiName( "JPsi" ), - phiName( "Phi" ), - evSetup( &es ), - jCollection( &jpsiCollection ), - pCollection( & phiCollection ) { - jpsiSel = new BPHMassSelect ( 2.80, 3.40 ); - mphiSel = new BPHMassSelect ( 1.005, 1.035 ); - massSel = new BPHMassSelect ( 3.50, 8.00 ); - chi2Sel = new BPHChi2Select ( 0.02 ); - mFitSel = new BPHMassFitSelect( jPsiName, - BPHParticleMasses::jPsiMass, - BPHParticleMasses::jPsiMWidth, - 5.00, 6.00 ); +BPHBsToJPsiPhiBuilder::BPHBsToJPsiPhiBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const std::vector& phiCollection) + : jPsiName("JPsi"), phiName("Phi"), evSetup(&es), jCollection(&jpsiCollection), pCollection(&phiCollection) { + jpsiSel = new BPHMassSelect(2.80, 3.40); + mphiSel = new BPHMassSelect(1.005, 1.035); + massSel = new BPHMassSelect(3.50, 8.00); + chi2Sel = new BPHChi2Select(0.02); + mFitSel = new BPHMassFitSelect(jPsiName, BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth, 5.00, 6.00); massConstr = true; minPDiff = 1.0e-4; updated = false; @@ -70,161 +62,122 @@ BPHBsToJPsiPhiBuilder::~BPHBsToJPsiPhiBuilder() { // Operations -- //-------------- vector BPHBsToJPsiPhiBuilder::build() { - - if ( updated ) return bsList; - - BPHRecoBuilder bBs( *evSetup ); - bBs.setMinPDiffererence( minPDiff ); - bBs.add( jPsiName, *jCollection ); - bBs.add( phiName, *pCollection ); - bBs.filter( jPsiName, *jpsiSel ); - bBs.filter( phiName, *mphiSel ); - - bBs.filter( *massSel ); - bBs.filter( *chi2Sel ); - if ( massConstr ) bBs.filter( *mFitSel ); - - bsList = BPHRecoCandidate::build( bBs ); -// -// Apply kinematic constraint on the JPsi mass. -// The operation is already performed when apply the mass selection, -// so it's not repeated. The following code is left as example -// for similar operations -// -// int iBs; -// int nBs = ( massConstr ? bsList.size() : 0 ); -// for ( iBs = 0; iBs < nBs; ++iBs ) { -// BPHRecoCandidate* cptr( const_cast( -// bsList[iBs].get() ) ); -// BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); -// double jMass = jpsi->constrMass(); -// if ( jMass < 0 ) continue; -// double sigma = jpsi->constrSigma(); -// cptr->kinematicTree( jPsiName, jMass, sigma ); -// } + if (updated) + return bsList; + + BPHRecoBuilder bBs(*evSetup); + bBs.setMinPDiffererence(minPDiff); + bBs.add(jPsiName, *jCollection); + bBs.add(phiName, *pCollection); + bBs.filter(jPsiName, *jpsiSel); + bBs.filter(phiName, *mphiSel); + + bBs.filter(*massSel); + bBs.filter(*chi2Sel); + if (massConstr) + bBs.filter(*mFitSel); + + bsList = BPHRecoCandidate::build(bBs); + // + // Apply kinematic constraint on the JPsi mass. + // The operation is already performed when apply the mass selection, + // so it's not repeated. The following code is left as example + // for similar operations + // + // int iBs; + // int nBs = ( massConstr ? bsList.size() : 0 ); + // for ( iBs = 0; iBs < nBs; ++iBs ) { + // BPHRecoCandidate* cptr( const_cast( + // bsList[iBs].get() ) ); + // BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); + // double jMass = jpsi->constrMass(); + // if ( jMass < 0 ) continue; + // double sigma = jpsi->constrSigma(); + // cptr->kinematicTree( jPsiName, jMass, sigma ); + // } updated = true; return bsList; - } /// set cuts -void BPHBsToJPsiPhiBuilder::setJPsiMassMin( double m ) { +void BPHBsToJPsiPhiBuilder::setJPsiMassMin(double m) { updated = false; - jpsiSel->setMassMin( m ); + jpsiSel->setMassMin(m); return; } - -void BPHBsToJPsiPhiBuilder::setJPsiMassMax( double m ) { +void BPHBsToJPsiPhiBuilder::setJPsiMassMax(double m) { updated = false; - jpsiSel->setMassMax( m ); + jpsiSel->setMassMax(m); return; } - -void BPHBsToJPsiPhiBuilder::setPhiMassMin( double m ) { +void BPHBsToJPsiPhiBuilder::setPhiMassMin(double m) { updated = false; - mphiSel->setMassMin( m ); + mphiSel->setMassMin(m); return; } - -void BPHBsToJPsiPhiBuilder::setPhiMassMax( double m ) { +void BPHBsToJPsiPhiBuilder::setPhiMassMax(double m) { updated = false; - mphiSel->setMassMax( m ); + mphiSel->setMassMax(m); return; } - -void BPHBsToJPsiPhiBuilder::setMassMin( double m ) { +void BPHBsToJPsiPhiBuilder::setMassMin(double m) { updated = false; - massSel->setMassMin( m ); + massSel->setMassMin(m); return; } - -void BPHBsToJPsiPhiBuilder::setMassMax( double m ) { +void BPHBsToJPsiPhiBuilder::setMassMax(double m) { updated = false; - massSel->setMassMax( m ); + massSel->setMassMax(m); return; } - -void BPHBsToJPsiPhiBuilder::setProbMin( double p ) { +void BPHBsToJPsiPhiBuilder::setProbMin(double p) { updated = false; - chi2Sel->setProbMin( p ); + chi2Sel->setProbMin(p); return; } - -void BPHBsToJPsiPhiBuilder::setMassFitMin( double m ) { +void BPHBsToJPsiPhiBuilder::setMassFitMin(double m) { updated = false; - mFitSel->setMassMin( m ); + mFitSel->setMassMin(m); return; } - -void BPHBsToJPsiPhiBuilder::setMassFitMax( double m ) { +void BPHBsToJPsiPhiBuilder::setMassFitMax(double m) { updated = false; - mFitSel->setMassMax( m ); + mFitSel->setMassMax(m); return; } - -void BPHBsToJPsiPhiBuilder::setConstr( bool flag ) { +void BPHBsToJPsiPhiBuilder::setConstr(bool flag) { updated = false; massConstr = flag; return; } /// get current cuts -double BPHBsToJPsiPhiBuilder::getJPsiMassMin() const { - return jpsiSel->getMassMin(); -} - - -double BPHBsToJPsiPhiBuilder::getJPsiMassMax() const { - return jpsiSel->getMassMax(); -} +double BPHBsToJPsiPhiBuilder::getJPsiMassMin() const { return jpsiSel->getMassMin(); } +double BPHBsToJPsiPhiBuilder::getJPsiMassMax() const { return jpsiSel->getMassMax(); } -double BPHBsToJPsiPhiBuilder::getPhiMassMin() const { - return mphiSel->getMassMin(); -} - - -double BPHBsToJPsiPhiBuilder::getPhiMassMax() const { - return mphiSel->getMassMax(); -} - - -double BPHBsToJPsiPhiBuilder::getMassMin() const { - return massSel->getMassMin(); -} - +double BPHBsToJPsiPhiBuilder::getPhiMassMin() const { return mphiSel->getMassMin(); } -double BPHBsToJPsiPhiBuilder::getMassMax() const { - return massSel->getMassMax(); -} - - -double BPHBsToJPsiPhiBuilder::getProbMin() const { - return chi2Sel->getProbMin(); -} +double BPHBsToJPsiPhiBuilder::getPhiMassMax() const { return mphiSel->getMassMax(); } +double BPHBsToJPsiPhiBuilder::getMassMin() const { return massSel->getMassMin(); } -double BPHBsToJPsiPhiBuilder::getMassFitMin() const { - return mFitSel->getMassMin(); -} - +double BPHBsToJPsiPhiBuilder::getMassMax() const { return massSel->getMassMax(); } -double BPHBsToJPsiPhiBuilder::getMassFitMax() const { - return mFitSel->getMassMax(); -} +double BPHBsToJPsiPhiBuilder::getProbMin() const { return chi2Sel->getProbMin(); } +double BPHBsToJPsiPhiBuilder::getMassFitMin() const { return mFitSel->getMassMin(); } -bool BPHBsToJPsiPhiBuilder::getConstr() const { - return massConstr; -} +double BPHBsToJPsiPhiBuilder::getMassFitMax() const { return mFitSel->getMassMax(); } +bool BPHBsToJPsiPhiBuilder::getConstr() const { return massConstr; } diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBuToJPsiKBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBuToJPsiKBuilder.cc index 7f25bc28adaf3..ab6eae652b248 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHBuToJPsiKBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHBuToJPsiKBuilder.cc @@ -33,28 +33,20 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHBuToJPsiKBuilder::BPHBuToJPsiKBuilder( const edm::EventSetup& es, - const std::vector& jpsiCollection, - const BPHRecoBuilder::BPHGenericCollection* kaonCollection ): - jPsiName( "JPsi" ), - kaonName( "Kaon" ), - evSetup( &es ), - jCollection( &jpsiCollection ), - kCollection( kaonCollection ) { - jpsiSel = new BPHMassSelect ( 2.80, 3.40 ); - knVeto = new BPHParticleNeutralVeto; - ptSel = new BPHParticlePtSelect ( 0.7 ); - etaSel = new BPHParticleEtaSelect( 10.0 ); - massSel = new BPHMassSelect ( 3.50, 8.00 ); - chi2Sel = new BPHChi2Select ( 0.02 ); - mFitSel = new BPHMassFitSelect ( jPsiName, - BPHParticleMasses::jPsiMass, - BPHParticleMasses::jPsiMWidth, - 5.00, 6.00 ); +BPHBuToJPsiKBuilder::BPHBuToJPsiKBuilder(const edm::EventSetup& es, + const std::vector& jpsiCollection, + const BPHRecoBuilder::BPHGenericCollection* kaonCollection) + : jPsiName("JPsi"), kaonName("Kaon"), evSetup(&es), jCollection(&jpsiCollection), kCollection(kaonCollection) { + jpsiSel = new BPHMassSelect(2.80, 3.40); + knVeto = new BPHParticleNeutralVeto; + ptSel = new BPHParticlePtSelect(0.7); + etaSel = new BPHParticleEtaSelect(10.0); + massSel = new BPHMassSelect(3.50, 8.00); + chi2Sel = new BPHChi2Select(0.02); + mFitSel = new BPHMassFitSelect(jPsiName, BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth, 5.00, 6.00); massConstr = true; minPDiff = 1.0e-4; updated = false; @@ -65,9 +57,9 @@ BPHBuToJPsiKBuilder::BPHBuToJPsiKBuilder( const edm::EventSetup& es, //-------------- BPHBuToJPsiKBuilder::~BPHBuToJPsiKBuilder() { delete jpsiSel; - delete knVeto; - delete ptSel; - delete etaSel; + delete knVeto; + delete ptSel; + delete etaSel; delete massSel; delete chi2Sel; delete mFitSel; @@ -77,163 +69,123 @@ BPHBuToJPsiKBuilder::~BPHBuToJPsiKBuilder() { // Operations -- //-------------- vector BPHBuToJPsiKBuilder::build() { - - if ( updated ) return buList; - - BPHRecoBuilder bBu( *evSetup ); - bBu.setMinPDiffererence( minPDiff ); - bBu.add( jPsiName, *jCollection ); - bBu.add( kaonName, kCollection, BPHParticleMasses::kaonMass, - BPHParticleMasses::kaonMSigma ); - bBu.filter( jPsiName, *jpsiSel ); - bBu.filter( kaonName, * knVeto ); - bBu.filter( kaonName, * ptSel ); - bBu.filter( kaonName, * etaSel ); - - bBu.filter( *massSel ); - bBu.filter( *chi2Sel ); - if ( massConstr ) bBu.filter( *mFitSel ); - - buList = BPHRecoCandidate::build( bBu ); -// -// Apply kinematic constraint on the JPsi mass. -// The operation is already performed when apply the mass selection, -// so it's not repeated. The following code is left as example -// for similar operations -// -// int iBu; -// int nBu = ( massConstr ? buList.size() : 0 ); -// for ( iBu = 0; iBu < nBu; ++iBu ) { -// BPHRecoCandidate* cptr( const_cast( -// buList[iBu].get() ) ); -// BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); -// double jMass = jpsi->constrMass(); -// if ( jMass < 0 ) continue; -// double sigma = jpsi->constrSigma(); -// cptr->kinematicTree( jPsiName, jMass, sigma ); -// } + if (updated) + return buList; + + BPHRecoBuilder bBu(*evSetup); + bBu.setMinPDiffererence(minPDiff); + bBu.add(jPsiName, *jCollection); + bBu.add(kaonName, kCollection, BPHParticleMasses::kaonMass, BPHParticleMasses::kaonMSigma); + bBu.filter(jPsiName, *jpsiSel); + bBu.filter(kaonName, *knVeto); + bBu.filter(kaonName, *ptSel); + bBu.filter(kaonName, *etaSel); + + bBu.filter(*massSel); + bBu.filter(*chi2Sel); + if (massConstr) + bBu.filter(*mFitSel); + + buList = BPHRecoCandidate::build(bBu); + // + // Apply kinematic constraint on the JPsi mass. + // The operation is already performed when apply the mass selection, + // so it's not repeated. The following code is left as example + // for similar operations + // + // int iBu; + // int nBu = ( massConstr ? buList.size() : 0 ); + // for ( iBu = 0; iBu < nBu; ++iBu ) { + // BPHRecoCandidate* cptr( const_cast( + // buList[iBu].get() ) ); + // BPHRecoConstCandPtr jpsi = cptr->getComp( jPsiName ); + // double jMass = jpsi->constrMass(); + // if ( jMass < 0 ) continue; + // double sigma = jpsi->constrSigma(); + // cptr->kinematicTree( jPsiName, jMass, sigma ); + // } updated = true; return buList; - } /// set cuts -void BPHBuToJPsiKBuilder::setJPsiMassMin( double m ) { +void BPHBuToJPsiKBuilder::setJPsiMassMin(double m) { updated = false; - jpsiSel->setMassMin( m ); + jpsiSel->setMassMin(m); return; } - -void BPHBuToJPsiKBuilder::setJPsiMassMax( double m ) { +void BPHBuToJPsiKBuilder::setJPsiMassMax(double m) { updated = false; - jpsiSel->setMassMax( m ); + jpsiSel->setMassMax(m); return; } - -void BPHBuToJPsiKBuilder::setKPtMin( double pt ) { +void BPHBuToJPsiKBuilder::setKPtMin(double pt) { updated = false; - ptSel->setPtMin( pt ); + ptSel->setPtMin(pt); return; } - -void BPHBuToJPsiKBuilder::setKEtaMax( double eta ) { +void BPHBuToJPsiKBuilder::setKEtaMax(double eta) { updated = false; - etaSel->setEtaMax( eta ); + etaSel->setEtaMax(eta); return; } - -void BPHBuToJPsiKBuilder::setMassMin( double m ) { +void BPHBuToJPsiKBuilder::setMassMin(double m) { updated = false; - massSel->setMassMin( m ); + massSel->setMassMin(m); return; } - -void BPHBuToJPsiKBuilder::setMassMax( double m ) { +void BPHBuToJPsiKBuilder::setMassMax(double m) { updated = false; - massSel->setMassMax( m ); + massSel->setMassMax(m); return; } - -void BPHBuToJPsiKBuilder::setProbMin( double p ) { +void BPHBuToJPsiKBuilder::setProbMin(double p) { updated = false; - chi2Sel->setProbMin( p ); + chi2Sel->setProbMin(p); return; } - -void BPHBuToJPsiKBuilder::setMassFitMin( double m ) { +void BPHBuToJPsiKBuilder::setMassFitMin(double m) { updated = false; - mFitSel->setMassMin( m ); + mFitSel->setMassMin(m); return; } - -void BPHBuToJPsiKBuilder::setMassFitMax( double m ) { +void BPHBuToJPsiKBuilder::setMassFitMax(double m) { updated = false; - mFitSel->setMassMax( m ); + mFitSel->setMassMax(m); return; } - -void BPHBuToJPsiKBuilder::setConstr( bool flag ) { +void BPHBuToJPsiKBuilder::setConstr(bool flag) { updated = false; massConstr = flag; return; } /// get current cuts -double BPHBuToJPsiKBuilder::getJPsiMassMin() const { - return jpsiSel->getMassMin(); -} - - -double BPHBuToJPsiKBuilder::getJPsiMassMax() const { - return jpsiSel->getMassMax(); -} +double BPHBuToJPsiKBuilder::getJPsiMassMin() const { return jpsiSel->getMassMin(); } +double BPHBuToJPsiKBuilder::getJPsiMassMax() const { return jpsiSel->getMassMax(); } -double BPHBuToJPsiKBuilder::getKPtMin() const { - return ptSel->getPtMin(); -} - - -double BPHBuToJPsiKBuilder::getKEtaMax() const { - return etaSel->getEtaMax(); -} - - -double BPHBuToJPsiKBuilder::getMassMin() const { - return massSel->getMassMin(); -} - +double BPHBuToJPsiKBuilder::getKPtMin() const { return ptSel->getPtMin(); } -double BPHBuToJPsiKBuilder::getMassMax() const { - return massSel->getMassMax(); -} - - -double BPHBuToJPsiKBuilder::getProbMin() const { - return chi2Sel->getProbMin(); -} +double BPHBuToJPsiKBuilder::getKEtaMax() const { return etaSel->getEtaMax(); } +double BPHBuToJPsiKBuilder::getMassMin() const { return massSel->getMassMin(); } -double BPHBuToJPsiKBuilder::getMassFitMin() const { - return mFitSel->getMassMin(); -} - +double BPHBuToJPsiKBuilder::getMassMax() const { return massSel->getMassMax(); } -double BPHBuToJPsiKBuilder::getMassFitMax() const { - return mFitSel->getMassMax(); -} +double BPHBuToJPsiKBuilder::getProbMin() const { return chi2Sel->getProbMin(); } +double BPHBuToJPsiKBuilder::getMassFitMin() const { return mFitSel->getMassMin(); } -bool BPHBuToJPsiKBuilder::getConstr() const { - return massConstr; -} +double BPHBuToJPsiKBuilder::getMassFitMax() const { return mFitSel->getMassMax(); } +bool BPHBuToJPsiKBuilder::getConstr() const { return massConstr; } diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHKx0ToKPiBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHKx0ToKPiBuilder.cc index 053a299687702..3298717d1ccd7 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHKx0ToKPiBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHKx0ToKPiBuilder.cc @@ -34,23 +34,17 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHKx0ToKPiBuilder::BPHKx0ToKPiBuilder( - const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* posCollection, - const BPHRecoBuilder::BPHGenericCollection* negCollection ): - kaonName( "Kaon" ), - pionName( "Pion" ), - evSetup( &es ), - pCollection( posCollection ), - nCollection( negCollection ) { - ptSel = new BPHParticlePtSelect ( 0.7 ); - etaSel = new BPHParticleEtaSelect( 10.0 ); - massSel = new BPHMassSelect( 0.75, 1.05 ); - chi2Sel = new BPHChi2Select( 0.0 ); +BPHKx0ToKPiBuilder::BPHKx0ToKPiBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* posCollection, + const BPHRecoBuilder::BPHGenericCollection* negCollection) + : kaonName("Kaon"), pionName("Pion"), evSetup(&es), pCollection(posCollection), nCollection(negCollection) { + ptSel = new BPHParticlePtSelect(0.7); + etaSel = new BPHParticleEtaSelect(10.0); + massSel = new BPHMassSelect(0.75, 1.05); + chi2Sel = new BPHChi2Select(0.0); updated = false; } @@ -58,8 +52,8 @@ BPHKx0ToKPiBuilder::BPHKx0ToKPiBuilder( // Destructor -- //-------------- BPHKx0ToKPiBuilder::~BPHKx0ToKPiBuilder() { - delete ptSel; - delete etaSel; + delete ptSel; + delete etaSel; delete massSel; delete chi2Sel; } @@ -68,128 +62,98 @@ BPHKx0ToKPiBuilder::~BPHKx0ToKPiBuilder() { // Operations -- //-------------- vector BPHKx0ToKPiBuilder::build() { + if (updated) + return kx0List; - if ( updated ) return kx0List; - - BPHRecoBuilder bKx0( *evSetup ); - bKx0.add( kaonName, pCollection, BPHParticleMasses::kaonMass, - BPHParticleMasses::kaonMSigma ); - bKx0.add( pionName, nCollection, BPHParticleMasses::pionMass, - BPHParticleMasses::pionMSigma ); - bKx0.filter( kaonName, *ptSel ); - bKx0.filter( pionName, *ptSel ); - bKx0.filter( kaonName, *etaSel ); - bKx0.filter( pionName, *etaSel ); - BPHMassSymSelect mTmpSel( kaonName, pionName, massSel ); - bKx0.filter( mTmpSel ); + BPHRecoBuilder bKx0(*evSetup); + bKx0.add(kaonName, pCollection, BPHParticleMasses::kaonMass, BPHParticleMasses::kaonMSigma); + bKx0.add(pionName, nCollection, BPHParticleMasses::pionMass, BPHParticleMasses::pionMSigma); + bKx0.filter(kaonName, *ptSel); + bKx0.filter(pionName, *ptSel); + bKx0.filter(kaonName, *etaSel); + bKx0.filter(pionName, *etaSel); + BPHMassSymSelect mTmpSel(kaonName, pionName, massSel); + bKx0.filter(mTmpSel); - vector - tmpList = BPHPlusMinusCandidate::build( bKx0, kaonName, pionName ); + vector tmpList = BPHPlusMinusCandidate::build(bKx0, kaonName, pionName); int ikx; int nkx = tmpList.size(); kx0List.clear(); - kx0List.reserve( nkx ); - BPHPlusMinusConstCandPtr pxt( nullptr ); - for ( ikx = 0; ikx < nkx; ++ikx ) { + kx0List.reserve(nkx); + BPHPlusMinusConstCandPtr pxt(nullptr); + for (ikx = 0; ikx < nkx; ++ikx) { BPHPlusMinusConstCandPtr& px0 = tmpList[ikx]; - BPHPlusMinusCandidatePtr pxb( new BPHPlusMinusCandidate( evSetup ) ); - const - BPHPlusMinusCandidate* kx0 = px0.get(); + BPHPlusMinusCandidatePtr pxb(new BPHPlusMinusCandidate(evSetup)); + const BPHPlusMinusCandidate* kx0 = px0.get(); BPHPlusMinusCandidate* kxb = pxb.get(); - kxb->add( pionName, kx0->originalReco( kx0->getDaug( kaonName ) ), - BPHParticleMasses::pionMass ); - kxb->add( kaonName, kx0->originalReco( kx0->getDaug( pionName ) ), - BPHParticleMasses::kaonMass ); - if ( fabs( kx0->composite().mass() - BPHParticleMasses::kx0Mass ) < - fabs( kxb->composite().mass() - BPHParticleMasses::kx0Mass ) ) - pxt = px0; - else pxt = pxb; - if ( !massSel->accept( *pxt ) ) continue; - if ( !chi2Sel->accept( *pxt ) ) continue; - kx0List.push_back( pxt ); + kxb->add(pionName, kx0->originalReco(kx0->getDaug(kaonName)), BPHParticleMasses::pionMass); + kxb->add(kaonName, kx0->originalReco(kx0->getDaug(pionName)), BPHParticleMasses::kaonMass); + if (fabs(kx0->composite().mass() - BPHParticleMasses::kx0Mass) < + fabs(kxb->composite().mass() - BPHParticleMasses::kx0Mass)) + pxt = px0; + else + pxt = pxb; + if (!massSel->accept(*pxt)) + continue; + if (!chi2Sel->accept(*pxt)) + continue; + kx0List.push_back(pxt); } updated = true; return kx0List; - } /// set cuts -void BPHKx0ToKPiBuilder::setPtMin( double pt ) { +void BPHKx0ToKPiBuilder::setPtMin(double pt) { updated = false; - ptSel->setPtMin( pt ); + ptSel->setPtMin(pt); return; } - -void BPHKx0ToKPiBuilder::setEtaMax( double eta ) { +void BPHKx0ToKPiBuilder::setEtaMax(double eta) { updated = false; - etaSel->setEtaMax( eta ); + etaSel->setEtaMax(eta); return; } - -void BPHKx0ToKPiBuilder::setMassMin( double m ) { +void BPHKx0ToKPiBuilder::setMassMin(double m) { updated = false; - massSel->setMassMin( m ); + massSel->setMassMin(m); return; } - -void BPHKx0ToKPiBuilder::setMassMax( double m ) { +void BPHKx0ToKPiBuilder::setMassMax(double m) { updated = false; - massSel->setMassMax( m ); + massSel->setMassMax(m); return; } - -void BPHKx0ToKPiBuilder::setProbMin( double p ) { +void BPHKx0ToKPiBuilder::setProbMin(double p) { updated = false; - chi2Sel->setProbMin( p ); + chi2Sel->setProbMin(p); return; } - -void BPHKx0ToKPiBuilder::setConstr( double mass, double sigma ) { +void BPHKx0ToKPiBuilder::setConstr(double mass, double sigma) { updated = false; - cMass = mass; + cMass = mass; cSigma = sigma; return; } /// get current cuts -double BPHKx0ToKPiBuilder::getPtMin() const { - return ptSel->getPtMin(); -} - - -double BPHKx0ToKPiBuilder::getEtaMax() const { - return etaSel->getEtaMax(); -} - - -double BPHKx0ToKPiBuilder::getMassMin() const { - return massSel->getMassMin(); -} +double BPHKx0ToKPiBuilder::getPtMin() const { return ptSel->getPtMin(); } +double BPHKx0ToKPiBuilder::getEtaMax() const { return etaSel->getEtaMax(); } -double BPHKx0ToKPiBuilder::getMassMax() const { - return massSel->getMassMax(); -} +double BPHKx0ToKPiBuilder::getMassMin() const { return massSel->getMassMin(); } +double BPHKx0ToKPiBuilder::getMassMax() const { return massSel->getMassMax(); } -double BPHKx0ToKPiBuilder::getProbMin() const { - return chi2Sel->getProbMin(); -} +double BPHKx0ToKPiBuilder::getProbMin() const { return chi2Sel->getProbMin(); } +double BPHKx0ToKPiBuilder::getConstrMass() const { return cMass; } -double BPHKx0ToKPiBuilder::getConstrMass() const { - return cMass; -} - - -double BPHKx0ToKPiBuilder::getConstrSigma() const { - return cSigma; -} - +double BPHKx0ToKPiBuilder::getConstrSigma() const { return cSigma; } diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHOniaToMuMuBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHOniaToMuMuBuilder.cc index bf869cb12df25..28356b73a4acd 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHOniaToMuMuBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHOniaToMuMuBuilder.cc @@ -32,33 +32,24 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHOniaToMuMuBuilder::BPHOniaToMuMuBuilder( - const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* muPosCollection, - const BPHRecoBuilder::BPHGenericCollection* muNegCollection ): - muPosName( "MuPos" ), - muNegName( "MuNeg" ), - evSetup( &es ), - posCollection( muPosCollection ), - negCollection( muNegCollection ) { - setParameters( Phi , 3.0, 10.0, 0.50, 1.50, 0.0, - BPHParticleMasses:: phiMass, BPHParticleMasses:: phiMWidth ); - setParameters( Psi1, 3.0, 10.0, 2.00, 3.40, 0.0, - BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth ); - setParameters( Psi2, 3.0, 10.0, 3.40, 6.00, 0.0, - BPHParticleMasses::psi2Mass, BPHParticleMasses::psi2MWidth ); - setParameters( Ups , 3.0, 10.0, 6.00, 12.00, 0.0, - -1.0 , 0.0 ); - setParameters( Ups1, 3.0, 10.0, 6.00, 9.75, 0.0, - BPHParticleMasses::ups1Mass, BPHParticleMasses::ups1MWidth ); - setParameters( Ups2, 3.0, 10.0, 9.75, 10.20, 0.0, - BPHParticleMasses::ups2Mass, BPHParticleMasses::ups2MWidth ); - setParameters( Ups3, 3.0, 10.0, 10.20, 12.00, 0.0, - BPHParticleMasses::ups3Mass, BPHParticleMasses::ups3MWidth ); +BPHOniaToMuMuBuilder::BPHOniaToMuMuBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* muPosCollection, + const BPHRecoBuilder::BPHGenericCollection* muNegCollection) + : muPosName("MuPos"), + muNegName("MuNeg"), + evSetup(&es), + posCollection(muPosCollection), + negCollection(muNegCollection) { + setParameters(Phi, 3.0, 10.0, 0.50, 1.50, 0.0, BPHParticleMasses::phiMass, BPHParticleMasses::phiMWidth); + setParameters(Psi1, 3.0, 10.0, 2.00, 3.40, 0.0, BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth); + setParameters(Psi2, 3.0, 10.0, 3.40, 6.00, 0.0, BPHParticleMasses::psi2Mass, BPHParticleMasses::psi2MWidth); + setParameters(Ups, 3.0, 10.0, 6.00, 12.00, 0.0, -1.0, 0.0); + setParameters(Ups1, 3.0, 10.0, 6.00, 9.75, 0.0, BPHParticleMasses::ups1Mass, BPHParticleMasses::ups1MWidth); + setParameters(Ups2, 3.0, 10.0, 9.75, 10.20, 0.0, BPHParticleMasses::ups2Mass, BPHParticleMasses::ups2MWidth); + setParameters(Ups3, 3.0, 10.0, 10.20, 12.00, 0.0, BPHParticleMasses::ups3Mass, BPHParticleMasses::ups3MWidth); updated = false; } @@ -66,12 +57,12 @@ BPHOniaToMuMuBuilder::BPHOniaToMuMuBuilder( // Destructor -- //-------------- BPHOniaToMuMuBuilder::~BPHOniaToMuMuBuilder() { - map< oniaType, OniaParameters >::iterator iter = oniaPar.begin(); - map< oniaType, OniaParameters >::iterator iend = oniaPar.end(); - while ( iter != iend ) { + map::iterator iter = oniaPar.begin(); + map::iterator iend = oniaPar.end(); + while (iter != iend) { OniaParameters& par = iter++->second; - delete par. ptSel; - delete par. etaSel; + delete par.ptSel; + delete par.etaSel; delete par.massSel; delete par.chi2Sel; } @@ -81,238 +72,227 @@ BPHOniaToMuMuBuilder::~BPHOniaToMuMuBuilder() { // Operations -- //-------------- vector BPHOniaToMuMuBuilder::build() { + if (updated) + return fullList; - if ( updated ) return fullList; - - BPHMultiSelect ptSel( BPHSelectOperation::or_mode ); - BPHMultiSelect etaSel( BPHSelectOperation::or_mode ); - BPHMultiSelect mSel( BPHSelectOperation::or_mode ); - BPHMultiSelect vSel( BPHSelectOperation::or_mode ); + BPHMultiSelect ptSel(BPHSelectOperation::or_mode); + BPHMultiSelect etaSel(BPHSelectOperation::or_mode); + BPHMultiSelect mSel(BPHSelectOperation::or_mode); + BPHMultiSelect vSel(BPHSelectOperation::or_mode); - map< oniaType, OniaParameters >::iterator iter = oniaPar.begin(); - map< oniaType, OniaParameters >::iterator iend = oniaPar.end(); - while ( iter != iend ) { + map::iterator iter = oniaPar.begin(); + map::iterator iend = oniaPar.end(); + while (iter != iend) { OniaParameters& par = iter++->second; - ptSel.include( *par. ptSel ); - etaSel.include( *par. etaSel ); - mSel.include( *par.massSel ); - vSel.include( *par.chi2Sel ); + ptSel.include(*par.ptSel); + etaSel.include(*par.etaSel); + mSel.include(*par.massSel); + vSel.include(*par.chi2Sel); } - BPHRecoBuilder bOnia( *evSetup ); - bOnia.add( muPosName, posCollection, BPHParticleMasses::muonMass, - BPHParticleMasses::muonMSigma ); - bOnia.add( muNegName, negCollection, BPHParticleMasses::muonMass, - BPHParticleMasses::muonMSigma ); - bOnia.filter( muPosName, ptSel ); - bOnia.filter( muNegName, ptSel ); - bOnia.filter( muPosName, etaSel ); - bOnia.filter( muNegName, etaSel ); - bOnia.filter( mSel ); - bOnia.filter( vSel ); - - fullList = BPHPlusMinusCandidate::build( bOnia, muPosName, muNegName ); + BPHRecoBuilder bOnia(*evSetup); + bOnia.add(muPosName, posCollection, BPHParticleMasses::muonMass, BPHParticleMasses::muonMSigma); + bOnia.add(muNegName, negCollection, BPHParticleMasses::muonMass, BPHParticleMasses::muonMSigma); + bOnia.filter(muPosName, ptSel); + bOnia.filter(muNegName, ptSel); + bOnia.filter(muPosName, etaSel); + bOnia.filter(muNegName, etaSel); + bOnia.filter(mSel); + bOnia.filter(vSel); + + fullList = BPHPlusMinusCandidate::build(bOnia, muPosName, muNegName); updated = true; return fullList; - } - vector BPHOniaToMuMuBuilder::getList( - oniaType type, - BPHRecoSelect * dSel, - BPHMomentumSelect* mSel, - BPHVertexSelect * vSel, - BPHFitSelect * kSel ) { - extractList( type ); + oniaType type, BPHRecoSelect* dSel, BPHMomentumSelect* mSel, BPHVertexSelect* vSel, BPHFitSelect* kSel) { + extractList(type); vector& list = oniaList[type]; int i; int n = list.size(); vector lsub; - lsub.reserve( n ); - for ( i = 0; i < n; ++i ) { + lsub.reserve(n); + for (i = 0; i < n; ++i) { BPHPlusMinusConstCandPtr ptr = list[i]; - const reco::Candidate* muPos = ptr->originalReco( ptr->getDaug( - muPosName ) ); - const reco::Candidate* muNeg = ptr->originalReco( ptr->getDaug( - muNegName ) ); - if ( ( dSel != nullptr ) && ( !dSel->accept( *muPos ) ) ) continue; - if ( ( dSel != nullptr ) && ( !dSel->accept( *muNeg ) ) ) continue; - if ( ( mSel != nullptr ) && ( !mSel->accept( *ptr ) ) ) continue; - if ( ( vSel != nullptr ) && ( !vSel->accept( *ptr ) ) ) continue; - if ( ( kSel != nullptr ) && ( !kSel->accept( *ptr ) ) ) continue; - lsub.push_back( list[i] ); + const reco::Candidate* muPos = ptr->originalReco(ptr->getDaug(muPosName)); + const reco::Candidate* muNeg = ptr->originalReco(ptr->getDaug(muNegName)); + if ((dSel != nullptr) && (!dSel->accept(*muPos))) + continue; + if ((dSel != nullptr) && (!dSel->accept(*muNeg))) + continue; + if ((mSel != nullptr) && (!mSel->accept(*ptr))) + continue; + if ((vSel != nullptr) && (!vSel->accept(*ptr))) + continue; + if ((kSel != nullptr) && (!kSel->accept(*ptr))) + continue; + lsub.push_back(list[i]); } return lsub; } - -BPHPlusMinusConstCandPtr BPHOniaToMuMuBuilder::getOriginalCandidate( - const BPHRecoCandidate& cand ) { - const reco::Candidate* mp = cand.originalReco( cand.getDaug( muPosName ) ); - const reco::Candidate* mn = cand.originalReco( cand.getDaug( muNegName ) ); +BPHPlusMinusConstCandPtr BPHOniaToMuMuBuilder::getOriginalCandidate(const BPHRecoCandidate& cand) { + const reco::Candidate* mp = cand.originalReco(cand.getDaug(muPosName)); + const reco::Candidate* mn = cand.originalReco(cand.getDaug(muNegName)); int nc = fullList.size(); int ic; - for ( ic = 0; ic < nc; ++ ic ) { + for (ic = 0; ic < nc; ++ic) { BPHPlusMinusConstCandPtr pmp = fullList[ic]; const BPHPlusMinusCandidate* pmc = pmp.get(); - if ( pmc->originalReco( pmc->getDaug( muPosName ) ) != mp ) continue; - if ( pmc->originalReco( pmc->getDaug( muNegName ) ) != mn ) continue; + if (pmc->originalReco(pmc->getDaug(muPosName)) != mp) + continue; + if (pmc->originalReco(pmc->getDaug(muNegName)) != mn) + continue; return pmp; } - return BPHPlusMinusConstCandPtr( nullptr ); + return BPHPlusMinusConstCandPtr(nullptr); } /// set cuts -void BPHOniaToMuMuBuilder::setPtMin( oniaType type, double pt ) { +void BPHOniaToMuMuBuilder::setPtMin(oniaType type, double pt) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.ptSel->setPtMin( pt ); + par.ptSel->setPtMin(pt); return; } - -void BPHOniaToMuMuBuilder::setEtaMax( oniaType type, double eta ) { +void BPHOniaToMuMuBuilder::setEtaMax(oniaType type, double eta) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.etaSel->setEtaMax( eta ); + par.etaSel->setEtaMax(eta); return; } - -void BPHOniaToMuMuBuilder::setMassMin( oniaType type, double m ) { +void BPHOniaToMuMuBuilder::setMassMin(oniaType type, double m) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.massSel->setMassMin( m ); + par.massSel->setMassMin(m); return; } - -void BPHOniaToMuMuBuilder::setMassMax( oniaType type, double m ) { +void BPHOniaToMuMuBuilder::setMassMax(oniaType type, double m) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.massSel->setMassMax( m ); + par.massSel->setMassMax(m); return; } - -void BPHOniaToMuMuBuilder::setProbMin( oniaType type, double p ) { +void BPHOniaToMuMuBuilder::setProbMin(oniaType type, double p) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.chi2Sel->setProbMin( p ); + par.chi2Sel->setProbMin(p); return; } - -void BPHOniaToMuMuBuilder::setConstr( oniaType type, - double mass, double sigma ) { +void BPHOniaToMuMuBuilder::setConstr(oniaType type, double mass, double sigma) { setNotUpdated(); OniaParameters& par = oniaPar[type]; - par.mass = mass; + par.mass = mass; par.sigma = sigma; return; } /// get current cuts -double BPHOniaToMuMuBuilder::getPtMin( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getPtMin(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.ptSel->getPtMin(); } - -double BPHOniaToMuMuBuilder::getEtaMax( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getEtaMax(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.etaSel->getEtaMax(); } - -double BPHOniaToMuMuBuilder::getMassMin( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getMassMin(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.massSel->getMassMin(); } - -double BPHOniaToMuMuBuilder::getMassMax( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getMassMax(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.massSel->getMassMax(); } - -double BPHOniaToMuMuBuilder::getProbMin( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getProbMin(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.chi2Sel->getProbMin(); } - -double BPHOniaToMuMuBuilder::getConstrMass( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getConstrMass(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.mass; } - -double BPHOniaToMuMuBuilder::getConstrSigma( oniaType type ) const { - const OniaParameters& par = oniaPar.at( type ); +double BPHOniaToMuMuBuilder::getConstrSigma(oniaType type) const { + const OniaParameters& par = oniaPar.at(type); return par.sigma; } - void BPHOniaToMuMuBuilder::setNotUpdated() { - map< oniaType, OniaParameters >::iterator iter = oniaPar.begin(); - map< oniaType, OniaParameters >::iterator iend = oniaPar.end(); - while ( iter != iend ) iter++->second.updated = false; + map::iterator iter = oniaPar.begin(); + map::iterator iend = oniaPar.end(); + while (iter != iend) + iter++->second.updated = false; updated = false; return; } - -void BPHOniaToMuMuBuilder::setParameters( oniaType type, - double ptMin, double etaMax, - double massMin, double massMax, - double probMin, - double mass, double sigma ) { +void BPHOniaToMuMuBuilder::setParameters(oniaType type, + double ptMin, + double etaMax, + double massMin, + double massMax, + double probMin, + double mass, + double sigma) { OniaParameters& par = oniaPar[type]; - par. ptSel = new BPHMuonPtSelect( ptMin ); - par. etaSel = new BPHMuonEtaSelect( etaMax ); - par.massSel = new BPHMassSelect( massMin, massMax ); - par.chi2Sel = new BPHChi2Select( probMin ); - par.mass = mass; - par.sigma = sigma; + par.ptSel = new BPHMuonPtSelect(ptMin); + par.etaSel = new BPHMuonEtaSelect(etaMax); + par.massSel = new BPHMassSelect(massMin, massMax); + par.chi2Sel = new BPHChi2Select(probMin); + par.mass = mass; + par.sigma = sigma; par.updated = false; return; } - -void BPHOniaToMuMuBuilder::extractList( oniaType type ) { - if ( !updated ) build(); +void BPHOniaToMuMuBuilder::extractList(oniaType type) { + if (!updated) + build(); OniaParameters& par = oniaPar[type]; vector& list = oniaList[type]; - if ( par.updated ) return; + if (par.updated) + return; int i; int n = fullList.size(); list.clear(); - list.reserve( n ); - for ( i = 0; i < n; ++i ) { + list.reserve(n); + for (i = 0; i < n; ++i) { BPHPlusMinusConstCandPtr ptr = fullList[i]; - const reco::Candidate* mcPos = ptr->getDaug( "MuPos" ); - const reco::Candidate* mcNeg = ptr->getDaug( "MuNeg" ); - const reco::Candidate* muPos = ptr->originalReco( mcPos ); - const reco::Candidate* muNeg = ptr->originalReco( mcNeg ); - if ( !par.massSel->accept( *ptr ) ) continue; - if ( !par. ptSel->accept( *muPos ) ) continue; - if ( !par. etaSel->accept( *muPos ) ) continue; - if ( !par. ptSel->accept( *muNeg ) ) continue; - if ( !par. etaSel->accept( *muNeg ) ) continue; - if ( !par.chi2Sel->accept( *ptr ) ) continue; - BPHPlusMinusCandidate* np = new BPHPlusMinusCandidate( evSetup ); - np->add( "MuPos", muPos, ptr->getTrackSearchList( mcPos ), - BPHParticleMasses::muonMass ); - np->add( "MuNeg", muNeg, ptr->getTrackSearchList( mcNeg ), - BPHParticleMasses::muonMass ); - if ( par.mass > 0.0 ) - np->setConstraint( par.mass, par.sigma ); - list.push_back( BPHPlusMinusConstCandPtr( np ) ); + const reco::Candidate* mcPos = ptr->getDaug("MuPos"); + const reco::Candidate* mcNeg = ptr->getDaug("MuNeg"); + const reco::Candidate* muPos = ptr->originalReco(mcPos); + const reco::Candidate* muNeg = ptr->originalReco(mcNeg); + if (!par.massSel->accept(*ptr)) + continue; + if (!par.ptSel->accept(*muPos)) + continue; + if (!par.etaSel->accept(*muPos)) + continue; + if (!par.ptSel->accept(*muNeg)) + continue; + if (!par.etaSel->accept(*muNeg)) + continue; + if (!par.chi2Sel->accept(*ptr)) + continue; + BPHPlusMinusCandidate* np = new BPHPlusMinusCandidate(evSetup); + np->add("MuPos", muPos, ptr->getTrackSearchList(mcPos), BPHParticleMasses::muonMass); + np->add("MuNeg", muNeg, ptr->getTrackSearchList(mcNeg), BPHParticleMasses::muonMass); + if (par.mass > 0.0) + np->setConstraint(par.mass, par.sigma); + list.push_back(BPHPlusMinusConstCandPtr(np)); } par.updated = true; return; } - diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHParticleMasses.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHParticleMasses.cc index 2591baf71a579..fd374fc19a38f 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHParticleMasses.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHParticleMasses.cc @@ -14,34 +14,32 @@ // Collaborating Class Headers -- //------------------------------- - //--------------- // C++ Headers -- //--------------- - //------------------- // Initializations -- //------------------- -const double BPHParticleMasses:: elMass = 0.510998928e-03; -const double BPHParticleMasses::muonMass = 0.1056583715; -const double BPHParticleMasses:: tauMass = 1.77682; -const double BPHParticleMasses::pionMass = 0.13957018; -const double BPHParticleMasses::kaonMass = 0.493667; -const double BPHParticleMasses:: kx0Mass = 0.89581; -const double BPHParticleMasses:: phiMass = 1.019461; -const double BPHParticleMasses::jPsiMass = 3.096916; -const double BPHParticleMasses::psi2Mass = 3.686109; -const double BPHParticleMasses::ups1Mass = 9.46030; +const double BPHParticleMasses::elMass = 0.510998928e-03; +const double BPHParticleMasses::muonMass = 0.1056583715; +const double BPHParticleMasses::tauMass = 1.77682; +const double BPHParticleMasses::pionMass = 0.13957018; +const double BPHParticleMasses::kaonMass = 0.493667; +const double BPHParticleMasses::kx0Mass = 0.89581; +const double BPHParticleMasses::phiMass = 1.019461; +const double BPHParticleMasses::jPsiMass = 3.096916; +const double BPHParticleMasses::psi2Mass = 3.686109; +const double BPHParticleMasses::ups1Mass = 9.46030; const double BPHParticleMasses::ups2Mass = 10.02326; const double BPHParticleMasses::ups3Mass = 10.3552; -const double BPHParticleMasses:: elMSigma = 0.000000011e-03; +const double BPHParticleMasses::elMSigma = 0.000000011e-03; const double BPHParticleMasses::muonMSigma = 0.0000000035; -const double BPHParticleMasses:: tauMSigma = 0.00016; +const double BPHParticleMasses::tauMSigma = 0.00016; const double BPHParticleMasses::pionMSigma = 0.00000035; const double BPHParticleMasses::kaonMSigma = 0.000016; -const double BPHParticleMasses:: kx0MWidth = 0.0474; -const double BPHParticleMasses:: phiMWidth = 0.004266; +const double BPHParticleMasses::kx0MWidth = 0.0474; +const double BPHParticleMasses::phiMWidth = 0.004266; const double BPHParticleMasses::jPsiMWidth = 0.000040; const double BPHParticleMasses::psi2MWidth = 0.000129; const double BPHParticleMasses::ups1MWidth = 0.00026; diff --git a/HeavyFlavorAnalysis/SpecificDecay/src/BPHPhiToKKBuilder.cc b/HeavyFlavorAnalysis/SpecificDecay/src/BPHPhiToKKBuilder.cc index 81e3d2985263e..03a441b6c2e3d 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/src/BPHPhiToKKBuilder.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/src/BPHPhiToKKBuilder.cc @@ -30,23 +30,17 @@ using namespace std; // Initializations -- //------------------- - //---------------- // Constructors -- //---------------- -BPHPhiToKKBuilder::BPHPhiToKKBuilder( - const edm::EventSetup& es, - const BPHRecoBuilder::BPHGenericCollection* kPosCollection, - const BPHRecoBuilder::BPHGenericCollection* kNegCollection ): - kPosName( "KPos" ), - kNegName( "KNeg" ), - evSetup( &es ), - posCollection( kPosCollection ), - negCollection( kNegCollection ) { - ptSel = new BPHParticlePtSelect ( 0.7 ); - etaSel = new BPHParticleEtaSelect( 10.0 ); - massSel = new BPHMassSelect( 1.0, 1.04 ); - chi2Sel = new BPHChi2Select( 0.0 ); +BPHPhiToKKBuilder::BPHPhiToKKBuilder(const edm::EventSetup& es, + const BPHRecoBuilder::BPHGenericCollection* kPosCollection, + const BPHRecoBuilder::BPHGenericCollection* kNegCollection) + : kPosName("KPos"), kNegName("KNeg"), evSetup(&es), posCollection(kPosCollection), negCollection(kNegCollection) { + ptSel = new BPHParticlePtSelect(0.7); + etaSel = new BPHParticleEtaSelect(10.0); + massSel = new BPHMassSelect(1.0, 1.04); + chi2Sel = new BPHChi2Select(0.0); updated = false; } @@ -54,8 +48,8 @@ BPHPhiToKKBuilder::BPHPhiToKKBuilder( // Destructor -- //-------------- BPHPhiToKKBuilder::~BPHPhiToKKBuilder() { - delete ptSel; - delete etaSel; + delete ptSel; + delete etaSel; delete massSel; delete chi2Sel; } @@ -64,103 +58,74 @@ BPHPhiToKKBuilder::~BPHPhiToKKBuilder() { // Operations -- //-------------- vector BPHPhiToKKBuilder::build() { + if (updated) + return phiList; - if ( updated ) return phiList; - - BPHRecoBuilder bPhi( *evSetup ); - bPhi.add( kPosName, posCollection, BPHParticleMasses::kaonMass, - BPHParticleMasses::kaonMSigma ); - bPhi.add( kNegName, negCollection, BPHParticleMasses::kaonMass, - BPHParticleMasses::kaonMSigma ); - bPhi.filter( kPosName, *ptSel ); - bPhi.filter( kNegName, *ptSel ); - bPhi.filter( kPosName, *etaSel ); - bPhi.filter( kNegName, *etaSel ); + BPHRecoBuilder bPhi(*evSetup); + bPhi.add(kPosName, posCollection, BPHParticleMasses::kaonMass, BPHParticleMasses::kaonMSigma); + bPhi.add(kNegName, negCollection, BPHParticleMasses::kaonMass, BPHParticleMasses::kaonMSigma); + bPhi.filter(kPosName, *ptSel); + bPhi.filter(kNegName, *ptSel); + bPhi.filter(kPosName, *etaSel); + bPhi.filter(kNegName, *etaSel); - bPhi.filter( *massSel ); - bPhi.filter( *chi2Sel ); + bPhi.filter(*massSel); + bPhi.filter(*chi2Sel); - phiList = BPHPlusMinusCandidate::build( bPhi, kPosName, kNegName ); + phiList = BPHPlusMinusCandidate::build(bPhi, kPosName, kNegName); updated = true; return phiList; - } /// set cuts -void BPHPhiToKKBuilder::setPtMin( double pt ) { +void BPHPhiToKKBuilder::setPtMin(double pt) { updated = false; - ptSel->setPtMin( pt ); + ptSel->setPtMin(pt); return; } - -void BPHPhiToKKBuilder::setEtaMax( double eta ) { +void BPHPhiToKKBuilder::setEtaMax(double eta) { updated = false; - etaSel->setEtaMax( eta ); + etaSel->setEtaMax(eta); return; } - -void BPHPhiToKKBuilder::setMassMin( double m ) { +void BPHPhiToKKBuilder::setMassMin(double m) { updated = false; - massSel->setMassMin( m ); + massSel->setMassMin(m); return; } - -void BPHPhiToKKBuilder::setMassMax( double m ) { +void BPHPhiToKKBuilder::setMassMax(double m) { updated = false; - massSel->setMassMax( m ); + massSel->setMassMax(m); return; } - -void BPHPhiToKKBuilder::setProbMin( double p ) { +void BPHPhiToKKBuilder::setProbMin(double p) { updated = false; - chi2Sel->setProbMin( p ); + chi2Sel->setProbMin(p); return; } - -void BPHPhiToKKBuilder::setConstr( double mass, double sigma ) { +void BPHPhiToKKBuilder::setConstr(double mass, double sigma) { updated = false; - cMass = mass; + cMass = mass; cSigma = sigma; return; } /// get current cuts -double BPHPhiToKKBuilder::getPtMin() const { - return ptSel->getPtMin(); -} - - -double BPHPhiToKKBuilder::getEtaMax() const { - return etaSel->getEtaMax(); -} - - -double BPHPhiToKKBuilder::getMassMin() const { - return massSel->getMassMin(); -} +double BPHPhiToKKBuilder::getPtMin() const { return ptSel->getPtMin(); } +double BPHPhiToKKBuilder::getEtaMax() const { return etaSel->getEtaMax(); } -double BPHPhiToKKBuilder::getMassMax() const { - return massSel->getMassMax(); -} +double BPHPhiToKKBuilder::getMassMin() const { return massSel->getMassMin(); } +double BPHPhiToKKBuilder::getMassMax() const { return massSel->getMassMax(); } -double BPHPhiToKKBuilder::getProbMin() const { - return chi2Sel->getProbMin(); -} +double BPHPhiToKKBuilder::getProbMin() const { return chi2Sel->getProbMin(); } +double BPHPhiToKKBuilder::getConstrMass() const { return cMass; } -double BPHPhiToKKBuilder::getConstrMass() const { - return cMass; -} - - -double BPHPhiToKKBuilder::getConstrSigma() const { - return cSigma; -} - +double BPHPhiToKKBuilder::getConstrSigma() const { return cSigma; } diff --git a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.cc b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.cc index 0018bd21981f6..2cf20078b7133 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.cc @@ -29,162 +29,130 @@ using namespace std; -#define SET_PAR(TYPE,NAME,PSET) ( NAME = PSET.getParameter< TYPE >( #NAME ) ) +#define SET_PAR(TYPE, NAME, PSET) (NAME = PSET.getParameter(#NAME)) // SET_PAR(string,xyz,ps); // is equivalent to // ( xyz = ps.getParameter< string >( "xyx" ) ) -CheckBPHWriteDecay::CheckBPHWriteDecay( const edm::ParameterSet& ps ) { - - SET_PAR( unsigned int, runNumber, ps ); - SET_PAR( unsigned int, evtNumber, ps ); - SET_PAR( vector, candsLabel, ps ); +CheckBPHWriteDecay::CheckBPHWriteDecay(const edm::ParameterSet& ps) { + SET_PAR(unsigned int, runNumber, ps); + SET_PAR(unsigned int, evtNumber, ps); + SET_PAR(vector, candsLabel, ps); int i; - int n = - candsLabel. size(); - candsToken.resize( n ); - for ( i = 0; i < n; ++i ) - consume< vector >( candsToken[i], - candsLabel[i] ); - - string fileName = ps.getParameter( "fileName" ); - if ( fileName != "" ) osPtr = new ofstream( fileName.c_str() ); - else osPtr = &cout; - -} - - -CheckBPHWriteDecay::~CheckBPHWriteDecay() { -} - - -void CheckBPHWriteDecay::fillDescriptions( - edm::ConfigurationDescriptions& descriptions ) { - edm::ParameterSetDescription desc; - vector v; - desc.add< vector >( "candsLabel", v ); - desc.add( "runNumber", 0 ); - desc.add( "evtNumber", 0 ); - desc.add( "fileName", "" ); - descriptions.add( "checkBPHWriteDecay", desc ); - return; + int n = candsLabel.size(); + candsToken.resize(n); + for (i = 0; i < n; ++i) + consume >(candsToken[i], candsLabel[i]); + + string fileName = ps.getParameter("fileName"); + if (fileName != "") + osPtr = new ofstream(fileName.c_str()); + else + osPtr = &cout; } +CheckBPHWriteDecay::~CheckBPHWriteDecay() {} -void CheckBPHWriteDecay::beginJob() { +void CheckBPHWriteDecay::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + vector v; + desc.add >("candsLabel", v); + desc.add("runNumber", 0); + desc.add("evtNumber", 0); + desc.add("fileName", ""); + descriptions.add("checkBPHWriteDecay", desc); return; } +void CheckBPHWriteDecay::beginJob() { return; } -void CheckBPHWriteDecay::analyze( const edm::Event& ev, - const edm::EventSetup& es ) { - +void CheckBPHWriteDecay::analyze(const edm::Event& ev, const edm::EventSetup& es) { ostream& os = *osPtr; - if ( ( runNumber != 0 ) && ( ev.id().run () != runNumber ) ) return; - if ( ( evtNumber != 0 ) && ( ev.id().event() != evtNumber ) ) return; - os << "--------- event " - << ev.id().run() << " / " - << ev.id().event() - << " ---------" << endl; + if ((runNumber != 0) && (ev.id().run() != runNumber)) + return; + if ((evtNumber != 0) && (ev.id().event() != evtNumber)) + return; + os << "--------- event " << ev.id().run() << " / " << ev.id().event() << " ---------" << endl; int il; - int nl = - candsLabel.size(); - for ( il = 0; il < nl; ++il ) { - edm::Handle< vector > cands; - candsToken[il].get( ev, cands ); + int nl = candsLabel.size(); + for (il = 0; il < nl; ++il) { + edm::Handle > cands; + candsToken[il].get(ev, cands); int ic; int nc = cands->size(); - for ( ic = 0; ic < nc; ++ ic ) { - os << "*********** " << candsLabel[il] << " " << ic << "/" << nc - << " ***********" - << endl; - const pat::CompositeCandidate& cand = cands->at( ic ); - dump( os, cand ); + for (ic = 0; ic < nc; ++ic) { + os << "*********** " << candsLabel[il] << " " << ic << "/" << nc << " ***********" << endl; + const pat::CompositeCandidate& cand = cands->at(ic); + dump(os, cand); } } return; - } - -void CheckBPHWriteDecay::endJob() { - return; -} - - -void CheckBPHWriteDecay::dump( std::ostream& os, - const pat::CompositeCandidate& cand ) { - - float mfit = ( cand.hasUserFloat( "fitMass" ) ? - cand. userFloat( "fitMass" ) : -1 ); - os << &cand - << " mass : " << cand.mass() << " " << mfit << " " - << ( cand.hasUserData ( "cowboy" ) ? - ( cand. userData( "cowboy" ) ? "cowboy" : "sailor" ) - : "" ) << endl; - writeMomentum( os, "cmom ", cand, false ); - writePosition( os, " xyz ", cand.momentum() ); - const reco::Vertex* vptr = - ( cand.hasUserData ( "vertex" ) ? - cand. userData( "vertex" ) : 0 ); - if ( vptr != 0 ) { - writePosition( os, "vpos : ", *vptr, false ); - os << " --- " << vptr->chi2() << " / " << vptr->ndof() - << " ( " << ChiSquaredProbability( vptr->chi2(), - vptr->ndof() ) << " ) " << endl; +void CheckBPHWriteDecay::endJob() { return; } + +void CheckBPHWriteDecay::dump(std::ostream& os, const pat::CompositeCandidate& cand) { + float mfit = (cand.hasUserFloat("fitMass") ? cand.userFloat("fitMass") : -1); + os << &cand << " mass : " << cand.mass() << " " << mfit << " " + << (cand.hasUserData("cowboy") ? (cand.userData("cowboy") ? "cowboy" : "sailor") : "") << endl; + writeMomentum(os, "cmom ", cand, false); + writePosition(os, " xyz ", cand.momentum()); + const reco::Vertex* vptr = (cand.hasUserData("vertex") ? cand.userData("vertex") : 0); + if (vptr != 0) { + writePosition(os, "vpos : ", *vptr, false); + os << " --- " << vptr->chi2() << " / " << vptr->ndof() << " ( " << ChiSquaredProbability(vptr->chi2(), vptr->ndof()) + << " ) " << endl; } - const reco::Vertex* vfit = - ( cand.hasUserData ( "fitVertex" ) ? - cand. userData( "fitVertex" ) : 0 ); - if ( vfit != 0 ) { - writePosition( os, "vfit : ", *vfit, false ); - os << " --- " << vfit->chi2() << " / " << vfit->ndof() - << " ( " << ChiSquaredProbability( vfit->chi2(), - vfit->ndof() ) << " ) " << endl; + const reco::Vertex* vfit = (cand.hasUserData("fitVertex") ? cand.userData("fitVertex") : 0); + if (vfit != 0) { + writePosition(os, "vfit : ", *vfit, false); + os << " --- " << vfit->chi2() << " / " << vfit->ndof() << " ( " << ChiSquaredProbability(vfit->chi2(), vfit->ndof()) + << " ) " << endl; } - if ( cand.hasUserData( "fitMomentum" ) ) - writePosition( os, "fmom : ", - *cand. userData< Vector3DBase >( "fitMomentum" ) ); + if (cand.hasUserData("fitMomentum")) + writePosition(os, "fmom : ", *cand.userData >("fitMomentum")); - if ( cand.hasUserData( "primaryVertex" ) ) { - const vertex_ref* pvr = cand.userData( "primaryVertex" ); - if ( pvr->isNonnull() ) { + if (cand.hasUserData("primaryVertex")) { + const vertex_ref* pvr = cand.userData("primaryVertex"); + if (pvr->isNonnull()) { const reco::Vertex* pvtx = pvr->get(); - if ( pvtx != 0 ) writePosition( os, "ppos ", *pvtx ); + if (pvtx != 0) + writePosition(os, "ppos ", *pvtx); } } int i; int n = cand.numberOfDaughters(); - for ( i = 0; i < n; ++i ) { - const reco::Candidate* dptr = cand.daughter( i ); + for (i = 0; i < n; ++i) { + const reco::Candidate* dptr = cand.daughter(i); os << "daug " << i << "/" << n << " : " << dptr; - writeMomentum( os, " == ", *dptr, false ); + writeMomentum(os, " == ", *dptr, false); os << " " << dptr->mass() << endl; - const pat::Muon* mptr = dynamic_cast( dptr ); + const pat::Muon* mptr = dynamic_cast(dptr); os << "muon " << i << "/" << n << " : " << mptr << endl; - const reco::Track* tptr = BPHTrackReference::getTrack( *dptr, "cfhpmnigs" ); + const reco::Track* tptr = BPHTrackReference::getTrack(*dptr, "cfhpmnigs"); os << "trk " << i << "/" << n << " : " << tptr; - if ( tptr != 0 ) writeMomentum( os, " == ", *tptr ); - else os << "no track" << endl; + if (tptr != 0) + writeMomentum(os, " == ", *tptr); + else + os << "no track" << endl; } const vector& names = cand.userDataNames(); int j; int m = names.size(); - for ( j = 0; j < m; ++j ) { + for (j = 0; j < m; ++j) { const string& dname = names[j]; - if ( dname.substr( 0, 5 ) != "refTo" ) continue; - const compcc_ref* ref = cand.userData( dname ); + if (dname.substr(0, 5) != "refTo") + continue; + const compcc_ref* ref = cand.userData(dname); os << dname << " : " << ref->get() << endl; } return; - } - #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( CheckBPHWriteDecay ); +DEFINE_FWK_MODULE(CheckBPHWriteDecay); diff --git a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.h b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.h index e9ac828a60558..45cf33f75239e 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.h +++ b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/CheckBPHWriteDecay.h @@ -22,55 +22,43 @@ class TH1F; class BPHRecoCandidate; -class CheckBPHWriteDecay: - public BPHAnalyzerWrapper { - - public: - - explicit CheckBPHWriteDecay( const edm::ParameterSet& ps ); +class CheckBPHWriteDecay : public BPHAnalyzerWrapper { +public: + explicit CheckBPHWriteDecay(const edm::ParameterSet& ps); virtual ~CheckBPHWriteDecay(); - static void fillDescriptions( edm::ConfigurationDescriptions& descriptions ); + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); virtual void beginJob(); - virtual void analyze( const edm::Event& ev, const edm::EventSetup& es ); + virtual void analyze(const edm::Event& ev, const edm::EventSetup& es); virtual void endJob(); - private: - +private: std::ostream* osPtr; unsigned int runNumber; unsigned int evtNumber; std::vector candsLabel; - std::vector< BPHTokenWrapper< std::vector > > - candsToken; + std::vector > > candsToken; - typedef edm::Ref< std::vector > vertex_ref; - typedef edm::Ref< pat::CompositeCandidateCollection > compcc_ref; + typedef edm::Ref > vertex_ref; + typedef edm::Ref compcc_ref; - static void dump( std::ostream& os, const pat::CompositeCandidate& cand ); - template - static void writePosition( std::ostream& os, - const std::string& s, const T& p, - bool endLine = true ) { - os << s << p.x() << " " - << p.y() << " " - << p.z(); - if ( endLine ) os << std::endl; + static void dump(std::ostream& os, const pat::CompositeCandidate& cand); + template + static void writePosition(std::ostream& os, const std::string& s, const T& p, bool endLine = true) { + os << s << p.x() << " " << p.y() << " " << p.z(); + if (endLine) + os << std::endl; return; } - template - static void writeMomentum( std::ostream& os, - const std::string& s, const T& p, - bool endLine = true ) { - os << s << p. pt() << " " - << p.eta() << " " - << p.phi(); - if ( endLine ) os << std::endl; + template + static void writeMomentum(std::ostream& os, const std::string& s, const T& p, bool endLine = true) { + os << s << p.pt() << " " << p.eta() << " " << p.phi(); + if (endLine) + os << std::endl; return; } - }; #endif diff --git a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.cc b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.cc index 1c34c714cf92b..c522cf4a30c9c 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.cc +++ b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.cc @@ -42,91 +42,82 @@ using namespace std; -#define SET_LABEL(NAME,PSET) ( NAME = PSET.getParameter( #NAME ) ) +#define SET_LABEL(NAME, PSET) (NAME = PSET.getParameter(#NAME)) // SET_LABEL(xyz,ps); // is equivalent to // xyz = ps.getParameter( "xyx" ) -TestBPHSpecificDecay::TestBPHSpecificDecay( const edm::ParameterSet& ps ) { - - usePM = ( ! SET_LABEL( patMuonLabel, ps ).empty() ); - useCC = ( ! SET_LABEL( ccCandsLabel, ps ).empty() ); - usePF = ( ! SET_LABEL( pfCandsLabel, ps ).empty() ); - usePC = ( ! SET_LABEL( pcCandsLabel, ps ).empty() ); - useGP = ( ! SET_LABEL( gpCandsLabel, ps ).empty() ); - - if ( usePM ) consume< pat::MuonCollection >( patMuonToken, - patMuonLabel ); - if ( useCC ) consume< vector >( ccCandsToken, - ccCandsLabel ); - if ( usePF ) consume< vector >( pfCandsToken, - pfCandsLabel ); - if ( usePC ) consume< vector >( pcCandsToken, - pcCandsLabel ); - if ( useGP ) consume< vector >( gpCandsToken, - gpCandsLabel ); - - SET_LABEL( outDump, ps ); - SET_LABEL( outHist, ps ); - if ( outDump == "" ) fPtr = &cout; - else fPtr = new ofstream( outDump.c_str() ); - -} - - -TestBPHSpecificDecay::~TestBPHSpecificDecay() { +TestBPHSpecificDecay::TestBPHSpecificDecay(const edm::ParameterSet& ps) { + usePM = (!SET_LABEL(patMuonLabel, ps).empty()); + useCC = (!SET_LABEL(ccCandsLabel, ps).empty()); + usePF = (!SET_LABEL(pfCandsLabel, ps).empty()); + usePC = (!SET_LABEL(pcCandsLabel, ps).empty()); + useGP = (!SET_LABEL(gpCandsLabel, ps).empty()); + + if (usePM) + consume(patMuonToken, patMuonLabel); + if (useCC) + consume >(ccCandsToken, ccCandsLabel); + if (usePF) + consume >(pfCandsToken, pfCandsLabel); + if (usePC) + consume >(pcCandsToken, pcCandsLabel); + if (useGP) + consume >(gpCandsToken, gpCandsLabel); + + SET_LABEL(outDump, ps); + SET_LABEL(outHist, ps); + if (outDump == "") + fPtr = &cout; + else + fPtr = new ofstream(outDump.c_str()); } - -void TestBPHSpecificDecay::fillDescriptions( - edm::ConfigurationDescriptions& descriptions ) { - edm::ParameterSetDescription desc; - desc.add( "patMuonLabel", "" ); - desc.add( "ccCandsLabel", "" ); - desc.add( "pfCandsLabel", "" ); - desc.add( "pcCandsLabel", "" ); - desc.add( "gpCandsLabel", "" ); - desc.add( "outDump", "dump.txt" ); - desc.add( "outHist", "hist.root" ); - descriptions.add( "testBPHSpecificDecay", desc ); - return; +TestBPHSpecificDecay::~TestBPHSpecificDecay() {} + +void TestBPHSpecificDecay::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { + edm::ParameterSetDescription desc; + desc.add("patMuonLabel", ""); + desc.add("ccCandsLabel", ""); + desc.add("pfCandsLabel", ""); + desc.add("pcCandsLabel", ""); + desc.add("gpCandsLabel", ""); + desc.add("outDump", "dump.txt"); + desc.add("outHist", "hist.root"); + descriptions.add("testBPHSpecificDecay", desc); + return; } - void TestBPHSpecificDecay::beginJob() { *fPtr << "TestBPHSpecificDecay::beginJob" << endl; - createHisto( "massJPsi" , 60, 2.95, 3.25 ); // JPsi mass - createHisto( "mcstJPsi" , 60, 2.95, 3.25 ); // JPsi mass, with constraint - createHisto( "massKx0" , 50, 0.80, 1.05 ); // Kx0 mass - createHisto( "massPhi" , 40, 1.01, 1.03 ); // Phi mass - createHisto( "massBu" , 20, 5.00, 5.50 ); // Bu mass - createHisto( "mcstBu" , 20, 5.00, 5.50 ); // Bu mass, with constraint - createHisto( "massBd" , 20, 5.00, 5.50 ); // Bd mass - createHisto( "mcstBd" , 20, 5.00, 5.50 ); // Bd mass, with constraint - createHisto( "massBs" , 20, 5.10, 5.60 ); // Bs mass - createHisto( "mcstBs" , 20, 5.10, 5.60 ); // Bs mass, with constraint - createHisto( "massBsPhi" , 50, 1.01, 1.03 ); // Phi mass in Bs decay - createHisto( "massBdKx0" , 50, 0.80, 1.05 ); // Kx0 mass in Bd decay - - createHisto( "massFull" , 200, 2.00, 12.00 ); // Full mass - createHisto( "massFsel" , 200, 2.00, 12.00 ); // Full mass - createHisto( "massPhi" , 70, 0.85, 1.20 ); // Psi1 mass - createHisto( "massPsi1" , 60, 2.95, 3.25 ); // Psi1 mass - createHisto( "massPsi2" , 50, 3.55, 3.80 ); // Psi2 mass - createHisto( "massUps1" , 130, 9.10, 9.75 ); // Ups1 mass - createHisto( "massUps2" , 90, 9.75, 10.20 ); // Ups2 mass - createHisto( "massUps3" , 80, 10.20, 10.60 ); // Ups3 mass + createHisto("massJPsi", 60, 2.95, 3.25); // JPsi mass + createHisto("mcstJPsi", 60, 2.95, 3.25); // JPsi mass, with constraint + createHisto("massKx0", 50, 0.80, 1.05); // Kx0 mass + createHisto("massPhi", 40, 1.01, 1.03); // Phi mass + createHisto("massBu", 20, 5.00, 5.50); // Bu mass + createHisto("mcstBu", 20, 5.00, 5.50); // Bu mass, with constraint + createHisto("massBd", 20, 5.00, 5.50); // Bd mass + createHisto("mcstBd", 20, 5.00, 5.50); // Bd mass, with constraint + createHisto("massBs", 20, 5.10, 5.60); // Bs mass + createHisto("mcstBs", 20, 5.10, 5.60); // Bs mass, with constraint + createHisto("massBsPhi", 50, 1.01, 1.03); // Phi mass in Bs decay + createHisto("massBdKx0", 50, 0.80, 1.05); // Kx0 mass in Bd decay + + createHisto("massFull", 200, 2.00, 12.00); // Full mass + createHisto("massFsel", 200, 2.00, 12.00); // Full mass + createHisto("massPhi", 70, 0.85, 1.20); // Psi1 mass + createHisto("massPsi1", 60, 2.95, 3.25); // Psi1 mass + createHisto("massPsi2", 50, 3.55, 3.80); // Psi2 mass + createHisto("massUps1", 130, 9.10, 9.75); // Ups1 mass + createHisto("massUps2", 90, 9.75, 10.20); // Ups2 mass + createHisto("massUps3", 80, 10.20, 10.60); // Ups3 mass return; } -void TestBPHSpecificDecay::analyze( const edm::Event& ev, - const edm::EventSetup& es ) { - +void TestBPHSpecificDecay::analyze(const edm::Event& ev, const edm::EventSetup& es) { ostream& outF = *fPtr; - outF << "--------- event " - << ev.id().run() << " / " - << ev.id().event() << " ---------" << endl; + outF << "--------- event " << ev.id().run() << " / " << ev.id().event() << " ---------" << endl; // get object collections // collections are got through "BPHTokenWrapper" interface to allow @@ -135,338 +126,311 @@ void TestBPHSpecificDecay::analyze( const edm::Event& ev, int nrc = 0; // get reco::PFCandidate collection (in full AOD ) - edm::Handle< vector > pfCands; - if ( usePF ) { - pfCandsToken.get( ev, pfCands ); + edm::Handle > pfCands; + if (usePF) { + pfCandsToken.get(ev, pfCands); nrc = pfCands->size(); } // get pat::PackedCandidate collection (in MiniAOD) // pat::PackedCandidate is not defined in CMSSW_5XY, so a - // typedef (BPHTrackReference::candidate) is used, actually referring + // typedef (BPHTrackReference::candidate) is used, actually referring // to pat::PackedCandidate only for CMSSW versions where it's defined - edm::Handle< vector > pcCands; - if ( usePC ) { - pcCandsToken.get( ev, pcCands ); + edm::Handle > pcCands; + if (usePC) { + pcCandsToken.get(ev, pcCands); nrc = pcCands->size(); } // get pat::GenericParticle collection (in skimmed data) - edm::Handle< vector > gpCands; - if ( useGP ) { - gpCandsToken.get( ev, gpCands ); + edm::Handle > gpCands; + if (useGP) { + gpCandsToken.get(ev, gpCands); nrc = gpCands->size(); } // get pat::Muon collection (in full AOD and MiniAOD) edm::Handle patMuon; - if ( usePM ) { - patMuonToken.get( ev, patMuon ); + if (usePM) { + patMuonToken.get(ev, patMuon); } // get muons from pat::CompositeCandidate objects describing onia; // muons from all composite objects are copied to an unique std::vector vector muDaugs; set muonSet; - if ( useCC ) { - edm::Handle< vector > ccCands; - ccCandsToken.get( ev, ccCands ); + if (useCC) { + edm::Handle > ccCands; + ccCandsToken.get(ev, ccCands); int n = ccCands->size(); muDaugs.clear(); - muDaugs.reserve( n ); + muDaugs.reserve(n); muonSet.clear(); set::const_iterator iter; set::const_iterator iend; int i; - for ( i = 0; i < n; ++i ) { - const pat::CompositeCandidate& cc = ccCands->at( i ); + for (i = 0; i < n; ++i) { + const pat::CompositeCandidate& cc = ccCands->at(i); int j; int m = cc.numberOfDaughters(); - for ( j = 0; j < m; ++j ) { - const reco::Candidate* dp = cc.daughter( j ); - const pat::Muon* mp = dynamic_cast( dp ); + for (j = 0; j < m; ++j) { + const reco::Candidate* dp = cc.daughter(j); + const pat::Muon* mp = dynamic_cast(dp); iter = muonSet.begin(); iend = muonSet.end(); - bool add = ( mp != 0 ) && ( muonSet.find( mp ) == iend ); - while ( add && ( iter != iend ) ) { - if ( BPHRecoBuilder::sameTrack( mp, *iter++, 1.0e-5 ) ) add = false; + bool add = (mp != 0) && (muonSet.find(mp) == iend); + while (add && (iter != iend)) { + if (BPHRecoBuilder::sameTrack(mp, *iter++, 1.0e-5)) + add = false; } - if ( add ) muonSet.insert( mp ); + if (add) + muonSet.insert(mp); } } iter = muonSet.begin(); iend = muonSet.end(); - while ( iter != iend ) muDaugs.push_back( *iter++ ); + while (iter != iend) + muDaugs.push_back(*iter++); } // reconstruct resonances outF << "build and dump full onia" << endl; BPHOniaToMuMuBuilder* onia = 0; - if ( usePM ) onia = new BPHOniaToMuMuBuilder( es, - BPHRecoBuilder::createCollection( patMuon, "cfmig" ), - BPHRecoBuilder::createCollection( patMuon, "cfmig" ) ); - else - if ( useCC ) onia = new BPHOniaToMuMuBuilder( es, - BPHRecoBuilder::createCollection( muDaugs, "cfmig" ), - BPHRecoBuilder::createCollection( muDaugs, "cfmig" ) ); + if (usePM) + onia = new BPHOniaToMuMuBuilder( + es, BPHRecoBuilder::createCollection(patMuon, "cfmig"), BPHRecoBuilder::createCollection(patMuon, "cfmig")); + else if (useCC) + onia = new BPHOniaToMuMuBuilder( + es, BPHRecoBuilder::createCollection(muDaugs, "cfmig"), BPHRecoBuilder::createCollection(muDaugs, "cfmig")); vector lFull = onia->build(); int iFull; int nFull = lFull.size(); outF << nFull << " onia cand found" << endl; - for ( iFull = 0; iFull < nFull; ++iFull ) dumpRecoCand( "Full", - lFull[iFull].get() ); - - BPHMuonPtSelect ptSel1( 3.0 ); - BPHMuonPtSelect ptSel2( 3.5 ); - BPHMuonPtSelect ptSel3( 4.5 ); - BPHMuonEtaSelect etaSel1( 1.6 ); - BPHMuonEtaSelect etaSel2( 1.4 ); - BPHMuonEtaSelect etaSel3( 1.2 ); - BPHMultiSelect select1( BPHSelectOperation::and_mode ); - select1.include( ptSel1 ); - select1.include( etaSel1 ); - select1.include( etaSel2, false ); - BPHMultiSelect select2( BPHSelectOperation::and_mode ); - select2.include( ptSel2 ); - select2.include( etaSel2 ); - select2.include( etaSel3, false ); - BPHMultiSelect select3( BPHSelectOperation::and_mode ); - select3.include( ptSel3 ); - select3.include( etaSel3 ); - BPHMultiSelect muoSel( BPHSelectOperation::or_mode ); - muoSel.include( select1 ); - muoSel.include( select2 ); - muoSel.include( select3 ); - - BPHMassSelect massPh( 0.85, 1.20 ); - BPHMassSelect massP1( 2.95, 3.25 ); - BPHMassSelect massP2( 3.55, 3.80 ); - BPHMassSelect massU1( 9.10, 9.75 ); - BPHMassSelect massU2( 9.75, 10.20 ); - BPHMassSelect massU3( 10.20, 10.60 ); + for (iFull = 0; iFull < nFull; ++iFull) + dumpRecoCand("Full", lFull[iFull].get()); + + BPHMuonPtSelect ptSel1(3.0); + BPHMuonPtSelect ptSel2(3.5); + BPHMuonPtSelect ptSel3(4.5); + BPHMuonEtaSelect etaSel1(1.6); + BPHMuonEtaSelect etaSel2(1.4); + BPHMuonEtaSelect etaSel3(1.2); + BPHMultiSelect select1(BPHSelectOperation::and_mode); + select1.include(ptSel1); + select1.include(etaSel1); + select1.include(etaSel2, false); + BPHMultiSelect select2(BPHSelectOperation::and_mode); + select2.include(ptSel2); + select2.include(etaSel2); + select2.include(etaSel3, false); + BPHMultiSelect select3(BPHSelectOperation::and_mode); + select3.include(ptSel3); + select3.include(etaSel3); + BPHMultiSelect muoSel(BPHSelectOperation::or_mode); + muoSel.include(select1); + muoSel.include(select2); + muoSel.include(select3); + + BPHMassSelect massPh(0.85, 1.20); + BPHMassSelect massP1(2.95, 3.25); + BPHMassSelect massP2(3.55, 3.80); + BPHMassSelect massU1(9.10, 9.75); + BPHMassSelect massU2(9.75, 10.20); + BPHMassSelect massU3(10.20, 10.60); outF << "extract and dump JPsi" << endl; - vector lJPsi = onia->getList( - BPHOniaToMuMuBuilder::Psi1 ); + vector lJPsi = onia->getList(BPHOniaToMuMuBuilder::Psi1); int iJPsi; int nJPsi = lJPsi.size(); outF << nJPsi << " JPsi cand found" << endl; - for ( iJPsi = 0; iJPsi < nJPsi; ++iJPsi ) dumpRecoCand( "JPsi", - lJPsi[iJPsi].get() ); + for (iJPsi = 0; iJPsi < nJPsi; ++iJPsi) + dumpRecoCand("JPsi", lJPsi[iJPsi].get()); outF << "extract and dump specific onia" << endl; - vector lPmm = onia->getList( - BPHOniaToMuMuBuilder::Phi, - &muoSel, &massPh ); - vector lPsi1 = onia->getList( - BPHOniaToMuMuBuilder::Psi1, - &muoSel, &massP1 ); - vector lPsi2 = onia->getList( - BPHOniaToMuMuBuilder::Psi2, - &muoSel, &massP2 ); - vector lUps1 = onia->getList( - BPHOniaToMuMuBuilder::Ups1, - &muoSel, &massU1 ); - vector lUps2 = onia->getList( - BPHOniaToMuMuBuilder::Ups2, - &muoSel, &massU2 ); - vector lUps3 = onia->getList( - BPHOniaToMuMuBuilder::Ups3, - &muoSel, &massU3 ); + vector lPmm = onia->getList(BPHOniaToMuMuBuilder::Phi, &muoSel, &massPh); + vector lPsi1 = onia->getList(BPHOniaToMuMuBuilder::Psi1, &muoSel, &massP1); + vector lPsi2 = onia->getList(BPHOniaToMuMuBuilder::Psi2, &muoSel, &massP2); + vector lUps1 = onia->getList(BPHOniaToMuMuBuilder::Ups1, &muoSel, &massU1); + vector lUps2 = onia->getList(BPHOniaToMuMuBuilder::Ups2, &muoSel, &massU2); + vector lUps3 = onia->getList(BPHOniaToMuMuBuilder::Ups3, &muoSel, &massU3); int iPhi; int nPhi = lPmm.size(); outF << nPhi << " PhiMuMu cand found" << endl; - for ( iPhi = 0; iPhi < nPhi ; ++iPhi ) dumpRecoCand( "PhiMuMu", - lPmm[iPhi ].get() ); + for (iPhi = 0; iPhi < nPhi; ++iPhi) + dumpRecoCand("PhiMuMu", lPmm[iPhi].get()); int iPsi1; int nPsi1 = lPsi1.size(); outF << nPsi1 << " Psi1 cand found" << endl; - for ( iPsi1 = 0; iPsi1 < nPsi1; ++iPsi1 ) dumpRecoCand( "Psi1", - lPsi1[iPsi1].get() ); + for (iPsi1 = 0; iPsi1 < nPsi1; ++iPsi1) + dumpRecoCand("Psi1", lPsi1[iPsi1].get()); int iPsi2; int nPsi2 = lPsi2.size(); outF << nPsi2 << " Psi2 cand found" << endl; - for ( iPsi2 = 0; iPsi2 < nPsi2; ++iPsi2 ) dumpRecoCand( "Psi2", - lPsi2[iPsi2].get() ); + for (iPsi2 = 0; iPsi2 < nPsi2; ++iPsi2) + dumpRecoCand("Psi2", lPsi2[iPsi2].get()); int iUps1; int nUps1 = lUps1.size(); outF << nUps1 << " Ups1 cand found" << endl; - for ( iUps1 = 0; iUps1 < nUps1; ++iUps1 ) dumpRecoCand( "Ups1", - lUps1[iUps1].get() ); + for (iUps1 = 0; iUps1 < nUps1; ++iUps1) + dumpRecoCand("Ups1", lUps1[iUps1].get()); int iUps2; int nUps2 = lUps2.size(); outF << nUps2 << " Ups2 cand found" << endl; - for ( iUps2 = 0; iUps2 < nUps2; ++iUps2 ) dumpRecoCand( "Ups2", - lUps2[iUps2].get() ); + for (iUps2 = 0; iUps2 < nUps2; ++iUps2) + dumpRecoCand("Ups2", lUps2[iUps2].get()); int iUps3; int nUps3 = lUps3.size(); outF << nUps3 << " Ups3 cand found" << endl; - for ( iUps3 = 0; iUps3 < nUps3; ++iUps3 ) dumpRecoCand( "Ups3", - lUps3[iUps3].get() ); + for (iUps3 = 0; iUps3 < nUps3; ++iUps3) + dumpRecoCand("Ups3", lUps3[iUps3].get()); delete onia; - if ( !nPsi1 ) return; - if ( !nrc ) return; + if (!nPsi1) + return; + if (!nrc) + return; - BPHParticlePtSelect tkPt( 0.7 ); - BPHMassSelect mJPsi( 3.00, 3.17 ); - BPHChi2Select chi2Bs( 0.02 ); + BPHParticlePtSelect tkPt(0.7); + BPHMassSelect mJPsi(3.00, 3.17); + BPHChi2Select chi2Bs(0.02); // build and dump Bu outF << "build and dump Bu" << endl; BPHBuToJPsiKBuilder* bu = 0; - if ( usePF ) bu = new BPHBuToJPsiKBuilder( es, lJPsi,//lFull,//lPsi1, - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) bu = new BPHBuToJPsiKBuilder( es, lJPsi,//lFull,//lPsi1, - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) bu = new BPHBuToJPsiKBuilder( es, lJPsi,//lFull,//lPsi1, - BPHRecoBuilder::createCollection( gpCands ) ); + if (usePF) + bu = new BPHBuToJPsiKBuilder(es, + lJPsi, //lFull,//lPsi1, + BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + bu = new BPHBuToJPsiKBuilder(es, + lJPsi, //lFull,//lPsi1, + BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + bu = new BPHBuToJPsiKBuilder(es, + lJPsi, //lFull,//lPsi1, + BPHRecoBuilder::createCollection(gpCands)); vector lBu = bu->build(); int iBu; int nBu = lBu.size(); outF << nBu << " Bu cand found" << endl; - for ( iBu = 0; iBu < nBu; ++iBu ) dumpRecoCand( "Bu", - lBu[iBu].get() ); + for (iBu = 0; iBu < nBu; ++iBu) + dumpRecoCand("Bu", lBu[iBu].get()); // the following is an example of decay reconstruction starting from // specific reco::Candidates // here the final decay products are taken from already reconstructed B+, // so there's no physical sense in the operation - for ( iBu = 0; iBu < nBu; ++iBu ) { + for (iBu = 0; iBu < nBu; ++iBu) { const BPHRecoCandidate* bu = lBu[iBu].get(); - const reco::Candidate* mPos = bu->originalReco( - bu->getDaug( "JPsi/MuPos" ) ); - const reco::Candidate* mNeg = bu->originalReco( - bu->getDaug( "JPsi/MuNeg" ) ); - const reco::Candidate* kaon = bu->originalReco( - bu->getDaug( "Kaon" ) ); - BPHRecoCandidatePtr njp( new BPHPlusMinusCandidate( &es ) ); - njp->add( "MuPos", mPos, - BPHParticleMasses::muonMass, - BPHParticleMasses::muonMSigma ); - njp->add( "MuNeg", mNeg, - BPHParticleMasses::muonMass, - BPHParticleMasses::muonMSigma ); - BPHRecoCandidate nbu( &es ); - nbu.add( "JPsi", njp ); - nbu.add( "Kaon", kaon, - BPHParticleMasses::kaonMass, - BPHParticleMasses::kaonMSigma ); - nbu.kinematicTree( "JPsi", - BPHParticleMasses::jPsiMass, - BPHParticleMasses::jPsiMWidth ); - dumpRecoCand( "nBu", &nbu ); + const reco::Candidate* mPos = bu->originalReco(bu->getDaug("JPsi/MuPos")); + const reco::Candidate* mNeg = bu->originalReco(bu->getDaug("JPsi/MuNeg")); + const reco::Candidate* kaon = bu->originalReco(bu->getDaug("Kaon")); + BPHRecoCandidatePtr njp(new BPHPlusMinusCandidate(&es)); + njp->add("MuPos", mPos, BPHParticleMasses::muonMass, BPHParticleMasses::muonMSigma); + njp->add("MuNeg", mNeg, BPHParticleMasses::muonMass, BPHParticleMasses::muonMSigma); + BPHRecoCandidate nbu(&es); + nbu.add("JPsi", njp); + nbu.add("Kaon", kaon, BPHParticleMasses::kaonMass, BPHParticleMasses::kaonMSigma); + nbu.kinematicTree("JPsi", BPHParticleMasses::jPsiMass, BPHParticleMasses::jPsiMWidth); + dumpRecoCand("nBu", &nbu); } // build and dump Kx0 BPHKx0ToKPiBuilder* kx0 = 0; - if ( usePF ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( pfCands ), - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( pcCands ), - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) kx0 = new BPHKx0ToKPiBuilder( es, - BPHRecoBuilder::createCollection( gpCands ), - BPHRecoBuilder::createCollection( gpCands ) ); + if (usePF) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(pfCands), BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(pcCands), BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + kx0 = new BPHKx0ToKPiBuilder( + es, BPHRecoBuilder::createCollection(gpCands), BPHRecoBuilder::createCollection(gpCands)); vector lKx0 = kx0->build(); int iKx0; int nKx0 = lKx0.size(); outF << nKx0 << " Kx0 cand found" << endl; - for ( iKx0 = 0; iKx0 < nKx0; ++iKx0 ) dumpRecoCand( "Kx0", - lKx0[iKx0].get() ); + for (iKx0 = 0; iKx0 < nKx0; ++iKx0) + dumpRecoCand("Kx0", lKx0[iKx0].get()); delete kx0; // build and dump Bd outF << "build and dump Bd" << endl; - if ( nKx0 ) { - BPHBdToJPsiKxBuilder* bd = new BPHBdToJPsiKxBuilder( es, lJPsi, lKx0 ); - vector lBd = bd->build(); - int iBd; - int nBd = lBd.size(); - outF << nBd << " Bd cand found" << endl; - for ( iBd = 0; iBd < nBd; ++iBd ) dumpRecoCand( "Bd", - lBd[iBd].get() ); + if (nKx0) { + BPHBdToJPsiKxBuilder* bd = new BPHBdToJPsiKxBuilder(es, lJPsi, lKx0); + vector lBd = bd->build(); + int iBd; + int nBd = lBd.size(); + outF << nBd << " Bd cand found" << endl; + for (iBd = 0; iBd < nBd; ++iBd) + dumpRecoCand("Bd", lBd[iBd].get()); } // build and dump Phi BPHPhiToKKBuilder* phi = 0; - if ( usePF ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( pfCands ), - BPHRecoBuilder::createCollection( pfCands ) ); - else - if ( usePC ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( pcCands ), - BPHRecoBuilder::createCollection( pcCands ) ); - else - if ( useGP ) phi = new BPHPhiToKKBuilder( es, - BPHRecoBuilder::createCollection( gpCands ), - BPHRecoBuilder::createCollection( gpCands ) ); + if (usePF) + phi = + new BPHPhiToKKBuilder(es, BPHRecoBuilder::createCollection(pfCands), BPHRecoBuilder::createCollection(pfCands)); + else if (usePC) + phi = + new BPHPhiToKKBuilder(es, BPHRecoBuilder::createCollection(pcCands), BPHRecoBuilder::createCollection(pcCands)); + else if (useGP) + phi = + new BPHPhiToKKBuilder(es, BPHRecoBuilder::createCollection(gpCands), BPHRecoBuilder::createCollection(gpCands)); vector lPkk = phi->build(); int iPkk; int nPkk = lPkk.size(); outF << nPkk << " PhiKK cand found" << endl; - for ( iPkk = 0; iPkk < nPkk; ++iPkk ) dumpRecoCand( "PhiKK", - lPkk[iPkk].get() ); + for (iPkk = 0; iPkk < nPkk; ++iPkk) + dumpRecoCand("PhiKK", lPkk[iPkk].get()); delete phi; // build and dump Bs outF << "build and dump Bs" << endl; - if ( nPkk ) { - BPHBsToJPsiPhiBuilder* bs = new BPHBsToJPsiPhiBuilder( es, lJPsi, lPkk ); - vector lBs = bs->build(); - int iBs; - int nBs = lBs.size(); - outF << nBs << " Bs cand found" << endl; - for ( iBs = 0; iBs < nBs; ++iBs ) dumpRecoCand( "Bs", - lBs[iBs].get() ); + if (nPkk) { + BPHBsToJPsiPhiBuilder* bs = new BPHBsToJPsiPhiBuilder(es, lJPsi, lPkk); + vector lBs = bs->build(); + int iBs; + int nBs = lBs.size(); + outF << nBs << " Bs cand found" << endl; + for (iBs = 0; iBs < nBs; ++iBs) + dumpRecoCand("Bs", lBs[iBs].get()); } return; - } - void TestBPHSpecificDecay::endJob() { *fPtr << "TestBPHSpecificDecay::endJob" << endl; TDirectory* currentDir = gDirectory; - TFile file( outHist.c_str(), "RECREATE" ); - map::iterator iter = histoMap.begin(); - map::iterator iend = histoMap.end(); - while ( iter != iend ) iter++->second->Write(); + TFile file(outHist.c_str(), "RECREATE"); + map::iterator iter = histoMap.begin(); + map::iterator iend = histoMap.end(); + while (iter != iend) + iter++->second->Write(); currentDir->cd(); return; } - -void TestBPHSpecificDecay::dumpRecoCand( const string& name, - const BPHRecoCandidate* cand ) { - - fillHisto( name, cand ); - if ( ( name == "PhiMuMu" ) || - ( name == "Psi1" ) || - ( name == "Psi2" ) || - ( name == "Ups1" ) || - ( name == "Ups2" ) || - ( name == "Ups3" ) ) fillHisto( "Fsel", cand ); +void TestBPHSpecificDecay::dumpRecoCand(const string& name, const BPHRecoCandidate* cand) { + fillHisto(name, cand); + if ((name == "PhiMuMu") || (name == "Psi1") || (name == "Psi2") || (name == "Ups1") || (name == "Ups2") || + (name == "Ups3")) + fillHisto("Fsel", cand); ostream& outF = *fPtr; @@ -474,152 +438,120 @@ void TestBPHSpecificDecay::dumpRecoCand( const string& name, static string sType = " sailor"; static string dType = ""; string* type; - const BPHPlusMinusCandidate* pmCand = - dynamic_cast( cand ); - if ( pmCand != 0 ) { - if ( pmCand->isCowboy() ) type = &cType; - else type = &sType; - } - else type = &dType; - - outF << "****** " << name << " cand mass: " - << cand->composite().mass() << " momentum " - << cand->composite().px() << " " - << cand->composite().py() << " " - << cand->composite().pz() << *type << endl; + const BPHPlusMinusCandidate* pmCand = dynamic_cast(cand); + if (pmCand != 0) { + if (pmCand->isCowboy()) + type = &cType; + else + type = &sType; + } else + type = &dType; + + outF << "****** " << name << " cand mass: " << cand->composite().mass() << " momentum " << cand->composite().px() + << " " << cand->composite().py() << " " << cand->composite().pz() << *type << endl; bool validFit = cand->isValidFit(); - const RefCountedKinematicTree kt = cand->kinematicTree(); + const RefCountedKinematicTree kt = cand->kinematicTree(); const RefCountedKinematicParticle kp = cand->currentParticle(); - if ( validFit ) { - outF << "****** " << name << " constr mass: " - << cand->p4().mass() << " momentum " - << cand->p4().px() << " " - << cand->p4().py() << " " - << cand->p4().pz() << endl; + if (validFit) { + outF << "****** " << name << " constr mass: " << cand->p4().mass() << " momentum " << cand->p4().px() << " " + << cand->p4().py() << " " << cand->p4().pz() << endl; } const reco::Vertex& vx = cand->vertex(); const reco::Vertex::Point& vp = vx.position(); double chi2 = vx.chi2(); - int ndof = lround( vx.ndof() ); - double prob = TMath::Prob( chi2, ndof ); + int ndof = lround(vx.ndof()); + double prob = TMath::Prob(chi2, ndof); string tdca = ""; - if ( pmCand != 0 ) { + if (pmCand != 0) { stringstream sstr; sstr << " - " << pmCand->cAppInRPhi().distance(); tdca = sstr.str(); } - outF << "****** " << name << " vertex: " - << vx.isFake() << " " << vx.isValid() << " - " - << chi2 << " " << ndof << " " << prob << " - " - << vp.X() << " " << vp.Y() << " " << vp.Z() << tdca << endl; + outF << "****** " << name << " vertex: " << vx.isFake() << " " << vx.isValid() << " - " << chi2 << " " << ndof << " " + << prob << " - " << vp.X() << " " << vp.Y() << " " << vp.Z() << tdca << endl; const vector& dl = cand->daugNames(); int i; int n = dl.size(); - for ( i = 0; i < n; ++i ) { + for (i = 0; i < n; ++i) { const string& name = dl[i]; - const reco::Candidate* dp = cand->getDaug( name ); - GlobalPoint gp( vp.X(), vp.Y(), vp.Z() ); - GlobalVector dm( 0.0, 0.0, 0.0 ); - const reco::TransientTrack* tt = cand->getTransientTrack( dp ); - if ( tt != 0 ) { - TrajectoryStateClosestToPoint tscp = - tt->trajectoryStateClosestToPoint( gp ); + const reco::Candidate* dp = cand->getDaug(name); + GlobalPoint gp(vp.X(), vp.Y(), vp.Z()); + GlobalVector dm(0.0, 0.0, 0.0); + const reco::TransientTrack* tt = cand->getTransientTrack(dp); + if (tt != 0) { + TrajectoryStateClosestToPoint tscp = tt->trajectoryStateClosestToPoint(gp); dm = tscp.momentum(); -// TrajectoryStateOnSurface tsos = tt->stateOnSurface( gp ); -// GlobalVector gv = tsos.globalMomentum(); + // TrajectoryStateOnSurface tsos = tt->stateOnSurface( gp ); + // GlobalVector gv = tsos.globalMomentum(); } - outF << "daughter " << i - << " " << name - << " " << ( dp->charge() > 0 ? '+' : '-' ) - << " momentum: " - << dp->px() << " " - << dp->py() << " " - << dp->pz() << " - at vertex: " - << dm.x() << " " - << dm.y() << " " - << dm.z() << endl; + outF << "daughter " << i << " " << name << " " << (dp->charge() > 0 ? '+' : '-') << " momentum: " << dp->px() << " " + << dp->py() << " " << dp->pz() << " - at vertex: " << dm.x() << " " << dm.y() << " " << dm.z() << endl; } const vector& dc = cand->compNames(); int j; int m = dc.size(); - for ( j = 0; j < m; ++j ) { + for (j = 0; j < m; ++j) { const string& name = dc[j]; - const BPHRecoCandidate* dp = cand->getComp( name ).get(); - outF << "composite daughter " << j - << " " << name - << " momentum: " - << dp->composite().px() << " " - << dp->composite().py() << " " - << dp->composite().pz() << endl; + const BPHRecoCandidate* dp = cand->getComp(name).get(); + outF << "composite daughter " << j << " " << name << " momentum: " << dp->composite().px() << " " + << dp->composite().py() << " " << dp->composite().pz() << endl; } - if ( validFit ) { - const RefCountedKinematicVertex kv = cand->currentDecayVertex(); - GlobalPoint gp = kv->position(); - outF << " kin fit vertex: " - << gp.x() << " " - << gp.y() << " " - << gp.z() << endl; - vector dk = kt->finalStateParticles(); - int k; - int l = dk.size(); - for ( k = 0; k < l; ++k ) { - const reco::TransientTrack& tt = dk[k]->refittedTransientTrack(); - TrajectoryStateClosestToPoint tscp = - tt.trajectoryStateClosestToPoint( gp ); - GlobalVector dm = tscp.momentum(); -// TrajectoryStateOnSurface tsos = tt.stateOnSurface( gp ); -// GlobalVector dm = tsos.globalMomentum(); - outF << "daughter " << k << " refitted: " - << dm.x() << " " - << dm.y() << " " - << dm.z() << endl; - } + if (validFit) { + const RefCountedKinematicVertex kv = cand->currentDecayVertex(); + GlobalPoint gp = kv->position(); + outF << " kin fit vertex: " << gp.x() << " " << gp.y() << " " << gp.z() << endl; + vector dk = kt->finalStateParticles(); + int k; + int l = dk.size(); + for (k = 0; k < l; ++k) { + const reco::TransientTrack& tt = dk[k]->refittedTransientTrack(); + TrajectoryStateClosestToPoint tscp = tt.trajectoryStateClosestToPoint(gp); + GlobalVector dm = tscp.momentum(); + // TrajectoryStateOnSurface tsos = tt.stateOnSurface( gp ); + // GlobalVector dm = tsos.globalMomentum(); + outF << "daughter " << k << " refitted: " << dm.x() << " " << dm.y() << " " << dm.z() << endl; + } } return; - } - -void TestBPHSpecificDecay::fillHisto( const string& name, - const BPHRecoCandidate* cand ) { +void TestBPHSpecificDecay::fillHisto(const string& name, const BPHRecoCandidate* cand) { string mass = "mass"; string mcst = "mcst"; - fillHisto( mass + name, cand->composite().mass() ); - if ( cand->isValidFit() ) - fillHisto( mcst + name, cand->p4() .mass() ); + fillHisto(mass + name, cand->composite().mass()); + if (cand->isValidFit()) + fillHisto(mcst + name, cand->p4().mass()); const vector& dc = cand->compNames(); int i; int n = dc.size(); - for ( i = 0; i < n; ++i ) { + for (i = 0; i < n; ++i) { const string& daug = dc[i]; - const BPHRecoCandidate* dptr = cand->getComp( daug ).get(); - fillHisto( mass + name + daug, dptr->composite().mass() ); + const BPHRecoCandidate* dptr = cand->getComp(daug).get(); + fillHisto(mass + name + daug, dptr->composite().mass()); } return; } - -void TestBPHSpecificDecay::fillHisto( const string& name, float x ) { - map::iterator iter = histoMap.find( name ); - map::iterator iend = histoMap.end(); - if ( iter == iend ) return; - iter->second->Fill( x ); +void TestBPHSpecificDecay::fillHisto(const string& name, float x) { + map::iterator iter = histoMap.find(name); + map::iterator iend = histoMap.end(); + if (iter == iend) + return; + iter->second->Fill(x); return; } - -void TestBPHSpecificDecay::createHisto( const string& name, - int nbin, float hmin, float hmax ) { - histoMap[name] = new TH1F( name.c_str(), name.c_str(), nbin, hmin, hmax ); +void TestBPHSpecificDecay::createHisto(const string& name, int nbin, float hmin, float hmax) { + histoMap[name] = new TH1F(name.c_str(), name.c_str(), nbin, hmin, hmax); return; } #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( TestBPHSpecificDecay ); +DEFINE_FWK_MODULE(TestBPHSpecificDecay); diff --git a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.h b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.h index 278b6020cf22e..c276440006a5d 100644 --- a/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.h +++ b/HeavyFlavorAnalysis/SpecificDecay/test/stubs/TestBPHSpecificDecay.h @@ -21,22 +21,18 @@ class TH1F; class BPHRecoCandidate; -class TestBPHSpecificDecay: - public BPHAnalyzerWrapper { - - public: - - explicit TestBPHSpecificDecay( const edm::ParameterSet& ps ); +class TestBPHSpecificDecay : public BPHAnalyzerWrapper { +public: + explicit TestBPHSpecificDecay(const edm::ParameterSet& ps); virtual ~TestBPHSpecificDecay(); - static void fillDescriptions( edm::ConfigurationDescriptions& descriptions ); + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); virtual void beginJob(); - virtual void analyze( const edm::Event& ev, const edm::EventSetup& es ); + virtual void analyze(const edm::Event& ev, const edm::EventSetup& es); virtual void endJob(); - private: - +private: std::string patMuonLabel; std::string ccCandsLabel; std::string pfCandsLabel; @@ -44,11 +40,11 @@ class TestBPHSpecificDecay: std::string gpCandsLabel; // token wrappers to allow running both on "old" and "new" CMSSW versions - BPHTokenWrapper< pat::MuonCollection > patMuonToken; - BPHTokenWrapper< std::vector > ccCandsToken; - BPHTokenWrapper< std::vector > pfCandsToken; - BPHTokenWrapper< std::vector > pcCandsToken; - BPHTokenWrapper< std::vector > gpCandsToken; + BPHTokenWrapper patMuonToken; + BPHTokenWrapper > ccCandsToken; + BPHTokenWrapper > pfCandsToken; + BPHTokenWrapper > pcCandsToken; + BPHTokenWrapper > gpCandsToken; bool usePM; bool useCC; @@ -61,17 +57,13 @@ class TestBPHSpecificDecay: std::ostream* fPtr; - std::map histoMap; - - void dumpRecoCand( const std::string& name, - const BPHRecoCandidate* cand ); - void fillHisto ( const std::string& name, - const BPHRecoCandidate* cand ); - void fillHisto( const std::string& name, float x ); + std::map histoMap; - void createHisto( const std::string& name, - int nbin, float hmin, float hmax ); + void dumpRecoCand(const std::string& name, const BPHRecoCandidate* cand); + void fillHisto(const std::string& name, const BPHRecoCandidate* cand); + void fillHisto(const std::string& name, float x); + void createHisto(const std::string& name, int nbin, float hmin, float hmax); }; #endif diff --git a/HiggsAnalysis/Skimming/interface/HeavyChHiggsToTauNuSkim.h b/HiggsAnalysis/Skimming/interface/HeavyChHiggsToTauNuSkim.h index 367dc95b4b1d6..a2b4cd3ad112a 100644 --- a/HiggsAnalysis/Skimming/interface/HeavyChHiggsToTauNuSkim.h +++ b/HiggsAnalysis/Skimming/interface/HeavyChHiggsToTauNuSkim.h @@ -30,47 +30,46 @@ #include class HeavyChHiggsToTauNuSkim : public edm::EDFilter { - - public: - explicit HeavyChHiggsToTauNuSkim(const edm::ParameterSet&); - ~HeavyChHiggsToTauNuSkim() override; - - bool filter(edm::Event&, const edm::EventSetup& ) override; - - private: - double deltaPhi(double phi1, double phi2){ - const double PI = 3.1415926535; - // in ORCA phi = [0,2pi], in TLorentzVector phi = [-pi,pi]. - // With the conversion below deltaPhi works ok despite the - // 2*pi difference in phi definitions. - if(phi1 < 0) phi1 += 2*PI; - if(phi2 < 0) phi2 += 2*PI; - - double dphi = fabs(phi1-phi2); - - if(dphi > PI) dphi = 2*PI - dphi; - return dphi; - } - - double deltaR(double eta1, double eta2, double phi1, double phi2){ - double dphi = deltaPhi(phi1,phi2); - double deta = fabs(eta1-eta2); - return sqrt(dphi*dphi + deta*deta); - } - - bool debug; - - edm::EDGetTokenT hltTauToken; - edm::EDGetTokenT jetToken; - int minNumberOfjets; - double jetEtMin; - double jetEtaMin; - double jetEtaMax; - double minDRFromTau; - - int nEvents, nSelectedEvents; +public: + explicit HeavyChHiggsToTauNuSkim(const edm::ParameterSet&); + ~HeavyChHiggsToTauNuSkim() override; + + bool filter(edm::Event&, const edm::EventSetup&) override; + +private: + double deltaPhi(double phi1, double phi2) { + const double PI = 3.1415926535; + // in ORCA phi = [0,2pi], in TLorentzVector phi = [-pi,pi]. + // With the conversion below deltaPhi works ok despite the + // 2*pi difference in phi definitions. + if (phi1 < 0) + phi1 += 2 * PI; + if (phi2 < 0) + phi2 += 2 * PI; + + double dphi = fabs(phi1 - phi2); + + if (dphi > PI) + dphi = 2 * PI - dphi; + return dphi; + } + + double deltaR(double eta1, double eta2, double phi1, double phi2) { + double dphi = deltaPhi(phi1, phi2); + double deta = fabs(eta1 - eta2); + return sqrt(dphi * dphi + deta * deta); + } + + bool debug; + + edm::EDGetTokenT hltTauToken; + edm::EDGetTokenT jetToken; + int minNumberOfjets; + double jetEtMin; + double jetEtaMin; + double jetEtaMax; + double minDRFromTau; + + int nEvents, nSelectedEvents; }; #endif - - - diff --git a/HiggsAnalysis/Skimming/interface/HiggsTo2GammaSkim.h b/HiggsAnalysis/Skimming/interface/HiggsTo2GammaSkim.h index 6918ee4e2e796..e2cd2d2218ed1 100644 --- a/HiggsAnalysis/Skimming/interface/HiggsTo2GammaSkim.h +++ b/HiggsAnalysis/Skimming/interface/HiggsTo2GammaSkim.h @@ -25,8 +25,7 @@ #include class HiggsTo2GammaSkim : public edm::EDFilter { - - public: +public: // Constructor explicit HiggsTo2GammaSkim(const edm::ParameterSet&); @@ -34,13 +33,11 @@ class HiggsTo2GammaSkim : public edm::EDFilter { ~HiggsTo2GammaSkim() override; /// Get event properties to send to builder to fill seed collection - bool filter(edm::Event&, const edm::EventSetup& ) override; - + bool filter(edm::Event&, const edm::EventSetup&) override; - private: +private: int nEvents, nSelectedEvents; - bool debug; float photon1MinPt; float photon2MinPt; diff --git a/HiggsAnalysis/Skimming/interface/HiggsToWW2LeptonsSkim.h b/HiggsAnalysis/Skimming/interface/HiggsToWW2LeptonsSkim.h index 1b81afa8ff5ab..28f0464b4e674 100644 --- a/HiggsAnalysis/Skimming/interface/HiggsToWW2LeptonsSkim.h +++ b/HiggsAnalysis/Skimming/interface/HiggsToWW2LeptonsSkim.h @@ -27,27 +27,23 @@ #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" class HiggsToWW2LeptonsSkim : public edm::EDFilter { - public: - explicit HiggsToWW2LeptonsSkim(const edm::ParameterSet&); - ~HiggsToWW2LeptonsSkim() override; - void endJob() override ; +public: + explicit HiggsToWW2LeptonsSkim(const edm::ParameterSet&); + ~HiggsToWW2LeptonsSkim() override; + void endJob() override; - bool filter(edm::Event&, const edm::EventSetup&) override; + bool filter(edm::Event&, const edm::EventSetup&) override; - private: - double singleTrackPtMin_; - double diTrackPtMin_; - double etaMin_; - double etaMax_; - unsigned int nEvents_; - unsigned int nAccepted_; +private: + double singleTrackPtMin_; + double diTrackPtMin_; + double etaMin_; + double etaMax_; + unsigned int nEvents_; + unsigned int nAccepted_; // Reco samples edm::EDGetTokenT theGLBMuonToken; edm::EDGetTokenT theGsfEToken; - }; #endif - - - diff --git a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsPreFilter.h b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsPreFilter.h index 51639adeb034b..496f32f91e303 100644 --- a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsPreFilter.h +++ b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsPreFilter.h @@ -26,8 +26,7 @@ #include "DataFormats/HepMCCandidate/interface/GenParticle.h" class HiggsToZZ4LeptonsPreFilter : public edm::EDFilter { - - public: +public: // Constructor explicit HiggsToZZ4LeptonsPreFilter(const edm::ParameterSet&); @@ -35,10 +34,9 @@ class HiggsToZZ4LeptonsPreFilter : public edm::EDFilter { ~HiggsToZZ4LeptonsPreFilter() override; /// Get event properties to send to builder to fill seed collection - bool filter(edm::Event&, const edm::EventSetup& ) override; - + bool filter(edm::Event&, const edm::EventSetup&) override; - private: +private: int evt, ikept; bool debug; diff --git a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkim.h b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkim.h index c2ecea660048c..31afae4f7640c 100644 --- a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkim.h +++ b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkim.h @@ -29,8 +29,7 @@ #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" class HiggsToZZ4LeptonsSkim : public edm::EDFilter { - - public: +public: // Constructor explicit HiggsToZZ4LeptonsSkim(const edm::ParameterSet&); @@ -38,13 +37,11 @@ class HiggsToZZ4LeptonsSkim : public edm::EDFilter { ~HiggsToZZ4LeptonsSkim() override; /// Get event properties to send to builder to fill seed collection - bool filter(edm::Event&, const edm::EventSetup& ) override; - + bool filter(edm::Event&, const edm::EventSetup&) override; - private: +private: int nEvents, nSelectedEvents; - bool debug; float stiffMinPt; float softMinPt; diff --git a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkimEff.h b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkimEff.h index ef56a190068a1..6c196d97a7d13 100644 --- a/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkimEff.h +++ b/HiggsAnalysis/Skimming/interface/HiggsToZZ4LeptonsSkimEff.h @@ -27,8 +27,7 @@ #include "DataFormats/HepMCCandidate/interface/GenParticle.h" class HiggsToZZ4LeptonsSkimEff : public edm::EDAnalyzer { - - public: +public: // Constructor explicit HiggsToZZ4LeptonsSkimEff(const edm::ParameterSet&); @@ -36,10 +35,9 @@ class HiggsToZZ4LeptonsSkimEff : public edm::EDAnalyzer { ~HiggsToZZ4LeptonsSkimEff() override; /// Get event properties to send to builder to fill seed collection - void analyze(const edm::Event&, const edm::EventSetup& ) override; - + void analyze(const edm::Event&, const edm::EventSetup&) override; - private: +private: bool debug; float stiffMinPt; float softMinPt; diff --git a/HiggsAnalysis/Skimming/src/HeavyChHiggsToTauNuSkim.cc b/HiggsAnalysis/Skimming/src/HeavyChHiggsToTauNuSkim.cc index f4e4d8d76d3fc..6eb1f3c0b9fbe 100644 --- a/HiggsAnalysis/Skimming/src/HeavyChHiggsToTauNuSkim.cc +++ b/HiggsAnalysis/Skimming/src/HeavyChHiggsToTauNuSkim.cc @@ -22,52 +22,45 @@ using namespace edm; using namespace std; using namespace reco; - HeavyChHiggsToTauNuSkim::HeavyChHiggsToTauNuSkim(const edm::ParameterSet& iConfig) { - - // Local Debug flag - debug = iConfig.getParameter("DebugHeavyChHiggsToTauNuSkim"); - - hltTauToken = consumes(iConfig.getParameter("HLTTauCollection")); - jetToken = consumes(iConfig.getParameter("JetTagCollection")); - minNumberOfjets = iConfig.getParameter("minNumberOfJets"); - jetEtMin = iConfig.getParameter("jetEtMin"); - jetEtaMin = iConfig.getParameter("jetEtaMin"); - jetEtaMax = iConfig.getParameter("jetEtaMax"); - minDRFromTau = iConfig.getParameter("minDRFromTau"); - - nEvents = 0; - nSelectedEvents = 0; - + // Local Debug flag + debug = iConfig.getParameter("DebugHeavyChHiggsToTauNuSkim"); + + hltTauToken = consumes(iConfig.getParameter("HLTTauCollection")); + jetToken = consumes(iConfig.getParameter("JetTagCollection")); + minNumberOfjets = iConfig.getParameter("minNumberOfJets"); + jetEtMin = iConfig.getParameter("jetEtMin"); + jetEtaMin = iConfig.getParameter("jetEtaMin"); + jetEtaMax = iConfig.getParameter("jetEtaMax"); + minDRFromTau = iConfig.getParameter("minDRFromTau"); + + nEvents = 0; + nSelectedEvents = 0; } - -HeavyChHiggsToTauNuSkim::~HeavyChHiggsToTauNuSkim(){ +HeavyChHiggsToTauNuSkim::~HeavyChHiggsToTauNuSkim() { edm::LogVerbatim("HeavyChHiggsToTauNuSkim") - << " Number_events_read " << nEvents - << " Number_events_kept " << nSelectedEvents - << " Efficiency " << ((double)nSelectedEvents)/((double) nEvents + 0.01) << std::endl; - + << " Number_events_read " << nEvents << " Number_events_kept " << nSelectedEvents << " Efficiency " + << ((double)nSelectedEvents) / ((double)nEvents + 0.01) << std::endl; } - -bool HeavyChHiggsToTauNuSkim::filter(edm::Event& iEvent, const edm::EventSetup& iSetup ){ - +bool HeavyChHiggsToTauNuSkim::filter(edm::Event& iEvent, const edm::EventSetup& iSetup) { nEvents++; Handle tauTagL3Handle; iEvent.getByToken(hltTauToken, tauTagL3Handle); - if ( !tauTagL3Handle.isValid() ) return false; - + if (!tauTagL3Handle.isValid()) + return false; Jet theTau; double maxEt = 0; - if (tauTagL3Handle.isValid() ) { - const IsolatedTauTagInfoCollection & L3Taus = *(tauTagL3Handle.product()); + if (tauTagL3Handle.isValid()) { + const IsolatedTauTagInfoCollection& L3Taus = *(tauTagL3Handle.product()); IsolatedTauTagInfoCollection::const_iterator i; - for ( i = L3Taus.begin(); i != L3Taus.end(); i++ ) { - if (i->discriminator() == 0) continue; + for (i = L3Taus.begin(); i != L3Taus.end(); i++) { + if (i->discriminator() == 0) + continue; Jet taujet = *(i->jet().get()); if (taujet.et() > maxEt) { maxEt = taujet.et(); @@ -76,27 +69,28 @@ bool HeavyChHiggsToTauNuSkim::filter(edm::Event& iEvent, const edm::EventSetup& } } - if (maxEt == 0) return false; + if (maxEt == 0) + return false; // jets Handle jetHandle; - iEvent.getByToken(jetToken,jetHandle); + iEvent.getByToken(jetToken, jetHandle); - if ( !jetHandle.isValid() ) return false; + if (!jetHandle.isValid()) + return false; bool accepted = false; - if (jetHandle.isValid() ) { + if (jetHandle.isValid()) { int nJets = 0; - const reco::CaloJetCollection & jets = *(jetHandle.product()); + const reco::CaloJetCollection& jets = *(jetHandle.product()); CaloJetCollection::const_iterator iJet; - for (iJet = jets.begin(); iJet!= jets.end(); iJet++ ) { - if (iJet->et() > jetEtMin && - iJet->eta() > jetEtaMin && - iJet->eta() < jetEtaMax ) { - double DR = deltaR(theTau.eta(),iJet->eta(),theTau.phi(),iJet->phi()); - if (DR > minDRFromTau) nJets++; + for (iJet = jets.begin(); iJet != jets.end(); iJet++) { + if (iJet->et() > jetEtMin && iJet->eta() > jetEtaMin && iJet->eta() < jetEtaMax) { + double DR = deltaR(theTau.eta(), iJet->eta(), theTau.phi(), iJet->phi()); + if (DR > minDRFromTau) + nJets++; } } if (nJets >= minNumberOfjets) { diff --git a/HiggsAnalysis/Skimming/src/HiggsTo2GammaSkim.cc b/HiggsAnalysis/Skimming/src/HiggsTo2GammaSkim.cc index 2661fef103cca..e12f5447050aa 100644 --- a/HiggsAnalysis/Skimming/src/HiggsTo2GammaSkim.cc +++ b/HiggsAnalysis/Skimming/src/HiggsTo2GammaSkim.cc @@ -7,7 +7,6 @@ * */ - // system include files #include @@ -28,58 +27,47 @@ using namespace std; using namespace edm; using namespace reco; - // Constructor HiggsTo2GammaSkim::HiggsTo2GammaSkim(const edm::ParameterSet& pset) { - // Local Debug flag - debug = pset.getParameter("DebugHiggsTo2GammaSkim"); + debug = pset.getParameter("DebugHiggsTo2GammaSkim"); // Reconstructed objects - thePhotonToken = consumes(pset.getParameter("PhotonCollectionLabel")); + thePhotonToken = consumes(pset.getParameter("PhotonCollectionLabel")); // Minimum Pt for photons for skimming - photon1MinPt = pset.getParameter("photon1MinimumPt"); - nPhotonMin = pset.getParameter("nPhotonMinimum"); - + photon1MinPt = pset.getParameter("photon1MinimumPt"); + nPhotonMin = pset.getParameter("nPhotonMinimum"); - nEvents = 0; + nEvents = 0; nSelectedEvents = 0; - } - // Destructor HiggsTo2GammaSkim::~HiggsTo2GammaSkim() { - - edm::LogVerbatim("HiggsTo2GammaSkim") - << " Number_events_read " << nEvents - << " Number_events_kept " << nSelectedEvents - << " Efficiency " << ((double)nSelectedEvents)/((double) nEvents + 0.01) << std::endl; + edm::LogVerbatim("HiggsTo2GammaSkim") << " Number_events_read " << nEvents << " Number_events_kept " + << nSelectedEvents << " Efficiency " + << ((double)nSelectedEvents) / ((double)nEvents + 0.01) << std::endl; } - - // Filter event -bool HiggsTo2GammaSkim::filter(edm::Event& event, const edm::EventSetup& setup ) { - +bool HiggsTo2GammaSkim::filter(edm::Event& event, const edm::EventSetup& setup) { nEvents++; using reco::PhotonCollection; - bool keepEvent = false; - int nPhotons = 0; + bool keepEvent = false; + int nPhotons = 0; // Look at photons: // Get the photon collection from the event edm::Handle photonHandle; - event.getByToken(thePhotonToken,photonHandle); + event.getByToken(thePhotonToken, photonHandle); - if ( photonHandle.isValid() ) { - - const reco::PhotonCollection* phoCollection = photonHandle.product(); + if (photonHandle.isValid()) { + const reco::PhotonCollection* phoCollection = photonHandle.product(); reco::PhotonCollection::const_iterator photons; @@ -88,18 +76,19 @@ bool HiggsTo2GammaSkim::filter(edm::Event& event, const edm::EventSetup& setup ) // Question: do we need to take the reconstructed primary vertex at this point? // Here, I assume that the et is taken with respect to the nominal vertex (0,0,0). - for ( photons = phoCollection->begin(); photons != phoCollection->end(); ++photons ) { + for (photons = phoCollection->begin(); photons != phoCollection->end(); ++photons) { float et_p = photons->et(); - if ( et_p > photon1MinPt) nPhotons++; + if (et_p > photon1MinPt) + nPhotons++; } } // Make decision: - if ( nPhotons >= nPhotonMin ) keepEvent = true; + if (nPhotons >= nPhotonMin) + keepEvent = true; - if (keepEvent) nSelectedEvents++; + if (keepEvent) + nSelectedEvents++; return keepEvent; } - - diff --git a/HiggsAnalysis/Skimming/src/HiggsToWW2LeptonsSkim.cc b/HiggsAnalysis/Skimming/src/HiggsToWW2LeptonsSkim.cc index 10dd31d66e8cf..87e0a0afa4eca 100644 --- a/HiggsAnalysis/Skimming/src/HiggsToWW2LeptonsSkim.cc +++ b/HiggsAnalysis/Skimming/src/HiggsToWW2LeptonsSkim.cc @@ -20,7 +20,6 @@ #include "DataFormats/Candidate/interface/Candidate.h" - #include #include "FWCore/MessageLogger/interface/MessageLogger.h" @@ -29,44 +28,31 @@ using namespace edm; using namespace std; using namespace reco; -HiggsToWW2LeptonsSkim::HiggsToWW2LeptonsSkim(const edm::ParameterSet& iConfig) : - nEvents_(0), nAccepted_(0) -{ - +HiggsToWW2LeptonsSkim::HiggsToWW2LeptonsSkim(const edm::ParameterSet& iConfig) : nEvents_(0), nAccepted_(0) { // Reconstructed objects - theGLBMuonToken = consumes(iConfig.getParameter("GlobalMuonCollectionLabel")); - theGsfEToken = consumes(iConfig.getParameter("ElectronCollectionLabel")); + theGLBMuonToken = consumes(iConfig.getParameter("GlobalMuonCollectionLabel")); + theGsfEToken = consumes(iConfig.getParameter("ElectronCollectionLabel")); singleTrackPtMin_ = iConfig.getParameter("SingleTrackPtMin"); - diTrackPtMin_ = iConfig.getParameter("DiTrackPtMin"); - etaMin_ = iConfig.getParameter("etaMin"); - etaMax_ = iConfig.getParameter("etaMax"); + diTrackPtMin_ = iConfig.getParameter("DiTrackPtMin"); + etaMin_ = iConfig.getParameter("etaMin"); + etaMax_ = iConfig.getParameter("etaMax"); } +HiggsToWW2LeptonsSkim::~HiggsToWW2LeptonsSkim() {} -HiggsToWW2LeptonsSkim::~HiggsToWW2LeptonsSkim() -{ -} - -void HiggsToWW2LeptonsSkim::endJob() -{ +void HiggsToWW2LeptonsSkim::endJob() { edm::LogVerbatim("HiggsToWW2LeptonsSkim") - << "Events read " << nEvents_ - << " Events accepted " << nAccepted_ - << "\nEfficiency " << ((double)nAccepted_)/((double)nEvents_) - << std::endl; + << "Events read " << nEvents_ << " Events accepted " << nAccepted_ << "\nEfficiency " + << ((double)nAccepted_) / ((double)nEvents_) << std::endl; } - -bool HiggsToWW2LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& iSetup) -{ - +bool HiggsToWW2LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& iSetup) { nEvents_++; bool accepted = false; bool accepted1 = false; int nTrackOver2ndCut = 0; - // Handle tracks; using reco::TrackCollection; @@ -75,16 +61,17 @@ bool HiggsToWW2LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& iSe edm::Handle muTracks; event.getByToken(theGLBMuonToken, muTracks); - if ( muTracks.isValid() ) { - + if (muTracks.isValid()) { reco::TrackCollection::const_iterator muons; // Loop over muon collections and count how many muons there are, // and how many are above threshold - for ( muons = muTracks->begin(); muons != muTracks->end(); ++muons ) { - if ( muons->eta() > etaMin_ && muons->eta() < etaMax_ ) { - if ( muons->pt() > singleTrackPtMin_ ) accepted1 = true; - if ( muons->pt() > diTrackPtMin_ ) nTrackOver2ndCut++; + for (muons = muTracks->begin(); muons != muTracks->end(); ++muons) { + if (muons->eta() > etaMin_ && muons->eta() < etaMax_) { + if (muons->pt() > singleTrackPtMin_) + accepted1 = true; + if (muons->pt() > diTrackPtMin_) + nTrackOver2ndCut++; } } } @@ -94,29 +81,30 @@ bool HiggsToWW2LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& iSe // Get the electron track collection from the event edm::Handle pTracks; - event.getByToken(theGsfEToken,pTracks); - - if ( pTracks.isValid() ) { + event.getByToken(theGsfEToken, pTracks); + if (pTracks.isValid()) { const reco::GsfElectronCollection* eTracks = pTracks.product(); reco::GsfElectronCollection::const_iterator electrons; // Loop over electron collections and count how many muons there are, // and how many are above threshold - for ( electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons ) { - if ( electrons->eta() > etaMin_ && electrons->eta() < etaMax_ ) { - if ( electrons->pt() > singleTrackPtMin_ ) accepted1 = true; - if ( electrons->pt() > diTrackPtMin_ ) nTrackOver2ndCut++; + for (electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons) { + if (electrons->eta() > etaMin_ && electrons->eta() < etaMax_) { + if (electrons->pt() > singleTrackPtMin_) + accepted1 = true; + if (electrons->pt() > diTrackPtMin_) + nTrackOver2ndCut++; } } } + if (accepted1 && nTrackOver2ndCut >= 2) + accepted = true; - if ( accepted1 && nTrackOver2ndCut >= 2 ) accepted = true; - - if ( accepted ) nAccepted_++; + if (accepted) + nAccepted_++; return accepted; - } diff --git a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsPreFilter.cc b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsPreFilter.cc index 453175e3c0b74..65b7e19ac1eb0 100644 --- a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsPreFilter.cc +++ b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsPreFilter.cc @@ -7,7 +7,6 @@ * */ - // system include files #include @@ -27,92 +26,93 @@ using namespace std; using namespace edm; using namespace reco; - // Constructor HiggsToZZ4LeptonsPreFilter::HiggsToZZ4LeptonsPreFilter(const edm::ParameterSet& pset) { - -// LeptonFlavour -// 0 = no tau -// 1 = 4 mu -// 2 = 4 e -// 3 = 2e 2mu + // LeptonFlavour + // 0 = no tau + // 1 = 4 mu + // 2 = 4 e + // 3 = 2e 2mu // Local Debug flag - debug = pset.getParameter("DebugHiggsToZZ4LeptonsPreFilter"); - leptonFlavour = pset.getParameter("HiggsToZZ4LeptonsPreFilterLeptonFlavour"); - genToken = consumes(edm::InputTag("genParticles")); + debug = pset.getParameter("DebugHiggsToZZ4LeptonsPreFilter"); + leptonFlavour = pset.getParameter("HiggsToZZ4LeptonsPreFilterLeptonFlavour"); + genToken = consumes(edm::InputTag("genParticles")); ikept = 0; evt = 0; } - // Destructor HiggsToZZ4LeptonsPreFilter::~HiggsToZZ4LeptonsPreFilter() { - std::cout << "number of events processed: " << evt << std::endl; std::cout << "number of events kept: " << ikept << std::endl; - } - // Filter event -bool HiggsToZZ4LeptonsPreFilter::filter(edm::Event& event, const edm::EventSetup& setup ) { - - bool keepEvent = false; +bool HiggsToZZ4LeptonsPreFilter::filter(edm::Event& event, const edm::EventSetup& setup) { + bool keepEvent = false; evt++; - bool FourL = false; - bool FourE = false; - bool FourM = false; + bool FourL = false; + bool FourE = false; + bool FourM = false; bool TwoETwoM = false; // get gen particle candidates Handle genParticles; event.getByToken(genToken, genParticles); - if ( genParticles.isValid() ) { - - int nElec = 0; - int nMuon = 0; - - for (GenParticleCollection::const_iterator mcIter=genParticles->begin(); mcIter!=genParticles->end(); ++mcIter) { - // Muons: - if ( mcIter->pdgId() == 13 || mcIter->pdgId() == -13) { - // Mother is a Z - if ( mcIter->mother()->pdgId() == 23 ) { - // In fiducial volume: - if ( mcIter->pt() < 3 ) continue; - if ( mcIter->eta() > -2.4 && mcIter->eta() < 2.4 ) nMuon++; - } - } - // Electrons: - if ( mcIter->pdgId() == 11 || mcIter->pdgId() == -11) - // Mother is a Z - if ( mcIter->mother()->pdgId() == 23 ) { - // In fiducial volume: - if ( mcIter->pt() < 3 ) continue; - if ( mcIter->eta() > -2.5 && mcIter->eta() < 2.5 ) nElec++; + if (genParticles.isValid()) { + int nElec = 0; + int nMuon = 0; + + for (GenParticleCollection::const_iterator mcIter = genParticles->begin(); mcIter != genParticles->end(); + ++mcIter) { + // Muons: + if (mcIter->pdgId() == 13 || mcIter->pdgId() == -13) { + // Mother is a Z + if (mcIter->mother()->pdgId() == 23) { + // In fiducial volume: + if (mcIter->pt() < 3) + continue; + if (mcIter->eta() > -2.4 && mcIter->eta() < 2.4) + nMuon++; + } } + // Electrons: + if (mcIter->pdgId() == 11 || mcIter->pdgId() == -11) + // Mother is a Z + if (mcIter->mother()->pdgId() == 23) { + // In fiducial volume: + if (mcIter->pt() < 3) + continue; + if (mcIter->eta() > -2.5 && mcIter->eta() < 2.5) + nElec++; + } } - - if (nElec > 3) FourE = true; - if (nMuon > 3) FourM = true; - if (nMuon > 1 && nElec > 1) TwoETwoM = true; - if ( FourE || FourM || TwoETwoM ) FourL = true; - - if ( leptonFlavour == 0 && FourL ) keepEvent = true; - if ( leptonFlavour == 1 && FourM ) keepEvent = true; - if ( leptonFlavour == 2 && FourE ) keepEvent = true; - if ( leptonFlavour == 3 && TwoETwoM ) keepEvent = true; - + if (nElec > 3) + FourE = true; + if (nMuon > 3) + FourM = true; + if (nMuon > 1 && nElec > 1) + TwoETwoM = true; + if (FourE || FourM || TwoETwoM) + FourL = true; + + if (leptonFlavour == 0 && FourL) + keepEvent = true; + if (leptonFlavour == 1 && FourM) + keepEvent = true; + if (leptonFlavour == 2 && FourE) + keepEvent = true; + if (leptonFlavour == 3 && TwoETwoM) + keepEvent = true; } - if (keepEvent ) ikept++; + if (keepEvent) + ikept++; return keepEvent; - } - - diff --git a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc index 9893eabae9b2a..a0e506016a33e 100644 --- a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc +++ b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkim.cc @@ -7,7 +7,6 @@ * */ - // system include files #include @@ -28,51 +27,41 @@ using namespace std; using namespace edm; using namespace reco; - // Constructor HiggsToZZ4LeptonsSkim::HiggsToZZ4LeptonsSkim(const edm::ParameterSet& pset) { - // Local Debug flag - debug = pset.getParameter("DebugHiggsToZZ4LeptonsSkim"); + debug = pset.getParameter("DebugHiggsToZZ4LeptonsSkim"); // Reconstructed objects - theGLBMuonToken = consumes(pset.getParameter("GlobalMuonCollectionLabel")); - theGsfEToken = consumes(pset.getParameter("ElectronCollectionLabel")); + theGLBMuonToken = consumes(pset.getParameter("GlobalMuonCollectionLabel")); + theGsfEToken = consumes(pset.getParameter("ElectronCollectionLabel")); // Minimum Pt for leptons for skimming - stiffMinPt = pset.getParameter("stiffMinimumPt"); - softMinPt = pset.getParameter("softMinimumPt"); - nStiffLeptonMin = pset.getParameter("nStiffLeptonMinimum"); - nLeptonMin = pset.getParameter("nLeptonMinimum"); + stiffMinPt = pset.getParameter("stiffMinimumPt"); + softMinPt = pset.getParameter("softMinimumPt"); + nStiffLeptonMin = pset.getParameter("nStiffLeptonMinimum"); + nLeptonMin = pset.getParameter("nLeptonMinimum"); - nEvents = 0; + nEvents = 0; nSelectedEvents = 0; - } - // Destructor HiggsToZZ4LeptonsSkim::~HiggsToZZ4LeptonsSkim() { - edm::LogVerbatim("HiggsToZZ4LeptonsSkim") - << " Number_events_read " << nEvents - << " Number_events_kept " << nSelectedEvents - << " Efficiency " << ((double)nSelectedEvents)/((double) nEvents + 0.01) << std::endl; + << " Number_events_read " << nEvents << " Number_events_kept " << nSelectedEvents << " Efficiency " + << ((double)nSelectedEvents) / ((double)nEvents + 0.01) << std::endl; } - - // Filter event -bool HiggsToZZ4LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& setup ) { - +bool HiggsToZZ4LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& setup) { nEvents++; using reco::TrackCollection; - bool keepEvent = false; - int nStiffLeptons = 0; - int nLeptons = 0; - + bool keepEvent = false; + int nStiffLeptons = 0; + int nLeptons = 0; // First look at muons: @@ -80,15 +69,16 @@ bool HiggsToZZ4LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& set edm::Handle muTracks; event.getByToken(theGLBMuonToken, muTracks); - if ( muTracks.isValid() ) { - + if (muTracks.isValid()) { reco::TrackCollection::const_iterator muons; // Loop over muon collections and count how many muons there are, // and how many are above threshold - for ( muons = muTracks->begin(); muons != muTracks->end(); ++muons ) { - if ( muons->pt() > stiffMinPt) nStiffLeptons++; - if ( muons->pt() > softMinPt) nLeptons++; + for (muons = muTracks->begin(); muons != muTracks->end(); ++muons) { + if (muons->pt() > stiffMinPt) + nStiffLeptons++; + if (muons->pt() > softMinPt) + nLeptons++; } } @@ -96,29 +86,30 @@ bool HiggsToZZ4LeptonsSkim::filter(edm::Event& event, const edm::EventSetup& set // Get the electron track collection from the event edm::Handle pTracks; - event.getByToken(theGsfEToken,pTracks); - - if ( pTracks.isValid() ) { + event.getByToken(theGsfEToken, pTracks); + if (pTracks.isValid()) { const reco::GsfElectronCollection* eTracks = pTracks.product(); reco::GsfElectronCollection::const_iterator electrons; // Loop over electron collections and count how many muons there are, // and how many are above threshold - for ( electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons ) { + for (electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons) { float pt_e = electrons->pt(); - if ( pt_e > stiffMinPt) nStiffLeptons++; - if ( pt_e > softMinPt) nLeptons++; + if (pt_e > stiffMinPt) + nStiffLeptons++; + if (pt_e > softMinPt) + nLeptons++; } } // Make decision: - if ( nStiffLeptons >= nStiffLeptonMin && nLeptons >= nLeptonMin) keepEvent = true; + if (nStiffLeptons >= nStiffLeptonMin && nLeptons >= nLeptonMin) + keepEvent = true; - if (keepEvent) nSelectedEvents++; + if (keepEvent) + nSelectedEvents++; return keepEvent; } - - diff --git a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkimEff.cc b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkimEff.cc index 3e9f82aaf9372..8cccc06ab88ef 100644 --- a/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkimEff.cc +++ b/HiggsAnalysis/Skimming/src/HiggsToZZ4LeptonsSkimEff.cc @@ -7,7 +7,6 @@ * */ - // system include files #include @@ -25,7 +24,6 @@ #include "DataFormats/Candidate/interface/CandMatchMap.h" #include "DataFormats/Common/interface/AssociationVector.h" - // C++ #include #include @@ -34,76 +32,62 @@ using namespace std; using namespace edm; using namespace reco; - // Constructor HiggsToZZ4LeptonsSkimEff::HiggsToZZ4LeptonsSkimEff(const edm::ParameterSet& pset) { - // Local Debug flag - debug = pset.getParameter("DebugHiggsToZZ4LeptonsSkim"); + debug = pset.getParameter("DebugHiggsToZZ4LeptonsSkim"); // Reconstructed objects - theGLBMuonToken = consumes(pset.getParameter("GlobalMuonCollectionLabel")); - theGsfEToken = consumes(pset.getParameter("ElectronCollectionLabel")); - genToken = consumes(edm::InputTag("genParticles")); + theGLBMuonToken = consumes(pset.getParameter("GlobalMuonCollectionLabel")); + theGsfEToken = consumes(pset.getParameter("ElectronCollectionLabel")); + genToken = consumes(edm::InputTag("genParticles")); // Minimum Pt for leptons for skimming // Minimum Pt for leptons for skimming - stiffMinPt = pset.getParameter("stiffMinimumPt"); - softMinPt = pset.getParameter("softMinimumPt"); - nStiffLeptonMin = pset.getParameter("nStiffLeptonMinimum"); - nLeptonMin = pset.getParameter("nLeptonMinimum"); + stiffMinPt = pset.getParameter("stiffMinimumPt"); + softMinPt = pset.getParameter("softMinimumPt"); + nStiffLeptonMin = pset.getParameter("nStiffLeptonMinimum"); + nLeptonMin = pset.getParameter("nLeptonMinimum"); - nEvents = 0; + nEvents = 0; nSelFourE = nSelFourM = nSelTwoETwoM = nSelFourL = nSelTau = 0; - nFourE = nFourM = nTwoETwoM = nFourL = nTau = 0; - + nFourE = nFourM = nTwoETwoM = nFourL = nTau = 0; } - // Destructor HiggsToZZ4LeptonsSkimEff::~HiggsToZZ4LeptonsSkimEff() { - std::cout << "Number of events read " << nEvents << std::endl; - std::cout << "*** Efficiency for the various subsamples *** " << endl; + std::cout << "*** Efficiency for the various subsamples *** " << endl; std::cout << "Four leptons: " - << " pres " << nFourL - << " kept " << nSelFourL - << " eff " << ((double)nSelFourL)/((double) nFourL + 0.0001) << std::endl; + << " pres " << nFourL << " kept " << nSelFourL << " eff " + << ((double)nSelFourL) / ((double)nFourL + 0.0001) << std::endl; std::cout << "Four muons: " - << " pres " << nFourM - << " kept " << nSelFourM - << " eff " << ((double)nSelFourM)/((double) nFourM + 0.0001) << std::endl; + << " pres " << nFourM << " kept " << nSelFourM << " eff " + << ((double)nSelFourM) / ((double)nFourM + 0.0001) << std::endl; std::cout << "Four elecs: " - << " pres " << nFourE - << " kept " << nSelFourE - << " eff " << ((double)nSelFourE)/((double) nFourE + 0.0001) << std::endl; + << " pres " << nFourE << " kept " << nSelFourE << " eff " + << ((double)nSelFourE) / ((double)nFourE + 0.0001) << std::endl; std::cout << "2 elec 2 mu: " - << " pres " << nTwoETwoM - << " kept " << nSelTwoETwoM - << " eff " << ((double)nSelTwoETwoM)/((double) nTwoETwoM + 0.0001) << std::endl; + << " pres " << nTwoETwoM << " kept " << nSelTwoETwoM << " eff " + << ((double)nSelTwoETwoM) / ((double)nTwoETwoM + 0.0001) << std::endl; std::cout << "with taus: " - << " pres " << nTau - << " kept " << nSelTau - << " eff " << ((double)nSelTau)/((double) nTau + 0.0001) << std::endl; - + << " pres " << nTau << " kept " << nSelTau << " eff " << ((double)nSelTau) / ((double)nTau + 0.0001) + << std::endl; } - - // Filter event -void HiggsToZZ4LeptonsSkimEff::analyze(const edm::Event& event, const edm::EventSetup& setup ) { - +void HiggsToZZ4LeptonsSkimEff::analyze(const edm::Event& event, const edm::EventSetup& setup) { nEvents++; using reco::TrackCollection; - bool keepEvent = false; + bool keepEvent = false; // First, pre-selection: int nMuon = 0; int nElec = 0; - int nTau = 0; + int nTau = 0; bool isFourE = false; bool isFourM = false; @@ -115,65 +99,65 @@ void HiggsToZZ4LeptonsSkimEff::analyze(const edm::Event& event, const edm::Event edm::Handle genCandidates; event.getByToken(genToken, genCandidates); - for ( CandidateCollection::const_iterator mcIter=genCandidates->begin(); mcIter!=genCandidates->end(); ++mcIter ) { - + for (CandidateCollection::const_iterator mcIter = genCandidates->begin(); mcIter != genCandidates->end(); ++mcIter) { // Muons: - if ( mcIter->pdgId() == 13 || mcIter->pdgId() == -13) { + if (mcIter->pdgId() == 13 || mcIter->pdgId() == -13) { // Mother is a Z - if ( mcIter->mother()->pdgId() == 23 ) { - // In fiducial volume: - if ( mcIter->eta() > -2.4 && mcIter->eta() < 2.4 ) nMuon++; + if (mcIter->mother()->pdgId() == 23) { + // In fiducial volume: + if (mcIter->eta() > -2.4 && mcIter->eta() < 2.4) + nMuon++; } } // Electrons: - if ( mcIter->pdgId() == 11 || mcIter->pdgId() == -11) { + if (mcIter->pdgId() == 11 || mcIter->pdgId() == -11) { // Mother is a Z - if ( mcIter->mother()->pdgId() == 23 ) { + if (mcIter->mother()->pdgId() == 23) { // In fiducial volume: - if ( mcIter->eta() > -2.5 && mcIter->eta() < 2.5 ) nElec++; + if (mcIter->eta() > -2.5 && mcIter->eta() < 2.5) + nElec++; } } // Taus: - if ( mcIter->pdgId() == 15 || mcIter->pdgId() == -15) { + if (mcIter->pdgId() == 15 || mcIter->pdgId() == -15) { // Mother is a Z - if ( mcIter->mother()->pdgId() == 23 ) { + if (mcIter->mother()->pdgId() == 23) { // In fiducial volume: - if ( mcIter->eta() > -2.5 && mcIter->eta() < 2.5 ) nTau++; + if (mcIter->eta() > -2.5 && mcIter->eta() < 2.5) + nTau++; } } - } - if (nElec > 3) { - isFourE = true; - nFourE++; - } - if (nMuon > 3) { - isFourM = true; - nFourM++; - } - if (nMuon > 1 && nElec > 1) { - isTwoETwoM = true; - nTwoETwoM++; - } - if ( isFourE || isFourM || isTwoETwoM ) { - isFourL = true; - nFourL++; - } - if (nTau > 1) { - isTau = true; - nTau++; - } + if (nElec > 3) { + isFourE = true; + nFourE++; + } + if (nMuon > 3) { + isFourM = true; + nFourM++; + } + if (nMuon > 1 && nElec > 1) { + isTwoETwoM = true; + nTwoETwoM++; + } + if (isFourE || isFourM || isTwoETwoM) { + isFourL = true; + nFourL++; + } + if (nTau > 1) { + isTau = true; + nTau++; + } - if ( isFourL ) { + if (isFourL) { keepEvent = true; } else { return; } - - int nStiffLeptons = 0; - int nLeptons = 0; + int nStiffLeptons = 0; + int nLeptons = 0; // First look at muons: @@ -181,54 +165,59 @@ void HiggsToZZ4LeptonsSkimEff::analyze(const edm::Event& event, const edm::Event edm::Handle muTracks; event.getByToken(theGLBMuonToken, muTracks); - if ( muTracks.isValid() ) { + if (muTracks.isValid()) { reco::TrackCollection::const_iterator muons; // Loop over muon collections and count how many muons there are, // and how many are above threshold - for ( muons = muTracks->begin(); muons != muTracks->end(); ++muons ) { - float pt_mu = muons->pt(); - if ( pt_mu > stiffMinPt ) nStiffLeptons++; - if ( pt_mu > softMinPt ) nLeptons++; + for (muons = muTracks->begin(); muons != muTracks->end(); ++muons) { + float pt_mu = muons->pt(); + if (pt_mu > stiffMinPt) + nStiffLeptons++; + if (pt_mu > softMinPt) + nLeptons++; } } - // Now look at electrons: // Get the electron track collection from the event edm::Handle pTracks; - event.getByToken(theGsfEToken,pTracks); - - if ( pTracks.isValid() ) { + event.getByToken(theGsfEToken, pTracks); + if (pTracks.isValid()) { const reco::GsfElectronCollection* eTracks = pTracks.product(); reco::GsfElectronCollection::const_iterator electrons; // Loop over electron collections and count how many muons there are, // and how many are above threshold - for ( electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons ) { + for (electrons = eTracks->begin(); electrons != eTracks->end(); ++electrons) { float pt_e = electrons->pt(); - if ( pt_e > stiffMinPt ) nStiffLeptons++; - if ( pt_e > softMinPt ) nLeptons++; + if (pt_e > stiffMinPt) + nStiffLeptons++; + if (pt_e > softMinPt) + nLeptons++; } } - // Make decision: - if ( nStiffLeptons >= nStiffLeptonMin && nLeptons >= nLeptonMin) { + if (nStiffLeptons >= nStiffLeptonMin && nLeptons >= nLeptonMin) { keepEvent = true; } else { keepEvent = false; } - if ( keepEvent ) { - if (isFourE) nSelFourE++; - if (isFourM) nSelFourM++; - if (isTwoETwoM) nSelTwoETwoM++; - if (isFourL) nSelFourL++; - if (isTau) nSelTau++; + if (keepEvent) { + if (isFourE) + nSelFourE++; + if (isFourM) + nSelFourM++; + if (isTwoETwoM) + nSelTwoETwoM++; + if (isFourL) + nSelFourL++; + if (isTau) + nSelTau++; } - } diff --git a/HiggsAnalysis/Skimming/src/SealModule.cc b/HiggsAnalysis/Skimming/src/SealModule.cc index 7a7b1ef5d5112..ebc94ace9f523 100644 --- a/HiggsAnalysis/Skimming/src/SealModule.cc +++ b/HiggsAnalysis/Skimming/src/SealModule.cc @@ -7,12 +7,9 @@ #include #include - DEFINE_FWK_MODULE(HiggsToZZ4LeptonsSkim); DEFINE_FWK_MODULE(HiggsToZZ4LeptonsSkimEff); DEFINE_FWK_MODULE(HiggsToZZ4LeptonsPreFilter); DEFINE_FWK_MODULE(HiggsToWW2LeptonsSkim); DEFINE_FWK_MODULE(HeavyChHiggsToTauNuSkim); DEFINE_FWK_MODULE(HiggsTo2GammaSkim); - - diff --git a/JetMETCorrections/Algorithms/interface/JetCorrectorImplMakerBase.h b/JetMETCorrections/Algorithms/interface/JetCorrectorImplMakerBase.h index 873bdbdcebe9c..cde8db8a72afd 100644 --- a/JetMETCorrections/Algorithms/interface/JetCorrectorImplMakerBase.h +++ b/JetMETCorrections/Algorithms/interface/JetCorrectorImplMakerBase.h @@ -4,7 +4,7 @@ // // Package: JetMETCorrections/Algorithms // Class : JetCorrectorImplMakerBase -// +// /**\class JetCorrectorImplMakerBase JetCorrectorImplMakerBase.h "JetMETCorrections/Algorithms/interface/JetCorrectorImplMakerBase.h" Description: [one line class summary] @@ -31,38 +31,34 @@ namespace edm { class ParameterSet; class EventSetup; class ParameterSetDescription; -} +} // namespace edm -class JetCorrectorImplMakerBase -{ - - public: +class JetCorrectorImplMakerBase { +public: JetCorrectorImplMakerBase(edm::ParameterSet const&); virtual ~JetCorrectorImplMakerBase(); - + // ---------- const member functions --------------------- - + // ---------- static member functions -------------------- static void addToDescription(edm::ParameterSetDescription& iDescription); - + // ---------- member functions --------------------------- - protected: - std::shared_ptr getCalculator(edm::EventSetup const&, - std::function levelCheck); - - private: - JetCorrectorImplMakerBase(const JetCorrectorImplMakerBase&) = delete; // stop default - - const JetCorrectorImplMakerBase& operator=(const JetCorrectorImplMakerBase&) = delete; // stop default - +protected: + std::shared_ptr getCalculator( + edm::EventSetup const&, std::function levelCheck); + +private: + JetCorrectorImplMakerBase(const JetCorrectorImplMakerBase&) = delete; // stop default + + const JetCorrectorImplMakerBase& operator=(const JetCorrectorImplMakerBase&) = delete; // stop default + // ---------- member data -------------------------------- std::string level_; std::string algo_; std::shared_ptr corrector_; unsigned long long cacheId_; - }; - #endif diff --git a/JetMETCorrections/Algorithms/interface/L1FastjetCorrector.h b/JetMETCorrections/Algorithms/interface/L1FastjetCorrector.h index 087e7feee10de..eca6e1f80c599 100644 --- a/JetMETCorrections/Algorithms/interface/L1FastjetCorrector.h +++ b/JetMETCorrections/Algorithms/interface/L1FastjetCorrector.h @@ -14,24 +14,21 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" #include "CondFormats/JetMETObjects/interface/FactorizedJetCorrectorCalculator.h" -class L1FastjetCorrector : public JetCorrector -{ +class L1FastjetCorrector : public JetCorrector { public: // construction / destruction L1FastjetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig); ~L1FastjetCorrector() override; - + public: //member functions - + /// apply correction using Jet information only double correction(const LorentzVector& fJet) const override; /// apply correction using Jet information only double correction(const reco::Jet& fJet) const override; /// apply correction using all event information - double correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const override; + double correction(const reco::Jet& fJet, const edm::Event& fEvent, const edm::EventSetup& fSetup) const override; /// if correction needs event information bool eventRequired() const override { return true; } diff --git a/JetMETCorrections/Algorithms/interface/L1FastjetCorrectorImpl.h b/JetMETCorrections/Algorithms/interface/L1FastjetCorrectorImpl.h index 4e7e4dab68fa5..523bf30abc3cc 100644 --- a/JetMETCorrections/Algorithms/interface/L1FastjetCorrectorImpl.h +++ b/JetMETCorrections/Algorithms/interface/L1FastjetCorrectorImpl.h @@ -18,29 +18,29 @@ namespace edm { class EventSetup; class ConsumesCollector; class ConfigurationDescriptions; -} +} // namespace edm class L1FastjetCorrectorImplMaker : public JetCorrectorImplMakerBase { - public: +public: L1FastjetCorrectorImplMaker(edm::ParameterSet const&, edm::ConsumesCollector); std::unique_ptr make(edm::Event const&, edm::EventSetup const&); static void fillDescriptions(edm::ConfigurationDescriptions& iDescriptions); - private: + +private: edm::EDGetTokenT rhoToken_; }; -class L1FastjetCorrectorImpl : public reco::JetCorrectorImpl -{ +class L1FastjetCorrectorImpl : public reco::JetCorrectorImpl { public: typedef L1FastjetCorrectorImplMaker Maker; // construction / destruction - L1FastjetCorrectorImpl(std::shared_ptr corrector, double rho): - rho_(rho),corrector_(corrector) {} - + L1FastjetCorrectorImpl(std::shared_ptr corrector, double rho) + : rho_(rho), corrector_(corrector) {} + //member functions - + /// apply correction using Jet information only double correction(const LorentzVector& fJet) const override; /// apply correction using Jet information only diff --git a/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrector.h b/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrector.h index 8269f11a80193..6779e644d3607 100644 --- a/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrector.h +++ b/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrector.h @@ -8,40 +8,36 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; } class FactorizedJetCorrectorCalculator; //----- LXXXCorrector interface ------------------------------- -class L1JPTOffsetCorrector : public JetCorrector -{ - public: - //----- constructors--------------------------------------- - L1JPTOffsetCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); - - //----- destructor ---------------------------------------- - ~L1JPTOffsetCorrector() override; - - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; - - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; - - //----- apply correction using all event information - double correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const override; - //----- if correction needs event information ------------- - bool eventRequired() const override {return true;} - bool refRequired() const override {return false;} - - private: - //----- member data --------------------------------------- - std::string mOffsetService; - bool mIsOffsetSet; - FactorizedJetCorrectorCalculator* mCorrector; +class L1JPTOffsetCorrector : public JetCorrector { +public: + //----- constructors--------------------------------------- + L1JPTOffsetCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); + + //----- destructor ---------------------------------------- + ~L1JPTOffsetCorrector() override; + + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; + + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; + + //----- apply correction using all event information + double correction(const reco::Jet& fJet, const edm::Event& fEvent, const edm::EventSetup& fSetup) const override; + //----- if correction needs event information ------------- + bool eventRequired() const override { return true; } + bool refRequired() const override { return false; } + +private: + //----- member data --------------------------------------- + std::string mOffsetService; + bool mIsOffsetSet; + FactorizedJetCorrectorCalculator* mCorrector; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrectorImpl.h b/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrectorImpl.h index 59f56e5d9d78b..4c08d99734cf9 100644 --- a/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrectorImpl.h +++ b/JetMETCorrections/Algorithms/interface/L1JPTOffsetCorrectorImpl.h @@ -9,53 +9,52 @@ #include "FWCore/Utilities/interface/EDGetToken.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; class Event; class EventSetup; class ConsumesCollector; class ConfigurationDescriptions; -} +} // namespace edm namespace reco { class JetCorrector; } class L1JPTOffsetCorrectorImplMaker : public JetCorrectorImplMakerBase { - public: +public: L1JPTOffsetCorrectorImplMaker(edm::ParameterSet const&, edm::ConsumesCollector); std::unique_ptr make(edm::Event const&, edm::EventSetup const&); static void fillDescriptions(edm::ConfigurationDescriptions& iDescriptions); - private: + +private: edm::EDGetTokenT offsetCorrectorToken_; bool useOffset_; }; //----- LXXXCorrector interface ------------------------------- -class L1JPTOffsetCorrectorImpl : public reco::JetCorrectorImpl -{ - public: +class L1JPTOffsetCorrectorImpl : public reco::JetCorrectorImpl { +public: typedef L1JPTOffsetCorrectorImplMaker Maker; - //----- constructors--------------------------------------- + //----- constructors--------------------------------------- L1JPTOffsetCorrectorImpl(std::shared_ptr corrector, - const reco::JetCorrector* offsetService); + const reco::JetCorrector* offsetService); - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; - //----- if correction needs event information ------------- - bool refRequired() const override {return false;} + //----- if correction needs event information ------------- + bool refRequired() const override { return false; } - private: - //----- member data --------------------------------------- - const reco::JetCorrector* offsetService_; - std::shared_ptr corrector_; +private: + //----- member data --------------------------------------- + const reco::JetCorrector* offsetService_; + std::shared_ptr corrector_; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/L1OffsetCorrector.h b/JetMETCorrections/Algorithms/interface/L1OffsetCorrector.h index 417bde87c2c63..e7c76fd259341 100644 --- a/JetMETCorrections/Algorithms/interface/L1OffsetCorrector.h +++ b/JetMETCorrections/Algorithms/interface/L1OffsetCorrector.h @@ -8,43 +8,38 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; } class FactorizedJetCorrectorCalculator; //----- LXXXCorrector interface ------------------------------- -class L1OffsetCorrector : public JetCorrector -{ - public: - //----- constructors--------------------------------------- - L1OffsetCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); +class L1OffsetCorrector : public JetCorrector { +public: + //----- constructors--------------------------------------- + L1OffsetCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); - //----- destructor ---------------------------------------- - ~L1OffsetCorrector() override; + //----- destructor ---------------------------------------- + ~L1OffsetCorrector() override; - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; - //----- apply correction using all event information - double correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const override; - //----- if correction needs event information ------------- - bool eventRequired() const override {return true;} + //----- apply correction using all event information + double correction(const reco::Jet& fJet, const edm::Event& fEvent, const edm::EventSetup& fSetup) const override; + //----- if correction needs event information ------------- + bool eventRequired() const override { return true; } - //----- if correction needs a jet reference ------------- - bool refRequired() const override { return false; } - - private: - //----- member data --------------------------------------- - std::string mVertexCollName; - int mMinVtxNdof; - FactorizedJetCorrectorCalculator* mCorrector; + //----- if correction needs a jet reference ------------- + bool refRequired() const override { return false; } +private: + //----- member data --------------------------------------- + std::string mVertexCollName; + int mMinVtxNdof; + FactorizedJetCorrectorCalculator* mCorrector; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/L1OffsetCorrectorImpl.h b/JetMETCorrections/Algorithms/interface/L1OffsetCorrectorImpl.h index eebcfe5b18262..de687f4ca0573 100644 --- a/JetMETCorrections/Algorithms/interface/L1OffsetCorrectorImpl.h +++ b/JetMETCorrections/Algorithms/interface/L1OffsetCorrectorImpl.h @@ -11,52 +11,49 @@ #include "DataFormats/VertexReco/interface/VertexFwd.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; class Event; class EventSetup; class ConsumesCollector; class ConfigurationDescriptions; -} +} // namespace edm class L1OffsetCorrectorImplMaker : public JetCorrectorImplMakerBase { - public: +public: L1OffsetCorrectorImplMaker(edm::ParameterSet const&, edm::ConsumesCollector); std::unique_ptr make(edm::Event const&, edm::EventSetup const&); static void fillDescriptions(edm::ConfigurationDescriptions& iDescriptions); - private: + +private: edm::EDGetTokenT verticesToken_; int minVtxNdof_; }; //----- LXXXCorrector interface ------------------------------- -class L1OffsetCorrectorImpl : public reco::JetCorrectorImpl -{ - public: +class L1OffsetCorrectorImpl : public reco::JetCorrectorImpl { +public: typedef L1OffsetCorrectorImplMaker Maker; - //----- constructors--------------------------------------- - L1OffsetCorrectorImpl(std::shared_ptr calculator, - int npv); - - //----- destructor ---------------------------------------- + //----- constructors--------------------------------------- + L1OffsetCorrectorImpl(std::shared_ptr calculator, int npv); - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; + //----- destructor ---------------------------------------- - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; - //----- if correction needs a jet reference ------------- - bool refRequired() const override { return false; } + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; - private: - //----- member data --------------------------------------- - std::shared_ptr corrector_; - int npv_; + //----- if correction needs a jet reference ------------- + bool refRequired() const override { return false; } +private: + //----- member data --------------------------------------- + std::shared_ptr corrector_; + int npv_; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/L6SLBCorrector.h b/JetMETCorrections/Algorithms/interface/L6SLBCorrector.h index 87da52fcb7dbd..ca1105129bdd2 100644 --- a/JetMETCorrections/Algorithms/interface/L6SLBCorrector.h +++ b/JetMETCorrections/Algorithms/interface/L6SLBCorrector.h @@ -15,55 +15,50 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" #include "DataFormats/BTauReco/interface/SoftLeptonTagInfo.h" - -class L6SLBCorrector : public JetCorrector -{ +class L6SLBCorrector : public JetCorrector { // // construction / destruction // public: - L6SLBCorrector (const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig); - ~L6SLBCorrector () override; - + L6SLBCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig); + ~L6SLBCorrector() override; // // member functions // public: /// apply correction using Jet information only - double correction (const LorentzVector& fJet) const override; + double correction(const LorentzVector& fJet) const override; /// apply correction using Jet information only - double correction (const reco::Jet& fJet) const override; + double correction(const reco::Jet& fJet) const override; /// apply correction using all event information - double correction (const reco::Jet& fJet, - const edm::RefToBase& refToRawJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const override; - + double correction(const reco::Jet& fJet, + const edm::RefToBase& refToRawJet, + const edm::Event& fEvent, + const edm::EventSetup& fSetup) const override; + /// if correction needs event information - bool eventRequired () const override {return true;} + bool eventRequired() const override { return true; } //----- if correction needs a jet reference ------------- - bool refRequired () const override {return true;} - + bool refRequired() const override { return true; } + // // private member functions // private: int getBTagInfoIndex(const edm::RefToBase& refToRawJet, - const std::vector& tags) const; - - + const std::vector& tags) const; + // // member data // private: - std::string tagName_; - bool addMuonToJet_; - edm::InputTag srcBTagInfoElec_; - edm::InputTag srcBTagInfoMuon_; + std::string tagName_; + bool addMuonToJet_; + edm::InputTag srcBTagInfoElec_; + edm::InputTag srcBTagInfoMuon_; FactorizedJetCorrectorCalculator* corrector_; - }; #endif diff --git a/JetMETCorrections/Algorithms/interface/L6SLBCorrectorImpl.h b/JetMETCorrections/Algorithms/interface/L6SLBCorrectorImpl.h index 44086b750ea59..768b69d757a9e 100644 --- a/JetMETCorrections/Algorithms/interface/L6SLBCorrectorImpl.h +++ b/JetMETCorrections/Algorithms/interface/L6SLBCorrectorImpl.h @@ -16,63 +16,60 @@ #include "CondFormats/JetMETObjects/interface/FactorizedJetCorrectorCalculator.h" #include "DataFormats/BTauReco/interface/SoftLeptonTagInfo.h" -namespace edm -{ +namespace edm { class ParameterSet; class Event; class EventSetup; class ConsumesCollector; class ConfigurationDescriptions; -} +} // namespace edm class L6SLBCorrectorImplMaker : public JetCorrectorImplMakerBase { - public: +public: L6SLBCorrectorImplMaker(edm::ParameterSet const&, edm::ConsumesCollector); std::unique_ptr make(edm::Event const&, edm::EventSetup const&); static void fillDescriptions(edm::ConfigurationDescriptions& iDescriptions); - private: + +private: edm::EDGetTokenT> elecToken_; edm::EDGetTokenT> muonToken_; - bool addMuonToJet_; + bool addMuonToJet_; }; -class L6SLBCorrectorImpl : public reco::JetCorrectorImpl -{ +class L6SLBCorrectorImpl : public reco::JetCorrectorImpl { // // construction / destruction // public: typedef L6SLBCorrectorImplMaker Maker; - L6SLBCorrectorImpl ( std::shared_ptr corrector, - edm::RefProd> const& bTagInfoMuon, - edm::RefProd> const& bTagInfoElec, - bool addMuonToJet); + L6SLBCorrectorImpl(std::shared_ptr corrector, + edm::RefProd> const& bTagInfoMuon, + edm::RefProd> const& bTagInfoElec, + bool addMuonToJet); // // member functions // public: /// apply correction using Jet information only - double correction (const LorentzVector& fJet) const override; + double correction(const LorentzVector& fJet) const override; /// apply correction using Jet information only - double correction (const reco::Jet& fJet) const override; + double correction(const reco::Jet& fJet) const override; /// apply correction using all event information - double correction (const reco::Jet& fJet, - const edm::RefToBase& refToRawJet) const override; - + double correction(const reco::Jet& fJet, const edm::RefToBase& refToRawJet) const override; + //----- if correction needs a jet reference ------------- - bool refRequired () const override {return true;} - + bool refRequired() const override { return true; } + // // private member functions // private: int getBTagInfoIndex(const edm::RefToBase& refToRawJet, - const std::vector& tags) const; - - + const std::vector& tags) const; + // // member data // @@ -82,8 +79,7 @@ class L6SLBCorrectorImpl : public reco::JetCorrectorImpl std::shared_ptr corrector_; edm::RefProd> bTagInfoMuon_; edm::RefProd> bTagInfoElec_; - bool addMuonToJet_; - + bool addMuonToJet_; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/LXXXCorrector.h b/JetMETCorrections/Algorithms/interface/LXXXCorrector.h index d5270e725f76d..311a469c1bef1 100644 --- a/JetMETCorrections/Algorithms/interface/LXXXCorrector.h +++ b/JetMETCorrections/Algorithms/interface/LXXXCorrector.h @@ -7,37 +7,35 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; } class FactorizedJetCorrector; //----- LXXXCorrector interface ------------------------------- -class LXXXCorrector : public JetCorrector -{ - public: - //----- constructors--------------------------------------- - LXXXCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); +class LXXXCorrector : public JetCorrector { +public: + //----- constructors--------------------------------------- + LXXXCorrector(const JetCorrectorParameters& fConfig, const edm::ParameterSet& fParameters); - //----- destructor ---------------------------------------- - ~LXXXCorrector() override; + //----- destructor ---------------------------------------- + ~LXXXCorrector() override; - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; - //----- if correction needs event information ------------- - bool eventRequired() const override {return false;} + //----- if correction needs event information ------------- + bool eventRequired() const override { return false; } - //----- if correction needs a jet reference ------------- - bool refRequired() const override { return false; } + //----- if correction needs a jet reference ------------- + bool refRequired() const override { return false; } - private: - //----- member data --------------------------------------- - unsigned mLevel; - FactorizedJetCorrectorCalculator* mCorrector; +private: + //----- member data --------------------------------------- + unsigned mLevel; + FactorizedJetCorrectorCalculator* mCorrector; }; #endif diff --git a/JetMETCorrections/Algorithms/interface/LXXXCorrectorImpl.h b/JetMETCorrections/Algorithms/interface/LXXXCorrectorImpl.h index 8bad44be6996c..5648d92dc22b0 100644 --- a/JetMETCorrections/Algorithms/interface/LXXXCorrectorImpl.h +++ b/JetMETCorrections/Algorithms/interface/LXXXCorrectorImpl.h @@ -8,18 +8,17 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" //----- classes declaration ----------------------------------- -namespace edm -{ +namespace edm { class ParameterSet; class Event; class EventSetup; class ConsumesCollector; class ConfigurationDescriptions; -} +} // namespace edm class FactorizedJetCorrector; class LXXXCorrectorImplMaker : public JetCorrectorImplMakerBase { - public: +public: LXXXCorrectorImplMaker(edm::ParameterSet const&, edm::ConsumesCollector); std::unique_ptr make(edm::Event const&, edm::EventSetup const&); @@ -27,27 +26,26 @@ class LXXXCorrectorImplMaker : public JetCorrectorImplMakerBase { }; //----- LXXXCorrectorImpl interface ------------------------------- -class LXXXCorrectorImpl : public reco::JetCorrectorImpl -{ - public: - typedef LXXXCorrectorImplMaker Maker; +class LXXXCorrectorImpl : public reco::JetCorrectorImpl { +public: + typedef LXXXCorrectorImplMaker Maker; - //----- constructors--------------------------------------- - LXXXCorrectorImpl(std::shared_ptr calculator, unsigned int level); + //----- constructors--------------------------------------- + LXXXCorrectorImpl(std::shared_ptr calculator, unsigned int level); - //----- apply correction using Jet information only ------- - double correction(const LorentzVector& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const LorentzVector& fJet) const override; - //----- apply correction using Jet information only ------- - double correction(const reco::Jet& fJet) const override; + //----- apply correction using Jet information only ------- + double correction(const reco::Jet& fJet) const override; - //----- if correction needs a jet reference ------------- - bool refRequired() const override { return false; } + //----- if correction needs a jet reference ------------- + bool refRequired() const override { return false; } - private: - //----- member data --------------------------------------- - unsigned int mLevel; - std::shared_ptr mCorrector; +private: + //----- member data --------------------------------------- + unsigned int mLevel; + std::shared_ptr mCorrector; }; #endif diff --git a/JetMETCorrections/Algorithms/src/JetCorrectorImplMakerBase.cc b/JetMETCorrections/Algorithms/src/JetCorrectorImplMakerBase.cc index d3012bfea98ad..cbb543423e18c 100644 --- a/JetMETCorrections/Algorithms/src/JetCorrectorImplMakerBase.cc +++ b/JetMETCorrections/Algorithms/src/JetCorrectorImplMakerBase.cc @@ -2,7 +2,7 @@ // // Package: JetMETCorrections/Algorithms // Class : JetCorrectorImplMakerBase -// +// // Implementation: // [Notes on implementation] // @@ -24,7 +24,6 @@ #include "CondFormats/JetMETObjects/interface/JetCorrectorParameters.h" #include "JetMETCorrections/Objects/interface/JetCorrectionsRecord.h" - // // constants, enums and typedefs // @@ -36,32 +35,28 @@ // // constructors and destructor // -JetCorrectorImplMakerBase::JetCorrectorImplMakerBase(edm::ParameterSet const& iPSet): - level_(iPSet.getParameter("level")), - algo_(iPSet.getParameter("algorithm")), - cacheId_(0) -{ -} +JetCorrectorImplMakerBase::JetCorrectorImplMakerBase(edm::ParameterSet const& iPSet) + : level_(iPSet.getParameter("level")), + algo_(iPSet.getParameter("algorithm")), + cacheId_(0) {} // JetCorrectorImplMakerBase::JetCorrectorImplMakerBase(const JetCorrectorImplMakerBase& rhs) // { // // do actual copying here; // } -JetCorrectorImplMakerBase::~JetCorrectorImplMakerBase() -{ -} +JetCorrectorImplMakerBase::~JetCorrectorImplMakerBase() {} // // member functions // -std::shared_ptr -JetCorrectorImplMakerBase::getCalculator(edm::EventSetup const& iSetup, std::function iLevelCheck) { +std::shared_ptr JetCorrectorImplMakerBase::getCalculator( + edm::EventSetup const& iSetup, std::function iLevelCheck) { auto const& rec = iSetup.get(); - if( cacheId_ != rec.cacheIdentifier()) { + if (cacheId_ != rec.cacheIdentifier()) { edm::ESHandle JetCorParColl; - rec.get(algo_,JetCorParColl); + rec.get(algo_, JetCorParColl); auto const& parameters = ((*JetCorParColl)[level_]); iLevelCheck(parameters.definitions().level()); @@ -74,8 +69,7 @@ JetCorrectorImplMakerBase::getCalculator(edm::EventSetup const& iSetup, std::fun return corrector_; } -void -JetCorrectorImplMakerBase::addToDescription(edm::ParameterSetDescription& iDescription) { +void JetCorrectorImplMakerBase::addToDescription(edm::ParameterSetDescription& iDescription) { iDescription.add("level"); iDescription.add("algorithm"); } diff --git a/JetMETCorrections/Algorithms/src/L1FastjetCorrector.cc b/JetMETCorrections/Algorithms/src/L1FastjetCorrector.cc index 8a5fb221f1b13..5febe7f8b226a 100644 --- a/JetMETCorrections/Algorithms/src/L1FastjetCorrector.cc +++ b/JetMETCorrections/Algorithms/src/L1FastjetCorrector.cc @@ -11,61 +11,48 @@ #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" - using namespace std; - //////////////////////////////////////////////////////////////////////////////// // construction / destruction //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ -L1FastjetCorrector::L1FastjetCorrector (const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) - : srcRho_(fConfig.getParameter("srcRho")) -{ +L1FastjetCorrector::L1FastjetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) + : srcRho_(fConfig.getParameter("srcRho")) { if (fParam.definitions().level() != "L1FastJet") - throw cms::Exception("L1FastjetCorrector")<<" correction level: "< vParam; vParam.push_back(fParam); mCorrector = new FactorizedJetCorrectorCalculator(vParam); } //______________________________________________________________________________ -L1FastjetCorrector::~L1FastjetCorrector () -{ - delete mCorrector; -} - +L1FastjetCorrector::~L1FastjetCorrector() { delete mCorrector; } //////////////////////////////////////////////////////////////////////////////// // implementation of member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ -double L1FastjetCorrector::correction (const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1FastjetCorrector::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } - //______________________________________________________________________________ -double L1FastjetCorrector::correction (const reco::Jet& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(reco::Jet), event required!"; +double L1FastjetCorrector::correction(const reco::Jet& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(reco::Jet), event required!"; return 1.0; } - //______________________________________________________________________________ double L1FastjetCorrector::correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const -{ + const edm::Event& fEvent, + const edm::EventSetup& fSetup) const { edm::Handle rho; - fEvent.getByLabel(srcRho_,rho); + fEvent.getByLabel(srcRho_, rho); double result(1.0); FactorizedJetCorrectorCalculator::VariableValues values; values.setJetEta(fJet.eta()); @@ -73,10 +60,6 @@ double L1FastjetCorrector::correction(const reco::Jet& fJet, values.setJetE(fJet.energy()); values.setJetA(fJet.jetArea()); values.setRho(*rho); - result = mCorrector->getCorrection(values); + result = mCorrector->getCorrection(values); return result; } - - - - diff --git a/JetMETCorrections/Algorithms/src/L1FastjetCorrectorImpl.cc b/JetMETCorrections/Algorithms/src/L1FastjetCorrectorImpl.cc index 5211d49922072..5c10bba754b44 100644 --- a/JetMETCorrections/Algorithms/src/L1FastjetCorrectorImpl.cc +++ b/JetMETCorrections/Algorithms/src/L1FastjetCorrectorImpl.cc @@ -24,62 +24,49 @@ using namespace std; -L1FastjetCorrectorImplMaker::L1FastjetCorrectorImplMaker(edm::ParameterSet const& fConfig, - edm::ConsumesCollector fCollector): - JetCorrectorImplMakerBase(fConfig), - rhoToken_(fCollector.consumes(fConfig.getParameter("srcRho"))) -{ -} +L1FastjetCorrectorImplMaker::L1FastjetCorrectorImplMaker(edm::ParameterSet const& fConfig, + edm::ConsumesCollector fCollector) + : JetCorrectorImplMakerBase(fConfig), + rhoToken_(fCollector.consumes(fConfig.getParameter("srcRho"))) {} -std::unique_ptr -L1FastjetCorrectorImplMaker::make(edm::Event const& fEvent, edm::EventSetup const& fSetup) { +std::unique_ptr L1FastjetCorrectorImplMaker::make(edm::Event const& fEvent, + edm::EventSetup const& fSetup) { auto corrector = getCalculator(fSetup, [](const std::string& level) { - if(level != "L1FastJet") { - throw cms::Exception("L1FastjetCorrector")<<" correction level: "< hRho; - fEvent.getByToken(rhoToken_,hRho); - return std::unique_ptr(new L1FastjetCorrectorImpl(corrector, *hRho) ); + fEvent.getByToken(rhoToken_, hRho); + return std::unique_ptr(new L1FastjetCorrectorImpl(corrector, *hRho)); } -void -L1FastjetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) -{ +void L1FastjetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) { edm::ParameterSetDescription desc; addToDescription(desc); desc.add("srcRho"); iDescriptions.addDefault(desc); } - //______________________________________________________________________________ //////////////////////////////////////////////////////////////////////////////// // implementation of member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ -double L1FastjetCorrectorImpl::correction (const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1FastjetCorrectorImpl::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } - //______________________________________________________________________________ -double L1FastjetCorrectorImpl::correction (const reco::Jet& fJet) const -{ +double L1FastjetCorrectorImpl::correction(const reco::Jet& fJet) const { FactorizedJetCorrectorCalculator::VariableValues values; values.setJetEta(fJet.eta()); values.setJetPt(fJet.pt()); values.setJetE(fJet.energy()); values.setJetA(fJet.jetArea()); values.setRho(rho_); - return corrector_->getCorrection(values); + return corrector_->getCorrection(values); } - - - - diff --git a/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrector.cc b/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrector.cc index bb77e74a25303..ef38a78ef047d 100644 --- a/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrector.cc +++ b/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrector.cc @@ -17,66 +17,57 @@ using namespace std; - -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrector constructor ------------------------------------------ //------------------------------------------------------------------------ -L1JPTOffsetCorrector::L1JPTOffsetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) -{ +L1JPTOffsetCorrector::L1JPTOffsetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) { mOffsetService = fConfig.getParameter("offsetService"); mIsOffsetSet = false; if (!mOffsetService.empty()) mIsOffsetSet = true; if (fParam.definitions().level() != "L1JPTOffset") - throw cms::Exception("L1OffsetCorrector")<<" correction level: "< vParam; vParam.push_back(fParam); mCorrector = new FactorizedJetCorrectorCalculator(vParam); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrector destructor ------------------------------------------- //------------------------------------------------------------------------ -L1JPTOffsetCorrector::~L1JPTOffsetCorrector() -{ - delete mCorrector; -} -//------------------------------------------------------------------------ +L1JPTOffsetCorrector::~L1JPTOffsetCorrector() { delete mCorrector; } +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double L1JPTOffsetCorrector::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1JPTOffsetCorrector::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double L1JPTOffsetCorrector::correction(const reco::Jet& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(reco::Jet), event required!"; +double L1JPTOffsetCorrector::correction(const reco::Jet& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(reco::Jet), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet using event indormation --------- //------------------------------------------------------------------------ -double L1JPTOffsetCorrector::correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const -{ +double L1JPTOffsetCorrector::correction(const reco::Jet& fJet, + const edm::Event& fEvent, + const edm::EventSetup& fSetup) const { double result = 1.; - const reco::JPTJet& jptjet = dynamic_cast (fJet); + const reco::JPTJet& jptjet = dynamic_cast(fJet); const edm::RefToBase& jptjetRef = jptjet.getCaloJetRef(); - reco::CaloJet const * rawcalojet = dynamic_cast( &* jptjetRef); + reco::CaloJet const* rawcalojet = dynamic_cast(&*jptjetRef); //------ access the offset correction service ---------------- double offset = 1.0; if (mIsOffsetSet) { - const JetCorrector* OffsetCorrector = JetCorrector::getJetCorrector(mOffsetService,fSetup); - offset = OffsetCorrector->correction(*rawcalojet,fEvent,fSetup); + const JetCorrector* OffsetCorrector = JetCorrector::getJetCorrector(mOffsetService, fSetup); + offset = OffsetCorrector->correction(*rawcalojet, fEvent, fSetup); } //------ calculate the correction for the JPT jet ------------ - TLorentzVector JPTrawP4(rawcalojet->px(),rawcalojet->py(),rawcalojet->pz(),rawcalojet->energy()); + TLorentzVector JPTrawP4(rawcalojet->px(), rawcalojet->py(), rawcalojet->pz(), rawcalojet->energy()); FactorizedJetCorrectorCalculator::VariableValues values; values.setJPTrawP4(JPTrawP4); values.setJPTrawOff(offset); @@ -84,4 +75,3 @@ double L1JPTOffsetCorrector::correction(const reco::Jet& fJet, result = mCorrector->getCorrection(values); return result; } - diff --git a/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrectorImpl.cc b/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrectorImpl.cc index 4f7b8a6f5e3e6..900aa78562860 100644 --- a/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrectorImpl.cc +++ b/JetMETCorrections/Algorithms/src/L1JPTOffsetCorrectorImpl.cc @@ -20,83 +20,71 @@ using namespace std; -L1JPTOffsetCorrectorImplMaker::L1JPTOffsetCorrectorImplMaker(edm::ParameterSet const& fConfig, edm::ConsumesCollector fCollector): - JetCorrectorImplMakerBase(fConfig), - useOffset_(false) -{ +L1JPTOffsetCorrectorImplMaker::L1JPTOffsetCorrectorImplMaker(edm::ParameterSet const& fConfig, + edm::ConsumesCollector fCollector) + : JetCorrectorImplMakerBase(fConfig), useOffset_(false) { auto const& offsetService = fConfig.getParameter("offsetService"); - if(not offsetService.label().empty()) { - useOffset_ =true; + if (not offsetService.label().empty()) { + useOffset_ = true; offsetCorrectorToken_ = fCollector.consumes(offsetService); } } -std::unique_ptr -L1JPTOffsetCorrectorImplMaker::make(edm::Event const& fEvent, edm::EventSetup const& fSetup) { +std::unique_ptr L1JPTOffsetCorrectorImplMaker::make(edm::Event const& fEvent, + edm::EventSetup const& fSetup) { reco::JetCorrector const* offset = nullptr; - if(useOffset_) { + if (useOffset_) { edm::Handle hOffset; - fEvent.getByToken(offsetCorrectorToken_,hOffset); + fEvent.getByToken(offsetCorrectorToken_, hOffset); offset = &(*hOffset); } - auto calculator = getCalculator(fSetup, - [](std::string const& level) - { - if ( level != "L1JPTOffset") { - throw cms::Exception("L1OffsetCorrector")<<" correction level: "<( new L1JPTOffsetCorrectorImpl(calculator,offset) ); + auto calculator = getCalculator(fSetup, [](std::string const& level) { + if (level != "L1JPTOffset") { + throw cms::Exception("L1OffsetCorrector") << " correction level: " << level << " is not L1JPTOffset"; + } + }); + return std::unique_ptr(new L1JPTOffsetCorrectorImpl(calculator, offset)); } -void -L1JPTOffsetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) -{ +void L1JPTOffsetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) { edm::ParameterSetDescription desc; addToDescription(desc); desc.add("offsetService"); iDescriptions.addDefault(desc); } - -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrectorImpl constructor ------------------------------------------ //------------------------------------------------------------------------ L1JPTOffsetCorrectorImpl::L1JPTOffsetCorrectorImpl(std::shared_ptr corrector, - const reco::JetCorrector* offsetService): - offsetService_(offsetService), - corrector_(corrector) -{ -} -//------------------------------------------------------------------------ + const reco::JetCorrector* offsetService) + : offsetService_(offsetService), corrector_(corrector) {} +//------------------------------------------------------------------------ //--- L1OffsetCorrectorImpl destructor ------------------------------------------- //------------------------------------------------------------------------ -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double L1JPTOffsetCorrectorImpl::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1JPTOffsetCorrectorImpl::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double L1JPTOffsetCorrectorImpl::correction(const reco::Jet& fJet) const -{ +double L1JPTOffsetCorrectorImpl::correction(const reco::Jet& fJet) const { double result = 1.; - const reco::JPTJet& jptjet = dynamic_cast (fJet); + const reco::JPTJet& jptjet = dynamic_cast(fJet); const edm::RefToBase& jptjetRef = jptjet.getCaloJetRef(); - reco::CaloJet const * rawcalojet = dynamic_cast( &* jptjetRef); + reco::CaloJet const* rawcalojet = dynamic_cast(&*jptjetRef); //------ access the offset correction service ---------------- double offset = 1.0; if (offsetService_) { - offset = offsetService_->correction(*rawcalojet); + offset = offsetService_->correction(*rawcalojet); } //------ calculate the correction for the JPT jet ------------ - TLorentzVector JPTrawP4(rawcalojet->px(),rawcalojet->py(),rawcalojet->pz(),rawcalojet->energy()); + TLorentzVector JPTrawP4(rawcalojet->px(), rawcalojet->py(), rawcalojet->pz(), rawcalojet->energy()); FactorizedJetCorrectorCalculator::VariableValues values; values.setJPTrawP4(JPTrawP4); values.setJPTrawOff(offset); @@ -104,4 +92,3 @@ double L1JPTOffsetCorrectorImpl::correction(const reco::Jet& fJet) const result = corrector_->getCorrection(values); return result; } - diff --git a/JetMETCorrections/Algorithms/src/L1OffsetCorrector.cc b/JetMETCorrections/Algorithms/src/L1OffsetCorrector.cc index 02aaa296822c5..0c06ba9ddecd4 100644 --- a/JetMETCorrections/Algorithms/src/L1OffsetCorrector.cc +++ b/JetMETCorrections/Algorithms/src/L1OffsetCorrector.cc @@ -15,61 +15,52 @@ using namespace std; - -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrector constructor ------------------------------------------ //------------------------------------------------------------------------ -L1OffsetCorrector::L1OffsetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) -{ +L1OffsetCorrector::L1OffsetCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) { mVertexCollName = fConfig.getParameter("vertexCollection"); - mMinVtxNdof = fConfig.getParameter("minVtxNdof"); + mMinVtxNdof = fConfig.getParameter("minVtxNdof"); if (fParam.definitions().level() != "L1Offset") - throw cms::Exception("L1OffsetCorrector")<<" correction level: "< vParam; vParam.push_back(fParam); mCorrector = new FactorizedJetCorrectorCalculator(vParam); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrector destructor ------------------------------------------- //------------------------------------------------------------------------ -L1OffsetCorrector::~L1OffsetCorrector() -{ - delete mCorrector; -} -//------------------------------------------------------------------------ +L1OffsetCorrector::~L1OffsetCorrector() { delete mCorrector; } +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double L1OffsetCorrector::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1OffsetCorrector::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double L1OffsetCorrector::correction(const reco::Jet& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(reco::Jet), event required!"; +double L1OffsetCorrector::correction(const reco::Jet& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(reco::Jet), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet using event indormation --------- //------------------------------------------------------------------------ -double L1OffsetCorrector::correction(const reco::Jet& fJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const -{ +double L1OffsetCorrector::correction(const reco::Jet& fJet, + const edm::Event& fEvent, + const edm::EventSetup& fSetup) const { double result = 1.; edm::Handle recVtxs; - fEvent.getByLabel(mVertexCollName,recVtxs); + fEvent.getByLabel(mVertexCollName, recVtxs); int NPV(0); - for(unsigned int ind=0;indsize();ind++) { + for (unsigned int ind = 0; ind < recVtxs->size(); ind++) { if (!((*recVtxs)[ind].isFake()) && (*recVtxs)[ind].ndof() > mMinVtxNdof) { NPV++; } - } + } if (NPV > 0) { FactorizedJetCorrectorCalculator::VariableValues values; values.setJetEta(fJet.eta()); @@ -80,4 +71,3 @@ double L1OffsetCorrector::correction(const reco::Jet& fJet, } return result; } - diff --git a/JetMETCorrections/Algorithms/src/L1OffsetCorrectorImpl.cc b/JetMETCorrections/Algorithms/src/L1OffsetCorrectorImpl.cc index bac650008fb16..50867989b9db1 100644 --- a/JetMETCorrections/Algorithms/src/L1OffsetCorrectorImpl.cc +++ b/JetMETCorrections/Algorithms/src/L1OffsetCorrectorImpl.cc @@ -18,38 +18,32 @@ using namespace std; -L1OffsetCorrectorImplMaker::L1OffsetCorrectorImplMaker(edm::ParameterSet const& fConfig, - edm::ConsumesCollector fCollector) : - JetCorrectorImplMakerBase(fConfig), - verticesToken_(fCollector.consumes(fConfig.getParameter("vertexCollection"))), - minVtxNdof_(fConfig.getParameter("minVtxNdof")) -{ -} -std::unique_ptr -L1OffsetCorrectorImplMaker::make(edm::Event const& fEvent, edm::EventSetup const& fSetup) -{ +L1OffsetCorrectorImplMaker::L1OffsetCorrectorImplMaker(edm::ParameterSet const& fConfig, + edm::ConsumesCollector fCollector) + : JetCorrectorImplMakerBase(fConfig), + verticesToken_( + fCollector.consumes(fConfig.getParameter("vertexCollection"))), + minVtxNdof_(fConfig.getParameter("minVtxNdof")) {} +std::unique_ptr L1OffsetCorrectorImplMaker::make(edm::Event const& fEvent, + edm::EventSetup const& fSetup) { edm::Handle recVtxs; - fEvent.getByToken(verticesToken_,recVtxs); + fEvent.getByToken(verticesToken_, recVtxs); int NPV(0); - for(auto const& vertex : *recVtxs) { + for (auto const& vertex : *recVtxs) { if ((not vertex.isFake()) and (vertex.ndof() > minVtxNdof_)) { NPV++; } } - - auto calculator = getCalculator(fSetup, - [](std::string const& level) - { - if ( level != "L1Offset") { - throw cms::Exception("L1OffsetCorrectorImpl")<<" correction level: "<(new L1OffsetCorrectorImpl(calculator,NPV)); + + auto calculator = getCalculator(fSetup, [](std::string const& level) { + if (level != "L1Offset") { + throw cms::Exception("L1OffsetCorrectorImpl") << " correction level: " << level << " is not L1Offset"; + } + }); + return std::unique_ptr(new L1OffsetCorrectorImpl(calculator, NPV)); } -void -L1OffsetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) -{ +void L1OffsetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) { edm::ParameterSetDescription desc; addToDescription(desc); desc.add("vertexCollection"); @@ -57,30 +51,24 @@ L1OffsetCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDe iDescriptions.addDefault(desc); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- L1OffsetCorrectorImpl constructor ------------------------------------------ //------------------------------------------------------------------------ L1OffsetCorrectorImpl::L1OffsetCorrectorImpl(std::shared_ptr calculator, - int npv): - corrector_(calculator), - npv_(npv) -{ -} + int npv) + : corrector_(calculator), npv_(npv) {} -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double L1OffsetCorrectorImpl::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L1OffsetCorrectorImpl::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double L1OffsetCorrectorImpl::correction(const reco::Jet& fJet) const -{ +double L1OffsetCorrectorImpl::correction(const reco::Jet& fJet) const { double result = 1.; if (npv_ > 0) { FactorizedJetCorrectorCalculator::VariableValues values; @@ -92,4 +80,3 @@ double L1OffsetCorrectorImpl::correction(const reco::Jet& fJet) const } return result; } - diff --git a/JetMETCorrections/Algorithms/src/L6SLBCorrector.cc b/JetMETCorrections/Algorithms/src/L6SLBCorrector.cc index 9d204cf450eb3..34717ce5e7af1 100644 --- a/JetMETCorrections/Algorithms/src/L6SLBCorrector.cc +++ b/JetMETCorrections/Algorithms/src/L6SLBCorrector.cc @@ -16,89 +16,71 @@ #include "DataFormats/TrackReco/interface/Track.h" - #include - using namespace std; - //////////////////////////////////////////////////////////////////////////////// // construction / destruction //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ L6SLBCorrector::L6SLBCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) - : addMuonToJet_(fConfig.getParameter("addMuonToJet")) - , srcBTagInfoElec_(fConfig.getParameter("srcBTagInfoElectron")) - , srcBTagInfoMuon_(fConfig.getParameter("srcBTagInfoMuon")) - , corrector_(nullptr) -{ + : addMuonToJet_(fConfig.getParameter("addMuonToJet")), + srcBTagInfoElec_(fConfig.getParameter("srcBTagInfoElectron")), + srcBTagInfoMuon_(fConfig.getParameter("srcBTagInfoMuon")), + corrector_(nullptr) { vector vParam; vParam.push_back(fParam); corrector_ = new FactorizedJetCorrectorCalculator(vParam); } //______________________________________________________________________________ -L6SLBCorrector::~L6SLBCorrector() -{ - delete corrector_; -} - +L6SLBCorrector::~L6SLBCorrector() { delete corrector_; } //////////////////////////////////////////////////////////////////////////////// // implementation of member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ -double L6SLBCorrector::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L6SLBCorrector::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } - //______________________________________________________________________________ -double L6SLBCorrector::correction(const reco::Jet& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(reco::Jet), event required!"; +double L6SLBCorrector::correction(const reco::Jet& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(reco::Jet), event required!"; return 1.0; } - //______________________________________________________________________________ double L6SLBCorrector::correction(const reco::Jet& fJet, - const edm::RefToBase& refToRawJet, - const edm::Event& fEvent, - const edm::EventSetup& fSetup) const -{ + const edm::RefToBase& refToRawJet, + const edm::Event& fEvent, + const edm::EventSetup& fSetup) const { FactorizedJetCorrectorCalculator::VariableValues values; values.setJetPt(fJet.pt()); values.setJetEta(fJet.eta()); values.setJetPhi(fJet.phi()); values.setJetE(fJet.energy()); - - edm::Handle< vector > muoninfos; - fEvent.getByLabel(srcBTagInfoMuon_,muoninfos); - - const reco::SoftLeptonTagInfo& sltMuon = - (*muoninfos)[getBTagInfoIndex(refToRawJet,*muoninfos)]; - if (sltMuon.leptons()>0) { + + edm::Handle > muoninfos; + fEvent.getByLabel(srcBTagInfoMuon_, muoninfos); + + const reco::SoftLeptonTagInfo& sltMuon = (*muoninfos)[getBTagInfoIndex(refToRawJet, *muoninfos)]; + if (sltMuon.leptons() > 0) { const edm::RefToBase& trackRef = sltMuon.lepton(0); values.setLepPx(trackRef->px()); values.setLepPy(trackRef->py()); values.setLepPz(trackRef->pz()); values.setAddLepToJet(addMuonToJet_); return corrector_->getCorrection(values); - } - else { - edm::Handle< vector > elecinfos; - fEvent.getByLabel(srcBTagInfoElec_,elecinfos); - const reco::SoftLeptonTagInfo& sltElec = - (*elecinfos)[getBTagInfoIndex(refToRawJet,*elecinfos)]; - if (sltElec.leptons()>0) { + } else { + edm::Handle > elecinfos; + fEvent.getByLabel(srcBTagInfoElec_, elecinfos); + const reco::SoftLeptonTagInfo& sltElec = (*elecinfos)[getBTagInfoIndex(refToRawJet, *elecinfos)]; + if (sltElec.leptons() > 0) { const edm::RefToBase& trackRef = sltElec.lepton(0); values.setLepPx(trackRef->px()); values.setLepPy(trackRef->py()); @@ -110,17 +92,15 @@ double L6SLBCorrector::correction(const reco::Jet& fJet, return 1.0; } - //////////////////////////////////////////////////////////////////////////////// // implementation of private member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ int L6SLBCorrector::getBTagInfoIndex(const edm::RefToBase& refToRawJet, - const vector& tags) - const -{ - for (unsigned int i=0;i& tags) const { + for (unsigned int i = 0; i < tags.size(); i++) + if (tags[i].jet().get() == refToRawJet.get()) + return i; return -1; } diff --git a/JetMETCorrections/Algorithms/src/L6SLBCorrectorImpl.cc b/JetMETCorrections/Algorithms/src/L6SLBCorrectorImpl.cc index c090e15d15022..f894c1bad6b9e 100644 --- a/JetMETCorrections/Algorithms/src/L6SLBCorrectorImpl.cc +++ b/JetMETCorrections/Algorithms/src/L6SLBCorrectorImpl.cc @@ -19,43 +19,33 @@ #include "DataFormats/TrackReco/interface/Track.h" - #include - using namespace std; -L6SLBCorrectorImplMaker::L6SLBCorrectorImplMaker(edm::ParameterSet const& fConfig, - edm::ConsumesCollector fCollector) - : JetCorrectorImplMakerBase(fConfig) - , elecToken_(fCollector.consumes>(fConfig.getParameter("srcBTagInfoElectron"))) - , muonToken_(fCollector.consumes>(fConfig.getParameter("srcBTagInfoMuon"))) - , addMuonToJet_(fConfig.getParameter("addMuonToJet")) -{ -} - -std::unique_ptr -L6SLBCorrectorImplMaker::make(edm::Event const&fEvent, edm::EventSetup const& fSetup) -{ - edm::Handle< std::vector > muoninfos; - fEvent.getByToken(muonToken_,muoninfos); +L6SLBCorrectorImplMaker::L6SLBCorrectorImplMaker(edm::ParameterSet const& fConfig, edm::ConsumesCollector fCollector) + : JetCorrectorImplMakerBase(fConfig), + elecToken_(fCollector.consumes>( + fConfig.getParameter("srcBTagInfoElectron"))), + muonToken_(fCollector.consumes>( + fConfig.getParameter("srcBTagInfoMuon"))), + addMuonToJet_(fConfig.getParameter("addMuonToJet")) {} + +std::unique_ptr L6SLBCorrectorImplMaker::make(edm::Event const& fEvent, + edm::EventSetup const& fSetup) { + edm::Handle> muoninfos; + fEvent.getByToken(muonToken_, muoninfos); edm::RefProd> muonProd(muoninfos); - edm::Handle< std::vector > elecinfos; - fEvent.getByToken(elecToken_,elecinfos); + edm::Handle> elecinfos; + fEvent.getByToken(elecToken_, elecinfos); edm::RefProd> elecProd(elecinfos); - auto calculator = getCalculator(fSetup, - [](std::string const& ) {}); - return std::unique_ptr(new L6SLBCorrectorImpl(calculator, - muonProd, - elecProd, - addMuonToJet_)); + auto calculator = getCalculator(fSetup, [](std::string const&) {}); + return std::unique_ptr(new L6SLBCorrectorImpl(calculator, muonProd, elecProd, addMuonToJet_)); } -void -L6SLBCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) -{ +void L6SLBCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) { edm::ParameterSetDescription desc; addToDescription(desc); desc.add("srcBTagInfoElectron"); @@ -70,62 +60,46 @@ L6SLBCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescr //______________________________________________________________________________ L6SLBCorrectorImpl::L6SLBCorrectorImpl(std::shared_ptr corrector, - edm::RefProd> const& bTagInfoMuon, - edm::RefProd> const& bTagInfoElec, - bool addMuonToJet): - corrector_(corrector), - bTagInfoMuon_(bTagInfoMuon), - bTagInfoElec_(bTagInfoElec), - addMuonToJet_(addMuonToJet) -{ -} + edm::RefProd> const& bTagInfoMuon, + edm::RefProd> const& bTagInfoElec, + bool addMuonToJet) + : corrector_(corrector), bTagInfoMuon_(bTagInfoMuon), bTagInfoElec_(bTagInfoElec), addMuonToJet_(addMuonToJet) {} //////////////////////////////////////////////////////////////////////////////// // implementation of member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ -double L6SLBCorrectorImpl::correction(const LorentzVector& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(LorentzVector), event required!"; +double L6SLBCorrectorImpl::correction(const LorentzVector& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(LorentzVector), event required!"; return 1.0; } - //______________________________________________________________________________ -double L6SLBCorrectorImpl::correction(const reco::Jet& fJet) const -{ - throw cms::Exception("EventRequired") - <<"Wrong interface correction(reco::Jet), event required!"; +double L6SLBCorrectorImpl::correction(const reco::Jet& fJet) const { + throw cms::Exception("EventRequired") << "Wrong interface correction(reco::Jet), event required!"; return 1.0; } - //______________________________________________________________________________ -double L6SLBCorrectorImpl::correction(const reco::Jet& fJet, - const edm::RefToBase& refToRawJet) const -{ +double L6SLBCorrectorImpl::correction(const reco::Jet& fJet, const edm::RefToBase& refToRawJet) const { FactorizedJetCorrectorCalculator::VariableValues values; values.setJetPt(fJet.pt()); values.setJetEta(fJet.eta()); values.setJetPhi(fJet.phi()); values.setJetE(fJet.energy()); - - const reco::SoftLeptonTagInfo& sltMuon = - (*bTagInfoMuon_)[getBTagInfoIndex(refToRawJet,*bTagInfoMuon_)]; - if (sltMuon.leptons()>0) { + + const reco::SoftLeptonTagInfo& sltMuon = (*bTagInfoMuon_)[getBTagInfoIndex(refToRawJet, *bTagInfoMuon_)]; + if (sltMuon.leptons() > 0) { const edm::RefToBase& trackRef = sltMuon.lepton(0); values.setLepPx(trackRef->px()); values.setLepPy(trackRef->py()); values.setLepPz(trackRef->pz()); values.setAddLepToJet(addMuonToJet_); return corrector_->getCorrection(values); - } - else { - const reco::SoftLeptonTagInfo& sltElec = - (*bTagInfoElec_)[getBTagInfoIndex(refToRawJet,*bTagInfoElec_)]; - if (sltElec.leptons()>0) { + } else { + const reco::SoftLeptonTagInfo& sltElec = (*bTagInfoElec_)[getBTagInfoIndex(refToRawJet, *bTagInfoElec_)]; + if (sltElec.leptons() > 0) { const edm::RefToBase& trackRef = sltElec.lepton(0); values.setLepPx(trackRef->px()); values.setLepPy(trackRef->py()); @@ -137,17 +111,15 @@ double L6SLBCorrectorImpl::correction(const reco::Jet& fJet, return 1.0; } - //////////////////////////////////////////////////////////////////////////////// // implementation of private member functions //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ int L6SLBCorrectorImpl::getBTagInfoIndex(const edm::RefToBase& refToRawJet, - const vector& tags) - const -{ - for (unsigned int i=0;i& tags) const { + for (unsigned int i = 0; i < tags.size(); i++) + if (tags[i].jet().get() == refToRawJet.get()) + return i; return -1; } diff --git a/JetMETCorrections/Algorithms/src/LXXXCorrector.cc b/JetMETCorrections/Algorithms/src/LXXXCorrector.cc index 29db87a446c9b..9a4ecb54aeec3 100644 --- a/JetMETCorrections/Algorithms/src/LXXXCorrector.cc +++ b/JetMETCorrections/Algorithms/src/LXXXCorrector.cc @@ -13,17 +13,15 @@ using namespace std; - -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- LXXXCorrector constructor ------------------------------------------ //------------------------------------------------------------------------ -LXXXCorrector::LXXXCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) -{ +LXXXCorrector::LXXXCorrector(const JetCorrectorParameters& fParam, const edm::ParameterSet& fConfig) { string level = fParam.definitions().level(); if (level == "L2Relative") mLevel = 2; else if (level == "L3Absolute") - mLevel = 3; + mLevel = 3; else if (level == "L4EMF") mLevel = 4; else if (level == "L5Flavor") @@ -33,23 +31,19 @@ LXXXCorrector::LXXXCorrector(const JetCorrectorParameters& fParam, const edm::Pa else if (level == "L2L3Residual") mLevel = 8; else - throw cms::Exception("LXXXCorrector")<<" unknown correction level "< vParam; vParam.push_back(fParam); mCorrector = new FactorizedJetCorrectorCalculator(vParam); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- LXXXCorrector destructor ------------------------------------------- //------------------------------------------------------------------------ -LXXXCorrector::~LXXXCorrector() -{ - delete mCorrector; -} -//------------------------------------------------------------------------ +LXXXCorrector::~LXXXCorrector() { delete mCorrector; } +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double LXXXCorrector::correction(const LorentzVector& fJet) const -{ +double LXXXCorrector::correction(const LorentzVector& fJet) const { // L4 correction requires more information than a simple 4-vector if (mLevel == 4) { throw cms::Exception("Invalid jet type") << "L4EMFCorrection is applicable to CaloJets only"; @@ -57,29 +51,27 @@ double LXXXCorrector::correction(const LorentzVector& fJet) const } FactorizedJetCorrectorCalculator::VariableValues values; - values.setJetEta(fJet.eta()); + values.setJetEta(fJet.eta()); values.setJetE(fJet.energy()); values.setJetPt(fJet.pt()); values.setJetPhi(fJet.phi()); return mCorrector->getCorrection(values); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double LXXXCorrector::correction(const reco::Jet& fJet) const -{ +double LXXXCorrector::correction(const reco::Jet& fJet) const { double result = 1.; // L4 correction applies to Calojets only if (mLevel == 4) { - const reco::CaloJet& caloJet = dynamic_cast (fJet); - FactorizedJetCorrectorCalculator::VariableValues values; - values.setJetEta(fJet.eta()); - values.setJetPt(fJet.pt()); - values.setJetEMF(caloJet.emEnergyFraction()); - result = mCorrector->getCorrection(values); - } - else + const reco::CaloJet& caloJet = dynamic_cast(fJet); + FactorizedJetCorrectorCalculator::VariableValues values; + values.setJetEta(fJet.eta()); + values.setJetPt(fJet.pt()); + values.setJetEMF(caloJet.emEnergyFraction()); + result = mCorrector->getCorrection(values); + } else result = correction(fJet.p4()); return result; } diff --git a/JetMETCorrections/Algorithms/src/LXXXCorrectorImpl.cc b/JetMETCorrections/Algorithms/src/LXXXCorrectorImpl.cc index 37cfc988992b8..3a2f4003562ed 100644 --- a/JetMETCorrections/Algorithms/src/LXXXCorrectorImpl.cc +++ b/JetMETCorrections/Algorithms/src/LXXXCorrectorImpl.cc @@ -15,59 +15,47 @@ using namespace std; +LXXXCorrectorImplMaker::LXXXCorrectorImplMaker(edm::ParameterSet const& fConfig, edm::ConsumesCollector) + : JetCorrectorImplMakerBase(fConfig) {} -LXXXCorrectorImplMaker::LXXXCorrectorImplMaker(edm::ParameterSet const& fConfig, edm::ConsumesCollector): -JetCorrectorImplMakerBase(fConfig) -{ +std::unique_ptr LXXXCorrectorImplMaker::make(edm::Event const&, edm::EventSetup const& fSetup) { + unsigned int level = 0; + auto calculator = getCalculator(fSetup, [&level](std::string const& levelName) { + if (levelName == "L2Relative") + level = 2; + else if (levelName == "L3Absolute") + level = 3; + else if (levelName == "L4EMF") + level = 4; + else if (levelName == "L5Flavor") + level = 5; + else if (levelName == "L7Parton") + level = 7; + else if (levelName == "L2L3Residual") + level = 8; + else + throw cms::Exception("LXXXCorrectorImpl") << " unknown correction level " << levelName; + }); + return std::unique_ptr(new LXXXCorrectorImpl(calculator, level)); } -std::unique_ptr -LXXXCorrectorImplMaker::make(edm::Event const&, edm::EventSetup const& fSetup) -{ - unsigned int level =0; - auto calculator = getCalculator(fSetup, - [&level](std::string const& levelName) - { - if (levelName == "L2Relative") - level = 2; - else if (levelName == "L3Absolute") - level = 3; - else if (levelName == "L4EMF") - level = 4; - else if (levelName == "L5Flavor") - level = 5; - else if (levelName == "L7Parton") - level = 7; - else if (levelName == "L2L3Residual") - level = 8; - else - throw cms::Exception("LXXXCorrectorImpl")<<" unknown correction level "<(new LXXXCorrectorImpl(calculator,level)); -} - -void -LXXXCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) -{ +void LXXXCorrectorImplMaker::fillDescriptions(edm::ConfigurationDescriptions& iDescriptions) { edm::ParameterSetDescription desc; addToDescription(desc); iDescriptions.addDefault(desc); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- LXXXCorrectorImpl constructor ------------------------------------------ //------------------------------------------------------------------------ -LXXXCorrectorImpl::LXXXCorrectorImpl(std::shared_ptr calculator, unsigned int level): - mLevel(level), - mCorrector(calculator) -{ -} -//------------------------------------------------------------------------ +LXXXCorrectorImpl::LXXXCorrectorImpl(std::shared_ptr calculator, + unsigned int level) + : mLevel(level), mCorrector(calculator) {} +//------------------------------------------------------------------------ //--- Returns correction for a given 4-vector ---------------------------- //------------------------------------------------------------------------ -double LXXXCorrectorImpl::correction(const LorentzVector& fJet) const -{ +double LXXXCorrectorImpl::correction(const LorentzVector& fJet) const { // L4 correction requires more information than a simple 4-vector if (mLevel == 4) { throw cms::Exception("Invalid jet type") << "L4EMFCorrection is applicable to CaloJets only"; @@ -75,29 +63,27 @@ double LXXXCorrectorImpl::correction(const LorentzVector& fJet) const } FactorizedJetCorrectorCalculator::VariableValues values; - values.setJetEta(fJet.eta()); + values.setJetEta(fJet.eta()); values.setJetE(fJet.energy()); values.setJetPt(fJet.pt()); values.setJetPhi(fJet.phi()); return mCorrector->getCorrection(values); } -//------------------------------------------------------------------------ +//------------------------------------------------------------------------ //--- Returns correction for a given jet --------------------------------- //------------------------------------------------------------------------ -double LXXXCorrectorImpl::correction(const reco::Jet& fJet) const -{ +double LXXXCorrectorImpl::correction(const reco::Jet& fJet) const { double result = 1.; // L4 correction applies to Calojets only if (mLevel == 4) { - const reco::CaloJet& caloJet = dynamic_cast (fJet); - FactorizedJetCorrectorCalculator::VariableValues values; - values.setJetEta(fJet.eta()); - values.setJetPt(fJet.pt()); - values.setJetEMF(caloJet.emEnergyFraction()); - result = mCorrector->getCorrection(values); - } - else + const reco::CaloJet& caloJet = dynamic_cast(fJet); + FactorizedJetCorrectorCalculator::VariableValues values; + values.setJetEta(fJet.eta()); + values.setJetPt(fJet.pt()); + values.setJetEMF(caloJet.emEnergyFraction()); + result = mCorrector->getCorrection(values); + } else result = correction(fJet.p4()); return result; } diff --git a/JetMETCorrections/InterpolationTables/interface/AbsArrayProjector.h b/JetMETCorrections/InterpolationTables/interface/AbsArrayProjector.h index 7946b9b337d63..e0e38ebdedc59 100644 --- a/JetMETCorrections/InterpolationTables/interface/AbsArrayProjector.h +++ b/JetMETCorrections/InterpolationTables/interface/AbsArrayProjector.h @@ -12,27 +12,23 @@ */ namespace npstat { - /** + /** // Interface class for piecemeal processing of array data and coordinates. // Intended for making multidimensional array projections. */ - template - struct AbsArrayProjector - { - virtual ~AbsArrayProjector() {} + template + struct AbsArrayProjector { + virtual ~AbsArrayProjector() {} - /** Clear all accumulated results */ - virtual void clear() = 0; + /** Clear all accumulated results */ + virtual void clear() = 0; - /** Process one array point */ - virtual void process(const unsigned *index, unsigned indexLen, - unsigned long linearIndex, - const Input& value) = 0; + /** Process one array point */ + virtual void process(const unsigned* index, unsigned indexLen, unsigned long linearIndex, const Input& value) = 0; - /** Return the result at the end of array processing */ - virtual Result result() = 0; - }; -} - -#endif // ABSARRAYPROJECTOR_HH_ + /** Return the result at the end of array processing */ + virtual Result result() = 0; + }; +} // namespace npstat +#endif // ABSARRAYPROJECTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h b/JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h index b2299b32cac2f..32a9a719276e7 100644 --- a/JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h +++ b/JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h @@ -12,26 +12,24 @@ */ namespace npstat { - /** + /** // Base class for a variety of multivariate functor-based calculations */ - struct AbsMultivariateFunctor - { - inline virtual ~AbsMultivariateFunctor() {} + struct AbsMultivariateFunctor { + inline virtual ~AbsMultivariateFunctor() {} - /** Function value */ - virtual double operator()(const double* point, unsigned dim) const = 0; + /** Function value */ + virtual double operator()(const double* point, unsigned dim) const = 0; - /** Minimum expected dimensionality */ - virtual unsigned minDim() const = 0; + /** Minimum expected dimensionality */ + virtual unsigned minDim() const = 0; - /** + /** // Maximum expected dimensionality // (will typically be equal to the minimum) */ - virtual unsigned maxDim() const {return minDim();} - }; -} - -#endif // NPSTAT_ABSMULTIVARIATEFUNCTOR_HH_ + virtual unsigned maxDim() const { return minDim(); } + }; +} // namespace npstat +#endif // NPSTAT_ABSMULTIVARIATEFUNCTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/AbsVisitor.h b/JetMETCorrections/InterpolationTables/interface/AbsVisitor.h index 10d7d7997dfbe..a2e229122e7d7 100644 --- a/JetMETCorrections/InterpolationTables/interface/AbsVisitor.h +++ b/JetMETCorrections/InterpolationTables/interface/AbsVisitor.h @@ -12,44 +12,41 @@ */ namespace npstat { - /** + /** // Interface class for piecemeal processing of a data collection */ - template - struct AbsVisitor - { - inline virtual ~AbsVisitor() {} + template + struct AbsVisitor { + inline virtual ~AbsVisitor() {} - /** Clear all accumulated results */ - virtual void clear() = 0; + /** Clear all accumulated results */ + virtual void clear() = 0; - /** Process one array point */ - virtual void process(const Input& value) = 0; + /** Process one array point */ + virtual void process(const Input& value) = 0; - /** Return the result at the end of array processing */ - virtual Result result() = 0; - }; + /** Return the result at the end of array processing */ + virtual Result result() = 0; + }; - /** + /** // Simple counter of visits is needed often, so it makes sense // to put it together with AbsVisitor in the same header. Do not // derive from this class, its destructor is not virtual. */ - template - class VisitCounter : public AbsVisitor - { - public: - inline VisitCounter() : counter_(0UL) {} - inline virtual ~VisitCounter() {} - - inline void clear() {counter_ = 0UL;} - inline void process(const Input&) {++counter_;} - inline unsigned long result() {return counter_;} - - private: - unsigned long counter_; - }; -} - -#endif // ABSVISITOR_HH_ - + template + class VisitCounter : public AbsVisitor { + public: + inline VisitCounter() : counter_(0UL) {} + inline virtual ~VisitCounter() {} + + inline void clear() { counter_ = 0UL; } + inline void process(const Input&) { ++counter_; } + inline unsigned long result() { return counter_; } + + private: + unsigned long counter_; + }; +} // namespace npstat + +#endif // ABSVISITOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ArrayND.h b/JetMETCorrections/InterpolationTables/interface/ArrayND.h index ab747e3c446a1..16d7ebd712952 100644 --- a/JetMETCorrections/InterpolationTables/interface/ArrayND.h +++ b/JetMETCorrections/InterpolationTables/interface/ArrayND.h @@ -23,7 +23,7 @@ #include "JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h" namespace npstat { - /** + /** // A class for multidimensional array manipulation. A number of methods // of this class will work only if dimensionality is limited by // CHAR_BIT*sizeof(unsigned long)-1 (which is 31 and 63 on 32- and 64-bit @@ -44,17 +44,16 @@ namespace npstat { // // Both StackLen and StackDim parameters must be positive. */ - template - class ArrayND - { - template - friend class ArrayND; + template + class ArrayND { + template + friend class ArrayND; - public: - typedef Numeric value_type; - typedef typename ProperDblFromCmpl::type proper_double; + public: + typedef Numeric value_type; + typedef typename ProperDblFromCmpl::type proper_double; - /** + /** // Default constructor creates an uninitialized array. // Only three things can be done safely with such an array: // @@ -68,10 +67,10 @@ namespace npstat { // an exception is thrown). Note that initialized array can not // be assigned from uninitialized one. */ - ArrayND(); + ArrayND(); - //@{ - /** + //@{ + /** // Constructor which creates arrays with the given shape. // The array data remains undefined. Simple inilitalization // of the data can be performed using methods clear() or @@ -79,14 +78,14 @@ namespace npstat { // can be done by "linearFill", "functorFill", or by setting // every array element to a desired value. */ - explicit ArrayND(const ArrayShape& shape); - ArrayND(const unsigned* shape, unsigned dim); - //@} + explicit ArrayND(const ArrayShape& shape); + ArrayND(const unsigned* shape, unsigned dim); + //@} - /** The copy constructor */ - ArrayND(const ArrayND&); + /** The copy constructor */ + ArrayND(const ArrayND&); - /** + /** // Converting constructor. It looks more general than the copy // constructor, but the actual copy constructor has to be created // anyway -- otherwise the compiler will generate an incorrect @@ -94,27 +93,25 @@ namespace npstat { // constructor essentially disables data type safety for copying // arrays -- but the code significantly gains in convenience. */ - template - ArrayND(const ArrayND&); + template + ArrayND(const ArrayND&); - /** + /** // Converting constructor where the array values are filled // by a functor using values of another array as arguments */ - template - ArrayND(const ArrayND&, Functor f); + template + ArrayND(const ArrayND&, Functor f); - /** Constructor from a subrange of another array */ - template - ArrayND(const ArrayND& from, - const ArrayRange& fromRange); + /** Constructor from a subrange of another array */ + template + ArrayND(const ArrayND& from, const ArrayRange& fromRange); - /** Similar constructor with a transforming functor */ - template - ArrayND(const ArrayND& from, - const ArrayRange& fromRange, Functor f); + /** Similar constructor with a transforming functor */ + template + ArrayND(const ArrayND& from, const ArrayRange& fromRange, Functor f); - /** + /** // Constructor from a slice of another array. The data of the // constructed array remains undefined. The argument "indices" // lists either the array indices whose numbers will be fixed @@ -125,45 +122,51 @@ namespace npstat { // used with methods "exportSlice", "importSlice", "project", etc. // of the parent array "slicedArray". */ - template - ArrayND(const ArrayND& slicedArray, - const unsigned *indices, unsigned nIndices); - - /** Outer product constructor */ - template - ArrayND(const ArrayND& a1, - const ArrayND& a2); - - //@{ - /** + template + ArrayND(const ArrayND& slicedArray, const unsigned* indices, unsigned nIndices); + + /** Outer product constructor */ + template + ArrayND(const ArrayND& a1, const ArrayND& a2); + + //@{ + /** // Constructor in which the spans are explicitly provided // for each dimension. The array data remains undefined. */ - explicit ArrayND(unsigned n0); - ArrayND(unsigned n0, unsigned n1); - ArrayND(unsigned n0, unsigned n1, unsigned n2); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4, unsigned n5); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4, unsigned n5, unsigned n6); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4, unsigned n5, unsigned n6, unsigned n7); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4, unsigned n5, unsigned n6, unsigned n7, - unsigned n8); - ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, - unsigned n4, unsigned n5, unsigned n6, unsigned n7, - unsigned n8, unsigned n9); - //@} - - /** Destructor */ - ~ArrayND(); - - /** + explicit ArrayND(unsigned n0); + ArrayND(unsigned n0, unsigned n1); + ArrayND(unsigned n0, unsigned n1, unsigned n2); + ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3); + ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, unsigned n4); + ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, unsigned n4, unsigned n5); + ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, unsigned n4, unsigned n5, unsigned n6); + ArrayND(unsigned n0, unsigned n1, unsigned n2, unsigned n3, unsigned n4, unsigned n5, unsigned n6, unsigned n7); + ArrayND(unsigned n0, + unsigned n1, + unsigned n2, + unsigned n3, + unsigned n4, + unsigned n5, + unsigned n6, + unsigned n7, + unsigned n8); + ArrayND(unsigned n0, + unsigned n1, + unsigned n2, + unsigned n3, + unsigned n4, + unsigned n5, + unsigned n6, + unsigned n7, + unsigned n8, + unsigned n9); + //@} + + /** Destructor */ + ~ArrayND(); + + /** // Assignment operator. The shape of the array on the right // must be compatible with the shape of the array on the left. // The only exception is when the array on the left has no shape @@ -171,184 +174,183 @@ namespace npstat { // its "uninitialize" method was called). In this case the array // on the left will assume the shape of the array on the right. */ - ArrayND& operator=(const ArrayND&); + ArrayND& operator=(const ArrayND&); - /** Converting assignment operator */ - template - ArrayND& operator=(const ArrayND&); + /** Converting assignment operator */ + template + ArrayND& operator=(const ArrayND&); - /** Converting assignment method with a transforming functor */ - template - ArrayND& assign(const ArrayND&, Functor f); + /** Converting assignment method with a transforming functor */ + template + ArrayND& assign(const ArrayND&, Functor f); - /** + /** // The function which can "uninitialize" the array to the same // state as produced by the default constructor. Can be applied // in order to force the assignment operators to work. */ - ArrayND& uninitialize(); + ArrayND& uninitialize(); - //@{ - /** + //@{ + /** // Element access using multidimensional array index // (no bounds checking). The length of the index array // must be equal to the rank of this object. */ - Numeric& value(const unsigned *index, unsigned indexLen); - const Numeric& value(const unsigned *index, unsigned indexLen) const; - //@} + Numeric& value(const unsigned* index, unsigned indexLen); + const Numeric& value(const unsigned* index, unsigned indexLen) const; + //@} - //@{ - /** + //@{ + /** // Element access using multidimensional array index // (with bounds checking) */ - Numeric& valueAt(const unsigned *index, unsigned indexLen); - const Numeric& valueAt(const unsigned *index, unsigned indexLen) const; - //@} + Numeric& valueAt(const unsigned* index, unsigned indexLen); + const Numeric& valueAt(const unsigned* index, unsigned indexLen) const; + //@} - //@{ - /** Element access using linear index (no bounds checking) */ - Numeric& linearValue(unsigned long index); - const Numeric& linearValue(unsigned long index) const; - //@} + //@{ + /** Element access using linear index (no bounds checking) */ + Numeric& linearValue(unsigned long index); + const Numeric& linearValue(unsigned long index) const; + //@} - //@{ - /** Element access using linear index (with bounds checking) */ - Numeric& linearValueAt(unsigned long index); - const Numeric& linearValueAt(unsigned long index) const; - //@} + //@{ + /** Element access using linear index (with bounds checking) */ + Numeric& linearValueAt(unsigned long index); + const Numeric& linearValueAt(unsigned long index) const; + //@} - /** Convert linear index into multidimensional index */ - void convertLinearIndex(unsigned long l, unsigned* index, - unsigned indexLen) const; + /** Convert linear index into multidimensional index */ + void convertLinearIndex(unsigned long l, unsigned* index, unsigned indexLen) const; - /** Convert multidimensional index into linear index */ - unsigned long linearIndex(const unsigned* idx, unsigned idxLen) const; + /** Convert multidimensional index into linear index */ + unsigned long linearIndex(const unsigned* idx, unsigned idxLen) const; - // Some inspectors - /** Total number of data array elements */ - inline unsigned long length() const {return len_;} + // Some inspectors + /** Total number of data array elements */ + inline unsigned long length() const { return len_; } - /** Linearized data */ - inline const Numeric* data() const {return data_;} + /** Linearized data */ + inline const Numeric* data() const { return data_; } - /** Check whether the array has been initialized */ - inline bool isShapeKnown() const {return shapeIsKnown_;} + /** Check whether the array has been initialized */ + inline bool isShapeKnown() const { return shapeIsKnown_; } - /** The number of array dimensions */ - inline unsigned rank() const {return dim_;} + /** The number of array dimensions */ + inline unsigned rank() const { return dim_; } - /** Get the complete shape */ - ArrayShape shape() const; + /** Get the complete shape */ + ArrayShape shape() const; - /** Shape data as a C-style array */ - inline const unsigned *shapeData() const {return shape_;} + /** Shape data as a C-style array */ + inline const unsigned* shapeData() const { return shape_; } - /** Get the complete range */ - ArrayRange fullRange() const; + /** Get the complete range */ + ArrayRange fullRange() const; - /** Get the number of elements in some particular dimension */ - unsigned span(unsigned dim) const; + /** Get the number of elements in some particular dimension */ + unsigned span(unsigned dim) const; - /** Maximum span among all dimensions */ - unsigned maximumSpan() const; + /** Maximum span among all dimensions */ + unsigned maximumSpan() const; - /** Minimum span among all dimensions */ - unsigned minimumSpan() const; + /** Minimum span among all dimensions */ + unsigned minimumSpan() const; - /** Get the strides */ - inline const unsigned long* strides() const {return strides_;} + /** Get the strides */ + inline const unsigned long* strides() const { return strides_; } - /** Check if all array elements are zero */ - bool isZero() const; + /** Check if all array elements are zero */ + bool isZero() const; - /** + /** // This method checks whether all array elements are // non-negative and, in addition, there is at least // one positive element */ - bool isDensity() const; + bool isDensity() const; - /** This method modifies all the data in one statement */ - template - ArrayND& setData(const Num2* data, unsigned long dataLength); + /** This method modifies all the data in one statement */ + template + ArrayND& setData(const Num2* data, unsigned long dataLength); - /** Compare two arrays for equality */ - template - bool operator==(const ArrayND&) const; + /** Compare two arrays for equality */ + template + bool operator==(const ArrayND&) const; - /** Logical negation of operator== */ - template - bool operator!=(const ArrayND&) const; + /** Logical negation of operator== */ + template + bool operator!=(const ArrayND&) const; - /** Largest absolute difference with another bin-compatible array */ - template - double maxAbsDifference(const ArrayND&) const; + /** Largest absolute difference with another bin-compatible array */ + template + double maxAbsDifference(const ArrayND&) const; - /** operator+ returns a copy of this array */ - ArrayND operator+() const; + /** operator+ returns a copy of this array */ + ArrayND operator+() const; - /** operator- applies the unary minus operator to every element */ - ArrayND operator-() const; + /** operator- applies the unary minus operator to every element */ + ArrayND operator-() const; - /** addition of two arrays */ - template - ArrayND operator+(const ArrayND& r) const; + /** addition of two arrays */ + template + ArrayND operator+(const ArrayND& r) const; - /** subtraction of two arrays */ - template - ArrayND operator-(const ArrayND& r) const; + /** subtraction of two arrays */ + template + ArrayND operator-(const ArrayND& r) const; - /** multiplication by a scalar */ - template - ArrayND operator*(const Num2& r) const; + /** multiplication by a scalar */ + template + ArrayND operator*(const Num2& r) const; - /** division by a scalar */ - template - ArrayND operator/(const Num2& r) const; + /** division by a scalar */ + template + ArrayND operator/(const Num2& r) const; - //@{ - /** + //@{ + /** // In-place operators. Note that these work faster than the binary // versions, i.e., A += B is much faster than A = A + B. */ - template - ArrayND& operator*=(const Num2& r); + template + ArrayND& operator*=(const Num2& r); - template - ArrayND& operator/=(const Num2& r); + template + ArrayND& operator/=(const Num2& r); - template - ArrayND& operator+=(const ArrayND& r); + template + ArrayND& operator+=(const ArrayND& r); - template - ArrayND& operator-=(const ArrayND& r); - //@} + template + ArrayND& operator-=(const ArrayND& r); + //@} - /** This method is equivalent to (but faster than) += r*c */ - template - ArrayND& addmul(const ArrayND& r, const Num3& c); + /** This method is equivalent to (but faster than) += r*c */ + template + ArrayND& addmul(const ArrayND& r, const Num3& c); - /** Outer product as a method (see also the outer product constructor) */ - template - ArrayND outer(const ArrayND& r) const; + /** Outer product as a method (see also the outer product constructor) */ + template + ArrayND outer(const ArrayND& r) const; - /** + /** // Contraction of a pair of indices. Note that the array length // must be the same in both dimensions. */ - ArrayND contract(unsigned pos1, unsigned pos2) const; + ArrayND contract(unsigned pos1, unsigned pos2) const; - /** + /** // Here, dot product corresponds to outer product followed // by the contraction over two indices -- the last index // of this object and the first index of the argument. */ - template - ArrayND dot(const ArrayND& r) const; + template + ArrayND dot(const ArrayND& r) const; - /** + /** // The intent of this method is to marginalize // over a set of indices with a prior. Essentially, we are // calculating integrals akin to p(y) = Integral f(y|x) g(x) dx @@ -362,33 +364,32 @@ namespace npstat { // to the dimension indexMap[0] of this array, dimension 1 // corresponds to indexMap[1], etc. */ - template - ArrayND marginalize(const ArrayND& prior, - const unsigned* indexMap, unsigned mapLen) const; + template + ArrayND marginalize(const ArrayND& prior, const unsigned* indexMap, unsigned mapLen) const; - /** Transposed array */ - ArrayND transpose(unsigned pos1, unsigned pos2) const; + /** Transposed array */ + ArrayND transpose(unsigned pos1, unsigned pos2) const; - /** Transpose without arguments can be invoked for 2-d arrays only */ - ArrayND transpose() const; + /** Transpose without arguments can be invoked for 2-d arrays only */ + ArrayND transpose() const; - /** + /** // Sum of all array elements which uses Num2 type as accumulator. // Typically, the precision and dynamic range of Num2 should be // suitably larger than the precision and dynamic range of Numeric. // For example, if Numeric is float then Num2 should be double, etc. */ - template - Num2 sum() const; + template + Num2 sum() const; - /** + /** // Sum of absolute values squared which uses Num2 as accumulator. // Function std::abs(Numeric) must exist. */ - template - Num2 sumsq() const; + template + Num2 sumsq() const; - /** + /** // Mixed derivative over all directions. Useful for generating // densities from distribution functions. The resulting array // will have one less point in each dimension. Class Num2 is @@ -396,24 +397,24 @@ namespace npstat { // Num2 to Numeric must exist. The result is multiplied by the // scale factor provided. */ - template - ArrayND derivative(double scale=1.0) const; + template + ArrayND derivative(double scale = 1.0) const; - /** + /** // The operation inverse to "derivative". Constructs multivariate // cumulative density function. */ - template - ArrayND cdfArray(double scale=1.0) const; + template + ArrayND cdfArray(double scale = 1.0) const; - /** + /** // Calculate just one multivariate cumulative density function // value. Point with given index will be included in the sum. */ - template - Num2 cdfValue(const unsigned *index, unsigned indexLen) const; + template + Num2 cdfValue(const unsigned* index, unsigned indexLen) const; - /** + /** // The next function turns the array data into the conditional // cumulative density function for the last dimension. "Num2" // is the type of accumulator class used. The cdf is stored @@ -424,23 +425,23 @@ namespace npstat { // utilized (rectangular integration is used in case // "useTrapezoids" value is "false"). */ - template - void convertToLastDimCdf(ArrayND* sumSlice, bool useTrapezoids); + template + void convertToLastDimCdf(ArrayND* sumSlice, bool useTrapezoids); - /** Minimum array element */ - Numeric min() const; + /** Minimum array element */ + Numeric min() const; - /** Minimum array element and its index */ - Numeric min(unsigned *index, unsigned indexLen) const; + /** Minimum array element and its index */ + Numeric min(unsigned* index, unsigned indexLen) const; - /** Maximum array element */ - Numeric max() const; + /** Maximum array element */ + Numeric max() const; - /** Maximum array element and its index */ - Numeric max(unsigned *index, unsigned indexLen) const; + /** Maximum array element and its index */ + Numeric max(unsigned* index, unsigned indexLen) const; - //@{ - /** + //@{ + /** // Closest value accessor (works as if the array allows access // with non-integer indices). For example, the second point // in some dimension will be accessed in case the coordinate @@ -448,11 +449,11 @@ namespace npstat { // used, for example, for implementing simple N-D histogramming // or for closest value interpolation and extrapolation. */ - Numeric& closest(const double *x, unsigned xDim); - const Numeric& closest(const double *x, unsigned xDim) const; - //@} + Numeric& closest(const double* x, unsigned xDim); + const Numeric& closest(const double* x, unsigned xDim) const; + //@} - /** + /** // Multilinear interpolation. Closest value extrapolation is used // in case some index is outside of the array bounds. Note that // this function works only if the array dimensionality is less @@ -460,17 +461,17 @@ namespace npstat { // which coincides with array index for x equal to unsigned // integers. */ - Numeric interpolate1(const double *x, unsigned xDim) const; + Numeric interpolate1(const double* x, unsigned xDim) const; - /** + /** // Multicubic interpolation. Closest value extrapolation is used // in case some index is outside of the array bounds. This // function is much slower than "interpolate1" (in the current // implementation, a recursive algorithm is used). */ - Numeric interpolate3(const double *x, unsigned xDim) const; + Numeric interpolate3(const double* x, unsigned xDim) const; - /** + /** // This method applies a single-argument functor to each // element of the array (in-place). The result returned // by the functor becomes the new value of the element. There @@ -479,54 +480,54 @@ namespace npstat { // for chaining of such methods. Use the transforming constructor // if you want a new array instead. */ - template - ArrayND& apply(Functor f); + template + ArrayND& apply(Functor f); - /** + /** // This method applies a single-argument functor to each // element of the array. The result returned by the functor // is ignored inside the scan. Depending on what the functor does, // the array values may or may not be modified (they can be modified // if the functor takes its argument via a non-const reference). */ - template - ArrayND& scanInPlace(Functor f); + template + ArrayND& scanInPlace(Functor f); - /** This method fills the array data with a constant value */ - ArrayND& constFill(Numeric c); + /** This method fills the array data with a constant value */ + ArrayND& constFill(Numeric c); - /** Zero the array out (every datum becomes Numeric()) */ - ArrayND& clear(); + /** Zero the array out (every datum becomes Numeric()) */ + ArrayND& clear(); - /** + /** // This method fills the array with a linear combination // of the index values. For example, a 2-d array element with indices // i, k will be set to (coeff[0]*i + coeff[1]*k + c). There must be // a conversion (static cast) from double into "Numeric". */ - ArrayND& linearFill(const double* coeff, unsigned coeffLen, double c); + ArrayND& linearFill(const double* coeff, unsigned coeffLen, double c); - /** + /** // This method fills the array from a functor // which takes (const unsigned* index, unsigned indexLen) // arguments. There must be a conversion (static cast) from // the functor result to the "Numeric" type. */ - template - ArrayND& functorFill(Functor f); + template + ArrayND& functorFill(Functor f); - /** + /** // This method can be used for arrays with rank // of at least 2 whose length is the same in all dimensions. // It puts static_cast(1) on the main diagonal and // Numeric() everywhere else. */ - ArrayND& makeUnit(); + ArrayND& makeUnit(); - /** This method turns all negative elements into zeros */ - ArrayND& makeNonNegative(); + /** This method turns all negative elements into zeros */ + ArrayND& makeNonNegative(); - /** + /** // This method accumulates marginals and divides // the array (treated as a distribution) by the product of the // marginals. Several iterations like this turn the distribution @@ -535,26 +536,24 @@ namespace npstat { // The function returns the actual number of iteration performed // when the given tolerance was reached for all marginals. */ - unsigned makeCopulaSteps(double tolerance, unsigned maxIterations); + unsigned makeCopulaSteps(double tolerance, unsigned maxIterations); - /** + /** // Loop over all elements of two compatible arrays and apply // a binary functor */ - template - void jointScan(ArrayND& other, Functor binaryFunct); + template + void jointScan(ArrayND& other, Functor binaryFunct); - /** Convenience method for element-by-element in-place multiplication + /** Convenience method for element-by-element in-place multiplication */ - template - inline ArrayND& inPlaceMul(const ArrayND& r) - { - jointScan(const_cast&>(r), - multeq_left()); - return *this; - } + template + inline ArrayND& inPlaceMul(const ArrayND& r) { + jointScan(const_cast&>(r), multeq_left()); + return *this; + } - /** + /** // Loop over subranges in two arrays in such a way that the functor // is called only if the indices on both sides are valid. The topology // of both arrays is assumed to be box-like (flat). The starting @@ -571,96 +570,93 @@ namespace npstat { // functor has been specified. Apply const_cast judiciously as needed, // other solutions of this problem are not any better. */ - template - void jointSubrangeScan(ArrayND& other, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - unsigned arrLen, - Functor binaryFunct); + template + void jointSubrangeScan(ArrayND& other, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + unsigned arrLen, + Functor binaryFunct); - /** + /** // Method similar to "jointSubrangeScan" in which the topology of // both arrays is assumed to be hypertoroidal (circular buffer in // every dimension) */ - template - void dualCircularScan(ArrayND& other, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - unsigned arrLen, - Functor binaryFunct); - - /** + template + void dualCircularScan(ArrayND& other, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + unsigned arrLen, + Functor binaryFunct); + + /** // Method similar to "jointSubrangeScan" in which the topology of // this array is assumed to be flat and the other array hypertoroidal */ - template - void flatCircularScan(ArrayND& other, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - unsigned arrLen, - Functor binaryFunct); - - /** + template + void flatCircularScan(ArrayND& other, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + unsigned arrLen, + Functor binaryFunct); + + /** // Method similar to "jointSubrangeScan" in which the topology of // this array is assumed to be hypertoroidal and the other array flat */ - template - void circularFlatScan(ArrayND& other, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - unsigned arrLen, - Functor binaryFunct); - - /** + template + void circularFlatScan(ArrayND& other, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + unsigned arrLen, + Functor binaryFunct); + + /** // This method runs over a subrange of the array // and calls the argument functor on every point. This // method will not call "clear" or "result" functions of // the argument functor. */ - template - void processSubrange(AbsArrayProjector& f, - const BoxND& subrange) const; + template + void processSubrange(AbsArrayProjector& f, const BoxND& subrange) const; - /** + /** // Copy a hyperrectangular subrange of this array potentially // completely overwriting the destination array. The starting // corner in this object where copying begins is provided by // the first two arguments. The subrange size is defined by // the shape of the destination array. */ - template - void exportSubrange(const unsigned* fromCorner, unsigned lenCorner, - ArrayND* dest) const; + template + void exportSubrange(const unsigned* fromCorner, unsigned lenCorner, ArrayND* dest) const; - /** The inverse operation to "exportSubrange" */ - template - void importSubrange(const unsigned* fromCorner, unsigned lenCorner, - const ArrayND& from); + /** The inverse operation to "exportSubrange" */ + template + void importSubrange(const unsigned* fromCorner, unsigned lenCorner, const ArrayND& from); - /** + /** // Check that all elements of this array differ from the // corresponding elements of another array by at most "eps". // Equivalent to maxAbsDifference(r) <= eps (but usually faster). */ - template - bool isClose(const ArrayND& r, double eps) const; + template + bool isClose(const ArrayND& r, double eps) const; - /** Check compatibility with another shape */ - bool isCompatible(const ArrayShape& shape) const; + /** Check compatibility with another shape */ + bool isCompatible(const ArrayShape& shape) const; - /** + /** // Check shape compatibility with another array. Equivalent to // but faster than isCompatible(r.shape()). */ - template - bool isShapeCompatible(const ArrayND& r) const; + template + bool isShapeCompatible(const ArrayND& r) const; - /** + /** // Joint cycle over the data of this array and the slice. // The array to which the "slice" argument refers should normally // be created by the slicing constructor using this array as @@ -669,14 +665,14 @@ namespace npstat { // is to be used for import/export of slice data and in-place // operations (addition, multiplication, etc). */ - template - void jointSliceScan(ArrayND& slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices, - Functor binaryFunct); + template + void jointSliceScan(ArrayND& slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices, + Functor binaryFunct); - /** + /** // Joint cycle over a slice this array and some memory buffer. // The length of the buffer must be equal to the length of the // slice, as in "jointSliceScan". This method is to be used @@ -684,610 +680,636 @@ namespace npstat { // (addition, multiplication, etc) with memory managed not // by ArrayND but in some other manner. */ - template - void jointMemSliceScan(Num2* buffer, unsigned long bufLen, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices, - Functor binaryFunct); + template + void jointMemSliceScan(Num2* buffer, + unsigned long bufLen, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices, + Functor binaryFunct); - /** Figure out the slice shape without actually making the slice */ - ArrayShape sliceShape(const unsigned *fixedIndices, - unsigned nFixedIndices) const; - - /** Convenience method for exporting a slice of this array */ - template - inline void exportSlice(ArrayND* slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices) const - { - assert(slice); - (const_cast(this))->jointSliceScan( - *slice, fixedIndices, fixedIndexValues, nFixedIndices, - scast_assign_right()); - } + /** Figure out the slice shape without actually making the slice */ + ArrayShape sliceShape(const unsigned* fixedIndices, unsigned nFixedIndices) const; + + /** Convenience method for exporting a slice of this array */ + template + inline void exportSlice(ArrayND* slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices) const { + assert(slice); + (const_cast(this)) + ->jointSliceScan(*slice, fixedIndices, fixedIndexValues, nFixedIndices, scast_assign_right()); + } - /** + /** // Convenience method for exporting a slice of this array // into a memory buffer */ - template - inline void exportMemSlice(Num2* buffer, unsigned long bufLen, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices) const - { - (const_cast(this))->jointMemSliceScan( - buffer, bufLen, fixedIndices, fixedIndexValues, - nFixedIndices, scast_assign_right()); - } + template + inline void exportMemSlice(Num2* buffer, + unsigned long bufLen, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices) const { + (const_cast(this)) + ->jointMemSliceScan( + buffer, bufLen, fixedIndices, fixedIndexValues, nFixedIndices, scast_assign_right()); + } - /** Convenience method for importing a slice into this array */ - template - inline void importSlice(const ArrayND& slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices) - { - jointSliceScan(const_cast&>(slice), - fixedIndices, fixedIndexValues, nFixedIndices, - scast_assign_left()); - } + /** Convenience method for importing a slice into this array */ + template + inline void importSlice(const ArrayND& slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices) { + jointSliceScan(const_cast&>(slice), + fixedIndices, + fixedIndexValues, + nFixedIndices, + scast_assign_left()); + } - /** + /** // Convenience method for importing a slice into this array // from a memory buffer */ - template - inline void importMemSlice(const Num2* buffer, unsigned long bufLen, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices) - { - jointMemSliceScan(const_cast(buffer), bufLen, - fixedIndices, fixedIndexValues, nFixedIndices, - scast_assign_left()); - } + template + inline void importMemSlice(const Num2* buffer, + unsigned long bufLen, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices) { + jointMemSliceScan(const_cast(buffer), + bufLen, + fixedIndices, + fixedIndexValues, + nFixedIndices, + scast_assign_left()); + } - /** + /** // This method applies the values in the slice to all other // coresponding values in the array. This can be used, for example, // to multiply/divide by some factor which varies across the slice. // The slice values will be used as the right functor argument. */ - template - void applySlice(ArrayND& slice, - const unsigned *fixedIndices, unsigned nFixedIndices, - Functor binaryFunct); + template + void applySlice(ArrayND& slice, + const unsigned* fixedIndices, + unsigned nFixedIndices, + Functor binaryFunct); - /** + /** // Convenience method which multiplies the array by a scale factor // which varies across the slice */ - template - inline ArrayND& multiplyBySlice(const ArrayND& slice, - const unsigned *fixedIndices, - unsigned nFixedIndices) - { - applySlice(const_cast&>(slice), - fixedIndices, nFixedIndices, - multeq_left()); - return *this; - } + template + inline ArrayND& multiplyBySlice(const ArrayND& slice, + const unsigned* fixedIndices, + unsigned nFixedIndices) { + applySlice( + const_cast&>(slice), fixedIndices, nFixedIndices, multeq_left()); + return *this; + } - //@{ - /** + //@{ + /** // This method fills a projection. The array to which // "projection" argument points should normally be created by // the slicing constructor using this array as an argument. // "projectedIndices" should be the same as "indices" specified // during the slice creation. */ - template - void project(ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - template - void project(ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - //@} - - //@{ - /** + template + void project(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void project(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + //@} + + //@{ + /** // Similar method to "project", but projections are added to // (or subtracted from) the existing projection data instead of // replacing them */ - template - void addToProjection(ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - template - void subtractFromProjection(ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - template - void addToProjection(ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - template - void subtractFromProjection(ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - //@} - - /** + template + void addToProjection(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void subtractFromProjection(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void addToProjection(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void subtractFromProjection(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + //@} + + /** // Rotation. Place the result into another array. The elements // with indices 0 in the current array will become elements with // indices "shifts" in the rotated array. */ - template - void rotate(const unsigned* shifts, unsigned lenShifts, - ArrayND* rotated) const; + template + void rotate(const unsigned* shifts, unsigned lenShifts, ArrayND* rotated) const; - /** + /** // Fill another array with all possible mirror images // of this one. This other array must have twice the span // in each dimension. */ - template - void multiMirror(ArrayND* out) const; + template + void multiMirror(ArrayND* out) const; - //@{ - /** + //@{ + /** // Fortran-style subscripting without bounds checking (of course, // with indices starting at 0). */ - Numeric& operator()(); - const Numeric& operator()() const; - - Numeric& operator()(unsigned i0); - const Numeric& operator()(unsigned i0) const; - - Numeric& operator()(unsigned i0, unsigned i1); - const Numeric& operator()(unsigned i0, unsigned i1) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2) const; - - Numeric& operator()(unsigned i0, unsigned i1, - unsigned i2, unsigned i3); - const Numeric& operator()(unsigned i0, unsigned i1, - unsigned i2, unsigned i3) const; - - Numeric& operator()(unsigned i0, unsigned i1, - unsigned i2, unsigned i3, unsigned i4); - const Numeric& operator()(unsigned i0, unsigned i1, - unsigned i2, unsigned i3, unsigned i4) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8) const; - - Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8, - unsigned i9); - const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8, - unsigned i9) const; - //@} - - //@{ - /** + Numeric& operator()(); + const Numeric& operator()() const; + + Numeric& operator()(unsigned i0); + const Numeric& operator()(unsigned i0) const; + + Numeric& operator()(unsigned i0, unsigned i1); + const Numeric& operator()(unsigned i0, unsigned i1) const; + + Numeric& operator()(unsigned i0, unsigned i1, unsigned i2); + const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2) const; + + Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3); + const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3) const; + + Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4); + const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4) const; + + Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5); + const Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5) const; + + Numeric& operator()(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6); + const Numeric& operator()( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6) const; + + Numeric& operator()( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7); + const Numeric& operator()( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7) const; + + Numeric& operator()(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8); + const Numeric& operator()(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8) const; + + Numeric& operator()(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9); + const Numeric& operator()(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9) const; + //@} + + //@{ + /** // Fortran-style subscripting with bounds checking (of course, // with indices starting at 0). */ - Numeric& at(); - const Numeric& at() const; - - Numeric& at(unsigned i0); - const Numeric& at(unsigned i0) const; - - Numeric& at(unsigned i0, unsigned i1); - const Numeric& at(unsigned i0, unsigned i1) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2) const; - - Numeric& at(unsigned i0, unsigned i1, - unsigned i2, unsigned i3); - const Numeric& at(unsigned i0, unsigned i1, - unsigned i2, unsigned i3) const; - - Numeric& at(unsigned i0, unsigned i1, - unsigned i2, unsigned i3, unsigned i4); - const Numeric& at(unsigned i0, unsigned i1, - unsigned i2, unsigned i3, unsigned i4) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8) const; - - Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8, - unsigned i9); - const Numeric& at(unsigned i0, unsigned i1, unsigned i2, - unsigned i3, unsigned i4, unsigned i5, - unsigned i6, unsigned i7, unsigned i8, - unsigned i9) const; - //@} - - //@{ - /** + Numeric& at(); + const Numeric& at() const; + + Numeric& at(unsigned i0); + const Numeric& at(unsigned i0) const; + + Numeric& at(unsigned i0, unsigned i1); + const Numeric& at(unsigned i0, unsigned i1) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2); + const Numeric& at(unsigned i0, unsigned i1, unsigned i2) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3); + const Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4); + const Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5); + const Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6); + const Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6) const; + + Numeric& at(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7); + const Numeric& at( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7) const; + + Numeric& at(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8); + const Numeric& at(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8) const; + + Numeric& at(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9); + const Numeric& at(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9) const; + //@} + + //@{ + /** // Subscripting by continuous coordinate. // Works similar to the "closest" method. */ - Numeric& cl(); - const Numeric& cl() const; - - Numeric& cl(double x0); - const Numeric& cl(double x0) const; - - Numeric& cl(double x0, double x1); - const Numeric& cl(double x0, double x1) const; - - Numeric& cl(double x0, double x1, double x2); - const Numeric& cl(double x0, double x1, double x2) const; - - Numeric& cl(double x0, double x1, - double x2, double x3); - const Numeric& cl(double x0, double x1, - double x2, double x3) const; - - Numeric& cl(double x0, double x1, - double x2, double x3, double x4); - const Numeric& cl(double x0, double x1, - double x2, double x3, double x4) const; - - Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5); - const Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5) const; - - Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6); - const Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6) const; - - Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7); - const Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7) const; - - Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7, double x8); - const Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7, double x8) const; - - Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7, double x8, - double x9); - const Numeric& cl(double x0, double x1, double x2, - double x3, double x4, double x5, - double x6, double x7, double x8, - double x9) const; - //@} - - //@{ - /** Methods related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static const char* classname(); - static inline unsigned version() {return 1;} - static void restore(const gs::ClassId& id, std::istream& in, - ArrayND* array); - private: - Numeric localData_[StackLen]; - Numeric* data_; - - unsigned long localStrides_[StackDim]; - unsigned long *strides_; - - unsigned localShape_[StackDim]; - unsigned *shape_; - - unsigned long len_; - unsigned dim_; - - bool shapeIsKnown_; - - // Basic initialization from unsigned* shape and dimensionality - void buildFromShapePtr(const unsigned*, unsigned); - - // Build strides_ array out of the shape_ array - void buildStrides(); - - // Recursive implementation of nested loops for "linearFill" - void linearFillLoop(unsigned level, double s0, - unsigned long idx, double shift, - const double* coeffs); - - // Recursive implementation of nested loops for "functorFill" - template - void functorFillLoop(unsigned level, unsigned long idx, - Functor f, unsigned* farg); - - // Recursive implementation of nested loops for "interpolate3" - Numeric interpolateLoop(unsigned level, const double *x, - const Numeric* base) const; - - // Recursive implementation of nested loops for the outer product - template - void outerProductLoop(unsigned level, unsigned long idx0, - unsigned long idx1, unsigned long idx2, - const ArrayND& a1, - const ArrayND& a2); - - // Recursive implementation of nested loops for contraction - void contractLoop(unsigned thisLevel, unsigned resLevel, - unsigned pos1, unsigned pos2, - unsigned long idxThis, unsigned long idxRes, - ArrayND& result) const; - - // Recursive implementation of nested loops for transposition - void transposeLoop(unsigned level, unsigned pos1, unsigned pos2, - unsigned long idxThis, unsigned long idxRes, - ArrayND& result) const; - - // Recursive implementation of nested loops for the dot product - template - void dotProductLoop(unsigned level, unsigned long idx0, - unsigned long idx1, unsigned long idx2, + Numeric& cl(); + const Numeric& cl() const; + + Numeric& cl(double x0); + const Numeric& cl(double x0) const; + + Numeric& cl(double x0, double x1); + const Numeric& cl(double x0, double x1) const; + + Numeric& cl(double x0, double x1, double x2); + const Numeric& cl(double x0, double x1, double x2) const; + + Numeric& cl(double x0, double x1, double x2, double x3); + const Numeric& cl(double x0, double x1, double x2, double x3) const; + + Numeric& cl(double x0, double x1, double x2, double x3, double x4); + const Numeric& cl(double x0, double x1, double x2, double x3, double x4) const; + + Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5); + const Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5) const; + + Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5, double x6); + const Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5, double x6) const; + + Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7); + const Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7) const; + + Numeric& cl(double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8); + const Numeric& cl( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8) const; + + Numeric& cl( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8, double x9); + const Numeric& cl( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8, double x9) + const; + //@} + + //@{ + /** Methods related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static const char* classname(); + static inline unsigned version() { return 1; } + static void restore(const gs::ClassId& id, std::istream& in, ArrayND* array); + + private: + Numeric localData_[StackLen]; + Numeric* data_; + + unsigned long localStrides_[StackDim]; + unsigned long* strides_; + + unsigned localShape_[StackDim]; + unsigned* shape_; + + unsigned long len_; + unsigned dim_; + + bool shapeIsKnown_; + + // Basic initialization from unsigned* shape and dimensionality + void buildFromShapePtr(const unsigned*, unsigned); + + // Build strides_ array out of the shape_ array + void buildStrides(); + + // Recursive implementation of nested loops for "linearFill" + void linearFillLoop(unsigned level, double s0, unsigned long idx, double shift, const double* coeffs); + + // Recursive implementation of nested loops for "functorFill" + template + void functorFillLoop(unsigned level, unsigned long idx, Functor f, unsigned* farg); + + // Recursive implementation of nested loops for "interpolate3" + Numeric interpolateLoop(unsigned level, const double* x, const Numeric* base) const; + + // Recursive implementation of nested loops for the outer product + template + void outerProductLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + unsigned long idx2, + const ArrayND& a1, + const ArrayND& a2); + + // Recursive implementation of nested loops for contraction + void contractLoop(unsigned thisLevel, + unsigned resLevel, + unsigned pos1, + unsigned pos2, + unsigned long idxThis, + unsigned long idxRes, + ArrayND& result) const; + + // Recursive implementation of nested loops for transposition + void transposeLoop(unsigned level, + unsigned pos1, + unsigned pos2, + unsigned long idxThis, + unsigned long idxRes, + ArrayND& result) const; + + // Recursive implementation of nested loops for the dot product + template + void dotProductLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + unsigned long idx2, + const ArrayND& r, + ArrayND& result) const; + + // Recursive implementation of nested loops for marginalization + template + Numeric marginalizeInnerLoop(unsigned long idx, + unsigned levelPr, + unsigned long idxPr, + const ArrayND& prior, + const unsigned* indexMap) const; + template + void marginalizeLoop(unsigned level, + unsigned long idx, + unsigned levelRes, + unsigned long idxRes, + const ArrayND& prior, + const unsigned* indexMap, + ArrayND& res) const; + + // Recursive implementation of nested loops for range copy + // with functor modification of elements + template + void copyRangeLoopFunct(unsigned level, + unsigned long idx0, + unsigned long idx1, const ArrayND& r, - ArrayND& result) const; - - // Recursive implementation of nested loops for marginalization - template - Numeric marginalizeInnerLoop(unsigned long idx, - unsigned levelPr, unsigned long idxPr, - const ArrayND& prior, - const unsigned* indexMap) const; - template - void marginalizeLoop(unsigned level, unsigned long idx, - unsigned levelRes, unsigned long idxRes, - const ArrayND& prior, - const unsigned* indexMap, ArrayND& res) const; - - // Recursive implementation of nested loops for range copy - // with functor modification of elements - template - void copyRangeLoopFunct(unsigned level, unsigned long idx0, - unsigned long idx1, - const ArrayND& r, - const ArrayRange& range, Functor f); - - // Loop over subrange in such a way that the functor is called - // only if indices on both sides are valid. The topology of both - // arrays is that of the hyperplane (flat). - template - void commonSubrangeLoop(unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& other, - Functor binaryFunct); - - // Similar loop with the topology of the hypertorus for both - // arrays (all indices of both arrays are wrapped around) - template - void dualCircularLoop(unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& other, - Functor binaryFunct); - - // Similar loop in which the topology of this array is assumed - // to be flat and the topology of the destination array is that - // of the hypertorus. Due to the asymmetry of the topologies, - // "const" function is not provided (use const_cast as appropriate). - template - void flatCircularLoop(unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& other, - Functor binaryFunct); - - // Similar loop in which the topology of this array is assumed - // to be hypertoroidal and the topology of the destination array - // is flat. - template - void circularFlatLoop(unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& other, - Functor binaryFunct); - - // Slice compatibility verification - template - unsigned long verifySliceCompatibility( - const ArrayND& slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices) const; - - // Buffer compatibility verification with a slice - unsigned long verifyBufferSliceCompatibility( - unsigned long bufLen, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices, - unsigned long* sliceStrides) const; - - // Recursive implementation of nested loops for slice operations - template - void jointSliceLoop(unsigned level, unsigned long idx0, - unsigned level1, unsigned long idx1, - Num2* sliceData, const unsigned long* sliceStrides, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - unsigned nFixedIndices, Functor binaryFunctor); - - // Recursive implementation of nested loops for "applySlice" - template - void scaleBySliceInnerLoop(unsigned level, unsigned long idx0, - Num2& scale, - const unsigned* projectedIndices, - unsigned nProjectedIndices, - Functor binaryFunct); - - template - void scaleBySliceLoop(unsigned level, unsigned long idx0, - unsigned level1, unsigned long idx1, - ArrayND& slice, - const unsigned *fixedIndices, - unsigned nFixedIndices, - Functor binaryFunct); - - // Recursive implementation of nested loops for projections - template - void projectInnerLoop(unsigned level, unsigned long idx0, - unsigned* currentIndex, - AbsArrayProjector& projector, - const unsigned* projectedIndices, - unsigned nProjectedIndices) const; - - template - void projectLoop(unsigned level, unsigned long idx0, - unsigned level1, unsigned long idx1, - unsigned* currentIndex, - ArrayND* projection, - AbsArrayProjector& projector, - const unsigned* projectedIndices, - unsigned nProjectedIndices, Op fcn) const; - - // Note that "projectLoop2" is almost identical to "projectLoop" - // while "projectInnerLoop2" is almost identical to "projectInnerLoop". - // It would make a lot of sense to combine these functions into - // the same code and then partially specialize the little piece - // where the "AbsVisitor" or "AbsArrayProjector" is actually called. - // Unfortunately, "AbsVisitor" and "AbsArrayProjector" are - // templates themselves, and it is not possible in C++ to partially - // specialize a function template (that is, even if we can specialize - // on "AbsVisitor" vs. "AbsArrayProjector", there is no way to - // specialize on their parameter types). - template - void projectLoop2(unsigned level, unsigned long idx0, - unsigned level1, unsigned long idx1, - ArrayND* projection, - AbsVisitor& projector, - const unsigned* projectedIndices, - unsigned nProjectedIndices, Op fcn) const; + const ArrayRange& range, + Functor f); + + // Loop over subrange in such a way that the functor is called + // only if indices on both sides are valid. The topology of both + // arrays is that of the hyperplane (flat). + template + void commonSubrangeLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& other, + Functor binaryFunct); - template - void projectInnerLoop2(unsigned level, unsigned long idx0, - AbsVisitor& projector, + // Similar loop with the topology of the hypertorus for both + // arrays (all indices of both arrays are wrapped around) + template + void dualCircularLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& other, + Functor binaryFunct); + + // Similar loop in which the topology of this array is assumed + // to be flat and the topology of the destination array is that + // of the hypertorus. Due to the asymmetry of the topologies, + // "const" function is not provided (use const_cast as appropriate). + template + void flatCircularLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& other, + Functor binaryFunct); + + // Similar loop in which the topology of this array is assumed + // to be hypertoroidal and the topology of the destination array + // is flat. + template + void circularFlatLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& other, + Functor binaryFunct); + + // Slice compatibility verification + template + unsigned long verifySliceCompatibility(const ArrayND& slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices) const; + + // Buffer compatibility verification with a slice + unsigned long verifyBufferSliceCompatibility(unsigned long bufLen, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices, + unsigned long* sliceStrides) const; + + // Recursive implementation of nested loops for slice operations + template + void jointSliceLoop(unsigned level, + unsigned long idx0, + unsigned level1, + unsigned long idx1, + Num2* sliceData, + const unsigned long* sliceStrides, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices, + Functor binaryFunctor); + + // Recursive implementation of nested loops for "applySlice" + template + void scaleBySliceInnerLoop(unsigned level, + unsigned long idx0, + Num2& scale, const unsigned* projectedIndices, - unsigned nProjectedIndices) const; - - template - void processSubrangeLoop(unsigned level, unsigned long idx0, - unsigned* currentIndex, - AbsArrayProjector& f, - const BoxND& subrange) const; - - // Sum of all points with the given index and below - template - Accumulator sumBelowLoop(unsigned level, unsigned long idx0, - const unsigned* limit) const; - - // Loop for "convertToLastDimCdf" - template - void convertToLastDimCdfLoop(ArrayND* sumSlice, unsigned level, - unsigned long idx0, - unsigned long idxSlice, - bool useTrapezoids); - - // Convert a coordinate into index. - // No checking whether "idim" is within limits. - unsigned coordToIndex(double coord, unsigned idim) const; - - // Verify that projection array is compatible with this one - template - void verifyProjectionCompatibility( - const ArrayND& projection, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - }; -} + unsigned nProjectedIndices, + Functor binaryFunct); + + template + void scaleBySliceLoop(unsigned level, + unsigned long idx0, + unsigned level1, + unsigned long idx1, + ArrayND& slice, + const unsigned* fixedIndices, + unsigned nFixedIndices, + Functor binaryFunct); + + // Recursive implementation of nested loops for projections + template + void projectInnerLoop(unsigned level, + unsigned long idx0, + unsigned* currentIndex, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void projectLoop(unsigned level, + unsigned long idx0, + unsigned level1, + unsigned long idx1, + unsigned* currentIndex, + ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices, + Op fcn) const; + + // Note that "projectLoop2" is almost identical to "projectLoop" + // while "projectInnerLoop2" is almost identical to "projectInnerLoop". + // It would make a lot of sense to combine these functions into + // the same code and then partially specialize the little piece + // where the "AbsVisitor" or "AbsArrayProjector" is actually called. + // Unfortunately, "AbsVisitor" and "AbsArrayProjector" are + // templates themselves, and it is not possible in C++ to partially + // specialize a function template (that is, even if we can specialize + // on "AbsVisitor" vs. "AbsArrayProjector", there is no way to + // specialize on their parameter types). + template + void projectLoop2(unsigned level, + unsigned long idx0, + unsigned level1, + unsigned long idx1, + ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices, + Op fcn) const; + + template + void projectInnerLoop2(unsigned level, + unsigned long idx0, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void processSubrangeLoop(unsigned level, + unsigned long idx0, + unsigned* currentIndex, + AbsArrayProjector& f, + const BoxND& subrange) const; + + // Sum of all points with the given index and below + template + Accumulator sumBelowLoop(unsigned level, unsigned long idx0, const unsigned* limit) const; + + // Loop for "convertToLastDimCdf" + template + void convertToLastDimCdfLoop( + ArrayND* sumSlice, unsigned level, unsigned long idx0, unsigned long idxSlice, bool useTrapezoids); + + // Convert a coordinate into index. + // No checking whether "idim" is within limits. + unsigned coordToIndex(double coord, unsigned idim) const; + + // Verify that projection array is compatible with this one + template + void verifyProjectionCompatibility(const ArrayND& projection, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + }; +} // namespace npstat #include #include @@ -1305,1611 +1327,1446 @@ namespace npstat { #include "JetMETCorrections/InterpolationTables/interface/ComplexComparesFalse.h" #include "JetMETCorrections/InterpolationTables/interface/ComplexComparesAbs.h" -#define me_macro_check_loop_prerequisites(METHOD, INNERLOOP) /**/ \ - template \ - template \ - void ArrayND:: METHOD ( \ - ArrayND& other, \ - const unsigned* thisCorner, \ - const unsigned* range, \ - const unsigned* otherCorner, \ - const unsigned arrLen, \ - Functor binaryFunct) \ - { \ - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( \ - "Initialize npstat::ArrayND before calling method \"" \ - #METHOD "\""); \ - if (!other.shapeIsKnown_) throw npstat::NpstatInvalidArgument( \ - "In npstat::ArrayND::" #METHOD ": uninitialized argument array");\ - if (dim_ != other.dim_) throw npstat::NpstatInvalidArgument( \ - "In npstat::ArrayND::" #METHOD ": incompatible argument array rank");\ - if (arrLen != dim_) throw npstat::NpstatInvalidArgument( \ - "In npstat::ArrayND::" #METHOD ": incompatible index length"); \ - if (dim_) \ - { \ - assert(thisCorner); \ - assert(range); \ - assert(otherCorner); \ - INNERLOOP (0U, 0UL, 0UL, thisCorner, range, \ - otherCorner, other, binaryFunct); \ - } \ - else \ - binaryFunct(localData_[0], other.localData_[0]); \ - } +#define me_macro_check_loop_prerequisites(METHOD, INNERLOOP) /**/ \ + template \ + template \ + void ArrayND::METHOD(ArrayND& other, \ + const unsigned* thisCorner, \ + const unsigned* range, \ + const unsigned* otherCorner, \ + const unsigned arrLen, \ + Functor binaryFunct) { \ + if (!shapeIsKnown_) \ + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"" #METHOD "\""); \ + if (!other.shapeIsKnown_) \ + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::" #METHOD ": uninitialized argument array"); \ + if (dim_ != other.dim_) \ + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::" #METHOD ": incompatible argument array rank"); \ + if (arrLen != dim_) \ + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::" #METHOD ": incompatible index length"); \ + if (dim_) { \ + assert(thisCorner); \ + assert(range); \ + assert(otherCorner); \ + INNERLOOP(0U, 0UL, 0UL, thisCorner, range, otherCorner, other, binaryFunct); \ + } else \ + binaryFunct(localData_[0], other.localData_[0]); \ + } namespace npstat { - template - template - void ArrayND::commonSubrangeLoop( - unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& r, - Functor binaryFunct) - { - const unsigned imax = range[level]; - - if (level == dim_ - 1) - { - Numeric* left = data_ + (idx0 + thisCorner[level]); - Numeric* const lMax = data_ + (idx0 + shape_[level]); - Num2* right = r.data_ + (idx1 + otherCorner[level]); - Num2* const rMax = r.data_ + (idx1 + r.shape_[level]); - - for (unsigned i=0; i - template - void ArrayND::dualCircularLoop( - unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& r, - Functor binaryFunct) - { - const unsigned imax = range[level]; - const unsigned leftShift = thisCorner[level]; - const unsigned leftPeriod = shape_[level]; - const unsigned rightShift = otherCorner[level]; - const unsigned rightPeriod = r.shape_[level]; - - if (level == dim_ - 1) - { - Numeric* left = data_ + idx0; - Num2* right = r.data_ + idx1; - for (unsigned i=0; i + template + void ArrayND::commonSubrangeLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& r, + Functor binaryFunct) { + const unsigned imax = range[level]; + + if (level == dim_ - 1) { + Numeric* left = data_ + (idx0 + thisCorner[level]); + Numeric* const lMax = data_ + (idx0 + shape_[level]); + Num2* right = r.data_ + (idx1 + otherCorner[level]); + Num2* const rMax = r.data_ + (idx1 + r.shape_[level]); + + for (unsigned i = 0; i < imax && left < lMax && right < rMax; ++i) + binaryFunct(*left++, *right++); + } else { + const unsigned long leftStride = strides_[level]; + const unsigned long leftMax = idx0 + shape_[level] * leftStride; + idx0 += thisCorner[level] * leftStride; + const unsigned long rightStride = r.strides_[level]; + const unsigned long rightMax = idx1 + r.shape_[level] * rightStride; + idx1 += otherCorner[level] * rightStride; + + for (unsigned i = 0; i < imax && idx0 < leftMax && idx1 < rightMax; ++i, idx0 += leftStride, idx1 += rightStride) + commonSubrangeLoop(level + 1, idx0, idx1, thisCorner, range, otherCorner, r, binaryFunct); + } + } + + template + template + void ArrayND::dualCircularLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& r, + Functor binaryFunct) { + const unsigned imax = range[level]; + const unsigned leftShift = thisCorner[level]; + const unsigned leftPeriod = shape_[level]; + const unsigned rightShift = otherCorner[level]; + const unsigned rightPeriod = r.shape_[level]; + + if (level == dim_ - 1) { + Numeric* left = data_ + idx0; + Num2* right = r.data_ + idx1; + for (unsigned i = 0; i < imax; ++i) + binaryFunct(left[(i + leftShift) % leftPeriod], right[(i + rightShift) % rightPeriod]); + } else { + const unsigned long leftStride = strides_[level]; + const unsigned long rightStride = r.strides_[level]; + for (unsigned i = 0; i < imax; ++i) + dualCircularLoop(level + 1, + idx0 + ((i + leftShift) % leftPeriod) * leftStride, + idx1 + ((i + rightShift) % rightPeriod) * rightStride, + thisCorner, + range, + otherCorner, + r, + binaryFunct); + } + } + + template + template + void ArrayND::flatCircularLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& r, + Functor binaryFunct) { + const unsigned imax = range[level]; + const unsigned rightShift = otherCorner[level]; + const unsigned rightPeriod = r.shape_[level]; + + if (level == dim_ - 1) { + Numeric* left = data_ + (idx0 + thisCorner[level]); + Numeric* const lMax = data_ + (idx0 + shape_[level]); + Num2* right = r.data_ + idx1; + + for (unsigned i = 0; i < imax && left < lMax; ++i) + binaryFunct(*left++, right[(i + rightShift) % rightPeriod]); + } else { + const unsigned long leftStride = strides_[level]; + const unsigned long leftMax = idx0 + shape_[level] * leftStride; + idx0 += thisCorner[level] * leftStride; + const unsigned long rightStride = r.strides_[level]; + + for (unsigned i = 0; i < imax && idx0 < leftMax; ++i, idx0 += leftStride) + flatCircularLoop(level + 1, + idx0, + idx1 + ((i + rightShift) % rightPeriod) * rightStride, + thisCorner, + range, + otherCorner, + r, + binaryFunct); + } + } + + template + template + void ArrayND::circularFlatLoop(unsigned level, + unsigned long idx0, + unsigned long idx1, + const unsigned* thisCorner, + const unsigned* range, + const unsigned* otherCorner, + ArrayND& r, + Functor binaryFunct) { + const unsigned imax = range[level]; + const unsigned leftShift = thisCorner[level]; + const unsigned leftPeriod = shape_[level]; + + if (level == dim_ - 1) { + Numeric* left = data_ + idx0; + Num2* right = r.data_ + (idx1 + otherCorner[level]); + Num2* const rMax = r.data_ + (idx1 + r.shape_[level]); + + for (unsigned i = 0; i < imax && right < rMax; ++i) + binaryFunct(left[(i + leftShift) % leftPeriod], *right++); + } else { + const unsigned long leftStride = strides_[level]; + const unsigned long rightStride = r.strides_[level]; + const unsigned long rightMax = idx1 + r.shape_[level] * rightStride; + idx1 += otherCorner[level] * rightStride; + + for (unsigned i = 0; i < imax && idx1 < rightMax; ++i, idx1 += rightStride) + circularFlatLoop(level + 1, + idx0 + ((i + leftShift) % leftPeriod) * leftStride, + idx1, + thisCorner, + range, + otherCorner, + r, + binaryFunct); + } + } + + me_macro_check_loop_prerequisites(jointSubrangeScan, commonSubrangeLoop) + me_macro_check_loop_prerequisites(dualCircularScan, dualCircularLoop) + me_macro_check_loop_prerequisites(flatCircularScan, + flatCircularLoop) me_macro_check_loop_prerequisites(circularFlatScan, + circularFlatLoop) + + template + template + Numeric ArrayND::marginalizeInnerLoop(unsigned long idx, + const unsigned levelPr, + unsigned long idxPr, + const ArrayND& prior, + const unsigned* indexMap) const { + Numeric sum = Numeric(); + const unsigned long myStride = strides_[indexMap[levelPr]]; + const unsigned imax = prior.shape_[levelPr]; + assert(imax == shape_[indexMap[levelPr]]); + if (levelPr == prior.dim_ - 1) { + for (unsigned i = 0; i < imax; ++i) + sum += data_[idx + i * myStride] * prior.data_[idxPr++]; + } else { + const unsigned long priorStride = prior.strides_[levelPr]; + for (unsigned i = 0; i < imax; ++i) { + sum += marginalizeInnerLoop(idx, levelPr + 1U, idxPr, prior, indexMap); + idx += myStride; + idxPr += priorStride; + } + } + return sum; + } + + template + template + void ArrayND::marginalizeLoop(const unsigned level, + unsigned long idx, + const unsigned levelRes, + unsigned long idxRes, + const ArrayND& prior, + const unsigned* indexMap, + ArrayND& result) const { + if (level == dim_) { + const Numeric res = marginalizeInnerLoop(idx, 0U, 0UL, prior, indexMap); + if (result.dim_) + result.data_[idxRes] = res; + else + result.localData_[0] = res; + } else { + // Check if this level is mapped or not + bool mapped = false; + for (unsigned i = 0; i < prior.dim_; ++i) + if (level == indexMap[i]) { + mapped = true; + break; } - else - { - const unsigned long leftStride = strides_[level]; - const unsigned long rightStride = r.strides_[level]; - for (unsigned i=0; i - template - void ArrayND::flatCircularLoop( - unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& r, - Functor binaryFunct) - { - const unsigned imax = range[level]; - const unsigned rightShift = otherCorner[level]; - const unsigned rightPeriod = r.shape_[level]; - - if (level == dim_ - 1) - { - Numeric* left = data_ + (idx0 + thisCorner[level]); - Numeric* const lMax = data_ + (idx0 + shape_[level]); - Num2* right = r.data_ + idx1; - - for (unsigned i=0; i + template + ArrayND ArrayND::marginalize( + const ArrayND& prior, const unsigned* indexMap, const unsigned mapLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"marginalize\""); + if (!(prior.dim_ && prior.dim_ <= dim_)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::marginalize: incompatible argument array rank"); + const unsigned resultDim = dim_ - prior.dim_; + + // Check that the index map is reasonable + if (mapLen != prior.dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::marginalize: incompatible index map length"); + assert(indexMap); + for (unsigned i = 0; i < mapLen; ++i) { + const unsigned thisInd = indexMap[i]; + if (shape_[thisInd] != prior.shape_[i]) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::marginalize: " + "incompatible argument array dimensions"); + if (thisInd >= dim_) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::marginalize: index map entry out of range"); + for (unsigned j = 0; j < i; ++j) + if (indexMap[j] == thisInd) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::marginalize: " + "duplicate entry in the index map"); + } + + // Build the shape for the array of results + ArrayShape newShape; + newShape.reserve(resultDim); + for (unsigned i = 0; i < dim_; ++i) { + bool mapped = false; + for (unsigned j = 0; j < mapLen; ++j) + if (indexMap[j] == i) { + mapped = true; + break; } - else - { - const unsigned long leftStride = strides_[level]; - const unsigned long leftMax = idx0 + shape_[level]*leftStride; - idx0 += thisCorner[level]*leftStride; - const unsigned long rightStride = r.strides_[level]; - - for (unsigned i=0; i + void ArrayND::buildFromShapePtr(const unsigned* sizes, const unsigned dim) { + dim_ = dim; + if (dim_) { + assert(sizes); + for (unsigned i = 0; i < dim_; ++i) + if (sizes[i] == 0) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::buildFromShapePtr: " + "detected span of zero"); + + // Copy the array shape and figure out the array length + shape_ = makeBuffer(dim_, localShape_, Dim); + for (unsigned i = 0; i < dim_; ++i) { + shape_[i] = sizes[i]; + len_ *= shape_[i]; + } + + // Figure out the array strides + buildStrides(); + + // Allocate the data array + data_ = makeBuffer(len_, localData_, Len); + } else { + localData_[0] = Numeric(); + data_ = localData_; + } + } + + template + template + ArrayND::ArrayND(const ArrayND& slicedArray, + const unsigned* fixedIndices, + const unsigned nFixedIndices) + : data_(0), + strides_(nullptr), + shape_(nullptr), + len_(1UL), + dim_(slicedArray.dim_ - nFixedIndices), + shapeIsKnown_(true) { + if (nFixedIndices) { + assert(fixedIndices); + if (nFixedIndices > slicedArray.dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND slicing constructor: too many fixed indices"); + if (!slicedArray.shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND slicing constructor: " + "uninitialized argument array"); - template - template - void ArrayND::circularFlatLoop( - unsigned level, unsigned long idx0, - unsigned long idx1, - const unsigned* thisCorner, - const unsigned* range, - const unsigned* otherCorner, - ArrayND& r, - Functor binaryFunct) - { - const unsigned imax = range[level]; - const unsigned leftShift = thisCorner[level]; - const unsigned leftPeriod = shape_[level]; - - if (level == dim_ - 1) - { - Numeric* left = data_ + idx0; - Num2* right = r.data_ + (idx1 + otherCorner[level]); - Num2* const rMax = r.data_ + (idx1 + r.shape_[level]); - - for (unsigned i=0; i= slicedArray.dim_) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND slicing " + "constructor: fixed index out of range"); + + // Build the shape for the slice + shape_ = makeBuffer(dim_, localShape_, StackDim); + unsigned idim = 0; + for (unsigned i = 0; i < slicedArray.dim_; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + break; + } + if (!fixed) { + assert(idim < dim_); + shape_[idim++] = slicedArray.shape_[i]; } - } + } + assert(idim == dim_); - me_macro_check_loop_prerequisites(jointSubrangeScan, commonSubrangeLoop) - me_macro_check_loop_prerequisites(dualCircularScan, dualCircularLoop) - me_macro_check_loop_prerequisites(flatCircularScan, flatCircularLoop) - me_macro_check_loop_prerequisites(circularFlatScan, circularFlatLoop) + if (dim_) { + // Copy the array shape and figure out the array length + for (unsigned i = 0; i < dim_; ++i) + len_ *= shape_[i]; - template - template - Numeric ArrayND::marginalizeInnerLoop( - unsigned long idx, const unsigned levelPr, unsigned long idxPr, - const ArrayND& prior, - const unsigned* indexMap) const - { - Numeric sum = Numeric(); - const unsigned long myStride = strides_[indexMap[levelPr]]; - const unsigned imax = prior.shape_[levelPr]; - assert(imax == shape_[indexMap[levelPr]]); - if (levelPr == prior.dim_ - 1) - { - for (unsigned i=0; i - template - void ArrayND::marginalizeLoop( - const unsigned level, unsigned long idx, - const unsigned levelRes, unsigned long idxRes, - const ArrayND& prior, - const unsigned* indexMap, ArrayND& result) const - { - if (level == dim_) - { - const Numeric res = marginalizeInnerLoop( - idx, 0U, 0UL, prior, indexMap); - if (result.dim_) - result.data_[idxRes] = res; - else - result.localData_[0] = res; - } - else - { - // Check if this level is mapped or not - bool mapped = false; - for (unsigned i=0; i + ArrayShape ArrayND::sliceShape(const unsigned* fixedIndices, + const unsigned nFixedIndices) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"sliceShape\""); + if (nFixedIndices) { + assert(fixedIndices); + if (nFixedIndices > dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::sliceShape: too many fixed indices"); + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::sliceShape: " + "fixed index out of range"); + ArrayShape sh; + sh.reserve(dim_ - nFixedIndices); + for (unsigned i = 0; i < dim_; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + break; + } + if (!fixed) + sh.push_back(shape_[i]); + } + return sh; + } else + return ArrayShape(shape_, shape_ + dim_); + } + + template + template + unsigned long ArrayND::verifySliceCompatibility(const ArrayND& slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + const unsigned nFixedIndices) const { + if (!(nFixedIndices && nFixedIndices <= dim_)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifySliceCompatibility: " + "invalid number of fixed indices"); + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "Initialize npstat::ArrayND before calling " + "method \"verifySliceCompatibility\""); + if (!slice.shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifySliceCompatibility: " + "uninitialized argument array"); + if (slice.dim_ != dim_ - nFixedIndices) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifySliceCompatibility: " + "incompatible argument array rank"); + assert(fixedIndices); + assert(fixedIndexValues); + + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::verifySliceCompatibility: " + "fixed index out of range"); + + // Check slice shape compatibility + unsigned long idx = 0UL; + unsigned sliceDim = 0U; + for (unsigned i = 0; i < dim_; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + if (fixedIndexValues[j] >= shape_[i]) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::verifySliceCompatibility: " + "fixed index value out of range"); + idx += fixedIndexValues[j] * strides_[i]; + break; } - } - - template - template - ArrayND - ArrayND::marginalize( - const ArrayND& prior, - const unsigned* indexMap, const unsigned mapLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"marginalize\""); - if (!(prior.dim_ && prior.dim_ <= dim_)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::marginalize: incompatible argument array rank"); - const unsigned resultDim = dim_ - prior.dim_; - - // Check that the index map is reasonable - if (mapLen != prior.dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::marginalize: incompatible index map length"); - assert(indexMap); - for (unsigned i=0; i= dim_) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::marginalize: index map entry out of range"); - for (unsigned j=0; j + unsigned long ArrayND::verifyBufferSliceCompatibility(const unsigned long bufLen, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + const unsigned nFixedIndices, + unsigned long* sliceStrides) const { + if (!(nFixedIndices && nFixedIndices <= dim_)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyBufferSliceCompatibility: " + "invalid number of fixed indices"); + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "Initialize npstat::ArrayND before calling " + "method \"verifyBufferSliceCompatibility\""); + assert(fixedIndices); + assert(fixedIndexValues); + + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::verifyBufferSliceCompatibility: " + "fixed index out of range"); + + // Figure out slice shape. Store it, temporarily, in sliceStrides. + unsigned long idx = 0UL; + unsigned sliceDim = 0U; + for (unsigned i = 0; i < dim_; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + if (fixedIndexValues[j] >= shape_[i]) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::verifyBufferSliceCompatibility:" + " fixed index value out of range"); + idx += fixedIndexValues[j] * strides_[i]; + break; } - - // Build the shape for the array of results - ArrayShape newShape; - newShape.reserve(resultDim); - for (unsigned i=0; i 0; --j) { + const unsigned long nextStride = sliceStrides[j] * shapeJ; + shapeJ = sliceStrides[j - 1]; + sliceStrides[j - 1] = nextStride; + } + expectedBufLen = sliceStrides[0] * shapeJ; + } + if (expectedBufLen != bufLen) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyBufferSliceCompatibility: " + "invalid memory buffer length"); + + return idx; + } + + template + template + void ArrayND::jointSliceLoop(const unsigned level, + const unsigned long idx0, + const unsigned level1, + const unsigned long idx1, + Num2* sliceData, + const unsigned long* sliceStrides, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + const unsigned nFixedIndices, + Op fcn) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == level) { + fixed = true; + break; + } + if (fixed) + jointSliceLoop( + level + 1, idx0, level1, idx1, sliceData, sliceStrides, fixedIndices, fixedIndexValues, nFixedIndices, fcn); + else { + const unsigned imax = shape_[level]; + const unsigned long stride = strides_[level]; + + if (level1 == dim_ - nFixedIndices - 1) { + sliceData += idx1; + Numeric* localData = data_ + idx0; + for (unsigned i = 0; i < imax; ++i) + fcn(localData[i * stride], sliceData[i]); + } else { + const unsigned long stride2 = sliceStrides[level1]; + for (unsigned i = 0; i < imax; ++i) + jointSliceLoop(level + 1, + idx0 + i * stride, + level1 + 1, + idx1 + i * stride2, + sliceData, + sliceStrides, + fixedIndices, + fixedIndexValues, + nFixedIndices, + fcn); + } + } + } + + template + template + void ArrayND::jointSliceScan(ArrayND& slice, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + const unsigned nFixedIndices, + Functor binaryFunct) { + const unsigned long idx = verifySliceCompatibility(slice, fixedIndices, fixedIndexValues, nFixedIndices); + if (slice.dim_) + jointSliceLoop( + 0U, idx, 0U, 0UL, slice.data_, slice.strides_, fixedIndices, fixedIndexValues, nFixedIndices, binaryFunct); + else + binaryFunct(data_[idx], slice.localData_[0]); + } + + template + template + void ArrayND::jointMemSliceScan(Num2* slice, + const unsigned long len, + const unsigned* fixedIndices, + const unsigned* fixedIndexValues, + unsigned nFixedIndices, + Functor binaryFunct) { + assert(slice); + if (dim_ > CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::jointMemSliceScan: " + "rank of this array is too large"); + unsigned long sliceStrides[CHAR_BIT * sizeof(unsigned long)]; + const unsigned long idx = + verifyBufferSliceCompatibility(len, fixedIndices, fixedIndexValues, nFixedIndices, sliceStrides); + if (dim_ > nFixedIndices) + jointSliceLoop(0U, idx, 0U, 0UL, slice, sliceStrides, fixedIndices, fixedIndexValues, nFixedIndices, binaryFunct); + else + binaryFunct(data_[idx], *slice); + } + + template + template + void ArrayND::projectInnerLoop(const unsigned level, + unsigned long idx0, + unsigned* currentIndex, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + // level : dimension number among indices which are being iterated + const unsigned idx = projectedIndices[level]; + const unsigned imax = shape_[idx]; + const unsigned long stride = strides_[idx]; + const bool last = (level == nProjectedIndices - 1); + + for (unsigned i = 0; i < imax; ++i) { + currentIndex[idx] = i; + if (last) + projector.process(currentIndex, dim_, idx0, data_[idx0]); + else + projectInnerLoop(level + 1, idx0, currentIndex, projector, projectedIndices, nProjectedIndices); + idx0 += stride; + } + } + + template + template + void ArrayND::projectLoop(const unsigned level, + const unsigned long idx0, + const unsigned level1, + const unsigned long idx1, + unsigned* currentIndex, + ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices, + Op fcn) const { + // level : dimension number in this array + // level1 : dimension number in the projection + // idx0 : linear index in this array + // idx1 : linear index in the projection + // currentIndex : cycled over in this loop with the exception of the + // dimensions which are iterated over to build the + // projection + if (level == dim_) { + assert(level1 == projection->dim_); + projector.clear(); + projectInnerLoop(0U, idx0, currentIndex, projector, projectedIndices, nProjectedIndices); + if (projection->dim_) + fcn(projection->data_[idx1], projector.result()); + else + fcn(projection->localData_[0], projector.result()); + } else { + bool iterated = false; + for (unsigned j = 0; j < nProjectedIndices; ++j) + if (projectedIndices[j] == level) { + iterated = true; + break; } - - ArrayND result(newShape); - assert(result.dim_ == resultDim); - bool calculated = false; - if (resultDim == 0) - { - calculated = true; - for (unsigned i=0; idim_ is 0. + // Therefore, it is safe to access projection->strides_. + const unsigned long stride2 = projection->strides_[level1]; + for (unsigned i = 0; i < imax; ++i) { + currentIndex[level] = i; + projectLoop(level + 1, + idx0 + i * stride, + level1 + 1, + idx1 + i * stride2, + currentIndex, + projection, + projector, + projectedIndices, + nProjectedIndices, + fcn); } - - if (!calculated) - marginalizeLoop(0U, 0UL, 0U, 0UL, prior, indexMap, result); - - return result; - } - - template - void ArrayND::buildFromShapePtr( - const unsigned* sizes, const unsigned dim) - { - dim_ = dim; - if (dim_) - { - assert(sizes); - for (unsigned i=0; i + template + void ArrayND::verifyProjectionCompatibility(const ArrayND& projection, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + if (!(nProjectedIndices && nProjectedIndices <= dim_)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyProjectionCompatibility: " + "invalid number of projected indices"); + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "Initialize npstat::ArrayND before calling " + "method \"verifyProjectionCompatibility\""); + if (!projection.shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyProjectionCompatibility: " + "uninitialized argument array"); + if (projection.dim_ != dim_ - nProjectedIndices) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyProjectionCompatibility: " + "incompatible argument array rank"); + assert(projectedIndices); + + for (unsigned j = 0; j < nProjectedIndices; ++j) + if (projectedIndices[j] >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::ArrayND::verifyProjectionCompatibility: " + "projected index out of range"); + + // Check projection shape compatibility + unsigned sliceDim = 0U; + for (unsigned i = 0; i < dim_; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nProjectedIndices; ++j) + if (projectedIndices[j] == i) { + fixed = true; + break; } - else - { - localData_[0] = Numeric(); - data_ = localData_; + if (!fixed) { + if (shape_[i] != projection.shape_[sliceDim]) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::verifyProjectionCompatibility: " + "incompatible argument array dimensions"); + ++sliceDim; + } + } + assert(sliceDim == projection.dim_); + } + + template + template + void ArrayND::project(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + unsigned ibuf[StackDim]; + unsigned* buf = makeBuffer(dim_, ibuf, StackDim); + for (unsigned i = 0; i < dim_; ++i) + buf[i] = 0U; + projectLoop(0U, + 0UL, + 0U, + 0UL, + buf, + projection, + projector, + projectedIndices, + nProjectedIndices, + scast_assign_left()); + destroyBuffer(buf, ibuf); + } + + template + template + void ArrayND::addToProjection(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + unsigned ibuf[StackDim]; + unsigned* buf = makeBuffer(dim_, ibuf, StackDim); + for (unsigned i = 0; i < dim_; ++i) + buf[i] = 0U; + projectLoop(0U, + 0UL, + 0U, + 0UL, + buf, + projection, + projector, + projectedIndices, + nProjectedIndices, + scast_pluseq_left()); + destroyBuffer(buf, ibuf); + } + + template + template + void ArrayND::subtractFromProjection(ArrayND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + unsigned ibuf[StackDim]; + unsigned* buf = makeBuffer(dim_, ibuf, StackDim); + for (unsigned i = 0; i < dim_; ++i) + buf[i] = 0U; + projectLoop(0U, + 0UL, + 0U, + 0UL, + buf, + projection, + projector, + projectedIndices, + nProjectedIndices, + scast_minuseq_left()); + destroyBuffer(buf, ibuf); + } + + template + template + void ArrayND::projectInnerLoop2(const unsigned level, + const unsigned long idx0, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + const unsigned idx = projectedIndices[level]; + const unsigned imax = shape_[idx]; + const unsigned long stride = strides_[idx]; + const bool last = (level == nProjectedIndices - 1); + + for (unsigned i = 0; i < imax; ++i) { + if (last) + projector.process(data_[idx0 + i * stride]); + else + projectInnerLoop2(level + 1, idx0 + i * stride, projector, projectedIndices, nProjectedIndices); + } + } + + template + template + void ArrayND::projectLoop2(const unsigned level, + const unsigned long idx0, + const unsigned level1, + const unsigned long idx1, + ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices, + Op fcn) const { + if (level == dim_) { + assert(level1 == projection->dim_); + projector.clear(); + projectInnerLoop2(0U, idx0, projector, projectedIndices, nProjectedIndices); + if (projection->dim_) + fcn(projection->data_[idx1], projector.result()); + else + fcn(projection->localData_[0], projector.result()); + } else { + bool fixed = false; + for (unsigned j = 0; j < nProjectedIndices; ++j) + if (projectedIndices[j] == level) { + fixed = true; + break; } - } - - template - template - ArrayND::ArrayND( - const ArrayND& slicedArray, - const unsigned *fixedIndices, const unsigned nFixedIndices) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(1UL), dim_(slicedArray.dim_ - nFixedIndices), - shapeIsKnown_(true) - { - if (nFixedIndices) - { - assert(fixedIndices); - if (nFixedIndices > slicedArray.dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND slicing constructor: too many fixed indices"); - if (!slicedArray.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND slicing constructor: " - "uninitialized argument array"); - - // Check that the fixed indices are within range - for (unsigned j=0; j= slicedArray.dim_) - throw npstat::NpstatOutOfRange("In npstat::ArrayND slicing " - "constructor: fixed index out of range"); - - // Build the shape for the slice - shape_ = makeBuffer(dim_, localShape_, StackDim); - unsigned idim = 0; - for (unsigned i=0; istrides_[level1]; + for (unsigned i = 0; i < imax; ++i) + projectLoop2(level + 1, + idx0 + i * stride, + level1 + 1, + idx1 + i * stride2, + projection, + projector, + projectedIndices, + nProjectedIndices, + fcn); + } + } + } + + template + template + void ArrayND::project(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + projectLoop2( + 0U, 0UL, 0U, 0UL, projection, projector, projectedIndices, nProjectedIndices, scast_assign_left()); + } + + template + template + void ArrayND::addToProjection(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + projectLoop2( + 0U, 0UL, 0U, 0UL, projection, projector, projectedIndices, nProjectedIndices, scast_pluseq_left()); + } + + template + template + void ArrayND::subtractFromProjection(ArrayND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + verifyProjectionCompatibility(*projection, projectedIndices, nProjectedIndices); + projectLoop2( + 0U, 0UL, 0U, 0UL, projection, projector, projectedIndices, nProjectedIndices, scast_minuseq_left()); + } + + template + template + void ArrayND::scaleBySliceInnerLoop(const unsigned level, + const unsigned long idx0, + Num2& scale, + const unsigned* projectedIndices, + const unsigned nProjectedIndices, + Functor binaryFunct) { + const unsigned idx = projectedIndices[level]; + const unsigned imax = shape_[idx]; + const unsigned long stride = strides_[idx]; + + if (level == nProjectedIndices - 1) { + Numeric* data = data_ + idx0; + for (unsigned i = 0; i < imax; ++i) + binaryFunct(data[i * stride], scale); + } else + for (unsigned i = 0; i < imax; ++i) + scaleBySliceInnerLoop(level + 1, idx0 + i * stride, scale, projectedIndices, nProjectedIndices, binaryFunct); + } + + template + template + void ArrayND::scaleBySliceLoop(unsigned level, + unsigned long idx0, + unsigned level1, + unsigned long idx1, + ArrayND& slice, + const unsigned* projectedIndices, + const unsigned nProjectedIndices, + Functor binaryFunct) { + if (level == dim_) { + assert(level1 == slice.dim_); + Num2& scaleFactor = slice.dim_ ? slice.data_[idx1] : slice.localData_[0]; + scaleBySliceInnerLoop(0U, idx0, scaleFactor, projectedIndices, nProjectedIndices, binaryFunct); + } else { + bool fixed = false; + for (unsigned j = 0; j < nProjectedIndices; ++j) + if (projectedIndices[j] == level) { + fixed = true; + break; } - else - { - new (this) ArrayND(slicedArray); - } - } - - template - ArrayShape ArrayND::sliceShape( - const unsigned *fixedIndices, const unsigned nFixedIndices) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"sliceShape\""); - if (nFixedIndices) - { - assert(fixedIndices); - if (nFixedIndices > dim_) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::sliceShape: too many fixed indices"); - for (unsigned j=0; j= dim_) - throw npstat::NpstatOutOfRange("In npstat::ArrayND::sliceShape: " - "fixed index out of range"); - ArrayShape sh; - sh.reserve(dim_ - nFixedIndices); - for (unsigned i=0; i - template - unsigned long ArrayND::verifySliceCompatibility( - const ArrayND& slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - const unsigned nFixedIndices) const - { - if (!(nFixedIndices && nFixedIndices <= dim_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifySliceCompatibility: " - "invalid number of fixed indices"); - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling " - "method \"verifySliceCompatibility\""); - if (!slice.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifySliceCompatibility: " - "uninitialized argument array"); - if (slice.dim_ != dim_ - nFixedIndices) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifySliceCompatibility: " - "incompatible argument array rank"); - assert(fixedIndices); - assert(fixedIndexValues); - - for (unsigned j=0; j= dim_) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::verifySliceCompatibility: " - "fixed index out of range"); - - // Check slice shape compatibility - unsigned long idx = 0UL; - unsigned sliceDim = 0U; - for (unsigned i=0; i= shape_[i]) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::verifySliceCompatibility: " - "fixed index value out of range"); - idx += fixedIndexValues[j]*strides_[i]; - break; - } - if (!fixed) - { - if (shape_[i] != slice.shape_[sliceDim]) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifySliceCompatibility: " - "incompatible argument array dimensions"); - ++sliceDim; - } - } - assert(sliceDim == slice.dim_); - return idx; - } - - template - unsigned long - ArrayND::verifyBufferSliceCompatibility( - const unsigned long bufLen, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - const unsigned nFixedIndices, - unsigned long* sliceStrides) const - { - if (!(nFixedIndices && nFixedIndices <= dim_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifyBufferSliceCompatibility: " - "invalid number of fixed indices"); - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling " - "method \"verifyBufferSliceCompatibility\""); - assert(fixedIndices); - assert(fixedIndexValues); - - for (unsigned j=0; j= dim_) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::verifyBufferSliceCompatibility: " - "fixed index out of range"); - - // Figure out slice shape. Store it, temporarily, in sliceStrides. - unsigned long idx = 0UL; - unsigned sliceDim = 0U; - for (unsigned i=0; i= shape_[i]) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::verifyBufferSliceCompatibility:" - " fixed index value out of range"); - idx += fixedIndexValues[j]*strides_[i]; - break; - } - if (!fixed) - sliceStrides[sliceDim++] = shape_[i]; - } - assert(sliceDim + nFixedIndices == dim_); - - // Convert the slice shape into slice strides - unsigned long expectedBufLen = 1UL; - if (sliceDim) - { - unsigned long shapeJ = sliceStrides[sliceDim - 1]; - sliceStrides[sliceDim - 1] = 1UL; - for (unsigned j=sliceDim - 1; j>0; --j) - { - const unsigned long nextStride = sliceStrides[j]*shapeJ; - shapeJ = sliceStrides[j - 1]; - sliceStrides[j - 1] = nextStride; - } - expectedBufLen = sliceStrides[0]*shapeJ; - } - if (expectedBufLen != bufLen) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifyBufferSliceCompatibility: " - "invalid memory buffer length"); - - return idx; - } - - template - template - void ArrayND::jointSliceLoop( - const unsigned level, const unsigned long idx0, - const unsigned level1, const unsigned long idx1, - Num2* sliceData, const unsigned long* sliceStrides, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - const unsigned nFixedIndices, - Op fcn) - { - bool fixed = false; - for (unsigned j=0; j - template - void ArrayND::jointSliceScan( - ArrayND& slice, - const unsigned *fixedIndices, - const unsigned *fixedIndexValues, - const unsigned nFixedIndices, - Functor binaryFunct) - { - const unsigned long idx = verifySliceCompatibility( - slice, fixedIndices, fixedIndexValues, nFixedIndices); - if (slice.dim_) - jointSliceLoop(0U, idx, 0U, 0UL, slice.data_, slice.strides_, - fixedIndices, fixedIndexValues, - nFixedIndices, binaryFunct); - else - binaryFunct(data_[idx], slice.localData_[0]); - } - - template - template - void ArrayND::jointMemSliceScan( - Num2* slice, const unsigned long len, - const unsigned *fixedIndices, const unsigned *fixedIndexValues, - unsigned nFixedIndices, Functor binaryFunct) - { - assert(slice); - if (dim_ > CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::jointMemSliceScan: " - "rank of this array is too large"); - unsigned long sliceStrides[CHAR_BIT*sizeof(unsigned long)]; - const unsigned long idx = verifyBufferSliceCompatibility( - len, fixedIndices, fixedIndexValues, nFixedIndices, sliceStrides); - if (dim_ > nFixedIndices) - jointSliceLoop(0U, idx, 0U, 0UL, slice, sliceStrides, - fixedIndices, fixedIndexValues, - nFixedIndices, binaryFunct); - else - binaryFunct(data_[idx], *slice); - } - - template - template - void ArrayND::projectInnerLoop( - const unsigned level, unsigned long idx0, - unsigned* currentIndex, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - // level : dimension number among indices which are being iterated - const unsigned idx = projectedIndices[level]; - const unsigned imax = shape_[idx]; - const unsigned long stride = strides_[idx]; - const bool last = (level == nProjectedIndices - 1); - - for (unsigned i = 0; i - template - void ArrayND::projectLoop( - const unsigned level, const unsigned long idx0, - const unsigned level1, const unsigned long idx1, - unsigned* currentIndex, - ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices, Op fcn) const - { - // level : dimension number in this array - // level1 : dimension number in the projection - // idx0 : linear index in this array - // idx1 : linear index in the projection - // currentIndex : cycled over in this loop with the exception of the - // dimensions which are iterated over to build the - // projection - if (level == dim_) - { - assert(level1 == projection->dim_); - projector.clear(); - projectInnerLoop(0U, idx0, currentIndex, projector, - projectedIndices, nProjectedIndices); - if (projection->dim_) - fcn(projection->data_[idx1], projector.result()); - else - fcn(projection->localData_[0], projector.result()); - } - else - { - bool iterated = false; - for (unsigned j=0; jdim_ is 0. - // Therefore, it is safe to access projection->strides_. - const unsigned long stride2 = projection->strides_[level1]; - for (unsigned i = 0; i - template - void ArrayND::verifyProjectionCompatibility( - const ArrayND& projection, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - if (!(nProjectedIndices && nProjectedIndices <= dim_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifyProjectionCompatibility: " - "invalid number of projected indices"); - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling " - "method \"verifyProjectionCompatibility\""); - if (!projection.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifyProjectionCompatibility: " - "uninitialized argument array"); - if (projection.dim_ != dim_ - nProjectedIndices) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::verifyProjectionCompatibility: " - "incompatible argument array rank"); - assert(projectedIndices); - - for (unsigned j=0; j= dim_) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::verifyProjectionCompatibility: " - "projected index out of range"); - - // Check projection shape compatibility - unsigned sliceDim = 0U; - for (unsigned i=0; i - template - void ArrayND::project( - ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - unsigned ibuf[StackDim]; - unsigned* buf = makeBuffer(dim_, ibuf, StackDim); - for (unsigned i=0; i()); - destroyBuffer(buf, ibuf); - } - - template - template - void ArrayND::addToProjection( - ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - unsigned ibuf[StackDim]; - unsigned* buf = makeBuffer(dim_, ibuf, StackDim); - for (unsigned i=0; i()); - destroyBuffer(buf, ibuf); - } - - template - template - void ArrayND::subtractFromProjection( - ArrayND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - unsigned ibuf[StackDim]; - unsigned* buf = makeBuffer(dim_, ibuf, StackDim); - for (unsigned i=0; i()); - destroyBuffer(buf, ibuf); - } - - template - template - void ArrayND::projectInnerLoop2( - const unsigned level, const unsigned long idx0, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - const unsigned idx = projectedIndices[level]; - const unsigned imax = shape_[idx]; - const unsigned long stride = strides_[idx]; - const bool last = (level == nProjectedIndices - 1); - - for (unsigned i = 0; i - template - void ArrayND::projectLoop2( - const unsigned level, const unsigned long idx0, - const unsigned level1, const unsigned long idx1, - ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices, Op fcn) const - { - if (level == dim_) - { - assert(level1 == projection->dim_); - projector.clear(); - projectInnerLoop2(0U, idx0, projector, - projectedIndices, nProjectedIndices); - if (projection->dim_) - fcn(projection->data_[idx1], projector.result()); - else - fcn(projection->localData_[0], projector.result()); - } - else - { - bool fixed = false; - for (unsigned j=0; jstrides_[level1]; - for (unsigned i = 0; i - template - void ArrayND::project( - ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - projectLoop2(0U, 0UL, 0U, 0UL, projection, - projector, projectedIndices, nProjectedIndices, - scast_assign_left()); - } - - template - template - void ArrayND::addToProjection( - ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - projectLoop2(0U, 0UL, 0U, 0UL, projection, - projector, projectedIndices, nProjectedIndices, - scast_pluseq_left()); - } - - template - template - void ArrayND::subtractFromProjection( - ArrayND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - verifyProjectionCompatibility(*projection, projectedIndices, - nProjectedIndices); - projectLoop2(0U, 0UL, 0U, 0UL, projection, - projector, projectedIndices, nProjectedIndices, - scast_minuseq_left()); - } - - template - template - void ArrayND::scaleBySliceInnerLoop( - const unsigned level, const unsigned long idx0, - Num2& scale, const unsigned *projectedIndices, - const unsigned nProjectedIndices, Functor binaryFunct) - { - const unsigned idx = projectedIndices[level]; - const unsigned imax = shape_[idx]; - const unsigned long stride = strides_[idx]; - - if (level == nProjectedIndices - 1) - { - Numeric* data = data_ + idx0; - for (unsigned i = 0; i - template - void ArrayND::scaleBySliceLoop( - unsigned level, unsigned long idx0, - unsigned level1, unsigned long idx1, - ArrayND& slice, - const unsigned *projectedIndices, - const unsigned nProjectedIndices, - Functor binaryFunct) - { - if (level == dim_) - { - assert(level1 == slice.dim_); - Num2& scaleFactor = slice.dim_ ? slice.data_[idx1] : - slice.localData_[0]; - scaleBySliceInnerLoop(0U, idx0, scaleFactor, projectedIndices, - nProjectedIndices, binaryFunct); - } - else - { - bool fixed = false; - for (unsigned j=0; j - template - void ArrayND::jointScan( - ArrayND& r, Functor binaryFunct) - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::jointScan: incompatible argument array shape"); - if (dim_) - for (unsigned long i=0; i - template - void ArrayND::applySlice( - ArrayND& slice, - const unsigned *fixedIndices, const unsigned nFixedIndices, - Functor binaryFunct) - { - if (nFixedIndices) - { - verifyProjectionCompatibility(slice, fixedIndices, nFixedIndices); - if (slice.dim_ == 0U) - for (unsigned long i=0; i - inline bool ArrayND::isCompatible( - const ArrayShape& shape) const - { - if (!shapeIsKnown_) - return false; - if (dim_ != shape.size()) - return false; - if (dim_) - { - for (unsigned i=0; i - template - inline bool ArrayND::isShapeCompatible( - const ArrayND& r) const - { - if (!shapeIsKnown_) - return false; - if (!r.shapeIsKnown_) - return false; - if (dim_ != r.dim_) - return false; - if (len_ != r.len_) - return false; - if (dim_) - { - assert(shape_); - assert(r.shape_); - for (unsigned i=0; i - template - void ArrayND::processSubrangeLoop( - const unsigned level, unsigned long idx0, - unsigned* currentIndex, - AbsArrayProjector& f, - const BoxND& subrange) const - { - // Deal with possible negative limits first - const Interval& levelRange(subrange[level]); - long long int iminl = static_cast(levelRange.min()); - if (iminl < 0LL) iminl = 0LL; - long long int imaxl = static_cast(levelRange.max()); - if (imaxl < 0LL) imaxl = 0LL; - - // Now deal with possible out-of-range limits - const unsigned imin = static_cast(iminl); - unsigned imax = static_cast(imaxl); - if (imax > shape_[level]) - imax = shape_[level]; - - if (level == dim_ - 1) - { - idx0 += imin; - for (unsigned i=imin; i - template - void ArrayND::processSubrange( - AbsArrayProjector& f, - const BoxND& subrange) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"processSubrange\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::processSubrange method " - "can not be used with array of 0 rank"); - if (dim_ != subrange.dim()) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::processSubrange: incompatible subrange rank"); - unsigned ibuf[StackDim]; - unsigned* buf = makeBuffer(dim_, ibuf, StackDim); - for (unsigned i=0; i - template - inline ArrayND& ArrayND::setData( - const Num2* data, const unsigned long dataLength) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"setData\""); - if (dataLength != len_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::setData: incompatible input data length"); - copyBuffer(data_, data, dataLength); - return *this; - } - - template - void ArrayND::buildStrides() - { - assert(dim_); - if (strides_ == nullptr) - strides_ = makeBuffer(dim_, localStrides_, Dim); - strides_[dim_ - 1] = 1UL; - for (unsigned j=dim_ - 1; j>0; --j) - strides_[j - 1] = strides_[j]*shape_[j]; - } - - template - inline ArrayND::ArrayND() - : data_(nullptr), strides_(nullptr), shape_(nullptr), - len_(0UL), dim_(0U), shapeIsKnown_(false) - { - localData_[0] = Numeric(); - data_ = localData_; - } - - template - ArrayND::ArrayND(const ArrayND& r) - : data_(nullptr), strides_(nullptr), shape_(nullptr), - len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) - { - if (dim_) - { - // Copy the shape - shape_ = makeBuffer(dim_, localShape_, Dim); - copyBuffer(shape_, r.shape_, dim_); - - // Copy the strides - strides_ = makeBuffer(dim_, localStrides_, Dim); - copyBuffer(strides_, r.strides_, dim_); - - // Copy the data - data_ = makeBuffer(len_, localData_, Len); - copyBuffer(data_, r.data_, len_); - } - else - { - assert(len_ == 1UL); - localData_[0] = r.localData_[0]; - data_ = localData_; - } - } - - template - template - ArrayND::ArrayND(const ArrayND& r) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) - { - if (dim_) - { - // Copy the shape - shape_ = makeBuffer(dim_, localShape_, Dim); - copyBuffer(shape_, r.shape_, dim_); - - // Copy the strides - strides_ = makeBuffer(dim_, localStrides_, Dim); - copyBuffer(strides_, r.strides_, dim_); - - // Copy the data - data_ = makeBuffer(len_, localData_, Len); - copyBuffer(data_, r.data_, len_); - } - else - { - assert(len_ == 1UL); - localData_[0] = static_cast(r.localData_[0]); - data_ = localData_; - } - } - - template - template - ArrayND::ArrayND(const ArrayND& r, - Functor f) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) - { - if (dim_) - { - // Copy the shape - shape_ = makeBuffer(dim_, localShape_, Dim); - copyBuffer(shape_, r.shape_, dim_); - - // Copy the strides - strides_ = makeBuffer(dim_, localStrides_, Dim); - copyBuffer(strides_, r.strides_, dim_); - - // Copy the data - data_ = makeBuffer(len_, localData_, Len); - for (unsigned long i=0; i(f(r.data_[i])); - } - else - { - assert(len_ == 1UL); - localData_[0] = static_cast(f(r.localData_[0])); - data_ = localData_; - } - } - - template - template - void ArrayND::copyRangeLoopFunct( - const unsigned level, unsigned long idx0, - unsigned long idx1, - const ArrayND& r, - const ArrayRange& range, Functor f) - { + if (fixed) { + scaleBySliceLoop(level + 1, idx0, level1, idx1, slice, projectedIndices, nProjectedIndices, binaryFunct); + } else { const unsigned imax = shape_[level]; - if (level == dim_ - 1) - { - Numeric* to = data_ + idx0; - const Num2* from = r.data_ + (idx1 + range[level].min()); - for (unsigned i=0; i(f(*from++)); - } - else - { - const unsigned long fromstride = r.strides_[level]; - const unsigned long tostride = strides_[level]; - idx1 += range[level].min()*fromstride; - for (unsigned i=0; i - template - ArrayND::ArrayND( - const ArrayND& r, const ArrayRange& range) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) - { - if (!range.isCompatible(r.shape_, r.dim_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND subrange constructor: invalid subrange"); - if (dim_) - { - len_ = range.rangeSize(); - if (!len_) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND subrange constructor: empty subrange"); - - // Figure out the shape - shape_ = makeBuffer(dim_, localShape_, Dim); - range.rangeLength(shape_, dim_); - - // Figure out the strides - buildStrides(); - - // Allocate the data array - data_ = makeBuffer(len_, localData_, Len); - - // Copy the data - if (dim_ > CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND subrange constructor: " - "input array rank is too large"); - unsigned lolim[CHAR_BIT*sizeof(unsigned long)]; - range.lowerLimits(lolim, dim_); - unsigned toBuf[CHAR_BIT*sizeof(unsigned long)]; - clearBuffer(toBuf, dim_); - (const_cast&>(r)).commonSubrangeLoop( - 0U, 0UL, 0UL, lolim, shape_, toBuf, *this, - scast_assign_right()); - } - else - { - assert(len_ == 1UL); - localData_[0] = static_cast(r.localData_[0]); - data_ = localData_; - } - } - - template - template - ArrayND::ArrayND( - const ArrayND& r, const ArrayRange& range, - Functor f) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) - { - if (!range.isCompatible(r.shape_, r.dim_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND transforming subrange constructor: " - "incompatible subrange"); - if (dim_) - { - len_ = range.rangeSize(); - if (!len_) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND transforming subrange constructor: " - "empty subrange"); - - // Figure out the shape - shape_ = makeBuffer(dim_, localShape_, Dim); - for (unsigned i=0; i(f(r.localData_[0])); - data_ = localData_; - } - } - - template - ArrayND::ArrayND(const ArrayShape& sh) - : data_(nullptr), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned sz = sh.size(); - buildFromShapePtr(sz ? &sh[0] : nullptr, sz); - } - - template - ArrayND::ArrayND(const unsigned* sizes, - const unsigned dim) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 1U; - unsigned sizes[dim]; - sizes[0] = n0; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, - const unsigned n1) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 2U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, - const unsigned n1, - const unsigned n2) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 3U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, - const unsigned n1, - const unsigned n2, - const unsigned n3) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 4U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, - const unsigned n1, - const unsigned n2, - const unsigned n3, - const unsigned n4) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 5U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, - const unsigned n1, - const unsigned n2, - const unsigned n3, - const unsigned n4, - const unsigned n5) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 6U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - sizes[5] = n5; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, + const unsigned long stride = strides_[level]; + const unsigned long stride2 = slice.strides_[level1]; + for (unsigned i = 0; i < imax; ++i) + scaleBySliceLoop(level + 1, + idx0 + i * stride, + level1 + 1, + idx1 + i * stride2, + slice, + projectedIndices, + nProjectedIndices, + binaryFunct); + } + } + } + + template + template + void ArrayND::jointScan(ArrayND& r, Functor binaryFunct) { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::jointScan: incompatible argument array shape"); + if (dim_) + for (unsigned long i = 0; i < len_; ++i) + binaryFunct(data_[i], r.data_[i]); + else + binaryFunct(localData_[0], r.localData_[0]); + } + + template + template + void ArrayND::applySlice(ArrayND& slice, + const unsigned* fixedIndices, + const unsigned nFixedIndices, + Functor binaryFunct) { + if (nFixedIndices) { + verifyProjectionCompatibility(slice, fixedIndices, nFixedIndices); + if (slice.dim_ == 0U) + for (unsigned long i = 0; i < len_; ++i) + binaryFunct(data_[i], slice.localData_[0]); + else + scaleBySliceLoop(0U, 0UL, 0U, 0UL, slice, fixedIndices, nFixedIndices, binaryFunct); + } else + jointScan(slice, binaryFunct); + } + + template + inline bool ArrayND::isCompatible(const ArrayShape& shape) const { + if (!shapeIsKnown_) + return false; + if (dim_ != shape.size()) + return false; + if (dim_) { + for (unsigned i = 0; i < dim_; ++i) + if (shape_[i] != shape[i]) + return false; + } else + assert(len_ == 1UL); + return true; + } + + template + template + inline bool ArrayND::isShapeCompatible(const ArrayND& r) const { + if (!shapeIsKnown_) + return false; + if (!r.shapeIsKnown_) + return false; + if (dim_ != r.dim_) + return false; + if (len_ != r.len_) + return false; + if (dim_) { + assert(shape_); + assert(r.shape_); + for (unsigned i = 0; i < dim_; ++i) + if (shape_[i] != r.shape_[i]) + return false; + } else + assert(len_ == 1UL); + return true; + } + + template + template + void ArrayND::processSubrangeLoop(const unsigned level, + unsigned long idx0, + unsigned* currentIndex, + AbsArrayProjector& f, + const BoxND& subrange) const { + // Deal with possible negative limits first + const Interval& levelRange(subrange[level]); + long long int iminl = static_cast(levelRange.min()); + if (iminl < 0LL) + iminl = 0LL; + long long int imaxl = static_cast(levelRange.max()); + if (imaxl < 0LL) + imaxl = 0LL; + + // Now deal with possible out-of-range limits + const unsigned imin = static_cast(iminl); + unsigned imax = static_cast(imaxl); + if (imax > shape_[level]) + imax = shape_[level]; + + if (level == dim_ - 1) { + idx0 += imin; + for (unsigned i = imin; i < imax; ++i, ++idx0) { + currentIndex[level] = i; + f.process(currentIndex, dim_, idx0, data_[idx0]); + } + } else { + const unsigned long stride = strides_[level]; + idx0 += imin * stride; + for (unsigned i = imin; i < imax; ++i) { + currentIndex[level] = i; + processSubrangeLoop(level + 1U, idx0, currentIndex, f, subrange); + idx0 += stride; + } + } + } + + template + template + void ArrayND::processSubrange(AbsArrayProjector& f, + const BoxND& subrange) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"processSubrange\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::processSubrange method " + "can not be used with array of 0 rank"); + if (dim_ != subrange.dim()) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::processSubrange: incompatible subrange rank"); + unsigned ibuf[StackDim]; + unsigned* buf = makeBuffer(dim_, ibuf, StackDim); + for (unsigned i = 0; i < dim_; ++i) + buf[i] = 0U; + processSubrangeLoop(0U, 0UL, buf, f, subrange); + destroyBuffer(buf, ibuf); + } + + template + template + inline ArrayND& ArrayND::setData(const Num2* data, + const unsigned long dataLength) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"setData\""); + if (dataLength != len_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::setData: incompatible input data length"); + copyBuffer(data_, data, dataLength); + return *this; + } + + template + void ArrayND::buildStrides() { + assert(dim_); + if (strides_ == nullptr) + strides_ = makeBuffer(dim_, localStrides_, Dim); + strides_[dim_ - 1] = 1UL; + for (unsigned j = dim_ - 1; j > 0; --j) + strides_[j - 1] = strides_[j] * shape_[j]; + } + + template + inline ArrayND::ArrayND() + : data_(nullptr), strides_(nullptr), shape_(nullptr), len_(0UL), dim_(0U), shapeIsKnown_(false) { + localData_[0] = Numeric(); + data_ = localData_; + } + + template + ArrayND::ArrayND(const ArrayND& r) + : data_(nullptr), strides_(nullptr), shape_(nullptr), len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) { + if (dim_) { + // Copy the shape + shape_ = makeBuffer(dim_, localShape_, Dim); + copyBuffer(shape_, r.shape_, dim_); + + // Copy the strides + strides_ = makeBuffer(dim_, localStrides_, Dim); + copyBuffer(strides_, r.strides_, dim_); + + // Copy the data + data_ = makeBuffer(len_, localData_, Len); + copyBuffer(data_, r.data_, len_); + } else { + assert(len_ == 1UL); + localData_[0] = r.localData_[0]; + data_ = localData_; + } + } + + template + template + ArrayND::ArrayND(const ArrayND& r) + : data_(0), strides_(nullptr), shape_(nullptr), len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) { + if (dim_) { + // Copy the shape + shape_ = makeBuffer(dim_, localShape_, Dim); + copyBuffer(shape_, r.shape_, dim_); + + // Copy the strides + strides_ = makeBuffer(dim_, localStrides_, Dim); + copyBuffer(strides_, r.strides_, dim_); + + // Copy the data + data_ = makeBuffer(len_, localData_, Len); + copyBuffer(data_, r.data_, len_); + } else { + assert(len_ == 1UL); + localData_[0] = static_cast(r.localData_[0]); + data_ = localData_; + } + } + + template + template + ArrayND::ArrayND(const ArrayND& r, Functor f) + : data_(0), strides_(nullptr), shape_(nullptr), len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) { + if (dim_) { + // Copy the shape + shape_ = makeBuffer(dim_, localShape_, Dim); + copyBuffer(shape_, r.shape_, dim_); + + // Copy the strides + strides_ = makeBuffer(dim_, localStrides_, Dim); + copyBuffer(strides_, r.strides_, dim_); + + // Copy the data + data_ = makeBuffer(len_, localData_, Len); + for (unsigned long i = 0; i < len_; ++i) + data_[i] = static_cast(f(r.data_[i])); + } else { + assert(len_ == 1UL); + localData_[0] = static_cast(f(r.localData_[0])); + data_ = localData_; + } + } + + template + template + void ArrayND::copyRangeLoopFunct(const unsigned level, + unsigned long idx0, + unsigned long idx1, + const ArrayND& r, + const ArrayRange& range, + Functor f) { + const unsigned imax = shape_[level]; + if (level == dim_ - 1) { + Numeric* to = data_ + idx0; + const Num2* from = r.data_ + (idx1 + range[level].min()); + for (unsigned i = 0; i < imax; ++i) + *to++ = static_cast(f(*from++)); + } else { + const unsigned long fromstride = r.strides_[level]; + const unsigned long tostride = strides_[level]; + idx1 += range[level].min() * fromstride; + for (unsigned i = 0; i < imax; ++i) { + copyRangeLoopFunct(level + 1, idx0, idx1, r, range, f); + idx0 += tostride; + idx1 += fromstride; + } + } + } + + template + template + ArrayND::ArrayND(const ArrayND& r, const ArrayRange& range) + : data_(0), strides_(nullptr), shape_(nullptr), len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) { + if (!range.isCompatible(r.shape_, r.dim_)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND subrange constructor: invalid subrange"); + if (dim_) { + len_ = range.rangeSize(); + if (!len_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND subrange constructor: empty subrange"); + + // Figure out the shape + shape_ = makeBuffer(dim_, localShape_, Dim); + range.rangeLength(shape_, dim_); + + // Figure out the strides + buildStrides(); + + // Allocate the data array + data_ = makeBuffer(len_, localData_, Len); + + // Copy the data + if (dim_ > CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND subrange constructor: " + "input array rank is too large"); + unsigned lolim[CHAR_BIT * sizeof(unsigned long)]; + range.lowerLimits(lolim, dim_); + unsigned toBuf[CHAR_BIT * sizeof(unsigned long)]; + clearBuffer(toBuf, dim_); + (const_cast&>(r)) + .commonSubrangeLoop(0U, 0UL, 0UL, lolim, shape_, toBuf, *this, scast_assign_right()); + } else { + assert(len_ == 1UL); + localData_[0] = static_cast(r.localData_[0]); + data_ = localData_; + } + } + + template + template + ArrayND::ArrayND(const ArrayND& r, const ArrayRange& range, Functor f) + : data_(0), strides_(nullptr), shape_(nullptr), len_(r.len_), dim_(r.dim_), shapeIsKnown_(r.shapeIsKnown_) { + if (!range.isCompatible(r.shape_, r.dim_)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND transforming subrange constructor: " + "incompatible subrange"); + if (dim_) { + len_ = range.rangeSize(); + if (!len_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND transforming subrange constructor: " + "empty subrange"); + + // Figure out the shape + shape_ = makeBuffer(dim_, localShape_, Dim); + for (unsigned i = 0; i < dim_; ++i) + shape_[i] = range[i].length(); + + // Figure out the strides + buildStrides(); + + // Allocate the data array + data_ = makeBuffer(len_, localData_, Len); + + // Transform the data + copyRangeLoopFunct(0U, 0UL, 0UL, r, range, f); + } else { + assert(len_ == 1UL); + localData_[0] = static_cast(f(r.localData_[0])); + data_ = localData_; + } + } + + template + ArrayND::ArrayND(const ArrayShape& sh) + : data_(nullptr), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned sz = sh.size(); + buildFromShapePtr(sz ? &sh[0] : nullptr, sz); + } + + template + ArrayND::ArrayND(const unsigned* sizes, const unsigned dim) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 1U; + unsigned sizes[dim]; + sizes[0] = n0; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 2U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 3U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 4U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND( + const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, const unsigned n4) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 5U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + sizes[4] = n4; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND( + const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, const unsigned n4, const unsigned n5) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 6U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + sizes[4] = n4; + sizes[5] = n5; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, const unsigned n4, const unsigned n5, const unsigned n6) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 7U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - sizes[5] = n5; - sizes[6] = n6; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 7U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + sizes[4] = n4; + sizes[5] = n5; + sizes[6] = n6; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, @@ -2917,23 +2774,22 @@ namespace npstat { const unsigned n5, const unsigned n6, const unsigned n7) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 8U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - sizes[5] = n5; - sizes[6] = n6; - sizes[7] = n7; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 8U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + sizes[4] = n4; + sizes[5] = n5; + sizes[6] = n6; + sizes[7] = n7; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, @@ -2942,24 +2798,23 @@ namespace npstat { const unsigned n6, const unsigned n7, const unsigned n8) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 9U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - sizes[5] = n5; - sizes[6] = n6; - sizes[7] = n7; - sizes[8] = n8; - buildFromShapePtr(sizes, dim); - } - - template - ArrayND::ArrayND(const unsigned n0, + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) { + const unsigned dim = 9U; + unsigned sizes[dim]; + sizes[0] = n0; + sizes[1] = n1; + sizes[2] = n2; + sizes[3] = n3; + sizes[4] = n4; + sizes[5] = n5; + sizes[6] = n6; + sizes[7] = n7; + sizes[8] = n8; + buildFromShapePtr(sizes, dim); + } + + template + ArrayND::ArrayND(const unsigned n0, const unsigned n1, const unsigned n2, const unsigned n3, @@ -2969,3187 +2824,2657 @@ namespace npstat { const unsigned n7, const unsigned n8, const unsigned n9) - : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), shapeIsKnown_(true) - { - const unsigned dim = 10U; - unsigned sizes[dim]; - sizes[0] = n0; - sizes[1] = n1; - sizes[2] = n2; - sizes[3] = n3; - sizes[4] = n4; - sizes[5] = n5; - sizes[6] = n6; - sizes[7] = n7; - sizes[8] = n8; - sizes[9] = n9; - buildFromShapePtr(sizes, dim); - } - - template - template - void ArrayND::outerProductLoop( - const unsigned level, unsigned long idx0, - unsigned long idx1, unsigned long idx2, - const ArrayND& a1, - const ArrayND& a2) - { - const unsigned imax = shape_[level]; - if (level == dim_ - 1) - { - for (unsigned i=0; i + template + void ArrayND::outerProductLoop(const unsigned level, + unsigned long idx0, + unsigned long idx1, + unsigned long idx2, + const ArrayND& a1, + const ArrayND& a2) { + const unsigned imax = shape_[level]; + if (level == dim_ - 1) { + for (unsigned i = 0; i < imax; ++i) + data_[idx0 + i] = a1.data_[idx1] * a2.data_[idx2 + i]; + } else { + for (unsigned i = 0; i < imax; ++i) { + outerProductLoop(level + 1, idx0, idx1, idx2, a1, a2); + idx0 += strides_[level]; + if (level < a1.dim_) + idx1 += a1.strides_[level]; + else + idx2 += a2.strides_[level - a1.dim_]; + } + } + } + + template + template + ArrayND::ArrayND(const ArrayND& a1, const ArrayND& a2) + : data_(0), strides_(nullptr), shape_(nullptr), len_(1UL), dim_(a1.dim_ + a2.dim_), shapeIsKnown_(true) { + if (!(a1.shapeIsKnown_ && a2.shapeIsKnown_)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND outer product constructor: " + "uninitialized argument array"); + if (dim_) { + shape_ = makeBuffer(dim_, localShape_, Dim); + copyBuffer(shape_, a1.shape_, a1.dim_); + copyBuffer(shape_ + a1.dim_, a2.shape_, a2.dim_); + + for (unsigned i = 0; i < dim_; ++i) { + assert(shape_[i]); + len_ *= shape_[i]; + } + + // Figure out the array strides + buildStrides(); + + // Allocate the data array + data_ = makeBuffer(len_, localData_, Len); + + // Fill the data array + if (a1.dim_ == 0) { + for (unsigned long i = 0; i < len_; ++i) + data_[i] = a1.localData_[0] * a2.data_[i]; + } else if (a2.dim_ == 0) { + for (unsigned long i = 0; i < len_; ++i) + data_[i] = a1.data_[i] * a2.localData_[0]; + } else + outerProductLoop(0U, 0UL, 0UL, 0UL, a1, a2); + } else { + localData_[0] = a1.localData_[0] * a2.localData_[0]; + data_ = localData_; + } + } + + template + inline ArrayND::~ArrayND() { + destroyBuffer(data_, localData_); + destroyBuffer(strides_, localStrides_); + destroyBuffer(shape_, localShape_); + } + + template + ArrayND& ArrayND::operator=(const ArrayND& r) { + if (this == &r) + return *this; + if (shapeIsKnown_) { + if (!r.shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND assignment operator: " + "uninitialized argument array"); + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND assignment operator: " + "incompatible argument array shape"); + if (dim_) + copyBuffer(data_, r.data_, len_); + else + localData_[0] = r.localData_[0]; + } else { + // This object is uninitialized. If the object on the + // right is itself initialized, make an in-place copy. + if (r.shapeIsKnown_) + new (this) ArrayND(r); + } + return *this; + } + + template + template + ArrayND& ArrayND::operator=(const ArrayND& r) { + if ((void*)this == (void*)(&r)) + return *this; + if (shapeIsKnown_) { + if (!r.shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND assignment operator: " + "uninitialized argument array"); + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND assignment operator: " + "incompatible argument array shape"); + if (dim_) + copyBuffer(data_, r.data_, len_); + else + localData_[0] = static_cast(r.localData_[0]); + } else { + // This object is uninitialized. If the object on the + // right is itself initialized, make an in-place copy. + if (r.shapeIsKnown_) + new (this) ArrayND(r); + } + return *this; + } + + template + template + ArrayND& ArrayND::assign(const ArrayND& r, Functor f) { + if (shapeIsKnown_) { + if (!r.shapeIsKnown_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::assign: uninitialized argument array"); + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::assign: incompatible argument array shape"); + if (dim_) + for (unsigned long i = 0; i < len_; ++i) + data_[i] = static_cast(f(r.data_[i])); + else + localData_[0] = static_cast(f(r.localData_[0])); + } else { + // This object is uninitialized. If the object on the + // right is itself initialized, build new array in place. + if (r.shapeIsKnown_) + new (this) ArrayND(r, f); + } + return *this; + } + + template + inline ArrayShape ArrayND::shape() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"shape\""); + return ArrayShape(shape_, shape_ + dim_); + } + + template + inline ArrayRange ArrayND::fullRange() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"fullRange\""); + ArrayRange range; + if (dim_) { + range.reserve(dim_); + for (unsigned i = 0; i < dim_; ++i) + range.push_back(Interval(0U, shape_[i])); + } + return range; + } + + template + bool ArrayND::isDensity() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"isDensity\""); + const Numeric zero = Numeric(); + bool hasPositive = false; + if (dim_) + for (unsigned long i = 0; i < len_; ++i) { + // Don't make comparisons whose result can be + // determined in advance by assuming that Numeric + // is an unsigned type. Some compilers will + // complain about it when this template is + // instantiated with such a type. + if (data_[i] == zero) + continue; + if (ComplexComparesFalse::less(zero, data_[i])) + hasPositive = true; else - { - for (unsigned i=0; i::less(zero, localData_[0]); + return hasPositive; + } + + template + bool ArrayND::isZero() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"isZero\""); + const Numeric zero = Numeric(); + if (dim_) { + for (unsigned long i = 0; i < len_; ++i) + if (data_[i] != zero) + return false; + } else if (localData_[0] != zero) + return false; + return true; + } + + template + void ArrayND::convertLinearIndex(unsigned long l, unsigned* idx, const unsigned idxLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "Initialize npstat::ArrayND before calling " + "method \"convertLinearIndex\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::convertLinearIndex method " + "can not be used with array of 0 rank"); + if (idxLen != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::convertLinearIndex: incompatible index length"); + if (l >= len_) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::convertLinearIndex: linear index out of range"); + assert(idx); + + for (unsigned i = 0; i < dim_; ++i) { + idx[i] = l / strides_[i]; + l -= (idx[i] * strides_[i]); + } + } + + template + unsigned long ArrayND::linearIndex(const unsigned* index, unsigned idxLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"linearIndex\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::linearIndex method " + "can not be used with array of 0 rank"); + if (idxLen != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::linearIndex: incompatible index length"); + assert(index); + + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) { + if (index[i] >= shape_[i]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::linearIndex: index out of range"); + idx += index[i] * strides_[i]; + } + return idx; + } + + template + inline Numeric& ArrayND::value(const unsigned* index, const unsigned dim) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"value\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::value: incompatible index length"); + if (dim) { + assert(index); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) + idx += index[i] * strides_[i]; + return data_[idx]; + } else + return localData_[0]; + } + + template + inline const Numeric& ArrayND::value(const unsigned* index, const unsigned dim) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"value\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::value: incompatible index length"); + if (dim) { + assert(index); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) + idx += index[i] * strides_[i]; + return data_[idx]; + } else + return localData_[0]; + } + + template + inline Numeric& ArrayND::linearValue(const unsigned long index) { + return data_[index]; + } + + template + inline const Numeric& ArrayND::linearValue(const unsigned long index) const { + return data_[index]; + } + + template + inline Numeric& ArrayND::linearValueAt(const unsigned long index) { + if (index >= len_) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::linearValueAt: linear index out of range"); + return data_[index]; + } + + template + inline const Numeric& ArrayND::linearValueAt(const unsigned long index) const { + if (index >= len_) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::linearValueAt: linear index out of range"); + return data_[index]; + } + + template + inline unsigned ArrayND::coordToIndex(const double x, const unsigned idim) const { + if (x <= 0.0) + return 0; + else if (x >= static_cast(shape_[idim] - 1)) + return shape_[idim] - 1; + else + return static_cast(std::floor(x + 0.5)); + } + + template + inline const Numeric& ArrayND::closest(const double* x, const unsigned dim) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"closest\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::closest: incompatible data length"); + if (dim) { + assert(x); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) + idx += coordToIndex(x[i], i) * strides_[i]; + return data_[idx]; + } else + return localData_[0]; + } + + template + inline Numeric& ArrayND::closest(const double* x, const unsigned dim) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"closest\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::closest: incompatible data length"); + if (dim) { + assert(x); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) + idx += coordToIndex(x[i], i) * strides_[i]; + return data_[idx]; + } else + return localData_[0]; + } + + template + inline const Numeric& ArrayND::valueAt(const unsigned* index, const unsigned dim) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"valueAt\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::valueAt: incompatible index length"); + if (dim) { + assert(index); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) { + if (index[i] >= shape_[i]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::valueAt: index out of range"); + idx += index[i] * strides_[i]; + } + return data_[idx]; + } else + return localData_[0]; + } + + template + inline Numeric& ArrayND::valueAt(const unsigned* index, const unsigned dim) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"valueAt\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::valueAt: incompatible index length"); + if (dim) { + assert(index); + unsigned long idx = 0UL; + for (unsigned i = 0; i < dim_; ++i) { + if (index[i] >= shape_[i]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::valueAt: index out of range"); + idx += index[i] * strides_[i]; + } + return data_[idx]; + } else + return localData_[0]; + } + + template + inline Numeric& ArrayND::operator()() { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator()\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + inline const Numeric& ArrayND::operator()() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator()\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i) { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 1 array)"); + return data_[i]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i) const { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 1 array)"); + return data_[i]; + } + + template + const Numeric& ArrayND::at() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"at\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + Numeric& ArrayND::at() { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"at\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + const Numeric& ArrayND::at(const unsigned i0) const { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 1 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 1)"); + return data_[i0]; + } + + template + Numeric& ArrayND::at(const unsigned i0) { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 1 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 1)"); + return data_[i0]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, const unsigned i1) { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 2 array)"); + return data_[i0 * strides_[0] + i1]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, const unsigned i1) const { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 2 array)"); + return data_[i0 * strides_[0] + i1]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, const unsigned i1) const { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 2 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 2)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 2)"); + return data_[i0 * strides_[0] + i1]; + } + + template + Numeric& ArrayND::at(const unsigned i0, const unsigned i1) { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 2 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 2)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 2)"); + return data_[i0 * strides_[0] + i1]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2) const { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 3 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3) const { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 4 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3]; + } + + template + inline const Numeric& ArrayND::operator()( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4) const { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 5 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5) const { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 6 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + i5]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6) const { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 7 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7) const { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 8 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8) const { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 9 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8]; + } + + template + inline const Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9) const { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 10 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8 * strides_[8] + i9]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, const unsigned i1, const unsigned i2) { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 3 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3) { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 4 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3]; + } + + template + inline Numeric& ArrayND::operator()( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4) { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 5 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5) { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 6 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + i5]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6) { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 7 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7) { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 8 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8) { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 9 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8]; + } + + template + inline Numeric& ArrayND::operator()(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9) { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::operator(): wrong # of args (not rank 10 array)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8 * strides_[8] + i9]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, const unsigned i1, const unsigned i2) const { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 3 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 3)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 3)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 3)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3) const { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 4 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 4)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 4)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 4)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 4)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3]; + } + + template + const Numeric& ArrayND::at( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4) const { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 5 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 5)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 5)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 5)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 5)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 5)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5) const { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 6 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 6)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 6)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 6)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 6)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 6)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 6)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + i5]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6) const { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 7 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 7)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 7)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 7)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 7)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 7)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 7)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 7)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7) const { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 8 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 8)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 8)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 8)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 8)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 8)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 8)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 8)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 8)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8) const { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 9 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 9)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 9)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 9)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 9)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 9)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 9)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 9)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 9)"); + if (i8 >= shape_[8]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 8 out of range (rank 9)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8]; + } + + template + const Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9) const { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 10 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 10)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 10)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 10)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 10)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 10)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 10)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 10)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 10)"); + if (i8 >= shape_[8]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 8 out of range (rank 10)"); + if (i9 >= shape_[9]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 9 out of range (rank 10)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8 * strides_[8] + i9]; + } + + template + Numeric& ArrayND::at(const unsigned i0, const unsigned i1, const unsigned i2) { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 3 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 3)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 3)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 3)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2]; + } + + template + Numeric& ArrayND::at(const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3) { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 4 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 4)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 4)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 4)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 4)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3]; + } + + template + Numeric& ArrayND::at( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4) { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 5 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 5)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 5)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 5)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 5)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 5)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4]; + } + + template + Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5) { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 6 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 6)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 6)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 6)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 6)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 6)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 6)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + i5]; + } + + template + Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6) { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 7 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 7)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 7)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 7)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 7)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 7)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 7)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 7)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6]; + } + + template + Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7) { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 8 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 8)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 8)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 8)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 8)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 8)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 8)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 8)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 8)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7]; + } + + template + Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8) { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 9 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 9)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 9)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 9)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 9)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 9)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 9)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 9)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 9)"); + if (i8 >= shape_[8]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 8 out of range (rank 9)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8]; + } + + template + Numeric& ArrayND::at(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9) { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::at: wrong # of args (not rank 10 array)"); + if (i0 >= shape_[0]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 0 out of range (rank 10)"); + if (i1 >= shape_[1]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 1 out of range (rank 10)"); + if (i2 >= shape_[2]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 2 out of range (rank 10)"); + if (i3 >= shape_[3]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 3 out of range (rank 10)"); + if (i4 >= shape_[4]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 4 out of range (rank 10)"); + if (i5 >= shape_[5]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 5 out of range (rank 10)"); + if (i6 >= shape_[6]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 6 out of range (rank 10)"); + if (i7 >= shape_[7]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 7 out of range (rank 10)"); + if (i8 >= shape_[8]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 8 out of range (rank 10)"); + if (i9 >= shape_[9]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::at: index 9 out of range (rank 10)"); + return data_[i0 * strides_[0] + i1 * strides_[1] + i2 * strides_[2] + i3 * strides_[3] + i4 * strides_[4] + + i5 * strides_[5] + i6 * strides_[6] + i7 * strides_[7] + i8 * strides_[8] + i9]; + } + + template + template + double ArrayND::maxAbsDifference(const ArrayND& r) const { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::maxAbsDifference: " + "incompatible argument array shape"); + if (dim_) { + double maxd = 0.0; + for (unsigned long i = 0; i < len_; ++i) { + const Numeric rval = r.data_[i]; + const double d = absDifference(data_[i], rval); + if (d > maxd) + maxd = d; + } + return maxd; + } else { + const Numeric rval = r.localData_[0]; + return absDifference(localData_[0], rval); + } + } + + template + template + bool ArrayND::operator==(const ArrayND& r) const { + if (shapeIsKnown_ != r.shapeIsKnown_) + return false; + if (r.dim_ != dim_) + return false; + if (r.len_ != len_) + return false; + for (unsigned i = 0; i < dim_; ++i) + if (shape_[i] != r.shape_[i]) + return false; + for (unsigned i = 0; i < dim_; ++i) + assert(strides_[i] == r.strides_[i]); + for (unsigned long j = 0; j < len_; ++j) + if (data_[j] != r.data_[j]) + return false; + return true; + } + + template + template + inline bool ArrayND::operator!=(const ArrayND& r) const { + return !(*this == r); + } + + template + template + ArrayND ArrayND::operator*(const Num2& r) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator*\""); + ArrayND result(shape_, dim_); + for (unsigned long i = 0; i < len_; ++i) + result.data_[i] = data_[i] * r; + return result; + } + + template + template + ArrayND ArrayND::operator/(const Num2& r) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator/\""); + if (r == Num2()) + throw npstat::NpstatRuntimeError("In npstat::ArrayND::operator/: division by zero"); + ArrayND result(shape_, dim_); + for (unsigned long i = 0; i < len_; ++i) + result.data_[i] = data_[i] / r; + return result; + } + + template + template + ArrayND ArrayND::operator+(const ArrayND& r) const { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::operator+: " + "incompatible argument array shape"); + ArrayND result(shape_, dim_); + for (unsigned long i = 0; i < len_; ++i) + result.data_[i] = data_[i] + r.data_[i]; + return result; + } + + template + template + ArrayND ArrayND::operator-(const ArrayND& r) const { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::operator-: " + "incompatible argument array shape"); + ArrayND result(shape_, dim_); + for (unsigned long i = 0; i < len_; ++i) + result.data_[i] = data_[i] - r.data_[i]; + return result; + } + + template + inline ArrayND ArrayND::operator+() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator+\""); + return *this; + } + + template + ArrayND ArrayND::operator-() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator-\""); + ArrayND result(shape_, dim_); + for (unsigned long i = 0; i < len_; ++i) + result.data_[i] = -data_[i]; + return result; + } + + template + template + ArrayND& ArrayND::operator*=(const Num2& r) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator*=\""); + for (unsigned long i = 0; i < len_; ++i) + data_[i] *= r; + return *this; + } + + template + ArrayND& ArrayND::makeNonNegative() { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"makeNonNegative\""); + const Numeric zero = Numeric(); + if (dim_) { + for (unsigned long i = 0; i < len_; ++i) + if (!(ComplexComparesAbs::more(data_[i], zero))) + data_[i] = zero; + } else if (!(ComplexComparesAbs::more(localData_[0], zero))) + localData_[0] = zero; + return *this; + } + + template + unsigned ArrayND::makeCopulaSteps(const double tolerance, const unsigned nCycles) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"makeCopulaSteps\""); + if (nCycles == 0U) + return 0U; + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::makeCopulaSteps method " + "can not be used with array of 0 rank"); + + const Numeric zero = Numeric(); + for (unsigned long i = 0; i < len_; ++i) + if (!(ComplexComparesAbs::more(data_[i], zero))) + data_[i] = zero; + + std::vector axesPtrBuf(dim_); + Numeric** axes = &axesPtrBuf[0]; + const Numeric one = static_cast(1); + + // Memory for the axis accumulators + unsigned idxSum = 0; + for (unsigned i = 0; i < dim_; ++i) + idxSum += shape_[i]; + std::vector axesBuf(idxSum); + axes[0] = &axesBuf[0]; + for (unsigned i = 1; i < dim_; ++i) + axes[i] = axes[i - 1] + shape_[i - 1]; + + // Accumulate axis projections + unsigned icycle = 0; + for (; icycle < nCycles; ++icycle) { + for (unsigned i = 0; i < idxSum; ++i) + axesBuf[i] = zero; + + // Accumulate sums for each axis + for (unsigned long idat = 0; idat < len_; ++idat) { + unsigned long l = idat; + for (unsigned i = 0; i < dim_; ++i) { + const unsigned idx = l / strides_[i]; + l -= (idx * strides_[i]); + axes[i][idx] += data_[idat]; } - } - - template - template - ArrayND::ArrayND(const ArrayND& a1, - const ArrayND& a2) - : data_(0), strides_(nullptr), shape_(nullptr), - len_(1UL), dim_(a1.dim_ + a2.dim_), shapeIsKnown_(true) - { - if (!(a1.shapeIsKnown_ && a2.shapeIsKnown_)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND outer product constructor: " - "uninitialized argument array"); - if (dim_) - { - shape_ = makeBuffer(dim_, localShape_, Dim); - copyBuffer(shape_, a1.shape_, a1.dim_); - copyBuffer(shape_+a1.dim_, a2.shape_, a2.dim_); - - for (unsigned i=0; i(amax); + for (unsigned a = 0; a < amax; ++a) + axes[i][a] /= axisAverage; + for (unsigned a = 0; a < amax && withinTolerance; ++a) { + const double adelta = absDifference(axes[i][a], one); + if (adelta > tolerance) + withinTolerance = false; } - } + } - template - inline ArrayND::~ArrayND() - { - destroyBuffer(data_, localData_); - destroyBuffer(strides_, localStrides_); - destroyBuffer(shape_, localShape_); - } + if (withinTolerance) + break; - template - ArrayND& - ArrayND::operator=(const ArrayND& r) - { - if (this == &r) - return *this; - if (shapeIsKnown_) - { - if (!r.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND assignment operator: " - "uninitialized argument array"); - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND assignment operator: " - "incompatible argument array shape"); - if (dim_) - copyBuffer(data_, r.data_, len_); - else - localData_[0] = r.localData_[0]; + const Numeric totalAverage = totalSum / static_cast(len_) / static_cast(dim_); + + // Run over all points again and divide by + // the product of marginals + for (unsigned long idat = 0; idat < len_; ++idat) { + unsigned long l = idat; + for (unsigned i = 0; i < dim_; ++i) { + const unsigned idx = l / strides_[i]; + l -= (idx * strides_[i]); + data_[idat] /= axes[i][idx]; } - else - { - // This object is uninitialized. If the object on the - // right is itself initialized, make an in-place copy. - if (r.shapeIsKnown_) - new (this) ArrayND(r); + data_[idat] /= totalAverage; + } + } + + return icycle; + } + + template + template + ArrayND& ArrayND::operator/=(const Num2& r) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"operator/=\""); + if (r == Num2()) + throw npstat::NpstatRuntimeError("In npstat::ArrayND::operator/=: division by zero"); + for (unsigned long i = 0; i < len_; ++i) + data_[i] /= r; + return *this; + } + + template + template + ArrayND& ArrayND::operator+=(const ArrayND& r) { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::operator+=: " + "incompatible argument array shape"); + for (unsigned long i = 0; i < len_; ++i) + data_[i] += r.data_[i]; + return *this; + } + + template + template + ArrayND& ArrayND::addmul(const ArrayND& r, const Num3& c) { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::addmul: " + "incompatible argument array shape"); + for (unsigned long i = 0; i < len_; ++i) + data_[i] += r.data_[i] * c; + return *this; + } + + template + template + ArrayND& ArrayND::operator-=(const ArrayND& r) { + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::operator-=: " + "incompatible argument array shape"); + for (unsigned long i = 0; i < len_; ++i) + data_[i] -= r.data_[i]; + return *this; + } + + template + Numeric ArrayND::interpolate1(const double* coords, const unsigned dim) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"interpolate1\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::interpolate1: incompatible coordinate length"); + if (dim) { + const unsigned maxdim = CHAR_BIT * sizeof(unsigned long); + if (dim_ >= maxdim) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::interpolate1: array rank is too large"); + + double dx[maxdim]; + unsigned ix[maxdim]; + for (unsigned i = 0; i < dim; ++i) { + const double x = coords[i]; + if (x <= 0.0) { + ix[i] = 0; + dx[i] = 0.0; + } else if (x >= static_cast(shape_[i] - 1)) { + ix[i] = shape_[i] - 1; + dx[i] = 0.0; + } else { + ix[i] = static_cast(std::floor(x)); + dx[i] = x - ix[i]; } - return *this; - } - - template - template - ArrayND& - ArrayND::operator=(const ArrayND& r) - { - if ((void*)this == (void*)(&r)) - return *this; - if (shapeIsKnown_) - { - if (!r.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND assignment operator: " - "uninitialized argument array"); - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND assignment operator: " - "incompatible argument array shape"); - if (dim_) - copyBuffer(data_, r.data_, len_); - else - localData_[0] = static_cast(r.localData_[0]); + } + + Numeric sum = Numeric(); + const unsigned long maxcycle = 1UL << dim; + for (unsigned long icycle = 0UL; icycle < maxcycle; ++icycle) { + double w = 1.0; + unsigned long icell = 0UL; + for (unsigned i = 0; i < dim; ++i) { + if (icycle & (1UL << i)) { + w *= dx[i]; + icell += strides_[i] * (ix[i] + 1U); + } else { + w *= (1.0 - dx[i]); + icell += strides_[i] * ix[i]; + } } - else - { - // This object is uninitialized. If the object on the - // right is itself initialized, make an in-place copy. - if (r.shapeIsKnown_) - new (this) ArrayND(r); + if (w > 0.0) + sum += data_[icell] * static_cast(w); + } + return sum; + } else + return localData_[0]; + } + + template + Numeric ArrayND::interpolateLoop(const unsigned level, + const double* coords, + const Numeric* base) const { + const unsigned npoints = shape_[level]; + const double x = coords[level]; + + unsigned ix, npt = 1; + double dx = 0.0; + if (x < 0.0) + ix = 0; + else if (x > static_cast(npoints - 1)) + ix = npoints - 1; + else { + ix = static_cast(std::floor(x)); + if (ix) + --ix; + unsigned imax = ix + 3; + while (imax >= npoints) { + if (ix) + --ix; + --imax; + } + dx = x - ix; + npt = imax + 1 - ix; + } + assert(npt >= 1 && npt <= 4); + + Numeric fit[4]; + if (level < dim_ - 1) + for (unsigned ipt = 0; ipt < npt; ++ipt) + fit[ipt] = interpolateLoop(level + 1, coords, base + (ix + ipt) * strides_[level]); + + const Numeric* const v = (level == dim_ - 1 ? base + ix : fit); + switch (npt) { + case 1: + return v[0]; + case 2: + return interpolate_linear(dx, v[0], v[1]); + case 3: + return interpolate_quadratic(dx, v[0], v[1], v[2]); + case 4: + return interpolate_cubic(dx, v[0], v[1], v[2], v[3]); + default: + assert(0); + return Numeric(); + } + } + + template + inline Numeric ArrayND::interpolate3(const double* coords, const unsigned dim) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"interpolate3\""); + if (dim != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::interpolate3: incompatible coordinate length"); + if (dim) { + assert(coords); + return interpolateLoop(0, coords, data_); + } else + return localData_[0]; + } + + template + template + ArrayND& ArrayND::apply(Functor f) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"apply\""); + for (unsigned long i = 0; i < len_; ++i) + data_[i] = static_cast(f(data_[i])); + return *this; + } + + template + template + ArrayND& ArrayND::scanInPlace(Functor f) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"scanInPlace\""); + for (unsigned long i = 0; i < len_; ++i) + f(data_[i]); + return *this; + } + + template + ArrayND& ArrayND::constFill(const Numeric c) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"constFill\""); + for (unsigned long i = 0; i < len_; ++i) + data_[i] = c; + return *this; + } + + template + inline ArrayND& ArrayND::clear() { + return constFill(Numeric()); + } + + template + ArrayND& ArrayND::uninitialize() { + destroyBuffer(data_, localData_); + destroyBuffer(strides_, localStrides_); + destroyBuffer(shape_, localShape_); + localData_[0] = Numeric(); + data_ = localData_; + strides_ = nullptr; + shape_ = nullptr; + len_ = 0; + dim_ = 0; + shapeIsKnown_ = false; + return *this; + } + + template + ArrayND& ArrayND::makeUnit() { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"makeUnit\""); + if (dim_ < 2) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::makeUnit method " + "can not be used with arrays of rank less than 2"); + constFill(Numeric()); + unsigned long stride = 0UL; + const unsigned dimlen = shape_[0]; + for (unsigned i = 0; i < dim_; ++i) { + if (shape_[i] != dimlen) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::makeUnit method needs " + "the array span to be the same in ech dimension"); + stride += strides_[i]; + } + const Numeric one(static_cast(1)); + for (unsigned i = 0; i < dimlen; ++i) + data_[i * stride] = one; + return *this; + } + + template + void ArrayND::linearFillLoop( + const unsigned level, const double s0, const unsigned long idx, const double shift, const double* coeffs) { + const unsigned imax = shape_[level]; + const double c = coeffs[level]; + if (level == dim_ - 1) { + Numeric* d = &data_[idx]; + for (unsigned i = 0; i < imax; ++i) { + // Note that we want to add "shift" only at the + // very end. This might improve the numerical + // precision of the result. + const double sum = s0 + c * i + shift; + d[i] = static_cast(sum); + } + } else { + const unsigned long stride = strides_[level]; + for (unsigned i = 0; i < imax; ++i) + linearFillLoop(level + 1, s0 + c * i, idx + i * stride, shift, coeffs); + } + } + + template + ArrayND& ArrayND::linearFill(const double* coeffs, + const unsigned dimCoeffs, + const double shift) { + // Make sure the object has been initialized + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"linearFill\""); + if (dim_ != dimCoeffs) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::linearFill: incompatible number of coefficients"); + if (dim_) { + assert(coeffs); + linearFillLoop(0U, 0.0, 0UL, shift, coeffs); + } else + localData_[0] = static_cast(shift); + return *this; + } + + template + template + void ArrayND::functorFillLoop(const unsigned level, + const unsigned long idx, + Functor f, + unsigned* farg) { + const unsigned imax = shape_[level]; + if (level == dim_ - 1) { + Numeric* d = &data_[idx]; + const unsigned* myarg = farg; + for (unsigned i = 0; i < imax; ++i) { + farg[level] = i; + d[i] = static_cast(f(myarg, dim_)); + } + } else { + const unsigned long stride = strides_[level]; + for (unsigned i = 0; i < imax; ++i) { + farg[level] = i; + functorFillLoop(level + 1, idx + i * stride, f, farg); + } + } + } + + template + template + void ArrayND::convertToLastDimCdfLoop( + ArrayND* sumSlice, const unsigned level, unsigned long idx0, unsigned long idxSlice, const bool useTrapezoids) { + static const proper_double half = 0.5; + const unsigned imax = shape_[level]; + if (level == dim_ - 1) { + Accumulator acc = Accumulator(); + Numeric* data = data_ + idx0; + if (useTrapezoids) { + Numeric oldval = Numeric(); + for (unsigned i = 0; i < imax; ++i) { + acc += (data[i] + oldval) * half; + oldval = data[i]; + data[i] = static_cast(acc); } - return *this; - } - - template - template - ArrayND& - ArrayND::assign(const ArrayND& r, - Functor f) - { - if (shapeIsKnown_) - { - if (!r.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::assign: uninitialized argument array"); - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::assign: incompatible argument array shape"); - if (dim_) - for (unsigned long i=0; i(f(r.data_[i])); - else - localData_[0] = static_cast(f(r.localData_[0])); + acc += oldval * half; + } else + for (unsigned i = 0; i < imax; ++i) { + acc += data[i]; + data[i] = static_cast(acc); } - else - { - // This object is uninitialized. If the object on the - // right is itself initialized, build new array in place. - if (r.shapeIsKnown_) - new (this) ArrayND(r, f); + if (sumSlice->dim_) + sumSlice->data_[idxSlice] = static_cast(acc); + else + sumSlice->localData_[0] = static_cast(acc); + } else { + const unsigned long stride = strides_[level]; + unsigned long sumStride = 0UL; + if (sumSlice->dim_) + sumStride = sumSlice->strides_[level]; + for (unsigned i = 0; i < imax; ++i) { + convertToLastDimCdfLoop(sumSlice, level + 1, idx0, idxSlice, useTrapezoids); + idx0 += stride; + idxSlice += sumStride; + } + } + } + + template + template + inline void ArrayND::convertToLastDimCdf(ArrayND* sumSlice, const bool useTrapezoids) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "Initialize npstat::ArrayND before calling " + "method \"convertToLastDimCdf\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::convertToLastDimCdf method " + "can not be used with array of 0 rank"); + assert(sumSlice); + if (!sumSlice->shapeIsKnown_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::convertToLastDimCdf: " + "uninitialized argument array"); + convertToLastDimCdfLoop(sumSlice, 0U, 0UL, 0UL, useTrapezoids); + } + + template + template + ArrayND& ArrayND::functorFill(Functor f) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"functorFill\""); + if (dim_) { + unsigned localIndex[Dim]; + unsigned* index = makeBuffer(dim_, localIndex, Dim); + functorFillLoop(0U, 0UL, f, index); + destroyBuffer(index, localIndex); + } else + localData_[0] = static_cast(f(static_cast(nullptr), 0U)); + return *this; + } + + template + template + bool ArrayND::isClose(const ArrayND& r, const double eps) const { + if (eps < 0.0) + throw npstat::NpstatDomainError("In npstat::ArrayND::isClose: tolerance must not be negative"); + if (!isShapeCompatible(r)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::isClose: incompatible argument array shape"); + if (dim_) { + for (unsigned long i = 0; i < len_; ++i) { + const Numeric rval = r.data_[i]; + if (static_cast(absDifference(data_[i], rval)) > eps) + return false; + } + } else { + const Numeric rval = r.localData_[0]; + if (static_cast(absDifference(localData_[0], rval)) > eps) + return false; + } + return true; + } + + template + template + ArrayND ArrayND::outer(const ArrayND& r) const { + return ArrayND(*this, r); + } + + template + void ArrayND::contractLoop(unsigned thisLevel, + const unsigned resLevel, + const unsigned pos1, + const unsigned pos2, + unsigned long idxThis, + unsigned long idxRes, + ArrayND& result) const { + while (thisLevel == pos1 || thisLevel == pos2) + ++thisLevel; + assert(thisLevel < dim_); + + if (resLevel == result.dim_ - 1) { + const unsigned ncontract = shape_[pos1]; + const unsigned imax = result.shape_[resLevel]; + const unsigned long stride = strides_[pos1] + strides_[pos2]; + for (unsigned i = 0; i < imax; ++i) { + const Numeric* tmp = data_ + (idxThis + i * strides_[thisLevel]); + Numeric sum = Numeric(); + for (unsigned j = 0; j < ncontract; ++j) + sum += tmp[j * stride]; + result.data_[idxRes + i] = sum; + } + } else { + const unsigned imax = result.shape_[resLevel]; + assert(imax == shape_[thisLevel]); + for (unsigned i = 0; i < imax; ++i) { + contractLoop(thisLevel + 1, resLevel + 1, pos1, pos2, idxThis, idxRes, result); + idxThis += strides_[thisLevel]; + idxRes += result.strides_[resLevel]; + } + } + } + + template + ArrayND ArrayND::contract(const unsigned pos1, const unsigned pos2) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"contract\""); + if (!(pos1 < dim_ && pos2 < dim_ && pos1 != pos2)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::contract: " + "incompatible contraction indices"); + if (shape_[pos1] != shape_[pos2]) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::contract: incompatible " + "length of contracted dimensions"); + + // Construct the new shape + unsigned newshapeBuf[Dim]; + unsigned* newshape = makeBuffer(dim_ - 2, newshapeBuf, Dim); + unsigned ishap = 0; + for (unsigned i = 0; i < dim_; ++i) + if (i != pos1 && i != pos2) + newshape[ishap++] = shape_[i]; + + // Form the result array + ArrayND result(newshape, ishap); + if (ishap) + contractLoop(0, 0, pos1, pos2, 0UL, 0UL, result); + else { + // We are just calculating the trace + Numeric sum = Numeric(); + const unsigned imax = shape_[0]; + const unsigned long stride = strides_[0] + strides_[1]; + for (unsigned i = 0; i < imax; ++i) + sum += data_[i * stride]; + result() = sum; + } + + destroyBuffer(newshape, newshapeBuf); + return result; + } + + template + void ArrayND::transposeLoop(const unsigned level, + const unsigned pos1, + const unsigned pos2, + unsigned long idxThis, + unsigned long idxRes, + ArrayND& result) const { + const unsigned imax = shape_[level]; + const unsigned long mystride = strides_[level]; + const unsigned relevel = level == pos1 ? pos2 : (level == pos2 ? pos1 : level); + const unsigned long restride = result.strides_[relevel]; + const bool ready = (level == dim_ - 1); + for (unsigned i = 0; i < imax; ++i) { + if (ready) + result.data_[idxRes] = data_[idxThis]; + else + transposeLoop(level + 1, pos1, pos2, idxThis, idxRes, result); + idxThis += mystride; + idxRes += restride; + } + } + + template + template + Num2 ArrayND::sum() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"sum\""); + Num2 sum = Num2(); + for (unsigned long i = 0; i < len_; ++i) + sum += data_[i]; + return sum; + } + + template + template + Num2 ArrayND::sumsq() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"sumsq\""); + Num2 sum = Num2(); + for (unsigned long i = 0; i < len_; ++i) { + const Num2 absval = absValue(data_[i]); + sum += absval * absval; + } + return sum; + } + + template + Numeric ArrayND::min() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"min\""); + if (dim_) { + Numeric minval(data_[0]); + for (unsigned long i = 1UL; i < len_; ++i) + if (ComplexComparesAbs::less(data_[i], minval)) + minval = data_[i]; + return minval; + } else + return localData_[0]; + } + + template + Numeric ArrayND::min(unsigned* index, const unsigned indexLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"min\""); + if (indexLen != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::min: incompatible index length"); + if (dim_) { + unsigned long minind = 0UL; + Numeric minval(data_[0]); + for (unsigned long i = 1UL; i < len_; ++i) + if (ComplexComparesAbs::less(data_[i], minval)) { + minval = data_[i]; + minind = i; } - return *this; - } - - template - inline ArrayShape ArrayND::shape() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"shape\""); - return ArrayShape(shape_, shape_+dim_); - } - - template - inline ArrayRange ArrayND::fullRange() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"fullRange\""); - ArrayRange range; - if (dim_) - { - range.reserve(dim_); - for (unsigned i=0; i(0U, shape_[i])); + convertLinearIndex(minind, index, indexLen); + return minval; + } else + return localData_[0]; + } + + template + Numeric ArrayND::max() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"max\""); + if (dim_) { + Numeric maxval(data_[0]); + for (unsigned long i = 1UL; i < len_; ++i) + if (ComplexComparesAbs::less(maxval, data_[i])) + maxval = data_[i]; + return maxval; + } else + return localData_[0]; + } + + template + Numeric ArrayND::max(unsigned* index, const unsigned indexLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"max\""); + if (indexLen != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::max: incompatible index length"); + if (dim_) { + unsigned long maxind = 0UL; + Numeric maxval(data_[0]); + for (unsigned long i = 1UL; i < len_; ++i) + if (ComplexComparesAbs::less(maxval, data_[i])) { + maxval = data_[i]; + maxind = i; } - return range; - } - - template - bool ArrayND::isDensity() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"isDensity\""); - const Numeric zero = Numeric(); - bool hasPositive = false; - if (dim_) - for (unsigned long i=0; i::less(zero, data_[i])) - hasPositive = true; - else - return false; - } - else - hasPositive = ComplexComparesFalse::less( - zero, localData_[0]); - return hasPositive; - } - - template - bool ArrayND::isZero() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"isZero\""); - const Numeric zero = Numeric(); - if (dim_) - { - for (unsigned long i=0; i + ArrayND ArrayND::transpose() const { + if (dim_ != 2) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::transpose method " + "can not be used with arrays of rank other than 2"); + unsigned newshape[2]; + newshape[0] = shape_[1]; + newshape[1] = shape_[0]; + ArrayND result(newshape, dim_); + const unsigned imax = shape_[0]; + const unsigned jmax = shape_[1]; + for (unsigned i = 0; i < imax; ++i) + for (unsigned j = 0; j < jmax; ++j) + result.data_[j * imax + i] = data_[i * jmax + j]; + return result; + } + + template + template + ArrayND ArrayND::derivative(const double inscale) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"derivative\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::derivative method " + "can not be used with array of 0 rank"); + + const typename ProperDblFromCmpl::type scale = inscale; + const unsigned maxdim = CHAR_BIT * sizeof(unsigned long); + if (dim_ >= maxdim) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::derivative: array rank is too large"); + const unsigned long maxcycle = 1UL << dim_; + + ArrayShape sh; + sh.reserve(dim_); + for (unsigned i = 0; i < dim_; ++i) { + if (shape_[i] <= 1U) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::derivative: in some dimendions " + "array size is too small"); + sh.push_back(shape_[i] - 1U); + } + + ArrayND result(sh); + const unsigned long rLen = result.length(); + for (unsigned long ilin = 0; ilin < rLen; ++ilin) { + result.convertLinearIndex(ilin, &sh[0], dim_); + + Accumulator deriv = Accumulator(); + for (unsigned long icycle = 0UL; icycle < maxcycle; ++icycle) { + unsigned long icell = 0UL; + unsigned n1 = 0U; + for (unsigned i = 0; i < dim_; ++i) { + if (icycle & (1UL << i)) { + ++n1; + icell += strides_[i] * (sh[i] + 1); + } else + icell += strides_[i] * sh[i]; } + if ((dim_ - n1) % 2U) + deriv -= data_[icell]; else - if (localData_[0] != zero) - return false; - return true; - } - - template - void ArrayND::convertLinearIndex( - unsigned long l, unsigned* idx, const unsigned idxLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling " - "method \"convertLinearIndex\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::convertLinearIndex method " - "can not be used with array of 0 rank"); - if (idxLen != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::convertLinearIndex: incompatible index length"); - if (l >= len_) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::convertLinearIndex: linear index out of range"); - assert(idx); - - for (unsigned i=0; i(deriv * scale); + } + + return result; + } + + template + template + Accumulator ArrayND::sumBelowLoop(const unsigned level, + unsigned long idx0, + const unsigned* limit) const { + Accumulator cdf = Accumulator(); + const unsigned imax = limit[level] + 1U; + if (level == dim_ - 1) { + Numeric* base = data_ + idx0; + for (unsigned i = 0; i < imax; ++i) + cdf += base[i]; + } else { + const unsigned long stride = strides_[level]; + for (unsigned i = 0; i < imax; ++i, idx0 += stride) + cdf += sumBelowLoop(level + 1, idx0, limit); + } + return cdf; + } + + template + template + Accumulator ArrayND::cdfValue(const unsigned* index, const unsigned indexLen) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"cdfValue\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::cdfValue method " + "can not be used with array of 0 rank"); + if (indexLen != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cdfValue: incompatible index length"); + for (unsigned i = 0; i < indexLen; ++i) + if (index[i] >= shape_[i]) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::cdfValue: index out of range"); + return sumBelowLoop(0, 0U, index); + } + + template + template + ArrayND ArrayND::cdfArray(const double inscale) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"cdfArray\""); + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::cdfArray method " + "can not be used with array of 0 rank"); + + const proper_double scale = inscale; + const unsigned maxdim = CHAR_BIT * sizeof(unsigned long); + if (dim_ >= maxdim) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cdfArray: array rank is too large"); + const unsigned long maxcycle = 1UL << dim_; + + ArrayShape sh; + sh.reserve(dim_); + for (unsigned i = 0; i < dim_; ++i) + sh.push_back(shape_[i] + 1U); + + ArrayND result(sh); + + unsigned* psh = &sh[0]; + const unsigned long len = result.length(); + for (unsigned long ipre = 0; ipre < len; ++ipre) { + result.convertLinearIndex(ipre, psh, dim_); + Accumulator deriv = Accumulator(); + bool has0 = false; + for (unsigned i = 0; i < dim_; ++i) + if (psh[i]-- == 0U) { + has0 = true; + break; } - } - - template - unsigned long ArrayND::linearIndex( - const unsigned* index, unsigned idxLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"linearIndex\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::linearIndex method " - "can not be used with array of 0 rank"); - if (idxLen != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::linearIndex: incompatible index length"); - assert(index); - - unsigned long idx = 0UL; - for (unsigned i=0; i= shape_[i]) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::linearIndex: index out of range"); - idx += index[i]*strides_[i]; + if (!has0) { + for (unsigned long icycle = 0UL; icycle < maxcycle; ++icycle) { + unsigned long icell = 0UL; + unsigned n1 = 0U; + for (unsigned i = 0; i < dim_; ++i) { + if (icycle & (1UL << i)) { + ++n1; + icell += result.strides_[i] * (psh[i] + 1); + } else + icell += result.strides_[i] * psh[i]; + } + if (n1 < dim_) { + if ((dim_ - n1) % 2U) + deriv += result.data_[icell]; + else + deriv -= result.data_[icell]; + } } - return idx; - } - - template - inline Numeric& ArrayND::value( - const unsigned *index, const unsigned dim) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"value\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::value: incompatible index length"); - if (dim) - { - assert(index); - unsigned long idx = 0UL; - for (unsigned i=0; i(value(psh, dim_) * scale); + } + result.data_[ipre] = deriv; + } + + // The "return" will convert Accumulator type into Numeric + return result; + } + + template + ArrayND ArrayND::transpose(const unsigned pos1, const unsigned pos2) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"transpose\""); + if (!(pos1 < dim_ && pos2 < dim_ && pos1 != pos2)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::transpose: " + "incompatible transposition indices"); + if (dim_ == 2) + return transpose(); + else { + // Construct the new shape + unsigned newshapeBuf[Dim]; + unsigned* newshape = makeBuffer(dim_, newshapeBuf, Dim); + copyBuffer(newshape, shape_, dim_); + std::swap(newshape[pos1], newshape[pos2]); + + // Form the result array + ArrayND result(newshape, dim_); + + // Fill the result array + transposeLoop(0, pos1, pos2, 0UL, 0UL, result); + + destroyBuffer(newshape, newshapeBuf); + return result; + } + } + + template + template + void ArrayND::multiMirror(ArrayND* out) const { + assert(out); + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"multiMirror\""); + if (!out->shapeIsKnown_) + *out = ArrayND(doubleShape(shape())); + if (dim_ != out->dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::multiMirror: incompatible argument array rank"); + + if (dim_) { + const unsigned* dshape = out->shape_; + for (unsigned i = 0; i < dim_; ++i) + if (dshape[i] != shape_[i] * 2U) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::multiMirror: " + "incompatible argument array shape"); + + if (dim_ >= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::multiMirror: " + "array rank is too large"); + const unsigned long maxcycle = 1UL << dim_; + std::vector indexbuf(dim_ * 2U); + unsigned* idx = &indexbuf[0]; + unsigned* mirror = idx + dim_; + + for (unsigned long ipt = 0; ipt < len_; ++ipt) { + unsigned long l = ipt; + for (unsigned i = 0; i < dim_; ++i) { + idx[i] = l / strides_[i]; + l -= (idx[i] * strides_[i]); } - else - return localData_[0]; - } - - template - inline const Numeric& ArrayND::value( - const unsigned *index, const unsigned dim) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"value\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::value: incompatible index length"); - if (dim) - { - assert(index); - unsigned long idx = 0UL; - for (unsigned i=0; ivalue(mirror, dim_) = data_[ipt]; } + } + } else + out->localData_[0] = static_cast(localData_[0]); + } + + template + template + void ArrayND::rotate(const unsigned* shifts, + const unsigned lenShifts, + ArrayND* rotated) const { + assert(rotated); + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"rotate\""); + // Can't rotate into itself -- it will be a mess + if ((void*)rotated == (void*)this) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::rotate: can not rotate array into itself"); + if (!rotated->shapeIsKnown_) + *rotated = *this; + if (dim_ != rotated->dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::rotate: incompatible argument array rank"); + if (lenShifts != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::rotate: incompatible dimensionality of shifts"); + + if (dim_) { + assert(shifts); + if (dim_ > CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::rotate: array rank is too large"); + unsigned buf[CHAR_BIT * sizeof(unsigned long)]; + clearBuffer(buf, dim_); + (const_cast(this)) + ->flatCircularLoop(0U, 0UL, 0UL, buf, shape_, shifts, *rotated, scast_assign_right()); + } else + rotated->localData_[0] = static_cast(localData_[0]); + } + + template + template + void ArrayND::dotProductLoop(const unsigned level, + unsigned long idx0, + unsigned long idx1, + unsigned long idx2, + const ArrayND& r, + ArrayND& result) const { + // idx0 -- this object + // idx1 -- dot product argument + // idx2 -- result + if (level == result.dim_) { + Numeric sum = Numeric(); + const unsigned imax = r.shape_[0]; + const unsigned rstride = r.strides_[0]; + const Numeric* l = data_ + idx0; + const Num2* ri = r.data_ + idx1; + for (unsigned i = 0; i < imax; ++i) + sum += l[i] * ri[i * rstride]; + result.data_[idx2] = sum; + } else { + const unsigned imax = result.shape_[level]; + for (unsigned i = 0; i < imax; ++i) { + dotProductLoop(level + 1, idx0, idx1, idx2, r, result); + idx2 += result.strides_[level]; + if (level < dim_ - 1) + idx0 += strides_[level]; else - return localData_[0]; - } - - template - inline Numeric& ArrayND::linearValue( - const unsigned long index) - { - return data_[index]; - } - - template - inline const Numeric& ArrayND::linearValue( - const unsigned long index) const - { - return data_[index]; - } - - template - inline Numeric& ArrayND::linearValueAt( - const unsigned long index) - { - if (index >= len_) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::linearValueAt: linear index out of range"); - return data_[index]; - } - - template - inline const Numeric& ArrayND::linearValueAt( - const unsigned long index) const - { - if (index >= len_) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::linearValueAt: linear index out of range"); - return data_[index]; - } - - template - inline unsigned ArrayND::coordToIndex( - const double x, const unsigned idim) const - { - if (x <= 0.0) - return 0; - else if (x >= static_cast(shape_[idim] - 1)) - return shape_[idim] - 1; - else - return static_cast(std::floor(x + 0.5)); - } - - template - inline const Numeric& ArrayND::closest( - const double *x, const unsigned dim) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"closest\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::closest: incompatible data length"); - if (dim) - { - assert(x); - unsigned long idx = 0UL; - for (unsigned i=0; i - inline Numeric& ArrayND::closest( - const double *x, const unsigned dim) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"closest\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::closest: incompatible data length"); - if (dim) - { - assert(x); - unsigned long idx = 0UL; - for (unsigned i=0; i - inline const Numeric& ArrayND::valueAt( - const unsigned *index, const unsigned dim) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"valueAt\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::valueAt: incompatible index length"); - if (dim) - { - assert(index); - unsigned long idx = 0UL; - for (unsigned i=0; i= shape_[i]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::valueAt: index out of range"); - idx += index[i]*strides_[i]; - } - return data_[idx]; - } - else - return localData_[0]; - } - - template - inline Numeric& ArrayND::valueAt( - const unsigned *index, const unsigned dim) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"valueAt\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::valueAt: incompatible index length"); - if (dim) - { - assert(index); - unsigned long idx = 0UL; - for (unsigned i=0; i= shape_[i]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::valueAt: index out of range"); - idx += index[i]*strides_[i]; - } - return data_[idx]; - } - else - return localData_[0]; - } - - template - inline Numeric& ArrayND::operator()() - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator()\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - inline const Numeric& ArrayND::operator()() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator()\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i) - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 1 array)"); - return data_[i]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i) const - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 1 array)"); - return data_[i]; - } - - template - const Numeric& ArrayND::at() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"at\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - Numeric& ArrayND::at() - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"at\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0) const - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 1 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 1)"); - return data_[i0]; - } - - template - Numeric& ArrayND::at( - const unsigned i0) - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 1 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 1)"); - return data_[i0]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1) - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 2 array)"); - return data_[i0*strides_[0] + i1]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1) const - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 2 array)"); - return data_[i0*strides_[0] + i1]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1) const - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 2 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 2)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 2)"); - return data_[i0*strides_[0] + i1]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1) - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 2 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 2)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 2)"); - return data_[i0*strides_[0] + i1]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2) const - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 3 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3) const - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 4 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + i3]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4) const - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 5 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5) const - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 6 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6) const - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 7 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + i6]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7) const - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 8 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8) const - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 9 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8]; - } - - template - inline const Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9) const - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 10 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8*strides_[8] + i9]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2) - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 3 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3) - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 4 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + i3]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4) - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 5 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5) - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 6 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6) - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 7 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + i6]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7) - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 8 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8) - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 9 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8]; - } - - template - inline Numeric& ArrayND::operator()( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9) - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator(): wrong # of args (not rank 10 array)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8*strides_[8] + i9]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2) const - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 3 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 3)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 3)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 3)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3) const - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 4 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 4)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 4)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 4)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 4)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + i3]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4) const - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 5 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 5)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 5)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 5)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 5)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 5)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5) const - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 6 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 6)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 6)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 6)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 6)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 6)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 6)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6) const - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 7 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 7)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 7)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 7)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 7)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 7)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 7)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 7)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + i6]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7) const - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 8 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 8)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 8)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 8)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 8)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 8)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 8)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 8)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 8)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8) const - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 9 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 9)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 9)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 9)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 9)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 9)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 9)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 9)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 9)"); - if (i8 >= shape_[8]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 8 out of range (rank 9)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8]; - } - - template - const Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9) const - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 10 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 10)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 10)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 10)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 10)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 10)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 10)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 10)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 10)"); - if (i8 >= shape_[8]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 8 out of range (rank 10)"); - if (i9 >= shape_[9]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 9 out of range (rank 10)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8*strides_[8] + i9]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2) - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 3 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 3)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 3)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 3)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3) - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 4 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 4)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 4)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 4)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 4)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + i3]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4) - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 5 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 5)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 5)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 5)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 5)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 5)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5) - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 6 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 6)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 6)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 6)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 6)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 6)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 6)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6) - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 7 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 7)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 7)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 7)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 7)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 7)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 7)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 7)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + i6]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7) - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 8 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 8)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 8)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 8)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 8)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 8)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 8)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 8)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 8)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8) - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 9 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 9)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 9)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 9)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 9)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 9)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 9)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 9)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 9)"); - if (i8 >= shape_[8]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 8 out of range (rank 9)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8]; - } - - template - Numeric& ArrayND::at( - const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9) - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::at: wrong # of args (not rank 10 array)"); - if (i0 >= shape_[0]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 0 out of range (rank 10)"); - if (i1 >= shape_[1]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 1 out of range (rank 10)"); - if (i2 >= shape_[2]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 2 out of range (rank 10)"); - if (i3 >= shape_[3]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 3 out of range (rank 10)"); - if (i4 >= shape_[4]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 4 out of range (rank 10)"); - if (i5 >= shape_[5]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 5 out of range (rank 10)"); - if (i6 >= shape_[6]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 6 out of range (rank 10)"); - if (i7 >= shape_[7]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 7 out of range (rank 10)"); - if (i8 >= shape_[8]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 8 out of range (rank 10)"); - if (i9 >= shape_[9]) throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::at: index 9 out of range (rank 10)"); - return data_[i0*strides_[0] + i1*strides_[1] + i2*strides_[2] + - i3*strides_[3] + i4*strides_[4] + i5*strides_[5] + - i6*strides_[6] + i7*strides_[7] + i8*strides_[8] + i9]; - } - - template - template - double ArrayND::maxAbsDifference( - const ArrayND& r) const - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::maxAbsDifference: " - "incompatible argument array shape"); - if (dim_) - { - double maxd = 0.0; - for (unsigned long i=0; i maxd) - maxd = d; - } - return maxd; - } - else - { - const Numeric rval = r.localData_[0]; - return absDifference(localData_[0], rval); - } - } - - template - template - bool ArrayND::operator==( - const ArrayND& r) const - { - if (shapeIsKnown_ != r.shapeIsKnown_) - return false; - if (r.dim_ != dim_) - return false; - if (r.len_ != len_) - return false; - for (unsigned i=0; i - template - inline bool ArrayND::operator!=( - const ArrayND& r) const - { - return !(*this == r); - } - - template - template - ArrayND - ArrayND::operator*(const Num2& r) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator*\""); - ArrayND result(shape_, dim_); - for (unsigned long i=0; i - template - ArrayND - ArrayND::operator/(const Num2& r) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator/\""); - if (r == Num2()) throw npstat::NpstatRuntimeError( - "In npstat::ArrayND::operator/: division by zero"); - ArrayND result(shape_, dim_); - for (unsigned long i=0; i - template - ArrayND - ArrayND::operator+( - const ArrayND& r) const - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator+: " - "incompatible argument array shape"); - ArrayND result(shape_, dim_); - for (unsigned long i=0; i - template - ArrayND - ArrayND::operator-( - const ArrayND& r) const - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator-: " - "incompatible argument array shape"); - ArrayND result(shape_, dim_); - for (unsigned long i=0; i - inline ArrayND ArrayND::operator+() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator+\""); - return *this; - } - - template - ArrayND ArrayND::operator-() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator-\""); - ArrayND result(shape_, dim_); - for (unsigned long i=0; i - template - ArrayND& - ArrayND::operator*=(const Num2& r) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator*=\""); - for (unsigned long i=0; i - ArrayND& - ArrayND::makeNonNegative() - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"makeNonNegative\""); - const Numeric zero = Numeric(); - if (dim_) - { - for (unsigned long i=0; i::more(data_[i], zero))) - data_[i] = zero; - } - else - if (!(ComplexComparesAbs::more(localData_[0], zero))) - localData_[0] = zero; - return *this; - } - - template - unsigned ArrayND::makeCopulaSteps( - const double tolerance, const unsigned nCycles) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"makeCopulaSteps\""); - if (nCycles == 0U) - return 0U; - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::makeCopulaSteps method " - "can not be used with array of 0 rank"); - - const Numeric zero = Numeric(); - for (unsigned long i=0; i::more(data_[i], zero))) - data_[i] = zero; - - std::vector axesPtrBuf(dim_); - Numeric** axes = &axesPtrBuf[0]; - const Numeric one = static_cast(1); - - // Memory for the axis accumulators - unsigned idxSum = 0; - for (unsigned i=0; i axesBuf(idxSum); - axes[0] = &axesBuf[0]; - for (unsigned i=1; i(amax); - for (unsigned a=0; a tolerance) - withinTolerance = false; - } - } - - if (withinTolerance) - break; - - const Numeric totalAverage = totalSum/ - static_cast(len_)/static_cast(dim_); - - // Run over all points again and divide by - // the product of marginals - for (unsigned long idat=0; idat - template - ArrayND& - ArrayND::operator/=(const Num2& r) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"operator/=\""); - if (r == Num2()) throw npstat::NpstatRuntimeError( - "In npstat::ArrayND::operator/=: division by zero"); - for (unsigned long i=0; i - template - ArrayND& - ArrayND::operator+=(const ArrayND& r) - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator+=: " - "incompatible argument array shape"); - for (unsigned long i=0; i - template - ArrayND& - ArrayND::addmul(const ArrayND& r, - const Num3& c) - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::addmul: " - "incompatible argument array shape"); - for (unsigned long i=0; i - template - ArrayND& - ArrayND::operator-=(const ArrayND& r) - { - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::operator-=: " - "incompatible argument array shape"); - for (unsigned long i=0; i - Numeric ArrayND::interpolate1( - const double *coords, const unsigned dim) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"interpolate1\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::interpolate1: incompatible coordinate length"); - if (dim) - { - const unsigned maxdim = CHAR_BIT*sizeof(unsigned long); - if (dim_ >= maxdim) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::interpolate1: array rank is too large"); - - double dx[maxdim]; - unsigned ix[maxdim]; - for (unsigned i=0; i= static_cast(shape_[i] - 1)) - { - ix[i] = shape_[i] - 1; - dx[i] = 0.0; - } - else - { - ix[i] = static_cast(std::floor(x)); - dx[i] = x - ix[i]; - } - } - - Numeric sum = Numeric(); - const unsigned long maxcycle = 1UL << dim; - for (unsigned long icycle=0UL; icycle 0.0) - sum += data_[icell]*static_cast(w); - } - return sum; - } - else - return localData_[0]; - } - - template - Numeric ArrayND::interpolateLoop( - const unsigned level, const double* coords, const Numeric* base) const - { - const unsigned npoints = shape_[level]; - const double x = coords[level]; - - unsigned ix, npt = 1; - double dx = 0.0; - if (x < 0.0) - ix = 0; - else if (x > static_cast(npoints - 1)) - ix = npoints - 1; - else - { - ix = static_cast(std::floor(x)); - if (ix) --ix; - unsigned imax = ix + 3; - while (imax >= npoints) - { - if (ix) --ix; - --imax; - } - dx = x - ix; - npt = imax + 1 - ix; - } - assert(npt >= 1 && npt <= 4); - - Numeric fit[4]; - if (level < dim_ - 1) - for (unsigned ipt=0; ipt - inline Numeric ArrayND::interpolate3( - const double* coords, const unsigned dim) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"interpolate3\""); - if (dim != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::interpolate3: incompatible coordinate length"); - if (dim) - { - assert(coords); - return interpolateLoop(0, coords, data_); - } - else - return localData_[0]; - } - - template - template - ArrayND& ArrayND::apply(Functor f) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"apply\""); - for (unsigned long i=0; i(f(data_[i])); - return *this; - } - - template - template - ArrayND& ArrayND::scanInPlace( - Functor f) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"scanInPlace\""); - for (unsigned long i=0; i - ArrayND& ArrayND::constFill( - const Numeric c) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"constFill\""); - for (unsigned long i=0; i - inline ArrayND& ArrayND::clear() - { - return constFill(Numeric()); - } - - template - ArrayND& ArrayND::uninitialize() - { - destroyBuffer(data_, localData_); - destroyBuffer(strides_, localStrides_); - destroyBuffer(shape_, localShape_); - localData_[0] = Numeric(); - data_ = localData_; - strides_ = nullptr; - shape_ = nullptr; - len_ = 0; - dim_ = 0; - shapeIsKnown_ = false; - return *this; - } - - template - ArrayND& ArrayND::makeUnit() - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"makeUnit\""); - if (dim_ < 2) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::makeUnit method " - "can not be used with arrays of rank less than 2"); - constFill(Numeric()); - unsigned long stride = 0UL; - const unsigned dimlen = shape_[0]; - for (unsigned i=0; i(1)); - for (unsigned i=0; i - void ArrayND::linearFillLoop( - const unsigned level, const double s0, const unsigned long idx, - const double shift, const double* coeffs) - { - const unsigned imax = shape_[level]; - const double c = coeffs[level]; - if (level == dim_ - 1) - { - Numeric* d = &data_[idx]; - for (unsigned i=0; i(sum); - } - } - else - { - const unsigned long stride = strides_[level]; - for (unsigned i=0; i - ArrayND& ArrayND::linearFill( - const double* coeffs, const unsigned dimCoeffs, const double shift) - { - // Make sure the object has been initialized - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"linearFill\""); - if (dim_ != dimCoeffs) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::linearFill: incompatible number of coefficients"); - if (dim_) - { - assert(coeffs); - linearFillLoop(0U, 0.0, 0UL, shift, coeffs); - } - else - localData_[0] = static_cast(shift); - return *this; - } - - template - template - void ArrayND::functorFillLoop( - const unsigned level, const unsigned long idx, - Functor f, unsigned* farg) - { - const unsigned imax = shape_[level]; - if (level == dim_ - 1) - { - Numeric* d = &data_[idx]; - const unsigned* myarg = farg; - for (unsigned i = 0; i(f(myarg, dim_)); - } - } - else - { - const unsigned long stride = strides_[level]; - for (unsigned i = 0; i - template - void ArrayND::convertToLastDimCdfLoop( - ArrayND* sumSlice, const unsigned level, unsigned long idx0, - unsigned long idxSlice, const bool useTrapezoids) - { - static const proper_double half = 0.5; - const unsigned imax = shape_[level]; - if (level == dim_ - 1) - { - Accumulator acc = Accumulator(); - Numeric* data = data_ + idx0; - if (useTrapezoids) - { - Numeric oldval = Numeric(); - for (unsigned i = 0; i(acc); - } - acc += oldval*half; - } - else - for (unsigned i = 0; i(acc); - } - if (sumSlice->dim_) - sumSlice->data_[idxSlice] = static_cast(acc); - else - sumSlice->localData_[0] = static_cast(acc); - } - else - { - const unsigned long stride = strides_[level]; - unsigned long sumStride = 0UL; - if (sumSlice->dim_) - sumStride = sumSlice->strides_[level]; - for (unsigned i = 0; i( - sumSlice, level+1, idx0, idxSlice, useTrapezoids); - idx0 += stride; - idxSlice += sumStride; - } - } - } - - template - template - inline void ArrayND::convertToLastDimCdf( - ArrayND* sumSlice, const bool useTrapezoids) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling " - "method \"convertToLastDimCdf\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::convertToLastDimCdf method " - "can not be used with array of 0 rank"); - assert(sumSlice); - if (!sumSlice->shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::convertToLastDimCdf: " - "uninitialized argument array"); - convertToLastDimCdfLoop(sumSlice, 0U, 0UL, 0UL, - useTrapezoids); - } - - template - template - ArrayND& ArrayND::functorFill(Functor f) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"functorFill\""); - if (dim_) - { - unsigned localIndex[Dim]; - unsigned* index = makeBuffer(dim_, localIndex, Dim); - functorFillLoop(0U, 0UL, f, index); - destroyBuffer(index, localIndex); - } - else - localData_[0] = static_cast( - f(static_cast(nullptr), 0U)); - return *this; - } - - template - template - bool ArrayND::isClose( - const ArrayND& r, const double eps) const - { - if (eps < 0.0) throw npstat::NpstatDomainError( - "In npstat::ArrayND::isClose: tolerance must not be negative"); - if (!isShapeCompatible(r)) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::isClose: incompatible argument array shape"); - if (dim_) - { - for (unsigned long i=0; i(absDifference(data_[i], rval)) > eps) - return false; - } - } - else - { - const Numeric rval = r.localData_[0]; - if (static_cast(absDifference(localData_[0], rval)) > eps) - return false; - } - return true; - } - - template - template - ArrayND ArrayND::outer( - const ArrayND& r) const - { - return ArrayND(*this, r); - } - - template - void ArrayND::contractLoop( - unsigned thisLevel, const unsigned resLevel, - const unsigned pos1, const unsigned pos2, - unsigned long idxThis, unsigned long idxRes, ArrayND& result) const - { - while (thisLevel == pos1 || thisLevel == pos2) - ++thisLevel; - assert(thisLevel < dim_); - - if (resLevel == result.dim_ - 1) - { - const unsigned ncontract = shape_[pos1]; - const unsigned imax = result.shape_[resLevel]; - const unsigned long stride = strides_[pos1] + strides_[pos2]; - for (unsigned i=0; i - ArrayND ArrayND::contract( - const unsigned pos1, const unsigned pos2) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"contract\""); - if (!(pos1 < dim_ && pos2 < dim_ && pos1 != pos2)) - throw npstat::NpstatInvalidArgument("In npstat::ArrayND::contract: " - "incompatible contraction indices"); - if (shape_[pos1] != shape_[pos2]) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::contract: incompatible " - "length of contracted dimensions"); - - // Construct the new shape - unsigned newshapeBuf[Dim]; - unsigned* newshape = makeBuffer(dim_ - 2, newshapeBuf, Dim); - unsigned ishap = 0; - for (unsigned i=0; i result(newshape, ishap); - if (ishap) - contractLoop(0, 0, pos1, pos2, 0UL, 0UL, result); - else - { - // We are just calculating the trace - Numeric sum = Numeric(); - const unsigned imax = shape_[0]; - const unsigned long stride = strides_[0] + strides_[1]; - for (unsigned i=0; i - void ArrayND::transposeLoop( - const unsigned level, const unsigned pos1, const unsigned pos2, - unsigned long idxThis, unsigned long idxRes, ArrayND& result) const - { - const unsigned imax = shape_[level]; - const unsigned long mystride = strides_[level]; - const unsigned relevel = level == pos1 ? pos2 : - (level == pos2 ? pos1 : level); - const unsigned long restride = result.strides_[relevel]; - const bool ready = (level == dim_ - 1); - for (unsigned i=0; i - template - Num2 ArrayND::sum() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"sum\""); - Num2 sum = Num2(); - for (unsigned long i=0; i - template - Num2 ArrayND::sumsq() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"sumsq\""); - Num2 sum = Num2(); - for (unsigned long i=0; i - Numeric ArrayND::min() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"min\""); - if (dim_) - { - Numeric minval(data_[0]); - for (unsigned long i=1UL; i::less(data_[i], minval)) - minval = data_[i]; - return minval; - } - else - return localData_[0]; - } - - template - Numeric ArrayND::min( - unsigned *index, const unsigned indexLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"min\""); - if (indexLen != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::min: incompatible index length"); - if (dim_) - { - unsigned long minind = 0UL; - Numeric minval(data_[0]); - for (unsigned long i=1UL; i::less(data_[i], minval)) - { - minval = data_[i]; - minind = i; - } - convertLinearIndex(minind, index, indexLen); - return minval; - } - else - return localData_[0]; - } - - template - Numeric ArrayND::max() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"max\""); - if (dim_) - { - Numeric maxval(data_[0]); - for (unsigned long i=1UL; i::less(maxval, data_[i])) - maxval = data_[i]; - return maxval; - } - else - return localData_[0]; - } - - template - Numeric ArrayND::max( - unsigned *index, const unsigned indexLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"max\""); - if (indexLen != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::max: incompatible index length"); - if (dim_) - { - unsigned long maxind = 0UL; - Numeric maxval(data_[0]); - for (unsigned long i=1UL; i::less(maxval, data_[i])) - { - maxval = data_[i]; - maxind = i; - } - convertLinearIndex(maxind, index, indexLen); - return maxval; - } - else - return localData_[0]; - } - - // Faster function for 2d transpose - template - ArrayND ArrayND::transpose() const - { - if (dim_ != 2) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::transpose method " - "can not be used with arrays of rank other than 2"); - unsigned newshape[2]; - newshape[0] = shape_[1]; - newshape[1] = shape_[0]; - ArrayND result(newshape, dim_); - const unsigned imax = shape_[0]; - const unsigned jmax = shape_[1]; - for (unsigned i=0; i - template - ArrayND ArrayND::derivative( - const double inscale) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"derivative\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::derivative method " - "can not be used with array of 0 rank"); - - const typename ProperDblFromCmpl::type scale = inscale; - const unsigned maxdim = CHAR_BIT*sizeof(unsigned long); - if (dim_ >= maxdim) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::derivative: array rank is too large"); - const unsigned long maxcycle = 1UL << dim_; - - ArrayShape sh; - sh.reserve(dim_); - for (unsigned i=0; i(deriv*scale); - } - - return result; - } - - template - template - Accumulator ArrayND::sumBelowLoop( - const unsigned level, unsigned long idx0, - const unsigned* limit) const - { - Accumulator cdf = Accumulator(); - const unsigned imax = limit[level] + 1U; - if (level == dim_ - 1) - { - Numeric* base = data_ + idx0; - for (unsigned i=0; i(level+1, idx0, limit); - } - return cdf; - } - - template - template - Accumulator ArrayND::cdfValue( - const unsigned *index, const unsigned indexLen) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"cdfValue\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::cdfValue method " - "can not be used with array of 0 rank"); - if (indexLen != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cdfValue: incompatible index length"); - for (unsigned i=0; i= shape_[i]) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::cdfValue: index out of range"); - return sumBelowLoop(0, 0U, index); - } - - template - template - ArrayND ArrayND::cdfArray( - const double inscale) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"cdfArray\""); - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::cdfArray method " - "can not be used with array of 0 rank"); - - const proper_double scale = inscale; - const unsigned maxdim = CHAR_BIT*sizeof(unsigned long); - if (dim_ >= maxdim) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cdfArray: array rank is too large"); - const unsigned long maxcycle = 1UL << dim_; - - ArrayShape sh; - sh.reserve(dim_); - for (unsigned i=0; i result(sh); - - unsigned* psh = &sh[0]; - const unsigned long len = result.length(); - for (unsigned long ipre=0; ipre(value(psh, dim_)*scale); - } - result.data_[ipre] = deriv; - } - - // The "return" will convert Accumulator type into Numeric - return result; - } - - template - ArrayND ArrayND::transpose( - const unsigned pos1, const unsigned pos2) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"transpose\""); - if (!(pos1 < dim_ && pos2 < dim_ && pos1 != pos2)) - throw npstat::NpstatInvalidArgument("In npstat::ArrayND::transpose: " - "incompatible transposition indices"); - if (dim_ == 2) - return transpose(); - else - { - // Construct the new shape - unsigned newshapeBuf[Dim]; - unsigned *newshape = makeBuffer(dim_, newshapeBuf, Dim); - copyBuffer(newshape, shape_, dim_); - std::swap(newshape[pos1], newshape[pos2]); - - // Form the result array - ArrayND result(newshape, dim_); - - // Fill the result array - transposeLoop(0, pos1, pos2, 0UL, 0UL, result); - - destroyBuffer(newshape, newshapeBuf); - return result; - } - } - - template - template - void ArrayND::multiMirror( - ArrayND* out) const - { - assert(out); - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"multiMirror\""); - if (!out->shapeIsKnown_) - *out = ArrayND(doubleShape(shape())); - if (dim_ != out->dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::multiMirror: incompatible argument array rank"); - - if (dim_) - { - const unsigned *dshape = out->shape_; - for (unsigned i=0; i= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::multiMirror: " - "array rank is too large"); - const unsigned long maxcycle = 1UL << dim_; - std::vector indexbuf(dim_*2U); - unsigned* idx = &indexbuf[0]; - unsigned* mirror = idx + dim_; - - for (unsigned long ipt=0; iptvalue(mirror, dim_) = data_[ipt]; - } - } - } - else - out->localData_[0] = static_cast(localData_[0]); - } - - template - template - void ArrayND::rotate( - const unsigned* shifts, const unsigned lenShifts, - ArrayND* rotated) const - { - assert(rotated); - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"rotate\""); - // Can't rotate into itself -- it will be a mess - if ((void*)rotated == (void*)this) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::rotate: can not rotate array into itself"); - if (!rotated->shapeIsKnown_) - *rotated = *this; - if (dim_ != rotated->dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::rotate: incompatible argument array rank"); - if (lenShifts != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::rotate: incompatible dimensionality of shifts"); - - if (dim_) - { - assert(shifts); - if (dim_ > CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::rotate: array rank is too large"); - unsigned buf[CHAR_BIT*sizeof(unsigned long)]; - clearBuffer(buf, dim_); - (const_cast(this))->flatCircularLoop( - 0U, 0UL, 0UL, buf, shape_, shifts, - *rotated, scast_assign_right()); - } - else - rotated->localData_[0] = static_cast(localData_[0]); - } - - template - template - void ArrayND::dotProductLoop( - const unsigned level, unsigned long idx0, - unsigned long idx1, unsigned long idx2, - const ArrayND& r, - ArrayND& result) const - { - // idx0 -- this object - // idx1 -- dot product argument - // idx2 -- result - if (level == result.dim_) - { - Numeric sum = Numeric(); - const unsigned imax = r.shape_[0]; - const unsigned rstride = r.strides_[0]; - const Numeric* l = data_ + idx0; - const Num2* ri = r.data_ + idx1; - for (unsigned i=0; i - template - ArrayND ArrayND::dot( - const ArrayND& r) const - { - if (!dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::dot method " - "can not be used with array of 0 rank"); - if (!r.dim_) throw npstat::NpstatInvalidArgument( - "npstat::ArrayND::dot method " - "can not be used with argument array of 0 rank"); - if (shape_[dim_ - 1] != r.shape_[0]) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::dot: incompatible argument array shape"); - - if (dim_ == 1 && r.dim_ == 1) - { - // Special case: the result is of 0 rank - ArrayND result(static_cast(nullptr), 0U); - Numeric sum = Numeric(); - const unsigned imax = shape_[0]; - for (unsigned i=0; i result(newshape, dim_+r.dim_-2); - - dotProductLoop(0U, 0UL, 0UL, 0UL, r, result); - - destroyBuffer(newshape, newshapeBuf); - return result; - } - } - - template - inline unsigned ArrayND::span(const unsigned dim) const - { - if (dim >= dim_) - throw npstat::NpstatOutOfRange( - "In npstat::ArrayND::span: dimension number is out of range"); - return shape_[dim]; - } - - template - unsigned ArrayND::maximumSpan() const - { - unsigned maxspan = 0; - for (unsigned i=0; i maxspan) - maxspan = shape_[i]; - return maxspan; - } - - template - unsigned ArrayND::minimumSpan() const - { - if (dim_ == 0) - return 0U; - unsigned minspan = shape_[0]; - for (unsigned i=1; i - inline const Numeric& ArrayND::cl() const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"cl\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0) const - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 1 array)"); - return data_[coordToIndex(i0, 0)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1) const - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 2 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2) const - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 3 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3) const - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 4 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4) const - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 5 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5) const - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 6 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6) const - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 7 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7) const - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 8 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7, - const double i8) const - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 9 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)*strides_[7] + - coordToIndex(i8, 8)]; - } - - template - inline const Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7, - const double i8, - const double i9) const - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 10 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)*strides_[7] + - coordToIndex(i8, 8)*strides_[8] + - coordToIndex(i9, 9)]; - } - - template - inline Numeric& ArrayND::cl() - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"cl\""); - if (dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 0 array)"); - return localData_[0]; - } - - template - inline Numeric& ArrayND::cl( - const double i0) - { - if (1U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 1 array)"); - return data_[coordToIndex(i0, 0)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1) - { - if (2U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 2 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2) - { - if (3U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 3 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3) - { - if (4U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 4 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4) - { - if (5U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 5 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5) - { - if (6U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 6 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6) - { - if (7U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 7 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7) - { - if (8U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 8 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7, - const double i8) - { - if (9U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 9 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)*strides_[7] + - coordToIndex(i8, 8)]; - } - - template - inline Numeric& ArrayND::cl( - const double i0, - const double i1, - const double i2, - const double i3, - const double i4, - const double i5, - const double i6, - const double i7, - const double i8, - const double i9) - { - if (10U != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::cl: wrong # of args (not rank 10 array)"); - return data_[coordToIndex(i0, 0)*strides_[0] + - coordToIndex(i1, 1)*strides_[1] + - coordToIndex(i2, 2)*strides_[2] + - coordToIndex(i3, 3)*strides_[3] + - coordToIndex(i4, 4)*strides_[4] + - coordToIndex(i5, 5)*strides_[5] + - coordToIndex(i6, 6)*strides_[6] + - coordToIndex(i7, 7)*strides_[7] + - coordToIndex(i8, 8)*strides_[8] + - coordToIndex(i9, 9)]; - } - - template - const char* ArrayND::classname() - { - static const std::string name( - gs::template_class_name("npstat::ArrayND")); - return name.c_str(); - } - - template - bool ArrayND::write(std::ostream& os) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"write\""); - gs::write_pod_vector(os, shape()); - return !os.fail() && - (dim_ ? gs::write_array(os, data_, len_) : - gs::write_item(os, localData_[0], false)); - } - - template - void ArrayND::restore( - const gs::ClassId& id, std::istream& in, ArrayND* array) - { - static const gs::ClassId current(gs::ClassId::makeId >()); - current.ensureSameId(id); - - ArrayShape rshape; - gs::read_pod_vector(in, &rshape); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::ArrayND::restore: input stream failure (checkpoint 0)"); - - assert(array); - array->uninitialize(); - array->dim_ = rshape.size(); - array->shapeIsKnown_ = true; - array->len_ = 1UL; - if (array->dim_) - { - array->shape_ = makeBuffer(array->dim_, array->localShape_, Dim); - for (unsigned i=0; idim_; ++i) - { - array->shape_[i] = rshape[i]; - assert(array->shape_[i]); - array->len_ *= array->shape_[i]; - } - array->buildStrides(); - array->data_ = makeBuffer(array->len_, array->localData_, Len); - gs::read_array(in, array->data_, array->len_); - } - else - gs::restore_item(in, array->localData_, false); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::ArrayND::restore: input stream failure (checkpoint 1)"); - } - - template - template - void ArrayND::exportSubrange( - const unsigned* corner, const unsigned lenCorner, - ArrayND* out) const - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"exportSubrange\""); - if (dim_ != lenCorner) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::exportSubrange: incompatible corner index length"); - assert(out); - if (!out->shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::exportSubrange: uninitialized argument array"); - if (out->dim_ != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::exportSubrange: incompatible argument array rank"); - - if (dim_) - { - assert(corner); - if (dim_ > CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::exportSubrange: " - "array rank is too large"); - unsigned toBuf[CHAR_BIT*sizeof(unsigned long)]; - clearBuffer(toBuf, dim_); - (const_cast(this))->commonSubrangeLoop( - 0U, 0UL, 0UL, corner, out->shape_, toBuf, *out, - scast_assign_right()); - } - else - out->localData_[0] = static_cast(localData_[0]); - } - - template - template - void ArrayND::importSubrange( - const unsigned* corner, const unsigned lenCorner, - const ArrayND& from) - { - if (!shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "Initialize npstat::ArrayND before calling method \"importSubrange\""); - if (dim_ != lenCorner) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::importSubrange: incompatible corner index length"); - if (!from.shapeIsKnown_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::importSubrange: uninitialized argument array"); - if (from.dim_ != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::importSubrange: incompatible argument array rank"); - - if (dim_) - { - assert(corner); - if (dim_ > CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayND::importSubrange: " - "array rank is too large"); - unsigned toBuf[CHAR_BIT*sizeof(unsigned long)]; - clearBuffer(toBuf, dim_); - commonSubrangeLoop(0U, 0UL, 0UL, corner, from.shape_, toBuf, - const_cast&>(from), - scast_assign_left()); - } - else - localData_[0] = static_cast(from.localData_[0]); - } -} - - -#endif // NPSTAT_ARRAYND_HH_ - + idx1 += r.strides_[level + 2 - dim_]; + } + } + } + + template + template + ArrayND ArrayND::dot(const ArrayND& r) const { + if (!dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::dot method " + "can not be used with array of 0 rank"); + if (!r.dim_) + throw npstat::NpstatInvalidArgument( + "npstat::ArrayND::dot method " + "can not be used with argument array of 0 rank"); + if (shape_[dim_ - 1] != r.shape_[0]) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::dot: incompatible argument array shape"); + + if (dim_ == 1 && r.dim_ == 1) { + // Special case: the result is of 0 rank + ArrayND result(static_cast(nullptr), 0U); + Numeric sum = Numeric(); + const unsigned imax = shape_[0]; + for (unsigned i = 0; i < imax; ++i) + sum += data_[i] * r.data_[i]; + result() = sum; + return result; + } else { + unsigned newshapeBuf[2 * Dim]; + unsigned* newshape = makeBuffer(dim_ + r.dim_ - 2, newshapeBuf, 2 * Dim); + copyBuffer(newshape, shape_, dim_ - 1); + copyBuffer(newshape + (dim_ - 1), r.shape_ + 1, r.dim_ - 1); + ArrayND result(newshape, dim_ + r.dim_ - 2); + + dotProductLoop(0U, 0UL, 0UL, 0UL, r, result); + + destroyBuffer(newshape, newshapeBuf); + return result; + } + } + + template + inline unsigned ArrayND::span(const unsigned dim) const { + if (dim >= dim_) + throw npstat::NpstatOutOfRange("In npstat::ArrayND::span: dimension number is out of range"); + return shape_[dim]; + } + + template + unsigned ArrayND::maximumSpan() const { + unsigned maxspan = 0; + for (unsigned i = 0; i < dim_; ++i) + if (shape_[i] > maxspan) + maxspan = shape_[i]; + return maxspan; + } + + template + unsigned ArrayND::minimumSpan() const { + if (dim_ == 0) + return 0U; + unsigned minspan = shape_[0]; + for (unsigned i = 1; i < dim_; ++i) + if (shape_[i] < minspan) + minspan = shape_[i]; + return minspan; + } + + template + inline const Numeric& ArrayND::cl() const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"cl\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + inline const Numeric& ArrayND::cl(const double i0) const { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 1 array)"); + return data_[coordToIndex(i0, 0)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, const double i1) const { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 2 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, const double i1, const double i2) const { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 3 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + coordToIndex(i2, 2)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3) const { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 4 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3)]; + } + + template + inline const Numeric& ArrayND::cl( + const double i0, const double i1, const double i2, const double i3, const double i4) const { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 5 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + coordToIndex(i4, 4)]; + } + + template + inline const Numeric& ArrayND::cl( + const double i0, const double i1, const double i2, const double i3, const double i4, const double i5) const { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 6 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6) const { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 7 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + coordToIndex(i6, 6)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7) const { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 8 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7, + const double i8) const { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 9 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7) * strides_[7] + coordToIndex(i8, 8)]; + } + + template + inline const Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7, + const double i8, + const double i9) const { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 10 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7) * strides_[7] + + coordToIndex(i8, 8) * strides_[8] + coordToIndex(i9, 9)]; + } + + template + inline Numeric& ArrayND::cl() { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"cl\""); + if (dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 0 array)"); + return localData_[0]; + } + + template + inline Numeric& ArrayND::cl(const double i0) { + if (1U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 1 array)"); + return data_[coordToIndex(i0, 0)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, const double i1) { + if (2U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 2 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, const double i1, const double i2) { + if (3U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 3 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + coordToIndex(i2, 2)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, const double i1, const double i2, const double i3) { + if (4U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 4 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3)]; + } + + template + inline Numeric& ArrayND::cl( + const double i0, const double i1, const double i2, const double i3, const double i4) { + if (5U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 5 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + coordToIndex(i4, 4)]; + } + + template + inline Numeric& ArrayND::cl( + const double i0, const double i1, const double i2, const double i3, const double i4, const double i5) { + if (6U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 6 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6) { + if (7U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 7 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + coordToIndex(i6, 6)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7) { + if (8U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 8 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7, + const double i8) { + if (9U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 9 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7) * strides_[7] + coordToIndex(i8, 8)]; + } + + template + inline Numeric& ArrayND::cl(const double i0, + const double i1, + const double i2, + const double i3, + const double i4, + const double i5, + const double i6, + const double i7, + const double i8, + const double i9) { + if (10U != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::cl: wrong # of args (not rank 10 array)"); + return data_[coordToIndex(i0, 0) * strides_[0] + coordToIndex(i1, 1) * strides_[1] + + coordToIndex(i2, 2) * strides_[2] + coordToIndex(i3, 3) * strides_[3] + + coordToIndex(i4, 4) * strides_[4] + coordToIndex(i5, 5) * strides_[5] + + coordToIndex(i6, 6) * strides_[6] + coordToIndex(i7, 7) * strides_[7] + + coordToIndex(i8, 8) * strides_[8] + coordToIndex(i9, 9)]; + } + + template + const char* ArrayND::classname() { + static const std::string name(gs::template_class_name("npstat::ArrayND")); + return name.c_str(); + } + + template + bool ArrayND::write(std::ostream& os) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"write\""); + gs::write_pod_vector(os, shape()); + return !os.fail() && (dim_ ? gs::write_array(os, data_, len_) : gs::write_item(os, localData_[0], false)); + } + + template + void ArrayND::restore(const gs::ClassId& id, std::istream& in, ArrayND* array) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + ArrayShape rshape; + gs::read_pod_vector(in, &rshape); + if (in.fail()) + throw gs::IOReadFailure("In npstat::ArrayND::restore: input stream failure (checkpoint 0)"); + + assert(array); + array->uninitialize(); + array->dim_ = rshape.size(); + array->shapeIsKnown_ = true; + array->len_ = 1UL; + if (array->dim_) { + array->shape_ = makeBuffer(array->dim_, array->localShape_, Dim); + for (unsigned i = 0; i < array->dim_; ++i) { + array->shape_[i] = rshape[i]; + assert(array->shape_[i]); + array->len_ *= array->shape_[i]; + } + array->buildStrides(); + array->data_ = makeBuffer(array->len_, array->localData_, Len); + gs::read_array(in, array->data_, array->len_); + } else + gs::restore_item(in, array->localData_, false); + if (in.fail()) + throw gs::IOReadFailure("In npstat::ArrayND::restore: input stream failure (checkpoint 1)"); + } + + template + template + void ArrayND::exportSubrange(const unsigned* corner, + const unsigned lenCorner, + ArrayND* out) const { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"exportSubrange\""); + if (dim_ != lenCorner) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::exportSubrange: incompatible corner index length"); + assert(out); + if (!out->shapeIsKnown_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::exportSubrange: uninitialized argument array"); + if (out->dim_ != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::exportSubrange: incompatible argument array rank"); + + if (dim_) { + assert(corner); + if (dim_ > CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::exportSubrange: " + "array rank is too large"); + unsigned toBuf[CHAR_BIT * sizeof(unsigned long)]; + clearBuffer(toBuf, dim_); + (const_cast(this)) + ->commonSubrangeLoop(0U, 0UL, 0UL, corner, out->shape_, toBuf, *out, scast_assign_right()); + } else + out->localData_[0] = static_cast(localData_[0]); + } + + template + template + void ArrayND::importSubrange(const unsigned* corner, + const unsigned lenCorner, + const ArrayND& from) { + if (!shapeIsKnown_) + throw npstat::NpstatInvalidArgument("Initialize npstat::ArrayND before calling method \"importSubrange\""); + if (dim_ != lenCorner) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::importSubrange: incompatible corner index length"); + if (!from.shapeIsKnown_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::importSubrange: uninitialized argument array"); + if (from.dim_ != dim_) + throw npstat::NpstatInvalidArgument("In npstat::ArrayND::importSubrange: incompatible argument array rank"); + + if (dim_) { + assert(corner); + if (dim_ > CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayND::importSubrange: " + "array rank is too large"); + unsigned toBuf[CHAR_BIT * sizeof(unsigned long)]; + clearBuffer(toBuf, dim_); + commonSubrangeLoop(0U, + 0UL, + 0UL, + corner, + from.shape_, + toBuf, + const_cast&>(from), + scast_assign_left()); + } else + localData_[0] = static_cast(from.localData_[0]); + } +} // namespace npstat + +#endif // NPSTAT_ARRAYND_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ArrayNDScanner.h b/JetMETCorrections/InterpolationTables/interface/ArrayNDScanner.h index 42a4e2cefa653..24343735d6deb 100644 --- a/JetMETCorrections/InterpolationTables/interface/ArrayNDScanner.h +++ b/JetMETCorrections/InterpolationTables/interface/ArrayNDScanner.h @@ -15,7 +15,7 @@ #include namespace npstat { - /** + /** * This class can be used to iterate over array indices without actually * building the array or requesting any memory from the heap. Typical use: * @@ -33,59 +33,61 @@ namespace npstat { * slices of some array (so that the array itself can not be used * to obtain similar information easily). */ - class ArrayNDScanner - { - public: - //@{ - /** Constructor from a multidimensional array shape */ - inline ArrayNDScanner(const unsigned* shape, const unsigned lenShape) - {initialize(shape, lenShape);} + class ArrayNDScanner { + public: + //@{ + /** Constructor from a multidimensional array shape */ + inline ArrayNDScanner(const unsigned* shape, const unsigned lenShape) { initialize(shape, lenShape); } - inline explicit ArrayNDScanner(const std::vector& shape) - {initialize(shape.empty() ? static_cast(nullptr) : - &shape[0], shape.size());} - //@} + inline explicit ArrayNDScanner(const std::vector& shape) { + initialize(shape.empty() ? static_cast(nullptr) : &shape[0], shape.size()); + } + //@} - /** Dimensionality of the scan */ - inline unsigned dim() const {return dim_;} + /** Dimensionality of the scan */ + inline unsigned dim() const { return dim_; } - /** Retrieve current state (i.e., linear index of the scan) */ - inline unsigned long state() const {return state_;} + /** Retrieve current state (i.e., linear index of the scan) */ + inline unsigned long state() const { return state_; } - /** Maximum possible state (i.e., linear index of the scan) */ - inline unsigned long maxState() const {return maxState_;} + /** Maximum possible state (i.e., linear index of the scan) */ + inline unsigned long maxState() const { return maxState_; } - /** Returns false when iteration is complete */ - inline bool isValid() const {return state_ < maxState_;} + /** Returns false when iteration is complete */ + inline bool isValid() const { return state_ < maxState_; } - /** Retrieve current multidimensional index */ - void getIndex(unsigned* index, unsigned indexBufferLen) const; + /** Retrieve current multidimensional index */ + void getIndex(unsigned* index, unsigned indexBufferLen) const; - /** Reset the state (as if the object has just been constructed) */ - inline void reset() {state_ = 0UL;} + /** Reset the state (as if the object has just been constructed) */ + inline void reset() { state_ = 0UL; } - /** Prefix increment */ - inline ArrayNDScanner& operator++() - {if (state_ < maxState_) ++state_; return *this;} + /** Prefix increment */ + inline ArrayNDScanner& operator++() { + if (state_ < maxState_) + ++state_; + return *this; + } - /** Postfix increment (distinguished by the dummy "int" parameter) */ - inline void operator++(int) {if (state_ < maxState_) ++state_;} + /** Postfix increment (distinguished by the dummy "int" parameter) */ + inline void operator++(int) { + if (state_ < maxState_) + ++state_; + } - /** Set the state directly */ - inline void setState(const unsigned long state) - {state_ = state <= maxState_ ? state : maxState_;} + /** Set the state directly */ + inline void setState(const unsigned long state) { state_ = state <= maxState_ ? state : maxState_; } - private: - ArrayNDScanner() = delete; - - void initialize(const unsigned* shape, unsigned lenShape); + private: + ArrayNDScanner() = delete; - unsigned long strides_[CHAR_BIT*sizeof(unsigned long)]; - unsigned long state_; - unsigned long maxState_; - unsigned dim_; - }; -} + void initialize(const unsigned* shape, unsigned lenShape); -#endif // NPSTAT_ARRAYSCANNER_HH_ + unsigned long strides_[CHAR_BIT * sizeof(unsigned long)]; + unsigned long state_; + unsigned long maxState_; + unsigned dim_; + }; +} // namespace npstat +#endif // NPSTAT_ARRAYSCANNER_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ArrayRange.h b/JetMETCorrections/InterpolationTables/interface/ArrayRange.h index a3acb24b29b49..0101befcdf8ed 100644 --- a/JetMETCorrections/InterpolationTables/interface/ArrayRange.h +++ b/JetMETCorrections/InterpolationTables/interface/ArrayRange.h @@ -15,69 +15,65 @@ #include "JetMETCorrections/InterpolationTables/interface/BoxND.h" namespace npstat { - /** + /** // Utility class for use in certain array iterations */ - struct ArrayRange : public BoxND - { - inline ArrayRange() {} + struct ArrayRange : public BoxND { + inline ArrayRange() {} - /** Constructor from a given number of dimensions */ - inline explicit ArrayRange(unsigned dim) : BoxND(dim) {} + /** Constructor from a given number of dimensions */ + inline explicit ArrayRange(unsigned dim) : BoxND(dim) {} - /** The given interval is repeated for every dimension */ - inline ArrayRange(unsigned dim, const Interval& r1) - : BoxND(dim, r1) {} + /** The given interval is repeated for every dimension */ + inline ArrayRange(unsigned dim, const Interval& r1) : BoxND(dim, r1) {} - //@{ - /** + //@{ + /** // Constructor which creates a range out of a shape // which is used to represent the upper limit. The // lower limit in each dimension is set to 0. */ - inline explicit ArrayRange(const ArrayShape& shape) - : BoxND(shape) {} - ArrayRange(const unsigned* shape, unsigned shapeLen); - //@} + inline explicit ArrayRange(const ArrayShape& shape) : BoxND(shape) {} + ArrayRange(const unsigned* shape, unsigned shapeLen); + //@} - /** + /** // The shape which corresponds to this range // (i.e., max - min in all dimensions) */ - ArrayShape shape() const; + ArrayShape shape() const; - //@{ - /** Check for compatibility with a shape */ - bool isCompatible(const ArrayShape& shape) const; - bool isCompatible(const unsigned* shape, unsigned shapeLen) const; - //@} + //@{ + /** Check for compatibility with a shape */ + bool isCompatible(const ArrayShape& shape) const; + bool isCompatible(const unsigned* shape, unsigned shapeLen) const; + //@} - /** How many elements will be iterated over? */ - unsigned long rangeSize() const; + /** How many elements will be iterated over? */ + unsigned long rangeSize() const; - /** Operator for use with maps */ - bool operator<(const ArrayRange&) const; + /** Operator for use with maps */ + bool operator<(const ArrayRange&) const; - /** + /** // This method changes the range of this object so that // for each dimension the minimum becomes larger by 1 and the // maximum smaller by 1. */ - ArrayRange& stripOuterLayer(); + ArrayRange& stripOuterLayer(); - /** + /** // Get the lower range limits into an array. The length of // the limit array should be at least equal to the dimensionality. */ - void lowerLimits(unsigned* limits, unsigned limitsLen) const; - - /** Get the upper range limits into an array */ - void upperLimits(unsigned* limits, unsigned limitsLen) const; + void lowerLimits(unsigned* limits, unsigned limitsLen) const; - /** Get the range into an array */ - void rangeLength(unsigned* range, unsigned rangeLen) const; - }; -} + /** Get the upper range limits into an array */ + void upperLimits(unsigned* limits, unsigned limitsLen) const; -#endif // NPSTAT_ARRAYRANGE_HH_ + /** Get the range into an array */ + void rangeLength(unsigned* range, unsigned rangeLen) const; + }; +} // namespace npstat +#endif // NPSTAT_ARRAYRANGE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ArrayShape.h b/JetMETCorrections/InterpolationTables/interface/ArrayShape.h index 83fc9a868c105..844c190bb95d9 100644 --- a/JetMETCorrections/InterpolationTables/interface/ArrayShape.h +++ b/JetMETCorrections/InterpolationTables/interface/ArrayShape.h @@ -14,52 +14,61 @@ #include namespace npstat { - /** + /** // This type will be used to specify // array length in each dimension */ - typedef std::vector ArrayShape; + typedef std::vector ArrayShape; - //@{ - /** + //@{ + /** // This convenience function will construct // an array shape using an explicit list of indices */ - ArrayShape makeShape(); - ArrayShape makeShape(unsigned i0); - ArrayShape makeShape(unsigned i0, unsigned i1); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8); - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, unsigned i9); - ArrayShape makeShape(const unsigned* indices, unsigned nIndices); - //@} + ArrayShape makeShape(); + ArrayShape makeShape(unsigned i0); + ArrayShape makeShape(unsigned i0, unsigned i1); + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2); + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3); + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4); + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5); + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6); + ArrayShape makeShape( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7); + ArrayShape makeShape(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8); + ArrayShape makeShape(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9); + ArrayShape makeShape(const unsigned* indices, unsigned nIndices); + //@} - /** Multiply the sise in each dimension by 2 */ - ArrayShape doubleShape(const ArrayShape& inputShape); + /** Multiply the sise in each dimension by 2 */ + ArrayShape doubleShape(const ArrayShape& inputShape); - /** Divide the size in each dimension by 2 (generate dynamic fault if odd) */ - ArrayShape halfShape(const ArrayShape& inputShape); + /** Divide the size in each dimension by 2 (generate dynamic fault if odd) */ + ArrayShape halfShape(const ArrayShape& inputShape); - /** + /** // This function returns true if the number of elements is // the same in both vectors and every element of the first vector // does not exceed corresponding element of the second */ - bool isSubShape(const ArrayShape& sh1, const ArrayShape& sh2); -} - -#endif // NPSTAT_ARRAYSHAPE_HH_ + bool isSubShape(const ArrayShape& sh1, const ArrayShape& sh2); +} // namespace npstat +#endif // NPSTAT_ARRAYSHAPE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/BoxND.h b/JetMETCorrections/InterpolationTables/interface/BoxND.h index 087bffaaec790..1498270bd414c 100644 --- a/JetMETCorrections/InterpolationTables/interface/BoxND.h +++ b/JetMETCorrections/InterpolationTables/interface/BoxND.h @@ -17,145 +17,142 @@ #include "JetMETCorrections/InterpolationTables/interface/Interval.h" namespace npstat { - /** + /** // Class to represent rectangles, boxes, and hyperboxes */ - template - struct BoxND : public std::vector > - { - /** Default constructor makes a 0-dimensional box */ - inline BoxND() {} + template + struct BoxND : public std::vector > { + /** Default constructor makes a 0-dimensional box */ + inline BoxND() {} - /** Interval in each dimension is made by its default constructor */ - inline explicit BoxND(const unsigned long dim) : - std::vector >(dim) {} + /** Interval in each dimension is made by its default constructor */ + inline explicit BoxND(const unsigned long dim) : std::vector >(dim) {} - /** Use the same interval in each dimension */ - inline BoxND(const unsigned long dim, const Interval& v) : - std::vector >(dim, v) {} + /** Use the same interval in each dimension */ + inline BoxND(const unsigned long dim, const Interval& v) : std::vector >(dim, v) {} - /** + /** // Constructor where one of the limits will be 0 and the other // will be generated from the given vector (which also determines // the dimensionality) */ - template - explicit BoxND(const std::vector& limits); + template + explicit BoxND(const std::vector& limits); - /** Converting constructor */ - template - explicit BoxND(const BoxND& r); + /** Converting constructor */ + template + explicit BoxND(const BoxND& r); - /** + /** // Get the data from a box of a different type. This method // works essentially as a converting assignment operator. */ - template - BoxND& copyFrom(const BoxND& r); + template + BoxND& copyFrom(const BoxND& r); - /** Box dimensionality */ - inline unsigned long dim() const {return this->size();} + /** Box dimensionality */ + inline unsigned long dim() const { return this->size(); } - /** Box volume */ - Numeric volume() const; + /** Box volume */ + Numeric volume() const; - /** + /** // Midpoint for every coordinate. The size of the "coord" // array should be at least as large as the box dimensionality. */ - void getMidpoint(Numeric* coord, unsigned long coordLen) const; + void getMidpoint(Numeric* coord, unsigned long coordLen) const; - //@{ - /** + //@{ + /** // This method return "true" if the corresponding function // of the Interval returns "true" for every coordinate. // There must be an automatic conversion from Num2 type into Numeric. */ - template - bool isInsideLower(const Num2* coord, unsigned long coordLen) const; - template - bool isInsideUpper(const Num2* coord, unsigned long coordLen) const; - template - bool isInsideWithBounds(const Num2* coord, unsigned long coordLen) const; - template - bool isInside(const Num2* coord, unsigned long coordLen) const; - //@} - - //@{ - /** Scaling of all limits by a constant */ - BoxND& operator*=(double r); - BoxND& operator/=(double r); - //@} - - //@{ - /** Scaling by a different constant in each dimension */ - BoxND& operator*=(const std::vector& scales); - BoxND& operator/=(const std::vector& scales); - //@} - - /** + template + bool isInsideLower(const Num2* coord, unsigned long coordLen) const; + template + bool isInsideUpper(const Num2* coord, unsigned long coordLen) const; + template + bool isInsideWithBounds(const Num2* coord, unsigned long coordLen) const; + template + bool isInside(const Num2* coord, unsigned long coordLen) const; + //@} + + //@{ + /** Scaling of all limits by a constant */ + BoxND& operator*=(double r); + BoxND& operator/=(double r); + //@} + + //@{ + /** Scaling by a different constant in each dimension */ + BoxND& operator*=(const std::vector& scales); + BoxND& operator/=(const std::vector& scales); + //@} + + /** // Scaling of all limits by a constant in such a way that the midpoint // remains unchanged */ - BoxND& expand(double r); + BoxND& expand(double r); - //@{ - /** + //@{ + /** // Scaling of all limits in such a way that the midpoint // remains unchanged, using a different scaling factor // in each dimension */ - BoxND& expand(const std::vector& scales); - BoxND& expand(const double* scales, unsigned long lenScales); - //@} + BoxND& expand(const std::vector& scales); + BoxND& expand(const double* scales, unsigned long lenScales); + //@} - //@{ - /** Shifting this object */ - template - BoxND& operator+=(const std::vector& shifts); - template - BoxND& operator-=(const std::vector& shifts); - template - BoxND& shift(const Num2* shifts, unsigned long lenShifts); - //@} + //@{ + /** Shifting this object */ + template + BoxND& operator+=(const std::vector& shifts); + template + BoxND& operator-=(const std::vector& shifts); + template + BoxND& shift(const Num2* shifts, unsigned long lenShifts); + //@} - /** Moving this object so that the midpoint is (0, 0, ..., 0) */ - BoxND& moveToOrigin(); + /** Moving this object so that the midpoint is (0, 0, ..., 0) */ + BoxND& moveToOrigin(); - /** Overlap volume with another box */ - Numeric overlapVolume(const BoxND& r) const; + /** Overlap volume with another box */ + Numeric overlapVolume(const BoxND& r) const; - /** A faster way to calculate overlapVolume(r)/volume() */ - double overlapFraction(const BoxND& r) const; + /** A faster way to calculate overlapVolume(r)/volume() */ + double overlapFraction(const BoxND& r) const; - /** Box with lower limit 0 and upper limit 1 in all coordinates */ - static BoxND unitBox(unsigned long ndim); + /** Box with lower limit 0 and upper limit 1 in all coordinates */ + static BoxND unitBox(unsigned long ndim); - /** + /** // Box with lower limit -1 and upper limit 1 in all coordinates. // Note that this will produce nonsense in case the Numeric type // is unsigned. */ - static BoxND sizeTwoBox(unsigned long ndim); + static BoxND sizeTwoBox(unsigned long ndim); - /** + /** // Box with all upper limits set to maximum possible Numeric // number and with lower limits set to negative maximum (this // will not work with unsigned long types) */ - static BoxND allSpace(unsigned long ndim); - - //@{ - /** Methods related to I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static const char* classname(); - static inline unsigned version() {return 1;} - static void restore(const gs::ClassId& id, std::istream& in, BoxND* box); - }; -} + static BoxND allSpace(unsigned long ndim); + + //@{ + /** Methods related to I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static const char* classname(); + static inline unsigned version() { return 1; } + static void restore(const gs::ClassId& id, std::istream& in, BoxND* box); + }; +} // namespace npstat //@{ /** Binary comparison for equality */ @@ -174,392 +171,343 @@ bool operator!=(const npstat::BoxND& l, const npstat::BoxND& r #include "Alignment/Geners/interface/IOIsUnsigned.hh" namespace npstat { - template - template - BoxND::BoxND(const BoxND& r) - { - const unsigned long dim = r.size(); - if (dim) - { - this->reserve(dim); - for (unsigned long i=0; i& ri(r[i]); - this->push_back(Interval(ri.min(), ri.max())); - } - } - } - - template - template - BoxND::BoxND(const std::vector& limits) - { - const unsigned long dim = limits.size(); - if (dim) - { - this->reserve(dim); - Numeric zero = Numeric(); - for (unsigned long i=0; i(limits[i])); - if (value >= zero) - this->push_back(Interval(zero, value)); - else - this->push_back(Interval(value, zero)); - } - } - } - - template - template - BoxND& BoxND::copyFrom(const BoxND& r) - { - if ((void *)this == (void *)(&r)) - return *this; - const unsigned long n = r.size(); - this->clear(); - this->reserve(n); - for (unsigned long i=0; i& ir(r[i]); - this->push_back(Interval(ir.min(), ir.max())); - } - return *this; - } - - template - Numeric BoxND::volume() const - { - Numeric v(static_cast(1)); - const unsigned long mydim = this->size(); - for (unsigned long i=0U; i - Numeric BoxND::overlapVolume(const BoxND& r) const - { - const unsigned long mydim = this->size(); - if (mydim == r.size()) - { - Numeric v(static_cast(1)); - for (unsigned long i=0U; i(0); + template + template + BoxND::BoxND(const BoxND& r) { + const unsigned long dim = r.size(); + if (dim) { + this->reserve(dim); + for (unsigned long i = 0; i < dim; ++i) { + const Interval& ri(r[i]); + this->push_back(Interval(ri.min(), ri.max())); + } } - - template - double BoxND::overlapFraction(const BoxND& r) const - { - const unsigned long mydim = this->size(); - if (mydim == r.size()) - { - double f = 1.0; - for (unsigned long i=0U; i + template + BoxND::BoxND(const std::vector& limits) { + const unsigned long dim = limits.size(); + if (dim) { + this->reserve(dim); + Numeric zero = Numeric(); + for (unsigned long i = 0; i < dim; ++i) { + const Numeric value(static_cast(limits[i])); + if (value >= zero) + this->push_back(Interval(zero, value)); else - return 0.0; - } - - template - void BoxND::getMidpoint(Numeric* coord, - const unsigned long coordLen) const - { - const unsigned long mydim = this->size(); - if (coordLen < mydim) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::getMidpoint: insufficient output buffer length"); - if (mydim) - { - assert(coord); - for (unsigned long i=0U; i - template - bool BoxND::isInsideLower(const Num2* coords, - const unsigned long coordLen) const - { - if (coordLen != this->size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::isInsideLower: " - "incompatible point dimensionality"); - const Interval* myptr = &(*this)[0]; - for (unsigned long i=0; ipush_back(Interval(value, zero)); + } } - - template - template - bool BoxND::isInsideUpper(const Num2* coords, - const unsigned long coordLen) const - { - if (coordLen != this->size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::isInsideUpper: " - "incompatible point dimensionality"); - const Interval* myptr = &(*this)[0]; - for (unsigned long i=0; i + template + BoxND& BoxND::copyFrom(const BoxND& r) { + if ((void*)this == (void*)(&r)) + return *this; + const unsigned long n = r.size(); + this->clear(); + this->reserve(n); + for (unsigned long i = 0; i < n; ++i) { + const Interval& ir(r[i]); + this->push_back(Interval(ir.min(), ir.max())); } - - template - template - bool BoxND::isInsideWithBounds(const Num2* coords, - const unsigned long coordLen) const - { - if (coordLen != this->size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::isInsideWithBounds: " - "incompatible point dimensionality"); - const Interval* myptr = &(*this)[0]; - for (unsigned long i=0; i + Numeric BoxND::volume() const { + Numeric v(static_cast(1)); + const unsigned long mydim = this->size(); + for (unsigned long i = 0U; i < mydim; ++i) + v *= (*this)[i].length(); + return v; + } + + template + Numeric BoxND::overlapVolume(const BoxND& r) const { + const unsigned long mydim = this->size(); + if (mydim == r.size()) { + Numeric v(static_cast(1)); + for (unsigned long i = 0U; i < mydim; ++i) + v *= (*this)[i].overlapLength(r[i]); + return v; + } else + return static_cast(0); + } + + template + double BoxND::overlapFraction(const BoxND& r) const { + const unsigned long mydim = this->size(); + if (mydim == r.size()) { + double f = 1.0; + for (unsigned long i = 0U; i < mydim; ++i) + f *= (*this)[i].overlapFraction(r[i]); + return f; + } else + return 0.0; + } + + template + void BoxND::getMidpoint(Numeric* coord, const unsigned long coordLen) const { + const unsigned long mydim = this->size(); + if (coordLen < mydim) + throw npstat::NpstatInvalidArgument("In npstat::BoxND::getMidpoint: insufficient output buffer length"); + if (mydim) { + assert(coord); + for (unsigned long i = 0U; i < mydim; ++i) + coord[i] = (*this)[i].midpoint(); } - - template - template - bool BoxND::isInside(const Num2* coords, - const unsigned long coordLen) const - { - if (coordLen != this->size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::isInside: incompatible point dimensionality"); - const Interval* myptr = &(*this)[0]; - for (unsigned long i=0; i - BoxND& BoxND::operator*=(const double r) - { - const unsigned long mydim = this->size(); - for (unsigned long i=0; i - BoxND& BoxND::moveToOrigin() - { - const unsigned long mydim = this->size(); - for (unsigned long i=0; i - BoxND& BoxND::expand(const double r) - { - const unsigned long mydim = this->size(); - for (unsigned long i=0; i - BoxND& BoxND::operator*=( - const std::vector& scales) - { - const unsigned long mydim = this->size(); - if (mydim != scales.size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::operator*=: " - "incompatible argument dimensionality"); - for (unsigned long i=0; i - BoxND& BoxND::expand( - const std::vector& scales) - { - const unsigned long mydim = this->size(); - if (mydim != scales.size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::expand: incompatible argument dimensionality"); - for (unsigned long i=0; i - BoxND& BoxND::expand( - const double* scales, const unsigned long lenScales) - { - const unsigned long mydim = this->size(); - if (mydim != lenScales) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::expand: incompatible argument dimensionality"); - if (mydim) - { - assert(scales); - for (unsigned long i=0; i - BoxND& BoxND::operator/=(const double r) - { - const unsigned long mydim = this->size(); - for (unsigned long i=0; i - BoxND& BoxND::operator/=( - const std::vector& scales) - { - const unsigned long mydim = this->size(); - if (mydim != scales.size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::operator/=: " - "incompatible argument dimensionality"); - for (unsigned long i=0; i - template - BoxND& BoxND::operator+=(const std::vector& shifts) - { - const unsigned long mydim = this->size(); - if (mydim != shifts.size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::operator+=: " - "incompatible argument dimensionality"); - for (unsigned long i=0; i(shifts[i]); - return *this; - } - - template - template - BoxND& BoxND::shift( - const Num2* shifts, const unsigned long shiftsLen) - { - const unsigned long mydim = this->size(); - if (mydim != shiftsLen) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::shift: incompatible argument dimensionality"); - if (mydim) - { - assert(shifts); - for (unsigned long i=0; i(shifts[i]); - } - return *this; - } - - template - template - BoxND& BoxND::operator-=(const std::vector& shifts) - { - const unsigned long mydim = this->size(); - if (mydim != shifts.size()) throw npstat::NpstatInvalidArgument( - "In npstat::BoxND::operator-=: " - "incompatible argument dimensionality"); - for (unsigned long i=0; i(shifts[i]); - return *this; - } - - template - BoxND BoxND::unitBox(const unsigned long ndim) - { - Interval unit(static_cast(0), - static_cast(1)); - return BoxND(ndim, unit); - } - - template - BoxND BoxND::sizeTwoBox(const unsigned long ndim) - { - const Numeric one = static_cast(1); - Interval i(-one, one); - return BoxND(ndim, i); - } - - template - BoxND BoxND::allSpace(const unsigned long ndim) - { - const Numeric maxval = std::numeric_limits::max(); - Interval i(static_cast(0), maxval); - if (!gs::IOIsUnsigned::value) - i.setMin(-maxval); - return BoxND(ndim, i); - } - - template - const char* BoxND::classname() - { - static const std::string na(gs::template_class_name("npstat::BoxND")); - return na.c_str(); + } + + template + template + bool BoxND::isInsideLower(const Num2* coords, const unsigned long coordLen) const { + if (coordLen != this->size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::isInsideLower: " + "incompatible point dimensionality"); + const Interval* myptr = &(*this)[0]; + for (unsigned long i = 0; i < coordLen; ++i) + if (!myptr[i].isInsideLower(coords[i])) + return false; + return true; + } + + template + template + bool BoxND::isInsideUpper(const Num2* coords, const unsigned long coordLen) const { + if (coordLen != this->size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::isInsideUpper: " + "incompatible point dimensionality"); + const Interval* myptr = &(*this)[0]; + for (unsigned long i = 0; i < coordLen; ++i) + if (!myptr[i].isInsideUpper(coords[i])) + return false; + return true; + } + + template + template + bool BoxND::isInsideWithBounds(const Num2* coords, const unsigned long coordLen) const { + if (coordLen != this->size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::isInsideWithBounds: " + "incompatible point dimensionality"); + const Interval* myptr = &(*this)[0]; + for (unsigned long i = 0; i < coordLen; ++i) + if (!myptr[i].isInsideWithBounds(coords[i])) + return false; + return true; + } + + template + template + bool BoxND::isInside(const Num2* coords, const unsigned long coordLen) const { + if (coordLen != this->size()) + throw npstat::NpstatInvalidArgument("In npstat::BoxND::isInside: incompatible point dimensionality"); + const Interval* myptr = &(*this)[0]; + for (unsigned long i = 0; i < coordLen; ++i) + if (!myptr[i].isInside(coords[i])) + return false; + return true; + } + + template + BoxND& BoxND::operator*=(const double r) { + const unsigned long mydim = this->size(); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] *= r; + return *this; + } + + template + BoxND& BoxND::moveToOrigin() { + const unsigned long mydim = this->size(); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i].moveMidpointTo0(); + return *this; + } + + template + BoxND& BoxND::expand(const double r) { + const unsigned long mydim = this->size(); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i].expand(r); + return *this; + } + + template + BoxND& BoxND::operator*=(const std::vector& scales) { + const unsigned long mydim = this->size(); + if (mydim != scales.size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::operator*=: " + "incompatible argument dimensionality"); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] *= scales[i]; + return *this; + } + + template + BoxND& BoxND::expand(const std::vector& scales) { + const unsigned long mydim = this->size(); + if (mydim != scales.size()) + throw npstat::NpstatInvalidArgument("In npstat::BoxND::expand: incompatible argument dimensionality"); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i].expand(scales[i]); + return *this; + } + + template + BoxND& BoxND::expand(const double* scales, const unsigned long lenScales) { + const unsigned long mydim = this->size(); + if (mydim != lenScales) + throw npstat::NpstatInvalidArgument("In npstat::BoxND::expand: incompatible argument dimensionality"); + if (mydim) { + assert(scales); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i].expand(scales[i]); } - - template - bool BoxND::write(std::ostream& of) const - { - const unsigned long mydim = this->size(); - std::vector limits; - limits.reserve(2UL*mydim); - for (unsigned long i=0; i + BoxND& BoxND::operator/=(const double r) { + const unsigned long mydim = this->size(); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] /= r; + return *this; + } + + template + BoxND& BoxND::operator/=(const std::vector& scales) { + const unsigned long mydim = this->size(); + if (mydim != scales.size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::operator/=: " + "incompatible argument dimensionality"); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] /= scales[i]; + return *this; + } + + template + template + BoxND& BoxND::operator+=(const std::vector& shifts) { + const unsigned long mydim = this->size(); + if (mydim != shifts.size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::operator+=: " + "incompatible argument dimensionality"); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] += static_cast(shifts[i]); + return *this; + } + + template + template + BoxND& BoxND::shift(const Num2* shifts, const unsigned long shiftsLen) { + const unsigned long mydim = this->size(); + if (mydim != shiftsLen) + throw npstat::NpstatInvalidArgument("In npstat::BoxND::shift: incompatible argument dimensionality"); + if (mydim) { + assert(shifts); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] += static_cast(shifts[i]); } - - template - void BoxND::restore(const gs::ClassId& id, std::istream& in, BoxND* b) - { - static const gs::ClassId current(gs::ClassId::makeId >()); - current.ensureSameId(id); - - std::vector limits; - gs::restore_item(in, &limits); - if (in.fail()) - throw gs::IOReadFailure("In npstat::BoxND::restore: input stream failure"); - const unsigned long nlimits = limits.size(); - if (nlimits % 2UL) - throw gs::IOInvalidData("In npstat::BoxND::restore: bad limits"); - assert(b); - b->clear(); - b->reserve(nlimits/2UL); - for (unsigned long i=0; ipush_back(npstat::Interval(limits[2U*i], limits[2U*i+1U])); + return *this; + } + + template + template + BoxND& BoxND::operator-=(const std::vector& shifts) { + const unsigned long mydim = this->size(); + if (mydim != shifts.size()) + throw npstat::NpstatInvalidArgument( + "In npstat::BoxND::operator-=: " + "incompatible argument dimensionality"); + for (unsigned long i = 0; i < mydim; ++i) + (*this)[i] -= static_cast(shifts[i]); + return *this; + } + + template + BoxND BoxND::unitBox(const unsigned long ndim) { + Interval unit(static_cast(0), static_cast(1)); + return BoxND(ndim, unit); + } + + template + BoxND BoxND::sizeTwoBox(const unsigned long ndim) { + const Numeric one = static_cast(1); + Interval i(-one, one); + return BoxND(ndim, i); + } + + template + BoxND BoxND::allSpace(const unsigned long ndim) { + const Numeric maxval = std::numeric_limits::max(); + Interval i(static_cast(0), maxval); + if (!gs::IOIsUnsigned::value) + i.setMin(-maxval); + return BoxND(ndim, i); + } + + template + const char* BoxND::classname() { + static const std::string na(gs::template_class_name("npstat::BoxND")); + return na.c_str(); + } + + template + bool BoxND::write(std::ostream& of) const { + const unsigned long mydim = this->size(); + std::vector limits; + limits.reserve(2UL * mydim); + for (unsigned long i = 0; i < mydim; ++i) { + limits.push_back((*this)[i].min()); + limits.push_back((*this)[i].max()); } -} + return gs::write_item(of, limits); + } + + template + void BoxND::restore(const gs::ClassId& id, std::istream& in, BoxND* b) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + std::vector limits; + gs::restore_item(in, &limits); + if (in.fail()) + throw gs::IOReadFailure("In npstat::BoxND::restore: input stream failure"); + const unsigned long nlimits = limits.size(); + if (nlimits % 2UL) + throw gs::IOInvalidData("In npstat::BoxND::restore: bad limits"); + assert(b); + b->clear(); + b->reserve(nlimits / 2UL); + for (unsigned long i = 0; i < nlimits / 2UL; ++i) + b->push_back(npstat::Interval(limits[2U * i], limits[2U * i + 1U])); + } +} // namespace npstat template -bool operator==(const npstat::BoxND& l, const npstat::BoxND& r) -{ - const unsigned long dim = l.size(); - if (dim != r.size()) - return false; - for (unsigned long i=0; i& l, const npstat::BoxND& r) { + const unsigned long dim = l.size(); + if (dim != r.size()) + return false; + for (unsigned long i = 0; i < dim; ++i) + if (l[i] != r[i]) + return false; + return true; } template -bool operator!=(const npstat::BoxND& l, const npstat::BoxND& r) -{ - return !(l == r); +bool operator!=(const npstat::BoxND& l, const npstat::BoxND& r) { + return !(l == r); } - -#endif // NPSTAT_BOXND_HH_ - +#endif // NPSTAT_BOXND_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/CircularMapper1d.h b/JetMETCorrections/InterpolationTables/interface/CircularMapper1d.h index babd3946d1306..e4c69bcc4ebaf 100644 --- a/JetMETCorrections/InterpolationTables/interface/CircularMapper1d.h +++ b/JetMETCorrections/InterpolationTables/interface/CircularMapper1d.h @@ -16,52 +16,49 @@ #include "JetMETCorrections/InterpolationTables/interface/LinearMapper1d.h" namespace npstat { - /** + /** // 1-d linear transformation functor followed by the shift of // the result into the interval [-T/2, T/2], where T is the period */ - class CircularMapper1d - { - public: - inline CircularMapper1d() : a_(1.0), b_(0.0), period_(2.0*M_PI) {} + class CircularMapper1d { + public: + inline CircularMapper1d() : a_(1.0), b_(0.0), period_(2.0 * M_PI) {} - inline CircularMapper1d(const double ca, const double cb, - const double cperiod) - : a_(ca), b_(cb), period_(std::abs(cperiod)) {check();} + inline CircularMapper1d(const double ca, const double cb, const double cperiod) + : a_(ca), b_(cb), period_(std::abs(cperiod)) { + check(); + } - inline CircularMapper1d(const LinearMapper1d& mapper, - const double cperiod) - : a_(mapper.a()), b_(mapper.b()), - period_(std::abs(cperiod)) {check();} + inline CircularMapper1d(const LinearMapper1d& mapper, const double cperiod) + : a_(mapper.a()), b_(mapper.b()), period_(std::abs(cperiod)) { + check(); + } - inline double operator()(const double& x) const - { - double value = a_*x + b_; - value -= period_*floor(value/period_); - if (value > period_/2.0) - value -= period_; - return value; - } + inline double operator()(const double& x) const { + double value = a_ * x + b_; + value -= period_ * floor(value / period_); + if (value > period_ / 2.0) + value -= period_; + return value; + } - inline double a() const {return a_;} - inline double b() const {return b_;} - inline double period() const {return period_;} - inline LinearMapper1d linearMapper() const - {return LinearMapper1d(a_, b_);} + inline double a() const { return a_; } + inline double b() const { return b_; } + inline double period() const { return period_; } + inline LinearMapper1d linearMapper() const { return LinearMapper1d(a_, b_); } - private: - inline void check() - { - if (!period_) throw npstat::NpstatInvalidArgument( - "In npstat::CircularMapper1d constructor: " - "invalid period argument (can not be 0)"); - } + private: + inline void check() { + if (!period_) + throw npstat::NpstatInvalidArgument( + "In npstat::CircularMapper1d constructor: " + "invalid period argument (can not be 0)"); + } - double a_; - double b_; - double period_; - }; -} - -#endif // NPSTAT_CIRCULARMAPPER1D_HH_ + double a_; + double b_; + double period_; + }; +} // namespace npstat +#endif // NPSTAT_CIRCULARMAPPER1D_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ComplexComparesAbs.h b/JetMETCorrections/InterpolationTables/interface/ComplexComparesAbs.h index 3e03304f7acb7..42c8207af58ad 100644 --- a/JetMETCorrections/InterpolationTables/interface/ComplexComparesAbs.h +++ b/JetMETCorrections/InterpolationTables/interface/ComplexComparesAbs.h @@ -15,33 +15,24 @@ #include namespace npstat { - /** + /** // This template compares two numbers. For simple numeric types // (int, double, etc) the numbers themselves are compared while // for std::complex<...> types absolute values are compared. */ - template - struct ComplexComparesAbs - { - inline static bool less(const T& l, const T& r) - {return l < r;} + template + struct ComplexComparesAbs { + inline static bool less(const T& l, const T& r) { return l < r; } - inline static bool more(const T& l, const T& r) - {return l > r;} - }; + inline static bool more(const T& l, const T& r) { return l > r; } + }; - template - struct ComplexComparesAbs > - { - inline static bool less(const std::complex& l, - const std::complex& r) - {return std::abs(l) < std::abs(r);} + template + struct ComplexComparesAbs > { + inline static bool less(const std::complex& l, const std::complex& r) { return std::abs(l) < std::abs(r); } - inline static bool more(const std::complex& l, - const std::complex& r) - {return std::abs(l) > std::abs(l);} - }; -} - -#endif // NPSTAT_COMPLEXCOMPARESABS_HH_ + inline static bool more(const std::complex& l, const std::complex& r) { return std::abs(l) > std::abs(l); } + }; +} // namespace npstat +#endif // NPSTAT_COMPLEXCOMPARESABS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ComplexComparesFalse.h b/JetMETCorrections/InterpolationTables/interface/ComplexComparesFalse.h index 333a7684c71c5..6101aed51430c 100644 --- a/JetMETCorrections/InterpolationTables/interface/ComplexComparesFalse.h +++ b/JetMETCorrections/InterpolationTables/interface/ComplexComparesFalse.h @@ -14,31 +14,24 @@ #include namespace npstat { - /** + /** // This template compares two numbers. For simple numeric types // (int, double, etc) the numbers themselves are compared while for // std::complex<...> types "false" is returned for every comparison. */ - template - struct ComplexComparesFalse - { - inline static bool less(const T& l, const T& r) - {return l < r;} + template + struct ComplexComparesFalse { + inline static bool less(const T& l, const T& r) { return l < r; } - inline static bool more(const T& l, const T& r) - {return l > r;} - }; + inline static bool more(const T& l, const T& r) { return l > r; } + }; - template - struct ComplexComparesFalse > - { - inline static bool less(const std::complex&, const std::complex&) - {return false;} + template + struct ComplexComparesFalse > { + inline static bool less(const std::complex&, const std::complex&) { return false; } - inline static bool more(const std::complex&, const std::complex&) - {return false;} - }; -} - -#endif // NPSTAT_COMPLEXCOMPARESFALSE_HH_ + inline static bool more(const std::complex&, const std::complex&) { return false; } + }; +} // namespace npstat +#endif // NPSTAT_COMPLEXCOMPARESFALSE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/CoordinateSelector.h b/JetMETCorrections/InterpolationTables/interface/CoordinateSelector.h index 291fbe652e5c9..a8774c5b0f965 100644 --- a/JetMETCorrections/InterpolationTables/interface/CoordinateSelector.h +++ b/JetMETCorrections/InterpolationTables/interface/CoordinateSelector.h @@ -18,33 +18,30 @@ #include "JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h" namespace npstat { - /** + /** // A trivial implementation of AbsMultivariateFunctor which selects // an element with a certain index from the input array */ - class CoordinateSelector : public AbsMultivariateFunctor - { - public: - inline explicit CoordinateSelector(const unsigned i) : index_(i) {} - - inline ~CoordinateSelector() override {} - - inline double operator()(const double* point, const unsigned dim) const override - { - if (dim <= index_) - throw npstat::NpstatInvalidArgument( - "In npstat::CoordinateSelector::operator(): " - "input array dimensionality is too small"); - return point[index_]; - } - inline unsigned minDim() const override {return index_ + 1U;} - inline unsigned maxDim() const override {return UINT_MAX;} - - private: - CoordinateSelector() = delete; - unsigned index_; - }; -} - -#endif // NPSTAT_COORDINATESELECTOR_HH_ - + class CoordinateSelector : public AbsMultivariateFunctor { + public: + inline explicit CoordinateSelector(const unsigned i) : index_(i) {} + + inline ~CoordinateSelector() override {} + + inline double operator()(const double* point, const unsigned dim) const override { + if (dim <= index_) + throw npstat::NpstatInvalidArgument( + "In npstat::CoordinateSelector::operator(): " + "input array dimensionality is too small"); + return point[index_]; + } + inline unsigned minDim() const override { return index_ + 1U; } + inline unsigned maxDim() const override { return UINT_MAX; } + + private: + CoordinateSelector() = delete; + unsigned index_; + }; +} // namespace npstat + +#endif // NPSTAT_COORDINATESELECTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/DualAxis.h b/JetMETCorrections/InterpolationTables/interface/DualAxis.h index f3cb277618421..59a8d7f1f78da 100644 --- a/JetMETCorrections/InterpolationTables/interface/DualAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/DualAxis.h @@ -16,121 +16,103 @@ #include "JetMETCorrections/InterpolationTables/interface/UniformAxis.h" namespace npstat { - /** + /** // Rectangular grid axis which can be either uniform or non-uniform. // Will work a little bit slower than either GridAxis or UniformAxis, // but can be used in place of either one of them. */ - class DualAxis - { - public: - // Constructors - inline DualAxis(const GridAxis& g) - : a_(g), u_(2, 0.0, 1.0), uniform_(false) {} + class DualAxis { + public: + // Constructors + inline DualAxis(const GridAxis& g) : a_(g), u_(2, 0.0, 1.0), uniform_(false) {} - inline DualAxis(const UniformAxis& u) - : a_(dummy_vec()), u_(u), uniform_(true) {} + inline DualAxis(const UniformAxis& u) : a_(dummy_vec()), u_(u), uniform_(true) {} - inline DualAxis(unsigned nCoords, double min, double max, - const char* label=nullptr) - : a_(dummy_vec()), u_(nCoords, min, max, label), uniform_(true) {} + inline DualAxis(unsigned nCoords, double min, double max, const char* label = nullptr) + : a_(dummy_vec()), u_(nCoords, min, max, label), uniform_(true) {} - inline explicit DualAxis(const std::vector& coords, - const bool useLogSpace=false) - : a_(coords, useLogSpace), u_(2, 0.0, 1.0), uniform_(false) {} + inline explicit DualAxis(const std::vector& coords, const bool useLogSpace = false) + : a_(coords, useLogSpace), u_(2, 0.0, 1.0), uniform_(false) {} - inline DualAxis(const std::vector& coords, const char* label, - const bool useLogSpace=false) - : a_(coords, label, useLogSpace), u_(2,0.0,1.0), uniform_(false) {} + inline DualAxis(const std::vector& coords, const char* label, const bool useLogSpace = false) + : a_(coords, label, useLogSpace), u_(2, 0.0, 1.0), uniform_(false) {} - // Inspectors - inline bool isUniform() const {return uniform_;} + // Inspectors + inline bool isUniform() const { return uniform_; } - inline unsigned nCoords() const - {return uniform_ ? u_.nCoords() : a_.nCoords();} + inline unsigned nCoords() const { return uniform_ ? u_.nCoords() : a_.nCoords(); } - inline double min() const - {return uniform_ ? u_.min() : a_.min();} + inline double min() const { return uniform_ ? u_.min() : a_.min(); } - inline double max() const - {return uniform_ ? u_.max() : a_.max();} + inline double max() const { return uniform_ ? u_.max() : a_.max(); } - inline const std::string& label() const - {return uniform_ ? u_.label() : a_.label();} + inline const std::string& label() const { return uniform_ ? u_.label() : a_.label(); } - inline bool usesLogSpace() const - {return uniform_ ? u_.usesLogSpace() : a_.usesLogSpace();} + inline bool usesLogSpace() const { return uniform_ ? u_.usesLogSpace() : a_.usesLogSpace(); } - inline std::pair getInterval(const double x) const - {return uniform_ ? u_.getInterval(x) : a_.getInterval(x);} + inline std::pair getInterval(const double x) const { + return uniform_ ? u_.getInterval(x) : a_.getInterval(x); + } - inline std::pair linearInterval(const double x) const - {return uniform_ ? u_.linearInterval(x) : a_.linearInterval(x);} + inline std::pair linearInterval(const double x) const { + return uniform_ ? u_.linearInterval(x) : a_.linearInterval(x); + } - inline double coordinate(const unsigned i) const - {return uniform_ ? u_.coordinate(i) : a_.coordinate(i);} + inline double coordinate(const unsigned i) const { return uniform_ ? u_.coordinate(i) : a_.coordinate(i); } - inline double length() const - {return uniform_ ? u_.length() : a_.length();} + inline double length() const { return uniform_ ? u_.length() : a_.length(); } - inline unsigned nIntervals() const - {return uniform_ ? u_.nIntervals() : a_.nIntervals();} + inline unsigned nIntervals() const { return uniform_ ? u_.nIntervals() : a_.nIntervals(); } - inline double intervalWidth(const unsigned i=0) const - {return uniform_ ? u_.intervalWidth(i) : a_.intervalWidth(i);} + inline double intervalWidth(const unsigned i = 0) const { + return uniform_ ? u_.intervalWidth(i) : a_.intervalWidth(i); + } - inline std::vector coords() const - {return uniform_ ? u_.coords() : a_.coords();} + inline std::vector coords() const { return uniform_ ? u_.coords() : a_.coords(); } - inline bool operator==(const DualAxis& r) const - {return uniform_ == r.uniform_ && a_ == r.a_ && u_ == r.u_;} + inline bool operator==(const DualAxis& r) const { return uniform_ == r.uniform_ && a_ == r.a_ && u_ == r.u_; } - inline bool operator!=(const DualAxis& r) const - {return !(*this == r);} + inline bool operator!=(const DualAxis& r) const { return !(*this == r); } - //@{ - /** + //@{ + /** // Return a pointer to the underlying axis. This will be // a null pointer if the axis does not correspond to the // constructed type. */ - inline const GridAxis* getGridAxis() const - {return uniform_ ? static_cast(nullptr) : &a_;} - - inline const UniformAxis* getUniformAxis() const - {return uniform_ ? &u_ : static_cast(nullptr);} - //@} - - /** Modify the axis label */ - inline void setLabel(const char* newlabel) - {uniform_ ? u_.setLabel(newlabel) : a_.setLabel(newlabel);} - - //@{ - /** Method related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static inline const char* classname() {return "npstat::DualAxis";} - static inline unsigned version() {return 1;} - static DualAxis* read(const gs::ClassId& id, std::istream& in); - - private: - GridAxis a_; - UniformAxis u_; - bool uniform_; - - inline static std::vector dummy_vec() - { - std::vector vec(2, 0.0); - vec[1] = 1.0; - return vec; - } - - inline DualAxis() - : a_(dummy_vec()), u_(2, 0.0, 1.0), uniform_(true) {} - }; -} - -#endif // NPSTAT_DUALAXIS_HH_ - + inline const GridAxis* getGridAxis() const { return uniform_ ? static_cast(nullptr) : &a_; } + + inline const UniformAxis* getUniformAxis() const { + return uniform_ ? &u_ : static_cast(nullptr); + } + //@} + + /** Modify the axis label */ + inline void setLabel(const char* newlabel) { uniform_ ? u_.setLabel(newlabel) : a_.setLabel(newlabel); } + + //@{ + /** Method related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static inline const char* classname() { return "npstat::DualAxis"; } + static inline unsigned version() { return 1; } + static DualAxis* read(const gs::ClassId& id, std::istream& in); + + private: + GridAxis a_; + UniformAxis u_; + bool uniform_; + + inline static std::vector dummy_vec() { + std::vector vec(2, 0.0); + vec[1] = 1.0; + return vec; + } + + inline DualAxis() : a_(dummy_vec()), u_(2, 0.0, 1.0), uniform_(true) {} + }; +} // namespace npstat + +#endif // NPSTAT_DUALAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/DualHistoAxis.h b/JetMETCorrections/InterpolationTables/interface/DualHistoAxis.h index 23b054461b5be..5b451ede73214 100644 --- a/JetMETCorrections/InterpolationTables/interface/DualHistoAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/DualHistoAxis.h @@ -15,157 +15,134 @@ #include "JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h" namespace npstat { - /** + /** // Histogram axis which can be either uniform or non-uniform. // Will work a little bit slower than either HistoAxis or NUHistoAxis, // but can be used in place of either one of them. */ - class DualHistoAxis - { - public: - // Constructors - inline DualHistoAxis(const NUHistoAxis& a) - : a_(a), u_(1U, 0.0, 1.0), uniform_(false) {} + class DualHistoAxis { + public: + // Constructors + inline DualHistoAxis(const NUHistoAxis& a) : a_(a), u_(1U, 0.0, 1.0), uniform_(false) {} - inline DualHistoAxis(const HistoAxis& u) - : a_(dummy_vec()), u_(u), uniform_(true) {} + inline DualHistoAxis(const HistoAxis& u) : a_(dummy_vec()), u_(u), uniform_(true) {} - inline DualHistoAxis(const std::vector& binEdges, - const char* label = nullptr) - : a_(binEdges, label), u_(1U, 0.0, 1.0), uniform_(false) {} + inline DualHistoAxis(const std::vector& binEdges, const char* label = nullptr) + : a_(binEdges, label), u_(1U, 0.0, 1.0), uniform_(false) {} - inline DualHistoAxis(unsigned nBins, double min, double max, - const char* label = nullptr) - : a_(dummy_vec()), u_(nBins, min, max, label), uniform_(true) {} + inline DualHistoAxis(unsigned nBins, double min, double max, const char* label = nullptr) + : a_(dummy_vec()), u_(nBins, min, max, label), uniform_(true) {} - // Inspectors - inline bool isUniform() const {return uniform_;} + // Inspectors + inline bool isUniform() const { return uniform_; } - inline double min() const - {return uniform_ ? u_.min() : a_.min();} + inline double min() const { return uniform_ ? u_.min() : a_.min(); } - inline double max() const - {return uniform_ ? u_.max() : a_.max();} + inline double max() const { return uniform_ ? u_.max() : a_.max(); } - inline Interval interval() const - {return uniform_ ? u_.interval() : a_.interval();} + inline Interval interval() const { return uniform_ ? u_.interval() : a_.interval(); } - inline double length() const - {return uniform_ ? u_.length() : a_.length();} + inline double length() const { return uniform_ ? u_.length() : a_.length(); } - inline unsigned nBins() const - {return uniform_ ? u_.nBins() : a_.nBins();} + inline unsigned nBins() const { return uniform_ ? u_.nBins() : a_.nBins(); } - inline double binWidth(const int binNum) const - {return uniform_ ? u_.binWidth(binNum) : a_.binWidth(binNum);} + inline double binWidth(const int binNum) const { return uniform_ ? u_.binWidth(binNum) : a_.binWidth(binNum); } - inline const std::string& label() const - {return uniform_ ? u_.label() : a_.label();} + inline const std::string& label() const { return uniform_ ? u_.label() : a_.label(); } - inline double binCenter(const int binNum) const - {return uniform_ ? u_.binCenter(binNum) : a_.binCenter(binNum);} + inline double binCenter(const int binNum) const { return uniform_ ? u_.binCenter(binNum) : a_.binCenter(binNum); } - inline double leftBinEdge(const int binNum) const - {return uniform_ ? u_.leftBinEdge(binNum) : a_.leftBinEdge(binNum);} + inline double leftBinEdge(const int binNum) const { + return uniform_ ? u_.leftBinEdge(binNum) : a_.leftBinEdge(binNum); + } - inline double rightBinEdge(const int binNum) const - {return uniform_ ? u_.rightBinEdge(binNum) : a_.rightBinEdge(binNum);} + inline double rightBinEdge(const int binNum) const { + return uniform_ ? u_.rightBinEdge(binNum) : a_.rightBinEdge(binNum); + } - inline Interval binInterval(const int binNum) const - {return uniform_ ? u_.binInterval(binNum) : a_.binInterval(binNum);} + inline Interval binInterval(const int binNum) const { + return uniform_ ? u_.binInterval(binNum) : a_.binInterval(binNum); + } - //@{ - /** + //@{ + /** // Return a pointer to the underlying axis. This will be // a null pointer if the axis does not correspond to the // constructed type. */ - inline const NUHistoAxis* getNUHistoAxis() const - {return uniform_ ? static_cast(nullptr) : &a_;} + inline const NUHistoAxis* getNUHistoAxis() const { + return uniform_ ? static_cast(nullptr) : &a_; + } - inline const HistoAxis* getHistoAxis() const - {return uniform_ ? &u_ : static_cast(nullptr);} - //@} + inline const HistoAxis* getHistoAxis() const { return uniform_ ? &u_ : static_cast(nullptr); } + //@} - /** Modify the axis label */ - inline void setLabel(const char* newlabel) - {uniform_ ? u_.setLabel(newlabel) : a_.setLabel(newlabel);} + /** Modify the axis label */ + inline void setLabel(const char* newlabel) { uniform_ ? u_.setLabel(newlabel) : a_.setLabel(newlabel); } - /** + /** // This method returns arbitrary integer bin number. // Possible output depends on whether the axis is uniform or not. */ - inline int binNumber(const double x) const - {return uniform_ ? u_.binNumber(x) : a_.binNumber(x);} + inline int binNumber(const double x) const { return uniform_ ? u_.binNumber(x) : a_.binNumber(x); } - /** + /** // Floating point bin number given the coordinate. Useful for // interpolation methods and such. */ - inline double fltBinNumber(const double x, - const bool mapLeftEdgeTo0=true) const - { - return uniform_ ? u_.fltBinNumber(x, mapLeftEdgeTo0) : - a_.fltBinNumber(x, mapLeftEdgeTo0); - } - - /** Return the closest valid bin number (above 0 and below nBins() ) */ - inline unsigned closestValidBin(const double x) const - {return uniform_ ? u_.closestValidBin(x) : a_.closestValidBin(x);} - - inline bool operator==(const DualHistoAxis& r) const - {return uniform_ == r.uniform_ && a_ == r.a_ && u_ == r.u_;} - - inline bool operator!=(const DualHistoAxis& r) const - {return !(*this == r);} - - /** Comparison within given tolerance */ - inline bool isClose(const DualHistoAxis& r, const double tol) const - { - return uniform_ == r.uniform_ && - a_.isClose(r.a_, tol) && - u_.isClose(r.u_, tol); - } - - /** Return uniformly rebinned axis */ - inline DualHistoAxis rebin(const unsigned newBins) const - {return DualHistoAxis(newBins, min(), max(), label().c_str());} - - //@{ - // Method related to "geners" I/O - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static inline const char* classname() {return "npstat::DualHistoAxis";} - static inline unsigned version() {return 1;} - static DualHistoAxis* read(const gs::ClassId& id, std::istream& in); - - private: - NUHistoAxis a_; - HistoAxis u_; - bool uniform_; - - template friend class HistoND; - - inline unsigned overflowIndex( - const double x, unsigned* binNumber) const - { - return uniform_ ? u_.overflowIndex(x, binNumber) : - a_.overflowIndex(x, binNumber); - } - - inline static std::vector dummy_vec() - { - std::vector vec(2, 0.0); - vec[1] = 1.0; - return vec; - } - - inline DualHistoAxis() - : a_(dummy_vec()), u_(1U, 0.0, 1.0), uniform_(true) {} - }; -} - -#endif // NPSTAT_DUALHISTOAXIS_HH_ - + inline double fltBinNumber(const double x, const bool mapLeftEdgeTo0 = true) const { + return uniform_ ? u_.fltBinNumber(x, mapLeftEdgeTo0) : a_.fltBinNumber(x, mapLeftEdgeTo0); + } + + /** Return the closest valid bin number (above 0 and below nBins() ) */ + inline unsigned closestValidBin(const double x) const { + return uniform_ ? u_.closestValidBin(x) : a_.closestValidBin(x); + } + + inline bool operator==(const DualHistoAxis& r) const { return uniform_ == r.uniform_ && a_ == r.a_ && u_ == r.u_; } + + inline bool operator!=(const DualHistoAxis& r) const { return !(*this == r); } + + /** Comparison within given tolerance */ + inline bool isClose(const DualHistoAxis& r, const double tol) const { + return uniform_ == r.uniform_ && a_.isClose(r.a_, tol) && u_.isClose(r.u_, tol); + } + + /** Return uniformly rebinned axis */ + inline DualHistoAxis rebin(const unsigned newBins) const { + return DualHistoAxis(newBins, min(), max(), label().c_str()); + } + + //@{ + // Method related to "geners" I/O + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static inline const char* classname() { return "npstat::DualHistoAxis"; } + static inline unsigned version() { return 1; } + static DualHistoAxis* read(const gs::ClassId& id, std::istream& in); + + private: + NUHistoAxis a_; + HistoAxis u_; + bool uniform_; + + template + friend class HistoND; + + inline unsigned overflowIndex(const double x, unsigned* binNumber) const { + return uniform_ ? u_.overflowIndex(x, binNumber) : a_.overflowIndex(x, binNumber); + } + + inline static std::vector dummy_vec() { + std::vector vec(2, 0.0); + vec[1] = 1.0; + return vec; + } + + inline DualHistoAxis() : a_(dummy_vec()), u_(1U, 0.0, 1.0), uniform_(true) {} + }; +} // namespace npstat + +#endif // NPSTAT_DUALHISTOAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/EquidistantSequence.h b/JetMETCorrections/InterpolationTables/interface/EquidistantSequence.h index c5f1e82ebf310..760101e7f73a2 100644 --- a/JetMETCorrections/InterpolationTables/interface/EquidistantSequence.h +++ b/JetMETCorrections/InterpolationTables/interface/EquidistantSequence.h @@ -14,38 +14,33 @@ #include namespace npstat { - /** + /** // A sequence of points equidistant in linear space. Note that // std::vector destructor is not virtual, so do not destroy this // class by base pointer or reference. */ - class EquidistantInLinearSpace : public std::vector - { - public: - EquidistantInLinearSpace(double minScale, double maxScale, - unsigned nScales); - virtual ~EquidistantInLinearSpace() {} + class EquidistantInLinearSpace : public std::vector { + public: + EquidistantInLinearSpace(double minScale, double maxScale, unsigned nScales); + virtual ~EquidistantInLinearSpace() {} - private: - EquidistantInLinearSpace() = delete; - }; + private: + EquidistantInLinearSpace() = delete; + }; - /** + /** // A sequence of points equidistant in log space. Note that // std::vector destructor is not virtual, so do not destroy this // class by base pointer or reference. */ - class EquidistantInLogSpace : public std::vector - { - public: - EquidistantInLogSpace(double minScale, double maxScale, - unsigned nScales); - virtual ~EquidistantInLogSpace() {} + class EquidistantInLogSpace : public std::vector { + public: + EquidistantInLogSpace(double minScale, double maxScale, unsigned nScales); + virtual ~EquidistantInLogSpace() {} - private: - EquidistantInLogSpace() = delete; - }; -} - -#endif // NPSTAT_EQUIDISTANTSEQUENCE_HH_ + private: + EquidistantInLogSpace() = delete; + }; +} // namespace npstat +#endif // NPSTAT_EQUIDISTANTSEQUENCE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/GridAxis.h b/JetMETCorrections/InterpolationTables/interface/GridAxis.h index c00e82496ca7e..2ea1c245e43dc 100644 --- a/JetMETCorrections/InterpolationTables/interface/GridAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/GridAxis.h @@ -20,35 +20,32 @@ #include "Alignment/Geners/interface/ClassId.hh" namespace npstat { - /** + /** // Information needed to define an axis of a rectangular grid. // The distance between grid points can change from point to point. // // The UniformAxis class will be more efficient in representing // equidistant grids. */ - class GridAxis - { - public: - //@{ - /** + class GridAxis { + public: + //@{ + /** // The number of grid coordinates provided must be at least 2. // Coordinates will be sorted internally in the increasing order. */ - explicit GridAxis(const std::vector& coords, - bool useLogSpace=false); - GridAxis(const std::vector& coords, const char* label, - bool useLogSpace=false); - //@} - - //@{ - /** Basic accessor returning a parameter provided in the constructor */ - inline const std::vector& coords() const {return coords_;} - inline const std::string& label() const {return label_;} - inline bool usesLogSpace() const {return useLogSpace_;} - //@} - - /** + explicit GridAxis(const std::vector& coords, bool useLogSpace = false); + GridAxis(const std::vector& coords, const char* label, bool useLogSpace = false); + //@} + + //@{ + /** Basic accessor returning a parameter provided in the constructor */ + inline const std::vector& coords() const { return coords_; } + inline const std::string& label() const { return label_; } + inline bool usesLogSpace() const { return useLogSpace_; } + //@} + + /** // This method returns the grid interval number and // the weight of the point at the left side of the interval. // The weight will be set to 1 if the given coordinate coincides @@ -61,9 +58,9 @@ namespace npstat { // with weight 0 for the left point (it is expected that weight 1 // will then be assigned to the right point). */ - std::pair getInterval(double coordinate) const; + std::pair getInterval(double coordinate) const; - /** + /** // This method returns the grid interval number and // the weight of the point at the left side of the interval. // The weight will be set to 1 if the given coordinate coincides @@ -77,61 +74,56 @@ namespace npstat { // will be calculated by linear extrapolation from the closest // interval in the grid (i.e., leftmost or rightmost). */ - std::pair linearInterval(double coordinate) const; - - //@{ - /** Convenience accessor */ - inline unsigned nCoords() const {return npt_;} - inline double coordinate(const unsigned i) const - {return coords_.at(i);} - inline double min() const {return coords_.front();} - inline double max() const {return coords_.back();} - inline double length() const {return coords_.back() - coords_.front();} - inline bool isUniform() const {return false;} - inline unsigned nIntervals() const {return coords_.size() - 1;} - inline double intervalWidth(const unsigned i=0) const - {return coords_.at(i+1) - coords_.at(i);} - //@} - - /** Compare two grids for equality */ - bool operator==(const GridAxis& r) const; - - /** Logical negation of operator== */ - inline bool operator!=(const GridAxis& r) const - {return !(*this == r);} - - /** + std::pair linearInterval(double coordinate) const; + + //@{ + /** Convenience accessor */ + inline unsigned nCoords() const { return npt_; } + inline double coordinate(const unsigned i) const { return coords_.at(i); } + inline double min() const { return coords_.front(); } + inline double max() const { return coords_.back(); } + inline double length() const { return coords_.back() - coords_.front(); } + inline bool isUniform() const { return false; } + inline unsigned nIntervals() const { return coords_.size() - 1; } + inline double intervalWidth(const unsigned i = 0) const { return coords_.at(i + 1) - coords_.at(i); } + //@} + + /** Compare two grids for equality */ + bool operator==(const GridAxis& r) const; + + /** Logical negation of operator== */ + inline bool operator!=(const GridAxis& r) const { return !(*this == r); } + + /** // Check for closeness of coordinates with another axis // within the given relative tolerance */ - bool isClose(const GridAxis& r, double tol) const; - - /** Modify the axis label */ - inline void setLabel(const char* newlabel) - {label_ = newlabel ? newlabel : "";} + bool isClose(const GridAxis& r, double tol) const; - //@{ - /** Method related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} + /** Modify the axis label */ + inline void setLabel(const char* newlabel) { label_ = newlabel ? newlabel : ""; } - static inline const char* classname() {return "npstat::GridAxis";} - static inline unsigned version() {return 2;} - static GridAxis* read(const gs::ClassId& id, std::istream& in); + //@{ + /** Method related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} - private: - void initialize(); + static inline const char* classname() { return "npstat::GridAxis"; } + static inline unsigned version() { return 2; } + static GridAxis* read(const gs::ClassId& id, std::istream& in); - std::vector coords_; - std::vector logs_; - std::string label_; - unsigned npt_; - bool useLogSpace_; + private: + void initialize(); - inline GridAxis() : npt_(0), useLogSpace_(false) {} - }; -} + std::vector coords_; + std::vector logs_; + std::string label_; + unsigned npt_; + bool useLogSpace_; -#endif // NPSTAT_GRIDAXIS_HH_ + inline GridAxis() : npt_(0), useLogSpace_(false) {} + }; +} // namespace npstat +#endif // NPSTAT_GRIDAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/HistoAxis.h b/JetMETCorrections/InterpolationTables/interface/HistoAxis.h index 46d65c72cd7bb..6d4c3e6f4d8a3 100644 --- a/JetMETCorrections/InterpolationTables/interface/HistoAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/HistoAxis.h @@ -19,144 +19,135 @@ #include "JetMETCorrections/InterpolationTables/interface/Interval.h" namespace npstat { - template class HistoND; - class DualHistoAxis; + template + class HistoND; + class DualHistoAxis; - /** + /** // Class which contain the information needed to define a histogram axis. // All bins will have the same width. See NUHistoAxis and DualHistoAxis // classes for non-uniform binning. */ - class HistoAxis - { - public: - /** + class HistoAxis { + public: + /** // Minimum and maximum will be internally swapped // if the minimum parameter is larger than the maximum */ - HistoAxis(unsigned nBins, double min, double max, - const char* label=nullptr); - - //@{ - /** Examine axis properties */ - inline double min() const {return min_;} - inline double max() const {return max_;} - inline Interval interval() const - {return Interval(min_, max_);} - inline double length() const {return max_ - min_;} - inline unsigned nBins() const {return nBins_;} - inline double binWidth(const int /*binNum*/=0) const {return bw_;} - inline const std::string& label() const {return label_;} - inline bool isUniform() const {return true;} - //@} - - /** Return the coordinate of the given bin center */ - inline double binCenter(const int binNum) const - {return min_ + (binNum + 0.5)*bw_;} - - /** Return the coordinate of the given bin left edge */ - inline double leftBinEdge(const int binNum) const - {return min_ + binNum*bw_;} - - /** Return the coordinate of the given bin right edge */ - inline double rightBinEdge(const int binNum) const - {return min_ + (binNum + 1)*bw_;} - - /** Return the coordinate interval occupied by the given bin */ - inline Interval binInterval(const int binNum) const - {return Interval(min_+binNum*bw_, min_+(binNum+1)*bw_);} - - /** Change the axis label */ - inline void setLabel(const char* newlabel) - {label_ = newlabel ? newlabel : "";} - - /** + HistoAxis(unsigned nBins, double min, double max, const char* label = nullptr); + + //@{ + /** Examine axis properties */ + inline double min() const { return min_; } + inline double max() const { return max_; } + inline Interval interval() const { return Interval(min_, max_); } + inline double length() const { return max_ - min_; } + inline unsigned nBins() const { return nBins_; } + inline double binWidth(const int /*binNum*/ = 0) const { return bw_; } + inline const std::string& label() const { return label_; } + inline bool isUniform() const { return true; } + //@} + + /** Return the coordinate of the given bin center */ + inline double binCenter(const int binNum) const { return min_ + (binNum + 0.5) * bw_; } + + /** Return the coordinate of the given bin left edge */ + inline double leftBinEdge(const int binNum) const { return min_ + binNum * bw_; } + + /** Return the coordinate of the given bin right edge */ + inline double rightBinEdge(const int binNum) const { return min_ + (binNum + 1) * bw_; } + + /** Return the coordinate interval occupied by the given bin */ + inline Interval binInterval(const int binNum) const { + return Interval(min_ + binNum * bw_, min_ + (binNum + 1) * bw_); + } + + /** Change the axis label */ + inline void setLabel(const char* newlabel) { label_ = newlabel ? newlabel : ""; } + + /** // This method returns arbitrary integer bin number, including // negative numbers and numbers which can exceed nBins()-1 */ - int binNumber(double x) const; + int binNumber(double x) const; - /** + /** // This method returns the closest valid bin number // (above 0 and below nBins() ) */ - unsigned closestValidBin(double x) const; + unsigned closestValidBin(double x) const; - /** + /** // Return the mapper which calculates floating point bin number // given the coordinate. The resulting bin number can go above // and below the axis range. If "mapLeftEdgeTo0" is specified // as "false", it is the center of the first bin which gets // mapped to 0. */ - LinearMapper1d binNumberMapper(bool mapLeftEdgeTo0=true) const; + LinearMapper1d binNumberMapper(bool mapLeftEdgeTo0 = true) const; - /** + /** // Floating point bin number given the coordinate (no bin number // truncation of any kind is performed). Works in exactly the same // way as the mapper returned by the previous method. */ - inline double fltBinNumber(const double x, - const bool mapLeftEdgeTo0=true) const - {return (x - min_)/bw_ - (mapLeftEdgeTo0 ? 0.0 : 0.5);} + inline double fltBinNumber(const double x, const bool mapLeftEdgeTo0 = true) const { + return (x - min_) / bw_ - (mapLeftEdgeTo0 ? 0.0 : 0.5); + } - /** + /** // The following function returns a mapper that can be // helpful in scanning a kernel (a density function) for // subsequent convolution with the histogram which contains // this axis. */ - CircularMapper1d kernelScanMapper(bool doubleRange) const; - - bool operator==(const HistoAxis&) const; - bool operator!=(const HistoAxis&) const; - - /** Comparison of axis coordinates within given tolerance */ - bool isClose(const HistoAxis&, double tol) const; - - /** Return rebinned axis */ - HistoAxis rebin(unsigned newBins) const; - - //@{ - /** Method related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static inline const char* classname() {return "npstat::HistoAxis";} - static inline unsigned version() {return 1;} - static HistoAxis* read(const gs::ClassId& id, std::istream& in); - - private: - double min_; - double max_; - double bw_; - std::string label_; - unsigned nBins_; - - template friend class HistoND; - friend class DualHistoAxis; - - inline unsigned overflowIndex( - const double x, unsigned* binNumber) const - { - if (x < min_) - return 0U; - else if (x >= max_) - return 2U; - else - { - const unsigned bin = static_cast((x - min_)/bw_); - *binNumber = bin >= nBins_ ? nBins_ - 1U : bin; - return 1U; - } - } - - unsigned overflowIndexWeighted(double x, unsigned* binNumber, - double *weight) const; - inline HistoAxis() : min_(0.0), max_(0.0), bw_(0.0), nBins_(0) {} - }; -} - -#endif // NPSTAT_HISTOAXIS_HH_ - + CircularMapper1d kernelScanMapper(bool doubleRange) const; + + bool operator==(const HistoAxis&) const; + bool operator!=(const HistoAxis&) const; + + /** Comparison of axis coordinates within given tolerance */ + bool isClose(const HistoAxis&, double tol) const; + + /** Return rebinned axis */ + HistoAxis rebin(unsigned newBins) const; + + //@{ + /** Method related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static inline const char* classname() { return "npstat::HistoAxis"; } + static inline unsigned version() { return 1; } + static HistoAxis* read(const gs::ClassId& id, std::istream& in); + + private: + double min_; + double max_; + double bw_; + std::string label_; + unsigned nBins_; + + template + friend class HistoND; + friend class DualHistoAxis; + + inline unsigned overflowIndex(const double x, unsigned* binNumber) const { + if (x < min_) + return 0U; + else if (x >= max_) + return 2U; + else { + const unsigned bin = static_cast((x - min_) / bw_); + *binNumber = bin >= nBins_ ? nBins_ - 1U : bin; + return 1U; + } + } + + unsigned overflowIndexWeighted(double x, unsigned* binNumber, double* weight) const; + inline HistoAxis() : min_(0.0), max_(0.0), bw_(0.0), nBins_(0) {} + }; +} // namespace npstat + +#endif // NPSTAT_HISTOAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/HistoND.h b/JetMETCorrections/InterpolationTables/interface/HistoND.h index faa4d543569b3..f983823afc5d9 100644 --- a/JetMETCorrections/InterpolationTables/interface/HistoND.h +++ b/JetMETCorrections/InterpolationTables/interface/HistoND.h @@ -15,7 +15,7 @@ #include "JetMETCorrections/InterpolationTables/interface/HistoAxis.h" namespace npstat { - /** + /** // (Almost) arbitrary-dimensional histogram with binning determined // by the second template parameter (typically HistoAxis or NUHistoAxis). // The dimensionality must not exceed CHAR_BIT*sizeof(unsigned long)-1 @@ -39,77 +39,88 @@ namespace npstat { // underlying array using the "binContents()" method and then examine // that array directly. */ - template - class HistoND - { - template friend class HistoND; - - public: - typedef Numeric value_type; - typedef Axis axis_type; - - enum RebinType { - SAMPLE = 0, - SUM, - AVERAGE - }; - - /** Main constructor for arbitrary-dimensional histograms */ - explicit HistoND(const std::vector& axes, const char* title=nullptr, - const char* accumulatedDataLabel=nullptr); - - /** Convenience constructor for 1-d histograms */ - explicit HistoND(const Axis& xAxis, const char* title=nullptr, - const char* accumulatedDataLabel=nullptr); - - /** Convenience constructor for 2-d histograms */ - HistoND(const Axis& xAxis, const Axis& yAxis, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); - - /** Convenience constructor for 3-d histograms */ - HistoND(const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); - - /** Convenience constructor for 4-d histograms */ - HistoND(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); - - /** Convenience constructor for 5-d histograms */ - HistoND(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, const Axis& vAxis, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); - - /** + template + class HistoND { + template + friend class HistoND; + + public: + typedef Numeric value_type; + typedef Axis axis_type; + + enum RebinType { SAMPLE = 0, SUM, AVERAGE }; + + /** Main constructor for arbitrary-dimensional histograms */ + explicit HistoND(const std::vector& axes, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); + + /** Convenience constructor for 1-d histograms */ + explicit HistoND(const Axis& xAxis, const char* title = nullptr, const char* accumulatedDataLabel = nullptr); + + /** Convenience constructor for 2-d histograms */ + HistoND(const Axis& xAxis, + const Axis& yAxis, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); + + /** Convenience constructor for 3-d histograms */ + HistoND(const Axis& xAxis, + const Axis& yAxis, + const Axis& zAxis, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); + + /** Convenience constructor for 4-d histograms */ + HistoND(const Axis& xAxis, + const Axis& yAxis, + const Axis& zAxis, + const Axis& tAxis, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); + + /** Convenience constructor for 5-d histograms */ + HistoND(const Axis& xAxis, + const Axis& yAxis, + const Axis& zAxis, + const Axis& tAxis, + const Axis& vAxis, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); + + /** // Simple constructor for uniformly binned histograms without // axis labels. Sequence size returned by the size() method of // both "shape" and "boundingBox" arguments must be the same. */ - HistoND(const ArrayShape& shape, const BoxND& boundingBox, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); + HistoND(const ArrayShape& shape, + const BoxND& boundingBox, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); - /** + /** // Converting constructor. The functor will be applied to all bins // of the argument histogram to fill the bins of the constructed // histogram. If the title and data label are not provided, they // will be cleared. */ - template - HistoND(const HistoND& h, const Functor& f, - const char* title=nullptr, const char* accumulatedDataLabel=nullptr); + template + HistoND(const HistoND& h, + const Functor& f, + const char* title = nullptr, + const char* accumulatedDataLabel = nullptr); - /** + /** // A slicing constructor. The new histogram will be created by // slicing another histogram. See the description of the slicing // constructor in the "ArrayND" class for the meaning of arguments // "indices" and "nIndices". The data of the newly created histogram // is cleared. */ - template - HistoND(const HistoND& h, const unsigned *indices, - unsigned nIndices, const char* title=nullptr); + template + HistoND(const HistoND& h, const unsigned* indices, unsigned nIndices, const char* title = nullptr); - /** + /** // A constructor that inserts a new axis into a histogram // (as if the argument histogram was a slice of the new histogram). // The "newAxisNumber" argument specifies the number of the @@ -118,11 +129,10 @@ namespace npstat { // argument histogram, the new axis will become last. The data // of the newly created histogram is cleared. */ - template - HistoND(const HistoND& h, const Axis& newAxis, - unsigned newAxisNumber, const char* title=nullptr); + template + HistoND(const HistoND& h, const Axis& newAxis, unsigned newAxisNumber, const char* title = nullptr); - /** + /** // Create a rebinned histogram with the same axis coverage. // Note that not all such operations will be meaningful if the // bin contents do not belong to one of the floating point types. @@ -139,194 +149,209 @@ namespace npstat { // bin edge. Naturally, the length of the "shifts" array should be // equal to the input histogram dimensionality. */ - template - HistoND(const HistoND& h, RebinType rType, - const unsigned *newBinCounts, unsigned lenNewBinCounts, - const double* shifts=nullptr, const char* title=nullptr); + template + HistoND(const HistoND& h, + RebinType rType, + const unsigned* newBinCounts, + unsigned lenNewBinCounts, + const double* shifts = nullptr, + const char* title = nullptr); - /** Copy constructor */ - HistoND(const HistoND&); + /** Copy constructor */ + HistoND(const HistoND&); - /** + /** // Assignment operator. Works even when the binning of the two // histograms is not compatible. */ - HistoND& operator=(const HistoND&); + HistoND& operator=(const HistoND&); - /** Histogram dimensionality */ - inline unsigned dim() const {return dim_;} + /** Histogram dimensionality */ + inline unsigned dim() const { return dim_; } - /** Histogram title */ - inline const std::string& title() const {return title_;} + /** Histogram title */ + inline const std::string& title() const { return title_; } - /** Label associated with accumulated data */ - inline const std::string& accumulatedDataLabel() const - {return accumulatedDataLabel_;} + /** Label associated with accumulated data */ + inline const std::string& accumulatedDataLabel() const { return accumulatedDataLabel_; } - /** Retrive a reference to the array of bin contents */ - inline const ArrayND& binContents() const {return data_;} + /** Retrive a reference to the array of bin contents */ + inline const ArrayND& binContents() const { return data_; } - /** Retrive a reference to the array of overflows */ - inline const ArrayND& overflows() const {return overflow_;} + /** Retrive a reference to the array of overflows */ + inline const ArrayND& overflows() const { return overflow_; } - /** Inspect histogram axes */ - inline const std::vector& axes() const {return axes_;} + /** Inspect histogram axes */ + inline const std::vector& axes() const { return axes_; } - /** Inspect a histogram axis for the given dimension */ - inline const Axis& axis(const unsigned i) const - {return axes_.at(i);} + /** Inspect a histogram axis for the given dimension */ + inline const Axis& axis(const unsigned i) const { return axes_.at(i); } - /** Total number of bins */ - inline unsigned long nBins() const {return data_.length();} + /** Total number of bins */ + inline unsigned long nBins() const { return data_.length(); } - /** Total number of fills performed */ - inline unsigned long nFillsTotal() const {return fillCount_;} + /** Total number of fills performed */ + inline unsigned long nFillsTotal() const { return fillCount_; } - /** Total number of fills which fell inside the histogram range */ - inline unsigned long nFillsInRange() const - {return fillCount_ - overCount_;} + /** Total number of fills which fell inside the histogram range */ + inline unsigned long nFillsInRange() const { return fillCount_ - overCount_; } - /** Total number of fills which fell outside the histogram range */ - inline unsigned long nFillsOver() const {return overCount_;} + /** Total number of fills which fell outside the histogram range */ + inline unsigned long nFillsOver() const { return overCount_; } - /** + /** // This method returns "true" if the method isUniform() // of each histogram axis returns "true" */ - bool isUniformlyBinned() const; + bool isUniformlyBinned() const; - /** Modify the histogram title */ - inline void setTitle(const char* newtitle) - {title_ = newtitle ? newtitle : ""; ++modCount_;} + /** Modify the histogram title */ + inline void setTitle(const char* newtitle) { + title_ = newtitle ? newtitle : ""; + ++modCount_; + } - /** Modify the label associated with accumulated data */ - inline void setAccumulatedDataLabel(const char* newlabel) - {accumulatedDataLabel_ = newlabel ? newlabel : ""; ++modCount_;} + /** Modify the label associated with accumulated data */ + inline void setAccumulatedDataLabel(const char* newlabel) { + accumulatedDataLabel_ = newlabel ? newlabel : ""; + ++modCount_; + } - /** Modify the label for the histogram axis with the given number */ - inline void setAxisLabel(const unsigned axisNum, const char* newlabel) - {axes_.at(axisNum).setLabel(newlabel); ++modCount_;} + /** Modify the label for the histogram axis with the given number */ + inline void setAxisLabel(const unsigned axisNum, const char* newlabel) { + axes_.at(axisNum).setLabel(newlabel); + ++modCount_; + } - /** + /** // This method returns width/area/volume/etc. of a single bin. // 1.0 is returned for a dimensionless histogram. */ - double binVolume(unsigned long binNumber=0) const; + double binVolume(unsigned long binNumber = 0) const; - /** + /** // Position of the bin center. Length of the "coords" array // (filled on return) should be equal to the dimensionality // of the histogram. */ - void binCenter(unsigned long binNumber, - double* coords, unsigned lenCoords) const; + void binCenter(unsigned long binNumber, double* coords, unsigned lenCoords) const; - /** + /** // Convenience function which fills out a vector of bin centers // in the same order as the linear order of binContents(). // The class "Point" must have a subscript operator, default // constructor, copy constructor, and the size() method (use, // for example, std::array). */ - template - void allBinCenters(std::vector* centers) const; + template + void allBinCenters(std::vector* centers) const; - /** Bounding box for the given bin */ - void binBox(unsigned long binNumber, BoxND* box) const; + /** Bounding box for the given bin */ + void binBox(unsigned long binNumber, BoxND* box) const; - /** Bounding box for the whole histogram */ - BoxND boundingBox() const; + /** Bounding box for the whole histogram */ + BoxND boundingBox() const; - /** + /** // Volume of the histogram bounding box (this direct call is faster // than calling boundingBox().volume() ). This function returns 1.0 // for 0-dim histogram, axis interval length for 1-d histogram, etc. */ - double volume() const; + double volume() const; - /** Integral of the histogram */ - double integral() const; + /** Integral of the histogram */ + double integral() const; - /** Clear the histogram contents (both bins and overflows) */ - void clear(); + /** Clear the histogram contents (both bins and overflows) */ + void clear(); - /** This method clears the bin contents but not overflows */ - void clearBinContents(); + /** This method clears the bin contents but not overflows */ + void clearBinContents(); - /** This method clears overflows but not the bin contents */ - void clearOverflows(); + /** This method clears overflows but not the bin contents */ + void clearOverflows(); - /** Comparison for equality */ - bool operator==(const HistoND&) const; + /** Comparison for equality */ + bool operator==(const HistoND&) const; - /** Logical negation of operator== */ - bool operator!=(const HistoND&) const; + /** Logical negation of operator== */ + bool operator!=(const HistoND&) const; - /** + /** // Check data for equality (both bin contents and overflows). // Do not compare axes, labels, fill counts, etc. */ - bool isSameData(const HistoND&) const; + bool isSameData(const HistoND&) const; - /** + /** // Fill function for histograms of arbitrary dimensionality. // The length of the "coords" array should be equal to the // histogram dimensionality. The Numeric type must have the "+=" // operator defined with the Num2 type on the right side. */ - template - void fill(const double* coords, unsigned coordLength, - const Num2& weight); + template + void fill(const double* coords, unsigned coordLength, const Num2& weight); - //@{ - /** + //@{ + /** // Convenience "fill" method for histograms of corresponding // dimensionality */ - template - void fill(const Num2& weight); + template + void fill(const Num2& weight); - template - void fill(double x0, const Num2& weight); + template + void fill(double x0, const Num2& weight); - template - void fill(double x0, double x1, const Num2& weight); + template + void fill(double x0, double x1, const Num2& weight); - template - void fill(double x0, double x1, double x2, const Num2& weight); + template + void fill(double x0, double x1, double x2, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, - const Num2& weight); + template + void fill(double x0, double x1, double x2, double x3, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - const Num2& weight); + template + void fill(double x0, double x1, double x2, double x3, double x4, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - double x5, const Num2& weight); + template + void fill(double x0, double x1, double x2, double x3, double x4, double x5, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, const Num2& weight); + template + void fill(double x0, double x1, double x2, double x3, double x4, double x5, double x6, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, const Num2& weight); + template + void fill( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, - const Num2& weight); + template + void fill(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + const Num2& weight); - template - void fill(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, double x9, - const Num2& weight); - //@} + template + void fill(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + double x9, + const Num2& weight); + //@} - /** + /** // Location-based dispatch method. The provided binary functor // will be called with the approprite histogram bin value as the // first argument and the weight as the second (functor return value @@ -339,155 +364,158 @@ namespace npstat { // functor, multiple things might be modified as the result of this // call: the bin value, the weight, and the functor internal state. */ - template - void dispatch(const double* coords, unsigned coordLength, - Num2& weight, Functor& f); + template + void dispatch(const double* coords, unsigned coordLength, Num2& weight, Functor& f); - //@{ - /** + //@{ + /** // Convenience "dispatch" method for histograms of corresponding // dimensionality */ - template - void dispatch(Num2& weight, Functor& f); + template + void dispatch(Num2& weight, Functor& f); - template - void dispatch(double x0, Num2& weight, Functor& f); + template + void dispatch(double x0, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, Num2& weight, Functor& f); + template + void dispatch(double x0, double x1, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, Num2& weight, - Functor& f); + template + void dispatch(double x0, double x1, double x2, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, - Num2& weight, Functor& f); + template + void dispatch(double x0, double x1, double x2, double x3, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - Num2& weight, Functor& f); + template + void dispatch(double x0, double x1, double x2, double x3, double x4, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - double x5, Num2& weight, Functor& f); + template + void dispatch(double x0, double x1, double x2, double x3, double x4, double x5, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, Num2& weight, Functor& f); + template + void dispatch(double x0, double x1, double x2, double x3, double x4, double x5, double x6, Num2& weight, Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, Num2& weight, - Functor& f); + template + void dispatch(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + Num2& weight, + Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, - Num2& weight, Functor& f); + template + void dispatch(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + Num2& weight, + Functor& f); - template - void dispatch(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, double x9, - Num2& weight, Functor& f); - //@} + template + void dispatch(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + double x9, + Num2& weight, + Functor& f); + //@} - /** + /** // The "examine" functions allow the user to access bin contents // when bins are addressed by their coordinates. Use "binContents()" // to access the data by bin numbers. Overflow bins will be accessed // if the given coordinates fall outside the histogram range. */ - const Numeric& examine(const double* coords, - unsigned coordLength) const; + const Numeric& examine(const double* coords, unsigned coordLength) const; - //@{ - /** + //@{ + /** // Convenience "examine" method for histograms of corresponding // dimensionality */ - const Numeric& examine() const; + const Numeric& examine() const; - const Numeric& examine(double x0) const; + const Numeric& examine(double x0) const; - const Numeric& examine(double x0, double x1) const; + const Numeric& examine(double x0, double x1) const; - const Numeric& examine(double x0, double x1, double x2) const; + const Numeric& examine(double x0, double x1, double x2) const; - const Numeric& examine(double x0, double x1, double x2, - double x3) const; + const Numeric& examine(double x0, double x1, double x2, double x3) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4) const; + const Numeric& examine(double x0, double x1, double x2, double x3, double x4) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4, double x5) const; + const Numeric& examine(double x0, double x1, double x2, double x3, double x4, double x5) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4, double x5, double x6) const; + const Numeric& examine(double x0, double x1, double x2, double x3, double x4, double x5, double x6) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, - double x7) const; + const Numeric& examine(double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8) const; + const Numeric& examine( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8) const; - const Numeric& examine(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8, double x9) const; - //@} + const Numeric& examine( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8, double x9) + const; + //@} - /** + /** // The "closestBin" functions are similar to the "examine" functions // but always return a valid bin and never overflow. This can be // useful for implementing lookup tables with constant extrapolation // outside of the histogram range. */ - const Numeric& closestBin(const double* coords, - unsigned coordLength) const; + const Numeric& closestBin(const double* coords, unsigned coordLength) const; - //@{ - /** + //@{ + /** // Convenience "closestBin" method for histograms of corresponding // dimensionality */ - const Numeric& closestBin() const; + const Numeric& closestBin() const; - const Numeric& closestBin(double x0) const; + const Numeric& closestBin(double x0) const; - const Numeric& closestBin(double x0, double x1) const; + const Numeric& closestBin(double x0, double x1) const; - const Numeric& closestBin(double x0, double x1, double x2) const; + const Numeric& closestBin(double x0, double x1, double x2) const; - const Numeric& closestBin(double x0, double x1, double x2, - double x3) const; + const Numeric& closestBin(double x0, double x1, double x2, double x3) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4) const; + const Numeric& closestBin(double x0, double x1, double x2, double x3, double x4) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4, double x5) const; + const Numeric& closestBin(double x0, double x1, double x2, double x3, double x4, double x5) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4, double x5, double x6) const; + const Numeric& closestBin(double x0, double x1, double x2, double x3, double x4, double x5, double x6) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, - double x7) const; + const Numeric& closestBin( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8) const; + const Numeric& closestBin( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8) const; - const Numeric& closestBin(double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8, double x9) const; - //@} + const Numeric& closestBin( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, double x8, double x9) + const; + //@} - /** + /** // The "fillC" functions are similar to the "fill" methods but // they preserve the centroid of the deposit. Note that, if the // histogram dimensionality is high, "fillC" works significantly @@ -509,66 +537,76 @@ namespace npstat { // HistoAxis rather than, let say, NUHistoAxis). They typically // will not even compile if the binning is not uniform. */ - template - void fillC(const double* coords, unsigned coordLength, - const Num2& weight); + template + void fillC(const double* coords, unsigned coordLength, const Num2& weight); - //@{ - /** + //@{ + /** // Convenience "fillC" method for histograms of corresponding // dimensionality */ - template - void fillC(const Num2& weight); - - template - void fillC(double x0, const Num2& weight); - - template - void fillC(double x0, double x1, const Num2& weight); - - template - void fillC(double x0, double x1, double x2, const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, - const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - double x5, const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, - const Num2& weight); - - template - void fillC(double x0, double x1, double x2, double x3, double x4, - double x5, double x6, double x7, double x8, double x9, - const Num2& weight); - //@} - - /** + template + void fillC(const Num2& weight); + + template + void fillC(double x0, const Num2& weight); + + template + void fillC(double x0, double x1, const Num2& weight); + + template + void fillC(double x0, double x1, double x2, const Num2& weight); + + template + void fillC(double x0, double x1, double x2, double x3, const Num2& weight); + + template + void fillC(double x0, double x1, double x2, double x3, double x4, const Num2& weight); + + template + void fillC(double x0, double x1, double x2, double x3, double x4, double x5, const Num2& weight); + + template + void fillC(double x0, double x1, double x2, double x3, double x4, double x5, double x6, const Num2& weight); + + template + void fillC( + double x0, double x1, double x2, double x3, double x4, double x5, double x6, double x7, const Num2& weight); + + template + void fillC(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + const Num2& weight); + + template + void fillC(double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + double x9, + const Num2& weight); + //@} + + /** // Fill from another histogram. Compatibility of axis limits // will not be checked, but compatibility of array shapes will be. */ - template - HistoND& operator+=(const HistoND& r); + template + HistoND& operator+=(const HistoND& r); - /** + /** // Subtract contents of another histogram. Equivalent to multiplying // the contents of the other histogram by -1 and then adding them. // One of the consequences of this approach is that, for histograms @@ -577,202 +615,249 @@ namespace npstat { // remain the same (up to round-off errors), the fill counts will // increase by twice the fill counts of "b". */ - template - HistoND& operator-=(const HistoND& r); + template + HistoND& operator-=(const HistoND& r); - //@{ - /** Method to set contents of individual bins (no bounds checking) */ - template - void setBin(const unsigned *index, unsigned indexLen, const Num2& v); - - template - void setBin(const Num2& v); + //@{ + /** Method to set contents of individual bins (no bounds checking) */ + template + void setBin(const unsigned* index, unsigned indexLen, const Num2& v); + + template + void setBin(const Num2& v); + + template + void setBin(unsigned i0, const Num2& v); + + template + void setBin(unsigned i0, unsigned i1, const Num2& v); + + template + void setBin(unsigned i0, unsigned i1, unsigned i2, const Num2& v); - template - void setBin(unsigned i0, const Num2& v); + template + void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, const Num2& v); - template - void setBin(unsigned i0, unsigned i1, const Num2& v); - - template - void setBin(unsigned i0, unsigned i1, unsigned i2, const Num2& v); + template + void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - const Num2& v); + template + void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, const Num2& v); + template + void setBin( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, const Num2& v); + template + void setBin(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, const Num2& v); + template + void setBin(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - const Num2& v); + template + void setBin(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9, + const Num2& v); - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, const Num2& v); + template + inline void setLinearBin(const unsigned long index, const Num2& v) { + data_.linearValue(index) = v; + ++modCount_; + } + //@} - template - void setBin(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, unsigned i9, const Num2& v); + //@{ + /** Method to set contents of individual bins with bounds checking */ + template + void setBinAt(const unsigned* index, unsigned indexLen, const Num2& v); - template - inline void setLinearBin(const unsigned long index, const Num2& v) - {data_.linearValue(index) = v; ++modCount_;} - //@} + template + void setBinAt(const Num2& v); - //@{ - /** Method to set contents of individual bins with bounds checking */ - template - void setBinAt(const unsigned *index, unsigned indexLen, const Num2& v); + template + void setBinAt(unsigned i0, const Num2& v); - template - void setBinAt(const Num2& v); + template + void setBinAt(unsigned i0, unsigned i1, const Num2& v); - template - void setBinAt(unsigned i0, const Num2& v); + template + void setBinAt(unsigned i0, unsigned i1, unsigned i2, const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, const Num2& v); + template + void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, const Num2& v); + template + void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - const Num2& v); + template + void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, const Num2& v); + template + void setBinAt( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, const Num2& v); + template + void setBinAt(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, const Num2& v); + template + void setBinAt(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - const Num2& v); + template + void setBinAt(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9, + const Num2& v); - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, const Num2& v); + template + inline void setLinearBinAt(const unsigned long index, const Num2& v) { + data_.linearValueAt(index) = v; + ++modCount_; + } + //@} - template - void setBinAt(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, unsigned i9, const Num2& v); - - template - inline void setLinearBinAt(const unsigned long index, const Num2& v) - {data_.linearValueAt(index) = v; ++modCount_;} - //@} + /** This method sets all bin contents in one fell swoop */ + template + void setBinContents(const Num2* data, unsigned long dataLength, bool clearOverflows = true); - /** This method sets all bin contents in one fell swoop */ - template - void setBinContents(const Num2* data, unsigned long dataLength, - bool clearOverflows=true); + /** This method sets all overflows in one fell swoop */ + template + void setOverflows(const Num2* data, unsigned long dataLength); - /** This method sets all overflows in one fell swoop */ - template - void setOverflows(const Num2* data, unsigned long dataLength); - - /** + /** // Setting bin contents to some constant value. // The Num2 type should allow automatic conversion to Numeric. */ - template - inline void setBinsToConst(const Num2& value) - {data_.constFill(value); ++modCount_;} + template + inline void setBinsToConst(const Num2& value) { + data_.constFill(value); + ++modCount_; + } - /** + /** // Setting overflows to some constant value. // The Num2 type should allow automatic conversion to Numeric. */ - template - inline void setOverflowsToConst(const Num2& value) - {overflow_.constFill(value); ++modCount_;} + template + inline void setOverflowsToConst(const Num2& value) { + overflow_.constFill(value); + ++modCount_; + } - /** + /** // This member function instructs the histogram to recalculate // the number of fills from data. It may be useful to call this // function after "setBinContents" in case the contents are filled // from another histogram. */ - void recalculateNFillsFromData(); + void recalculateNFillsFromData(); - //@{ - /** + //@{ + /** // This method is intended for data format conversion // programs only, not for typical histogramming use */ - inline void setNFillsTotal(const unsigned long i) - {fillCount_ = i; ++modCount_;} - inline void setNFillsOver(const unsigned long i) - {overCount_ = i; ++modCount_;} - //@} - - /** In-place multiplication by a scalar (scaling) */ - template - HistoND& operator*=(const Num2& r); - - /** In-place division by a scalar */ - template - HistoND& operator/=(const Num2& r); - - //@{ - /** Multiplication by a value which is different for every bin */ - template - void scaleBinContents(const Num2* data, unsigned long dataLength); - - template - void scaleOverflows(const Num2* data, unsigned long dataLength); - //@} - - //@{ - /** + inline void setNFillsTotal(const unsigned long i) { + fillCount_ = i; + ++modCount_; + } + inline void setNFillsOver(const unsigned long i) { + overCount_ = i; + ++modCount_; + } + //@} + + /** In-place multiplication by a scalar (scaling) */ + template + HistoND& operator*=(const Num2& r); + + /** In-place division by a scalar */ + template + HistoND& operator/=(const Num2& r); + + //@{ + /** Multiplication by a value which is different for every bin */ + template + void scaleBinContents(const Num2* data, unsigned long dataLength); + + template + void scaleOverflows(const Num2* data, unsigned long dataLength); + //@} + + //@{ + /** // In-place addition of a scalar to all bins. Equivalent to calling // the "fill" function with the same weight once for every bin. */ - template - void addToBinContents(const Num2& weight); + template + void addToBinContents(const Num2& weight); - template - void addToOverflows(const Num2& weight); - //@} + template + void addToOverflows(const Num2& weight); + //@} - //@{ - /** + //@{ + /** // In-place addition of an array. Equivalent to calling the "fill" // function once for every bin with the weight taken from the // corresponding array element. */ - template - void addToBinContents(const Num2* data, unsigned long dataLength); + template + void addToBinContents(const Num2* data, unsigned long dataLength); - template - void addToOverflows(const Num2* data, unsigned long dataLength); - //@} + template + void addToOverflows(const Num2* data, unsigned long dataLength); + //@} - /** + /** // Add contents of all bins inside the given box to the accumulator. // Note that Numeric type must support multiplication by a double // in order for this function to work (it calculates the overlap @@ -780,12 +865,11 @@ namespace npstat { // by that fraction for subsequent accumulation). The operation // Acc += Numeric must be defined. */ - template - void accumulateBinsInBox(const BoxND& box, Acc* acc, - bool calculateAverage = false) const; + template + void accumulateBinsInBox(const BoxND& box, Acc* acc, bool calculateAverage = false) const; - //@{ - /** + //@{ + /** // Code for projecting one histogram onto another. For now, // this is done for bin contents only, not for overflows. // The projection should be created in advance from this @@ -795,23 +879,23 @@ namespace npstat { // Note that you might want to recalculate the number of fills // from data after performing all projections needed. */ - template - void addToProjection(HistoND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - - template - void addToProjection(HistoND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - unsigned nProjectedIndices) const; - //@} - - /** Transpose the histogram axes and bin contents */ - HistoND transpose(unsigned axisNum1, unsigned axisNum2) const; - - /** + template + void addToProjection(HistoND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + + template + void addToProjection(HistoND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + unsigned nProjectedIndices) const; + //@} + + /** Transpose the histogram axes and bin contents */ + HistoND transpose(unsigned axisNum1, unsigned axisNum2) const; + + /** // This method returns the number of modifications // performed on the histogram since its creation. This number // is always increasing during the lifetime of the histogram @@ -823,54 +907,56 @@ namespace npstat { // This number is pure transient, it is not serialized and // does not participate in histogram comparisons for equality. */ - inline unsigned long getModCount() const {return modCount_;} + inline unsigned long getModCount() const { return modCount_; } - /** + /** // Indicate that the histogram contents have changed. Should // be used by any code which directly modifies histogram bins // (after using const_cast on the relevant reference). */ - inline void incrModCount() {++modCount_;} - - //@{ - /** Method related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static const char* classname(); - static inline unsigned version() {return 1;} - static HistoND* read(const gs::ClassId& id, std::istream& in); - - private: - HistoND() = delete; - - // Special constructor which speeds up the "transpose" operation. - // Does not do full error checking (some of it is done in transpose). - HistoND(const HistoND& r, unsigned ax1, unsigned ax2); - - template - void fillPreservingCentroid(const Num2& weight); - - template - void accumulateBinsLoop(unsigned level, const BoxND& box, - unsigned* idx, Acc* accumulator, - double overlapFraction, long double* wsum) const; - std::string title_; - std::string accumulatedDataLabel_; - ArrayND data_; - ArrayND overflow_; - std::vector axes_; - mutable std::vector weightBuf_; - mutable std::vector indexBuf_; - unsigned long fillCount_; - unsigned long overCount_; - unsigned long modCount_; - unsigned dim_; - - }; + inline void incrModCount() { ++modCount_; } - /** + //@{ + /** Method related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static const char* classname(); + static inline unsigned version() { return 1; } + static HistoND* read(const gs::ClassId& id, std::istream& in); + + private: + HistoND() = delete; + + // Special constructor which speeds up the "transpose" operation. + // Does not do full error checking (some of it is done in transpose). + HistoND(const HistoND& r, unsigned ax1, unsigned ax2); + + template + void fillPreservingCentroid(const Num2& weight); + + template + void accumulateBinsLoop(unsigned level, + const BoxND& box, + unsigned* idx, + Acc* accumulator, + double overlapFraction, + long double* wsum) const; + std::string title_; + std::string accumulatedDataLabel_; + ArrayND data_; + ArrayND overflow_; + std::vector axes_; + mutable std::vector weightBuf_; + mutable std::vector indexBuf_; + unsigned long fillCount_; + unsigned long overCount_; + unsigned long modCount_; + unsigned dim_; + }; + + /** // Reset negative histogram bins to zero and then divide histogram // bin contents by the histogram integral. If the "knownNonNegative" // argument is true, it will be assumed that there are no negative @@ -884,18 +970,18 @@ namespace npstat { // Making such operation a member would make creation of HistoND // scripting API (e.g., for python) more difficult. */ - template - void convertHistoToDensity(Histo* histogram, bool knownNonNegative=false); + template + void convertHistoToDensity(Histo* histogram, bool knownNonNegative = false); - /** + /** // Generate a density scanning map for subsequent use with // the "DensityScanND" template. Naturally, only histograms // with uniform binning can be used here. */ - template - std::vector densityScanHistoMap(const Histo& histo); + template + std::vector densityScanHistoMap(const Histo& histo); - /** + /** // Generate a density scanning map for subsequent use with the // "DensityScanND" template when a density is to be convolved with // the histogram data. Only histograms with uniform binning @@ -905,10 +991,9 @@ namespace npstat { // will be mirrored (or just empty range added) to avoid circular // spilling after convolution. */ - template - std::vector convolutionHistoMap(const Histo& histo, - bool doubleDataRange); -} + template + std::vector convolutionHistoMap(const Histo& histo, bool doubleDataRange); +} // namespace npstat #include #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" @@ -920,2746 +1005,2560 @@ namespace npstat { #include "Alignment/Geners/interface/binaryIO.hh" namespace npstat { - namespace Private { - template - ArrayShape makeHistoShape(const std::vector& axes) - { - const unsigned n = axes.size(); - ArrayShape result; - result.reserve(n); - for (unsigned i=0; i - ArrayShape makeHistoShape(const Axis& xAxis) - { - ArrayShape result; - result.reserve(1U); - result.push_back(xAxis.nBins()); - return result; - } - - template - ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis) - { - ArrayShape result; - result.reserve(2U); - result.push_back(xAxis.nBins()); - result.push_back(yAxis.nBins()); - return result; - } - - template - ArrayShape makeHistoShape(const Axis& xAxis, - const Axis& yAxis, - const Axis& zAxis) - { - ArrayShape result; - result.reserve(3U); - result.push_back(xAxis.nBins()); - result.push_back(yAxis.nBins()); - result.push_back(zAxis.nBins()); - return result; - } - - template - ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis) - { - ArrayShape result; - result.reserve(4U); - result.push_back(xAxis.nBins()); - result.push_back(yAxis.nBins()); - result.push_back(zAxis.nBins()); - result.push_back(tAxis.nBins()); - return result; - } - - template - ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, - const Axis& vAxis) - { - ArrayShape result; - result.reserve(5U); - result.push_back(xAxis.nBins()); - result.push_back(yAxis.nBins()); - result.push_back(zAxis.nBins()); - result.push_back(tAxis.nBins()); - result.push_back(vAxis.nBins()); - return result; - } - - template - std::vector rebinAxes(const std::vector& axes, - const unsigned *newBins, - const unsigned lenNewBins) - { - const unsigned dim = axes.size(); - if (lenNewBins != dim) throw npstat::NpstatInvalidArgument( - "In npstat::Private::rebinAxes: invalid length " - "of the new bins array"); - assert(newBins); - std::vector newAxes; - newAxes.reserve(dim); - for (unsigned i=0; i - std::vector axesOfASlice(const std::vector& axes, - const unsigned *fixedIndices, - const unsigned nFixedIndices) - { - const unsigned dim = axes.size(); - std::vector newAxes; - if (nFixedIndices == 0U) throw npstat::NpstatInvalidArgument( - "In npstat::Private::axesOfASlice: " - "at least one fixed index must be specified"); - if (nFixedIndices > dim) throw npstat::NpstatInvalidArgument( - "In npstat::Private::axesOfASlice: too many fixed indices"); - assert(fixedIndices); - for (unsigned i=0; i= dim) throw npstat::NpstatInvalidArgument( - "In npstat::Private::axesOfASlice: fixed index out of range"); - newAxes.reserve(dim - nFixedIndices); - for (unsigned i=0; i - ArrayShape shapeOfASlice(const std::vector& axes, - const unsigned *fixedIndices, - const unsigned nFixedIndices) - { - const unsigned dim = axes.size(); - if (nFixedIndices == 0U) throw npstat::NpstatInvalidArgument( - "In npstat::Private::shapeOfASlice: " - "at least one fixed index must be specified"); - if (nFixedIndices > dim) throw npstat::NpstatInvalidArgument( - "In npstat::Private::shapeOfASlice: too many fixed indices"); - assert(fixedIndices); - - // Check that the fixed indices are within range - for (unsigned j=0; j= dim) throw npstat::NpstatInvalidArgument( - "In npstat::Private::shapeOfASlice: fixed index out of range"); - - // Build the shape for the slice - ArrayShape sh; - if (nFixedIndices < dim) - sh.reserve(dim - nFixedIndices); - for (unsigned i=0; i - std::vector addAxis(const std::vector& axes, - const Axis& newAxis, - const unsigned newAxisNumber) - { - const unsigned dim = axes.size(); - std::vector newAxes; - newAxes.reserve(dim + 1U); - unsigned iadd = 0; - for (unsigned i=0; i - ArrayShape shapeWithExtraAxis(const std::vector& axes, - const Axis& newAxis, - const unsigned newAxisNumber) - { - const unsigned dim = axes.size(); - ArrayShape result; - result.reserve(dim + 1U); - unsigned iadd = 0; - for (unsigned i=0; i - template - void HistoND::accumulateBinsLoop( - const unsigned level, const BoxND& box, - unsigned* idx, Acc* accumulator, const double overlapFraction, - long double* wsum) const - { - const Interval& boxSide(box[level]); - const Axis& axis(axes_[level]); - const unsigned nbins = axis.nBins(); - const bool lastLevel = level == dim_ - 1U; - for (unsigned i=0; i 0.0) - { - idx[level] = i; - if (lastLevel) - { - *accumulator += over*data_.value(idx, dim_); - *wsum += over; - } - else - accumulateBinsLoop(level+1U, box, idx, accumulator, - over, wsum); - } - } - } - - template - template - void HistoND::accumulateBinsInBox( - const BoxND& box, Acc* accumulator, - const bool calculateAverage) const - { - if (box.size() != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::accumulateBinsInBox: " - "incompatible box dimensionality"); - assert(accumulator); - if (dim_) - { - long double wsum = 0.0L; - for (unsigned i=0; i 0.0L) - *accumulator *= static_cast(1.0L/wsum); - } + namespace Private { + template + ArrayShape makeHistoShape(const std::vector& axes) { + const unsigned n = axes.size(); + ArrayShape result; + result.reserve(n); + for (unsigned i = 0; i < n; ++i) + result.push_back(axes[i].nBins()); + return result; + } + + template + ArrayShape makeHistoShape(const Axis& xAxis) { + ArrayShape result; + result.reserve(1U); + result.push_back(xAxis.nBins()); + return result; + } + + template + ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis) { + ArrayShape result; + result.reserve(2U); + result.push_back(xAxis.nBins()); + result.push_back(yAxis.nBins()); + return result; + } + + template + ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis, const Axis& zAxis) { + ArrayShape result; + result.reserve(3U); + result.push_back(xAxis.nBins()); + result.push_back(yAxis.nBins()); + result.push_back(zAxis.nBins()); + return result; + } + + template + ArrayShape makeHistoShape(const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const Axis& tAxis) { + ArrayShape result; + result.reserve(4U); + result.push_back(xAxis.nBins()); + result.push_back(yAxis.nBins()); + result.push_back(zAxis.nBins()); + result.push_back(tAxis.nBins()); + return result; + } + + template + ArrayShape makeHistoShape( + const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const Axis& tAxis, const Axis& vAxis) { + ArrayShape result; + result.reserve(5U); + result.push_back(xAxis.nBins()); + result.push_back(yAxis.nBins()); + result.push_back(zAxis.nBins()); + result.push_back(tAxis.nBins()); + result.push_back(vAxis.nBins()); + return result; + } + + template + std::vector rebinAxes(const std::vector& axes, const unsigned* newBins, const unsigned lenNewBins) { + const unsigned dim = axes.size(); + if (lenNewBins != dim) + throw npstat::NpstatInvalidArgument( + "In npstat::Private::rebinAxes: invalid length " + "of the new bins array"); + assert(newBins); + std::vector newAxes; + newAxes.reserve(dim); + for (unsigned i = 0; i < dim; ++i) + newAxes.push_back(axes[i].rebin(newBins[i])); + return newAxes; + } + + template + std::vector axesOfASlice(const std::vector& axes, + const unsigned* fixedIndices, + const unsigned nFixedIndices) { + const unsigned dim = axes.size(); + std::vector newAxes; + if (nFixedIndices == 0U) + throw npstat::NpstatInvalidArgument( + "In npstat::Private::axesOfASlice: " + "at least one fixed index must be specified"); + if (nFixedIndices > dim) + throw npstat::NpstatInvalidArgument("In npstat::Private::axesOfASlice: too many fixed indices"); + assert(fixedIndices); + for (unsigned i = 0; i < nFixedIndices; ++i) + if (fixedIndices[i] >= dim) + throw npstat::NpstatInvalidArgument("In npstat::Private::axesOfASlice: fixed index out of range"); + newAxes.reserve(dim - nFixedIndices); + for (unsigned i = 0; i < dim; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + break; + } + if (!fixed) + newAxes.push_back(axes[i]); + } + if (newAxes.size() != dim - nFixedIndices) + throw npstat::NpstatInvalidArgument("In npstat::Private::axesOfASlice: duplicate fixed index"); + return newAxes; + } + + template + ArrayShape shapeOfASlice(const std::vector& axes, + const unsigned* fixedIndices, + const unsigned nFixedIndices) { + const unsigned dim = axes.size(); + if (nFixedIndices == 0U) + throw npstat::NpstatInvalidArgument( + "In npstat::Private::shapeOfASlice: " + "at least one fixed index must be specified"); + if (nFixedIndices > dim) + throw npstat::NpstatInvalidArgument("In npstat::Private::shapeOfASlice: too many fixed indices"); + assert(fixedIndices); + + // Check that the fixed indices are within range + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] >= dim) + throw npstat::NpstatInvalidArgument("In npstat::Private::shapeOfASlice: fixed index out of range"); + + // Build the shape for the slice + ArrayShape sh; + if (nFixedIndices < dim) + sh.reserve(dim - nFixedIndices); + for (unsigned i = 0; i < dim; ++i) { + bool fixed = false; + for (unsigned j = 0; j < nFixedIndices; ++j) + if (fixedIndices[j] == i) { + fixed = true; + break; + } + if (!fixed) + sh.push_back(axes[i].nBins()); + } + if (sh.size() != dim - nFixedIndices) + throw npstat::NpstatInvalidArgument("In npstat::Private::shapeOfASlice: duplicate fixed index"); + return sh; + } + + template + std::vector addAxis(const std::vector& axes, const Axis& newAxis, const unsigned newAxisNumber) { + const unsigned dim = axes.size(); + std::vector newAxes; + newAxes.reserve(dim + 1U); + unsigned iadd = 0; + for (unsigned i = 0; i < dim; ++i) { + if (newAxisNumber == i) + newAxes.push_back(newAxis); else - *accumulator += 1.0*data_(); - } - - template - inline void HistoND::clearBinContents() - { - data_.clear(); - fillCount_ = 0UL; - ++modCount_; - } - - template - inline void HistoND::clearOverflows() - { - overflow_.clear(); - overCount_ = 0UL; - ++modCount_; - } - - template - inline void HistoND::clear() - { - clearBinContents(); - clearOverflows(); - ++modCount_; - } - - template - HistoND::HistoND(const std::vector& axesIn, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(axesIn)), - overflow_(ArrayShape(axesIn.size(), 3U)), - axes_(axesIn), - weightBuf_(axesIn.size()), - indexBuf_(2U*axesIn.size()), - modCount_(0UL), - dim_(axesIn.size()) - { - if (dim_ >= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::HistoND constructor: requested histogram " - "dimensionality is not supported (too large)"); - clear(); - } - - template - HistoND::HistoND(const Axis& xAxis, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(xAxis)), - overflow_(ArrayShape(1U, 3U)), - weightBuf_(1U), - indexBuf_(2U*1U), - modCount_(0UL), - dim_(1U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - clear(); - } - - template - HistoND::HistoND(const Axis& xAxis, const Axis& yAxis, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(xAxis, yAxis)), - overflow_(ArrayShape(2U, 3U)), - weightBuf_(2U), - indexBuf_(2U*2U), - modCount_(0UL), - dim_(2U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - clear(); - } - - template - HistoND::HistoND(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const char* title, - const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(xAxis, yAxis, zAxis)), - overflow_(ArrayShape(3U, 3U)), - weightBuf_(3U), - indexBuf_(2U*3U), - modCount_(0UL), - dim_(3U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - clear(); - } - - template - HistoND::HistoND(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(xAxis, yAxis, zAxis, tAxis)), - overflow_(ArrayShape(4U, 3U)), - weightBuf_(4U), - indexBuf_(2U*4U), - modCount_(0UL), - dim_(4U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - axes_.push_back(tAxis); - clear(); - } - - template - HistoND::HistoND(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, - const Axis& vAxis, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(Private::makeHistoShape(xAxis, yAxis, zAxis, tAxis, vAxis)), - overflow_(ArrayShape(5U, 3U)), - weightBuf_(5U), - indexBuf_(2U*5U), - modCount_(0UL), - dim_(5U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - axes_.push_back(tAxis); - axes_.push_back(vAxis); - clear(); - } - - template - HistoND::HistoND(const ArrayShape& shape, - const BoxND& boundingBox, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(shape), - overflow_(ArrayShape(shape.size(), 3U)), - weightBuf_(shape.size()), - indexBuf_(2U*shape.size()), - modCount_(0UL), - dim_(shape.size()) - { - if (boundingBox.size() != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND constructor: " - "incompatible bounding box dimensionality"); - if (dim_ >= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::HistoND constructor: requested histogram " - "dimensionality is not supported (too large)"); - axes_.reserve(dim_); - for (unsigned i=0; i - template - HistoND::HistoND( - const HistoND& r, const Functor& f, - const char* title, const char* label) - : title_(title ? title : ""), - accumulatedDataLabel_(label ? label : ""), - data_(r.data_, f), - overflow_(r.overflow_, f), - axes_(r.axes_), - weightBuf_(r.dim_), - indexBuf_(2U*r.dim_), - fillCount_(r.fillCount_), - overCount_(r.overCount_), - modCount_(0UL), - dim_(r.dim_) - { - } - - template - template - HistoND::HistoND( - const HistoND& h, const unsigned *indices, - const unsigned nIndices, const char* title) - : title_(title ? title : ""), - accumulatedDataLabel_(h.accumulatedDataLabel_), - data_(Private::shapeOfASlice(h.axes_, indices, nIndices)), - overflow_(ArrayShape(data_.rank(), 3U)), - axes_(Private::axesOfASlice(h.axes_, indices, nIndices)), - weightBuf_(data_.rank()), - indexBuf_(2U*data_.rank()), - modCount_(0UL), - dim_(data_.rank()) - { - clear(); - } - - template - template - HistoND::HistoND( - const HistoND& h, const Axis& newAxis, - const unsigned newAxisNumber, const char* title) - : title_(title ? title : ""), - accumulatedDataLabel_(h.accumulatedDataLabel_), - data_(Private::shapeWithExtraAxis(h.axes_, newAxis, newAxisNumber)), - overflow_(data_.rank(), 3U), - axes_(Private::addAxis(h.axes_, newAxis, newAxisNumber)), - weightBuf_(data_.rank()), - indexBuf_(2U*data_.rank()), - modCount_(0UL), - dim_(data_.rank()) - { - if (dim_ >= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::HistoND constructor: requested histogram " - "dimensionality is not supported (too large)"); - clear(); - } - - template - template - HistoND::HistoND( - const HistoND& h, const RebinType rType, - const unsigned *newBinCounts, const unsigned lenNewBinCounts, - const double* shifts, const char* title) - : title_(title ? title : h.title_.c_str()), - accumulatedDataLabel_(h.accumulatedDataLabel_), - data_(newBinCounts, lenNewBinCounts), - overflow_(h.overflow_), - axes_(Private::rebinAxes(h.axes_, newBinCounts, lenNewBinCounts)), - weightBuf_(h.dim_), - indexBuf_(2U*h.dim_), - fillCount_(h.fillCount_), - overCount_(h.overCount_), - modCount_(0UL), - dim_(h.dim_) - { - const unsigned long newBins = data_.length(); - const Axis* ax = &axes_[0]; - unsigned* ubuf = &indexBuf_[0]; - - // Fill out the bins of the new histogram - if (rType == SAMPLE) - { - double* buf = &weightBuf_[0]; - for (unsigned long ibin=0; ibin + ArrayShape shapeWithExtraAxis(const std::vector& axes, const Axis& newAxis, const unsigned newAxisNumber) { + const unsigned dim = axes.size(); + ArrayShape result; + result.reserve(dim + 1U); + unsigned iadd = 0; + for (unsigned i = 0; i < dim; ++i) { + if (newAxisNumber == i) + result.push_back(newAxis.nBins()); else - { - const Numeric zero = Numeric(); - BoxND binLimits(dim_); - for (unsigned long ibin=0; ibin - bool HistoND::isUniformlyBinned() const - { - for (unsigned i=0; i - double HistoND::integral() const - { - typedef typename PreciseType::type Precise; - - if (dim_ == 0U) - return 0.0; - if (isUniformlyBinned()) - { - Precise sum = data_.template sum(); - return static_cast(sum)*binVolume(); - } + result.push_back(axes[iadd++].nBins()); + } + if (iadd == dim) + result.push_back(newAxis.nBins()); + else + result.push_back(axes[iadd].nBins()); + return result; + } + + inline void h_badargs(const char* method) { + std::ostringstream os; + os << "In npstat::HistoND::" << method << ": number of arguments" + << " is incompatible with histogram dimensionality"; + throw npstat::NpstatInvalidArgument(os.str()); + } + } // namespace Private + + template + template + void HistoND::accumulateBinsLoop(const unsigned level, + const BoxND& box, + unsigned* idx, + Acc* accumulator, + const double overlapFraction, + long double* wsum) const { + const Interval& boxSide(box[level]); + const Axis& axis(axes_[level]); + const unsigned nbins = axis.nBins(); + const bool lastLevel = level == dim_ - 1U; + for (unsigned i = 0; i < nbins; ++i) { + const double over = overlapFraction * axis.binInterval(i).overlapFraction(boxSide); + if (over > 0.0) { + idx[level] = i; + if (lastLevel) { + *accumulator += over * data_.value(idx, dim_); + *wsum += over; + } else + accumulateBinsLoop(level + 1U, box, idx, accumulator, over, wsum); + } + } + } + + template + template + void HistoND::accumulateBinsInBox(const BoxND& box, + Acc* accumulator, + const bool calculateAverage) const { + if (box.size() != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::accumulateBinsInBox: " + "incompatible box dimensionality"); + assert(accumulator); + if (dim_) { + long double wsum = 0.0L; + for (unsigned i = 0; i < dim_; ++i) + indexBuf_[i] = 0U; + accumulateBinsLoop(0U, box, &indexBuf_[0], accumulator, 1.0, &wsum); + if (calculateAverage && wsum > 0.0L) + *accumulator *= static_cast(1.0L / wsum); + } else + *accumulator += 1.0 * data_(); + } + + template + inline void HistoND::clearBinContents() { + data_.clear(); + fillCount_ = 0UL; + ++modCount_; + } + + template + inline void HistoND::clearOverflows() { + overflow_.clear(); + overCount_ = 0UL; + ++modCount_; + } + + template + inline void HistoND::clear() { + clearBinContents(); + clearOverflows(); + ++modCount_; + } + + template + HistoND::HistoND(const std::vector& axesIn, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(axesIn)), + overflow_(ArrayShape(axesIn.size(), 3U)), + axes_(axesIn), + weightBuf_(axesIn.size()), + indexBuf_(2U * axesIn.size()), + modCount_(0UL), + dim_(axesIn.size()) { + if (dim_ >= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND constructor: requested histogram " + "dimensionality is not supported (too large)"); + clear(); + } + + template + HistoND::HistoND(const Axis& xAxis, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(xAxis)), + overflow_(ArrayShape(1U, 3U)), + weightBuf_(1U), + indexBuf_(2U * 1U), + modCount_(0UL), + dim_(1U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + clear(); + } + + template + HistoND::HistoND(const Axis& xAxis, const Axis& yAxis, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(xAxis, yAxis)), + overflow_(ArrayShape(2U, 3U)), + weightBuf_(2U), + indexBuf_(2U * 2U), + modCount_(0UL), + dim_(2U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + clear(); + } + + template + HistoND::HistoND( + const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(xAxis, yAxis, zAxis)), + overflow_(ArrayShape(3U, 3U)), + weightBuf_(3U), + indexBuf_(2U * 3U), + modCount_(0UL), + dim_(3U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + clear(); + } + + template + HistoND::HistoND( + const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const Axis& tAxis, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(xAxis, yAxis, zAxis, tAxis)), + overflow_(ArrayShape(4U, 3U)), + weightBuf_(4U), + indexBuf_(2U * 4U), + modCount_(0UL), + dim_(4U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + axes_.push_back(tAxis); + clear(); + } + + template + HistoND::HistoND(const Axis& xAxis, + const Axis& yAxis, + const Axis& zAxis, + const Axis& tAxis, + const Axis& vAxis, + const char* title, + const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(Private::makeHistoShape(xAxis, yAxis, zAxis, tAxis, vAxis)), + overflow_(ArrayShape(5U, 3U)), + weightBuf_(5U), + indexBuf_(2U * 5U), + modCount_(0UL), + dim_(5U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + axes_.push_back(tAxis); + axes_.push_back(vAxis); + clear(); + } + + template + HistoND::HistoND(const ArrayShape& shape, + const BoxND& boundingBox, + const char* title, + const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(shape), + overflow_(ArrayShape(shape.size(), 3U)), + weightBuf_(shape.size()), + indexBuf_(2U * shape.size()), + modCount_(0UL), + dim_(shape.size()) { + if (boundingBox.size() != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND constructor: " + "incompatible bounding box dimensionality"); + if (dim_ >= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND constructor: requested histogram " + "dimensionality is not supported (too large)"); + axes_.reserve(dim_); + for (unsigned i = 0; i < dim_; ++i) + axes_.push_back(Axis(shape[i], boundingBox[i].min(), boundingBox[i].max())); + clear(); + } + + template + template + HistoND::HistoND(const HistoND& r, const Functor& f, const char* title, const char* label) + : title_(title ? title : ""), + accumulatedDataLabel_(label ? label : ""), + data_(r.data_, f), + overflow_(r.overflow_, f), + axes_(r.axes_), + weightBuf_(r.dim_), + indexBuf_(2U * r.dim_), + fillCount_(r.fillCount_), + overCount_(r.overCount_), + modCount_(0UL), + dim_(r.dim_) {} + + template + template + HistoND::HistoND(const HistoND& h, + const unsigned* indices, + const unsigned nIndices, + const char* title) + : title_(title ? title : ""), + accumulatedDataLabel_(h.accumulatedDataLabel_), + data_(Private::shapeOfASlice(h.axes_, indices, nIndices)), + overflow_(ArrayShape(data_.rank(), 3U)), + axes_(Private::axesOfASlice(h.axes_, indices, nIndices)), + weightBuf_(data_.rank()), + indexBuf_(2U * data_.rank()), + modCount_(0UL), + dim_(data_.rank()) { + clear(); + } + + template + template + HistoND::HistoND(const HistoND& h, + const Axis& newAxis, + const unsigned newAxisNumber, + const char* title) + : title_(title ? title : ""), + accumulatedDataLabel_(h.accumulatedDataLabel_), + data_(Private::shapeWithExtraAxis(h.axes_, newAxis, newAxisNumber)), + overflow_(data_.rank(), 3U), + axes_(Private::addAxis(h.axes_, newAxis, newAxisNumber)), + weightBuf_(data_.rank()), + indexBuf_(2U * data_.rank()), + modCount_(0UL), + dim_(data_.rank()) { + if (dim_ >= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND constructor: requested histogram " + "dimensionality is not supported (too large)"); + clear(); + } + + template + template + HistoND::HistoND(const HistoND& h, + const RebinType rType, + const unsigned* newBinCounts, + const unsigned lenNewBinCounts, + const double* shifts, + const char* title) + : title_(title ? title : h.title_.c_str()), + accumulatedDataLabel_(h.accumulatedDataLabel_), + data_(newBinCounts, lenNewBinCounts), + overflow_(h.overflow_), + axes_(Private::rebinAxes(h.axes_, newBinCounts, lenNewBinCounts)), + weightBuf_(h.dim_), + indexBuf_(2U * h.dim_), + fillCount_(h.fillCount_), + overCount_(h.overCount_), + modCount_(0UL), + dim_(h.dim_) { + const unsigned long newBins = data_.length(); + const Axis* ax = &axes_[0]; + unsigned* ubuf = &indexBuf_[0]; + + // Fill out the bins of the new histogram + if (rType == SAMPLE) { + double* buf = &weightBuf_[0]; + for (unsigned long ibin = 0; ibin < newBins; ++ibin) { + data_.convertLinearIndex(ibin, ubuf, dim_); + if (shifts) + for (unsigned i = 0; i < dim_; ++i) + buf[i] = ax[i].binCenter(ubuf[i]) + shifts[i]; else - { - Precise sum = Precise(); - const Numeric* data = data_.data(); - const unsigned long len = data_.length(); - for (unsigned long i=0; i(sum); - } - } - - template - BoxND HistoND::boundingBox() const - { - BoxND box; - if (dim_) - { - box.reserve(dim_); - const Axis* ax = &axes_[0]; - for (unsigned i=0; i - void HistoND::binCenter( - const unsigned long binNumber, - double* coords, const unsigned lenCoords) const - { - if (dim_ != lenCoords) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::binCenter: " - "incompatible input point dimensionality"); - if (dim_) - { - assert(coords); - data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); - const Axis* ax = &axes_[0]; - for (unsigned i=0; i - template - void HistoND::allBinCenters( - std::vector* centers) const - { - assert(centers); - centers->clear(); - const unsigned long len = data_.length(); - centers->reserve(len); - unsigned* ibuf = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - Point center; - if (center.size() < dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::allBinCenters: " - "incompatible point dimensionality (too small)"); - typename Point::value_type* cdat = ¢er[0]; - - for (unsigned long i=0; ipush_back(center); + for (unsigned i = 0; i < dim_; ++i) + buf[i] = ax[i].binCenter(ubuf[i]); + data_.linearValue(ibin) = h.examine(buf, dim_); + } + } else { + const Numeric zero = Numeric(); + BoxND binLimits(dim_); + for (unsigned long ibin = 0; ibin < newBins; ++ibin) { + data_.convertLinearIndex(ibin, ubuf, dim_); + for (unsigned i = 0; i < dim_; ++i) + binLimits[i] = ax[i].binInterval(ubuf[i]); + Numeric& thisBin(data_.linearValue(ibin)); + thisBin = zero; + h.accumulateBinsInBox(binLimits, &thisBin, rType == AVERAGE); + } + } + } + + template + bool HistoND::isUniformlyBinned() const { + for (unsigned i = 0; i < dim_; ++i) + if (!axes_[i].isUniform()) + return false; + return true; + } + + template + double HistoND::integral() const { + typedef typename PreciseType::type Precise; + + if (dim_ == 0U) + return 0.0; + if (isUniformlyBinned()) { + Precise sum = data_.template sum(); + return static_cast(sum) * binVolume(); + } else { + Precise sum = Precise(); + const Numeric* data = data_.data(); + const unsigned long len = data_.length(); + for (unsigned long i = 0; i < len; ++i) + sum += data[i] * binVolume(i); + return static_cast(sum); + } + } + + template + BoxND HistoND::boundingBox() const { + BoxND box; + if (dim_) { + box.reserve(dim_); + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + box.push_back(ax[i].interval()); + } + return box; + } + + template + void HistoND::binCenter(const unsigned long binNumber, + double* coords, + const unsigned lenCoords) const { + if (dim_ != lenCoords) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::binCenter: " + "incompatible input point dimensionality"); + if (dim_) { + assert(coords); + data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + coords[i] = ax[i].binCenter(indexBuf_[i]); + } + } + + template + template + void HistoND::allBinCenters(std::vector* centers) const { + assert(centers); + centers->clear(); + const unsigned long len = data_.length(); + centers->reserve(len); + unsigned* ibuf = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + Point center; + if (center.size() < dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::allBinCenters: " + "incompatible point dimensionality (too small)"); + typename Point::value_type* cdat = ¢er[0]; + + for (unsigned long i = 0; i < len; ++i) { + data_.convertLinearIndex(i, ibuf, dim_); + for (unsigned idim = 0; idim < dim_; ++idim) + cdat[idim] = ax[idim].binCenter(ibuf[idim]); + centers->push_back(center); + } + } + + template + void HistoND::binBox(const unsigned long binNumber, BoxND* box) const { + assert(box); + box->clear(); + if (dim_) { + box->reserve(dim_); + data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + box->push_back(ax[i].binInterval(indexBuf_[i])); + } + } + + template + inline bool HistoND::isSameData(const HistoND& r) const { + return dim_ == r.dim_ && overflow_ == r.overflow_ && data_ == r.data_; + } + + template + inline bool HistoND::operator==(const HistoND& r) const { + return dim_ == r.dim_ && fillCount_ == r.fillCount_ && overCount_ == r.overCount_ && title_ == r.title_ && + accumulatedDataLabel_ == r.accumulatedDataLabel_ && axes_ == r.axes_ && overflow_ == r.overflow_ && + data_ == r.data_; + } + + template + inline bool HistoND::operator!=(const HistoND& r) const { + return !(*this == r); + } + + template + double HistoND::binVolume(const unsigned long binNumber) const { + double v = 1.0; + if (dim_) { + data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + v *= ax[i].binWidth(indexBuf_[i]); + } + return v; + } + + template + double HistoND::volume() const { + double v = 1.0; + if (dim_) { + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + v *= (ax[i].max() - ax[i].min()); + } + return v; + } + + template + template + void HistoND::fill(const double* coords, const unsigned coordLength, const Num2& w) { + if (coordLength != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::fill: " + "incompatible input point dimensionality"); + if (coordLength) { + assert(coords); + unsigned* idx = &indexBuf_[0]; + unsigned* over = idx + dim_; + const Axis* ax = &axes_[0]; + unsigned overflown = 0U; + for (unsigned i = 0; i < dim_; ++i) { + over[i] = ax[i].overflowIndex(coords[i], idx + i); + overflown |= (over[i] - 1U); + } + if (overflown) { + overflow_.value(over, dim_) += w; + ++overCount_; + } else + data_.value(idx, dim_) += w; + } else + data_() += w; + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double* coords, const unsigned coordLength, Num2& w, Functor& f) { + if (coordLength != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::dispatch: " + "incompatible input point dimensionality"); + if (coordLength) { + assert(coords); + unsigned* idx = &indexBuf_[0]; + unsigned* over = idx + dim_; + const Axis* ax = &axes_[0]; + unsigned overflown = 0U; + for (unsigned i = 0; i < dim_; ++i) { + over[i] = ax[i].overflowIndex(coords[i], idx + i); + overflown |= (over[i] - 1U); + } + if (overflown) + f(overflow_.value(over, dim_), w); + else + f(data_.value(idx, dim_), w); + } else + f(data_(), w); + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double* coords, const unsigned coordLength) const { + if (coordLength != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::examine: " + "incompatible input point dimensionality"); + if (coordLength) { + assert(coords); + unsigned* idx = &indexBuf_[0]; + unsigned* over = idx + dim_; + const Axis* ax = &axes_[0]; + unsigned overflown = 0U; + for (unsigned i = 0; i < dim_; ++i) { + over[i] = ax[i].overflowIndex(coords[i], idx + i); + overflown |= (over[i] - 1U); + } + if (overflown) + return overflow_.value(over, dim_); + else + return data_.value(idx, dim_); + } else + return data_(); + } + + template + const Numeric& HistoND::closestBin(const double* coords, const unsigned coordLength) const { + if (coordLength != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::closestBin: " + "incompatible input point dimensionality"); + if (coordLength) { + assert(coords); + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + for (unsigned i = 0; i < dim_; ++i) + idx[i] = ax[i].closestValidBin(coords[i]); + return data_.value(idx, dim_); + } else + return data_(); + } + + template + template + void HistoND::fillPreservingCentroid(const Num2& value) { + const double* weights = &weightBuf_[0]; + const unsigned* cell = &indexBuf_[0]; + const unsigned long* strides = data_.strides(); + const unsigned long maxcycle = 1UL << dim_; + for (unsigned long icycle = 0; icycle < maxcycle; ++icycle) { + double w = 1.0; + unsigned long icell = 0UL; + for (unsigned i = 0; i < dim_; ++i) { + if (icycle & (1UL << i)) { + w *= (1.0 - weights[i]); + icell += strides[i] * (cell[i] + 1U); + } else { + w *= weights[i]; + icell += strides[i] * cell[i]; } - } - - template - void HistoND::binBox(const unsigned long binNumber, - BoxND* box) const - { - assert(box); - box->clear(); - if (dim_) - { - box->reserve(dim_); - data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); - const Axis* ax = &axes_[0]; - for (unsigned i=0; ipush_back(ax[i].binInterval(indexBuf_[i])); - } - } - - template - inline bool HistoND::isSameData(const HistoND& r) const - { - return dim_ == r.dim_ && - overflow_ == r.overflow_ && - data_ == r.data_; - } - - template - inline bool HistoND::operator==(const HistoND& r) const - { - return dim_ == r.dim_ && - fillCount_ == r.fillCount_ && - overCount_ == r.overCount_ && - title_ == r.title_ && - accumulatedDataLabel_ == r.accumulatedDataLabel_ && - axes_ == r.axes_ && - overflow_ == r.overflow_ && - data_ == r.data_; - } - - template - inline bool HistoND::operator!=(const HistoND& r) const - { - return !(*this == r); - } - - template - double HistoND::binVolume( - const unsigned long binNumber) const - { - double v = 1.0; - if (dim_) - { - data_.convertLinearIndex(binNumber, &indexBuf_[0], dim_); - const Axis* ax = &axes_[0]; - for (unsigned i=0; i - double HistoND::volume() const - { - double v = 1.0; - if (dim_) - { - const Axis* ax = &axes_[0]; - for (unsigned i=0; i - template - void HistoND::fill( - const double* coords, const unsigned coordLength, const Num2& w) - { - if (coordLength != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::fill: " - "incompatible input point dimensionality"); - if (coordLength) - { - assert(coords); - unsigned* idx = &indexBuf_[0]; - unsigned* over = idx + dim_; - const Axis* ax = &axes_[0]; - unsigned overflown = 0U; - for (unsigned i=0; i - template - void HistoND::dispatch( - const double* coords, const unsigned coordLength, Num2& w, Functor& f) - { - if (coordLength != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::dispatch: " - "incompatible input point dimensionality"); - if (coordLength) - { - assert(coords); - unsigned* idx = &indexBuf_[0]; - unsigned* over = idx + dim_; - const Axis* ax = &axes_[0]; - unsigned overflown = 0U; - for (unsigned i=0; i - const Numeric& HistoND::examine( - const double* coords, const unsigned coordLength) const - { - if (coordLength != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::examine: " - "incompatible input point dimensionality"); - if (coordLength) - { - assert(coords); - unsigned* idx = &indexBuf_[0]; - unsigned* over = idx + dim_; - const Axis* ax = &axes_[0]; - unsigned overflown = 0U; - for (unsigned i=0; i - const Numeric& HistoND::closestBin( - const double* coords, const unsigned coordLength) const - { - if (coordLength != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::closestBin: " - "incompatible input point dimensionality"); - if (coordLength) - { - assert(coords); - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - for (unsigned i=0; i - template - void HistoND::fillPreservingCentroid(const Num2& value) - { - const double* weights = &weightBuf_[0]; - const unsigned* cell = &indexBuf_[0]; - const unsigned long* strides = data_.strides(); - const unsigned long maxcycle = 1UL << dim_; - for (unsigned long icycle=0; icycle - template - void HistoND::fillC( - const double* coords, const unsigned coordLength, const Num2& w) - { - if (coordLength != dim_) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::fillC: " - "incompatible input point dimensionality"); - if (coordLength) - { - assert(coords); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - unsigned* over = idx + dim_; - const Axis* ax = &axes_[0]; - unsigned overflown = 0U; - for (unsigned i=0; i - template - inline void HistoND::fill(const Num2& w) - { - if (dim_) Private::h_badargs("fill"); - data_() += w; - ++fillCount_; ++modCount_; - } - - template - template - inline void HistoND::dispatch(Num2& w, Functor& f) - { - if (dim_) Private::h_badargs("dispatch"); - f(data_(), w); - ++modCount_; - } - - template - template - inline void HistoND::fillC(const Num2& w) - { - if (dim_) Private::h_badargs("fillC"); - data_() += w; - ++fillCount_; ++modCount_; - } - - template - inline const Numeric& HistoND::examine() const - { - if (dim_) Private::h_badargs("examine"); - return data_(); - } - - template - inline const Numeric& HistoND::closestBin() const - { - if (dim_) Private::h_badargs("closestBin"); - return data_(); - } - - template - template - void HistoND::fill(const double x0, const Num2& w) - { - if (dim_ != 1U) Private::h_badargs("fill"); - unsigned i0 = 0; - const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); - if (ov0 == 1U) - data_(i0) += w; - else - { - overflow_(ov0) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, Num2& w, Functor& f) - { - if (dim_ != 1U) Private::h_badargs("dispatch"); - unsigned i0 = 0; - const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); - if (ov0 == 1U) - f(data_(i0), w); - else - f(overflow_(ov0), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const Num2& w) - { - if (dim_ != 1U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const unsigned ov0 = axes_[0].overflowIndexWeighted(x0, idx, wg); - if (ov0 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(ov0) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - inline const Numeric& HistoND::examine(const double x0) const - { - if (dim_ != 1U) Private::h_badargs("examine"); - unsigned i0 = 0; - const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); - if (ov0 == 1U) - return data_(i0); - else - return overflow_(ov0); - } - - template - inline const Numeric& HistoND::closestBin(const double x0) const - { - if (dim_ != 1U) Private::h_badargs("closestBin"); - const unsigned i0 = axes_[0].closestValidBin(x0); - return data_(i0); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const Num2& w) - { - if (dim_ != 2U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - if (o0 == 1U && o1 == 1U) - data_(i0, i1) += w; - else - { - overflow_(o0, o1) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - Num2& w, Functor& f) - { - if (dim_ != 2U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - if (o0 == 1U && o1 == 1U) - f(data_(i0, i1), w); - else - f(overflow_(o0, o1), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const Num2& w) - { - if (dim_ != 2U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - if (o0 == 1U && o1 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine(const double x0, - const double x1) const - { - if (dim_ != 2U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - if (o0 == 1U && o1 == 1U) - return data_(i0, i1); - else - return overflow_(o0, o1); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1) const - { - if (dim_ != 2U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - return data_(i0, i1); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const Num2& w) - { - if (dim_ != 3U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0, i2 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - if (o0 == 1U && o1 == 1U && o2 == 1U) - data_(i0, i1, i2) += w; - else - { - overflow_(o0, o1, o2) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, Num2& w, Functor& f) - { - if (dim_ != 3U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0, i2 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - if (o0 == 1U && o1 == 1U && o2 == 1U) - f(data_(i0, i1, i2), w); - else - f(overflow_(o0, o1, o2), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const Num2& w) - { - if (dim_ != 3U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - if (o0 == 1U && o1 == 1U && o2 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine(const double x0, - const double x1, - const double x2) const - { - if (dim_ != 3U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0, i2 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - if (o0 == 1U && o1 == 1U && o2 == 1U) - return data_(i0, i1, i2); - else - return overflow_(o0, o1, o2); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2) const - { - if (dim_ != 3U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - return data_(i0, i1, i2); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const Num2& w) - { - if (dim_ != 4U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) - data_(i0, i1, i2, i3) += w; - else - { - overflow_(o0, o1, o2, o3) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - Num2& w, Functor& f) - { - if (dim_ != 4U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) - f(data_(i0, i1, i2, i3), w); - else - f(overflow_(o0, o1, o2, o3), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const Num2& w) - { - if (dim_ != 4U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine(const double x0, - const double x1, - const double x2, - const double x3) const - { - if (dim_ != 4U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) - return data_(i0, i1, i2, i3); - else - return overflow_(o0, o1, o2, o3); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3) const - { - if (dim_ != 4U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - return data_(i0, i1, i2, i3); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const Num2& w) - { - if (dim_ != 5U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) - data_(i0, i1, i2, i3, i4) += w; - else - { - overflow_(o0, o1, o2, o3, o4) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, Num2& w, Functor& f) - { - if (dim_ != 5U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) - f(data_(i0, i1, i2, i3, i4), w); - else - f(overflow_(o0, o1, o2, o3, o4), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const Num2& w) - { - if (dim_ != 5U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine( - const double x0, const double x1, - const double x2, const double x3, - const double x4) const - { - if (dim_ != 5U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) - return data_(i0, i1, i2, i3, i4); - else - return overflow_(o0, o1, o2, o3, o4); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4) const - { - if (dim_ != 5U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - return data_(i0, i1, i2, i3, i4); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const Num2& w) - { - if (dim_ != 6U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U) - data_(i0, i1, i2, i3, i4, i5) += w; - else - { - overflow_(o0, o1, o2, o3, o4, o5) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - Num2& w, Functor& f) - { - if (dim_ != 6U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U) - f(data_(i0, i1, i2, i3, i4, i5), w); - else - f(overflow_(o0, o1, o2, o3, o4, o5), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const Num2& w) - { - if (dim_ != 6U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx+5, wg+5); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4, o5) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5) const - { - if (dim_ != 6U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U) - return data_(i0, i1, i2, i3, i4, i5); - else - return overflow_(o0, o1, o2, o3, o4, o5); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5) const - { - if (dim_ != 6U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - const unsigned i5 = ax[5].closestValidBin(x5); - return data_(i0, i1, i2, i3, i4, i5); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const Num2& w) - { - if (dim_ != 7U) Private::h_badargs("fill"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) - data_(i0, i1, i2, i3, i4, i5, i6) += w; - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, Num2& w, Functor& f) - { - if (dim_ != 7U) Private::h_badargs("dispatch"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) - f(data_(i0, i1, i2, i3, i4, i5, i6), w); - else - f(overflow_(o0, o1, o2, o3, o4, o5, o6), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const Num2& w) - { - if (dim_ != 7U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx+5, wg+5); - const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx+6, wg+6); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine( - const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6) const - { - if (dim_ != 7U) Private::h_badargs("examine"); - unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - if (o0 == 1U && o1 == 1U && o2 == 1U && - o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) - return data_(i0, i1, i2, i3, i4, i5, i6); - else - return overflow_(o0, o1, o2, o3, o4, o5, o6); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6) const - { - if (dim_ != 7U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - const unsigned i5 = ax[5].closestValidBin(x5); - const unsigned i6 = ax[6].closestValidBin(x6); - return data_(i0, i1, i2, i3, i4, i5, i6); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const Num2& w) - { - if (dim_ != 8U) Private::h_badargs("fill"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && - o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) - data_(i0, i1, i2, i3, i4, i5, i6, i7) += w; - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - Num2& w, Functor& f) - { - if (dim_ != 8U) Private::h_badargs("dispatch"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && - o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) - f(data_(i0, i1, i2, i3, i4, i5, i6, i7), w); - else - f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const Num2& w) - { - if (dim_ != 8U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx+5, wg+5); - const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx+6, wg+6); - const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx+7, wg+7); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && - o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine( - const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, - const double x7) const - { - if (dim_ != 8U) Private::h_badargs("examine"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && - o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) - return data_(i0, i1, i2, i3, i4, i5, i6, i7); - else - return overflow_(o0, o1, o2, o3, o4, o5, o6, o7); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7) const - { - if (dim_ != 8U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - const unsigned i5 = ax[5].closestValidBin(x5); - const unsigned i6 = ax[6].closestValidBin(x6); - const unsigned i7 = ax[7].closestValidBin(x7); - return data_(i0, i1, i2, i3, i4, i5, i6, i7); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, const Num2& w) - { - if (dim_ != 9U) Private::h_badargs("fill"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) - data_(i0, i1, i2, i3, i4, i5, i6, i7, i8) += w; - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, Num2& w, Functor& f) - { - if (dim_ != 9U) Private::h_badargs("dispatch"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) - f(data_(i0, i1, i2, i3, i4, i5, i6, i7, i8), w); - else - f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, const Num2& w) - { - if (dim_ != 9U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx+5, wg+5); - const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx+6, wg+6); - const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx+7, wg+7); - const unsigned o8 = ax[8].overflowIndexWeighted(x8, idx+8, wg+8); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine( - const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8) const - { - if (dim_ != 9U) Private::h_badargs("examine"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) - return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8); - else - return overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7, - const double x8) const - { - if (dim_ != 9U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - const unsigned i5 = ax[5].closestValidBin(x5); - const unsigned i6 = ax[6].closestValidBin(x6); - const unsigned i7 = ax[7].closestValidBin(x7); - const unsigned i8 = ax[8].closestValidBin(x8); - return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8); - } - - template - template - void HistoND::fill(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, const double x9, - const Num2& w) - { - if (dim_ != 10U) Private::h_badargs("fill"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0, i9=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - const unsigned o9 = ax[9].overflowIndex(x9, &i9); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && o9 == 1U) - data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) += w; - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - template - void HistoND::dispatch(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, const double x9, - Num2& w, Functor& f) - { - if (dim_ != 10U) Private::h_badargs("dispatch"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0, i9=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - const unsigned o9 = ax[9].overflowIndex(x9, &i9); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && o9 == 1U) - f(data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9), w); - else - f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9), w); - ++modCount_; - } - - template - template - void HistoND::fillC(const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, const double x9, - const Num2& w) - { - if (dim_ != 10U) Private::h_badargs("fillC"); - double* wg = &weightBuf_[0]; - unsigned* idx = &indexBuf_[0]; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx+0, wg+0); - const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx+1, wg+1); - const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx+2, wg+2); - const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx+3, wg+3); - const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx+4, wg+4); - const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx+5, wg+5); - const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx+6, wg+6); - const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx+7, wg+7); - const unsigned o8 = ax[8].overflowIndexWeighted(x8, idx+8, wg+8); - const unsigned o9 = ax[9].overflowIndexWeighted(x9, idx+9, wg+9); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && o9 == 1U) - fillPreservingCentroid(w); - else - { - overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9) += w; - ++overCount_; - } - ++fillCount_; ++modCount_; - } - - template - const Numeric& HistoND::examine( - const double x0, const double x1, - const double x2, const double x3, - const double x4, const double x5, - const double x6, const double x7, - const double x8, - const double x9) const - { - if (dim_ != 10U) Private::h_badargs("examine"); - unsigned i0=0, i1=0, i2=0, i3=0, i4=0, i5=0, i6=0, i7=0, i8=0, i9=0; - const Axis* ax = &axes_[0]; - const unsigned o0 = ax[0].overflowIndex(x0, &i0); - const unsigned o1 = ax[1].overflowIndex(x1, &i1); - const unsigned o2 = ax[2].overflowIndex(x2, &i2); - const unsigned o3 = ax[3].overflowIndex(x3, &i3); - const unsigned o4 = ax[4].overflowIndex(x4, &i4); - const unsigned o5 = ax[5].overflowIndex(x5, &i5); - const unsigned o6 = ax[6].overflowIndex(x6, &i6); - const unsigned o7 = ax[7].overflowIndex(x7, &i7); - const unsigned o8 = ax[8].overflowIndex(x8, &i8); - const unsigned o9 = ax[9].overflowIndex(x9, &i9); - if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && - o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && o9 == 1U) - return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9); - else - return overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9); - } - - template - const Numeric& HistoND::closestBin(const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7, - const double x8, - const double x9) const - { - if (dim_ != 10U) Private::h_badargs("closestBin"); - const Axis* ax = &axes_[0]; - const unsigned i0 = ax[0].closestValidBin(x0); - const unsigned i1 = ax[1].closestValidBin(x1); - const unsigned i2 = ax[2].closestValidBin(x2); - const unsigned i3 = ax[3].closestValidBin(x3); - const unsigned i4 = ax[4].closestValidBin(x4); - const unsigned i5 = ax[5].closestValidBin(x5); - const unsigned i6 = ax[6].closestValidBin(x6); - const unsigned i7 = ax[7].closestValidBin(x7); - const unsigned i8 = ax[8].closestValidBin(x8); - const unsigned i9 = ax[9].closestValidBin(x9); - return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9); - } - - template - template - inline void HistoND::setBin(const unsigned *index, - const unsigned indexLen, - const Num2& v) - { - data_.value(index, indexLen) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned *index, - const unsigned indexLen, - const Num2& v) - { - data_.valueAt(index, indexLen) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const Num2& v) - { - data_() = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const Num2& v) - { - data_.at() = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin( - const unsigned i0, const Num2& v) - { - data_(i0) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt( - const unsigned i0, const Num2& v) - { - data_.at(i0) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const Num2& v) - { - data_(i0, i1) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const Num2& v) - { - data_.at(i0, i1) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const Num2& v) - { - data_(i0, i1, i2) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const Num2& v) - { - data_(i0, i1, i2, i3) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const Num2& v) - { - data_(i0, i1, i2, i3, i4) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const Num2& v) - { - data_(i0, i1, i2, i3, i4, i5) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const Num2& v) - { - data_(i0, i1, i2, i3, i4, i5, i6) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const Num2& v) - { - data_(i0, i1, i2, i3, i4, i5, i6, i7) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const Num2& v) - { - data_(i0, i1, i2, i3, i4, i5, i6, i7, i8) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBin(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9, - const Num2& v) - { - data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const Num2& v) - { - data_.at(i0, i1, i2) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const Num2& v) - { - data_.at(i0, i1, i2, i3) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4, i5) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4, i5, i6) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4, i5, i6, i7) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4, i5, i6, i7, i8) = v; - ++modCount_; - } - - template - template - inline void HistoND::setBinAt(const unsigned i0, - const unsigned i1, - const unsigned i2, - const unsigned i3, - const unsigned i4, - const unsigned i5, - const unsigned i6, - const unsigned i7, - const unsigned i8, - const unsigned i9, - const Num2& v) - { - data_.at(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) = v; - ++modCount_; - } - - template - template - inline HistoND& HistoND::operator+=( - const HistoND& r) - { - data_ += r.data_; - overflow_ += r.overflow_; - fillCount_ += r.fillCount_; - overCount_ += r.overCount_; - ++modCount_; - return *this; - } - - template - template - inline HistoND& HistoND::operator-=( - const HistoND& r) - { - data_ -= r.data_; - overflow_ -= r.overflow_; - - // Subtraction does not make much sense for fill counts. - // We will assume that what we want should be equivalent - // to the in-place multiplication of the other histogram - // by -1 and then adding. - // - fillCount_ += r.fillCount_; - overCount_ += r.overCount_; - - ++modCount_; - return *this; - } - - template - template - inline HistoND& - HistoND::operator*=(const Num2& r) - { - data_ *= r; - overflow_ *= r; - ++modCount_; - return *this; - } - - template - template - inline HistoND& - HistoND::operator/=(const Num2& r) - { - data_ /= r; - overflow_ /= r; - ++modCount_; - return *this; - } - - template - HistoND::HistoND(const HistoND& r, - const unsigned ax1, - const unsigned ax2) - : title_(r.title_), - accumulatedDataLabel_(r.accumulatedDataLabel_), - data_(r.data_.transpose(ax1, ax2)), - overflow_(r.overflow_.transpose(ax1, ax2)), - axes_(r.axes_), - weightBuf_(r.weightBuf_), - indexBuf_(r.indexBuf_), - fillCount_(r.fillCount_), - overCount_(r.overCount_), - modCount_(0UL), - dim_(r.dim_) - { - std::swap(axes_[ax1], axes_[ax2]); - } - - template - HistoND::HistoND(const HistoND& r) - : title_(r.title_), - accumulatedDataLabel_(r.accumulatedDataLabel_), - data_(r.data_), - overflow_(r.overflow_), - axes_(r.axes_), - weightBuf_(r.weightBuf_), - indexBuf_(r.indexBuf_), - fillCount_(r.fillCount_), - overCount_(r.overCount_), - modCount_(0UL), - dim_(r.dim_) - { - } - - template - HistoND& HistoND::operator=(const HistoND& r) - { - if (&r != this) - { - title_ = r.title_; - accumulatedDataLabel_ = r.accumulatedDataLabel_; - data_.uninitialize(); - data_ = r.data_; - overflow_.uninitialize(); - overflow_ = r.overflow_; - axes_ = r.axes_; - weightBuf_ = r.weightBuf_; - indexBuf_ = r.indexBuf_; - fillCount_ = r.fillCount_; - overCount_ = r.overCount_; - dim_ = r.dim_; - ++modCount_; - } - return *this; - } - - template - HistoND HistoND::transpose( - const unsigned axisNum1, const unsigned axisNum2) const - { - if (axisNum1 >= dim_ || axisNum2 >= dim_) - throw npstat::NpstatOutOfRange("In npstat::HistoND::transpose: " - "axis number is out of range"); - if (axisNum1 == axisNum2) - // Just make a copy - return *this; - else - return HistoND(*this, axisNum1, axisNum2); - } - - template - template - void HistoND::addToBinContents(const Num2& weight) - { - const unsigned long nDat = data_.length(); - Numeric* data = const_cast(data_.data()); - for (unsigned long i=0; i - template - void HistoND::addToOverflows(const Num2& weight) - { - const unsigned long nOver = overflow_.length(); - Numeric* data = const_cast(overflow_.data()); - for (unsigned long i=0; i - template - void HistoND::addToBinContents( - const Num2* data, const unsigned long dataLength) - { - if (dataLength != data_.length()) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::addToBinContents: incompatible data length"); - assert(data); - Numeric* dat = const_cast(data_.data()); - for (unsigned long i=0; i - template - void HistoND::addToOverflows( - const Num2* data, const unsigned long dataLength) - { - if (dataLength != overflow_.length()) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::addToOverflows: incompatible data length"); - assert(data); - Numeric* dat = const_cast(overflow_.data()); - for (unsigned long i=0; i - template - void HistoND::scaleBinContents( - const Num2* data, const unsigned long dataLength) - { - if (dataLength != data_.length()) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::scaleBinContents: incompatible data length"); - assert(data); - Numeric* dat = const_cast(data_.data()); - for (unsigned long i=0; i - template - void HistoND::scaleOverflows( - const Num2* data, const unsigned long dataLength) - { - if (dataLength != overflow_.length()) throw npstat::NpstatInvalidArgument( - "In npstat::HistoND::scaleOverflows: incompatible data length"); - assert(data); - Numeric* dat = const_cast(overflow_.data()); - for (unsigned long i=0; i - template - inline void HistoND::setBinContents( - const Num2* data, const unsigned long dataLength, - const bool clearOverflowsNow) - { - data_.setData(data, dataLength); - if (clearOverflowsNow) - clearOverflows(); - ++modCount_; - } - - template - template - inline void HistoND::setOverflows( - const Num2* data, const unsigned long dataLength) - { - overflow_.setData(data, dataLength); - ++modCount_; - } - - template - inline void HistoND::recalculateNFillsFromData() - { - const long double nOver = overflow_.template sum(); - const long double nData = data_.template sum(); - overCount_ = static_cast(nOver); - fillCount_ = static_cast(nData + nOver); - ++modCount_; - } - - template - template - inline void HistoND::addToProjection( - HistoND* projection, - AbsArrayProjector& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - data_.addToProjection(&projection->data_, projector, - projectedIndices, nProjectedIndices); - projection->fillCount_ += projection->nBins(); - projection->modCount_++; - } - - template - template - inline void HistoND::addToProjection( - HistoND* projection, - AbsVisitor& projector, - const unsigned *projectedIndices, - const unsigned nProjectedIndices) const - { - assert(projection); - data_.addToProjection(&projection->data_, projector, - projectedIndices, nProjectedIndices); - projection->fillCount_ += projection->nBins(); - projection->modCount_++; - } - - template - const char* HistoND::classname() - { - static const std::string myClass(gs::template_class_name( - "npstat::HistoND")); - return myClass.c_str(); - } - - template - bool HistoND::write(std::ostream& of) const - { - gs::write_pod(of, title_); - gs::write_pod(of, accumulatedDataLabel_); - gs::write_pod(of, fillCount_); - gs::write_pod(of, overCount_); - - return !of.fail() && - gs::write_obj_vector(of, axes_) && - data_.classId().write(of) && - data_.write(of) && - overflow_.write(of); - } - - template - HistoND* HistoND::read(const gs::ClassId& id, - std::istream& in) - { - static const gs::ClassId current( - gs::ClassId::makeId >()); - current.ensureSameId(id); - - std::string title; - gs::read_pod(in, &title); - - std::string accumulatedDataLabel; - gs::read_pod(in, &accumulatedDataLabel); - - unsigned long fillCount = 0, overCount = 0; - gs::read_pod(in, &fillCount); - gs::read_pod(in, &overCount); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::HistoND::read: input stream failure"); - - std::vector axes; - gs::read_heap_obj_vector_as_placed(in, &axes); - gs::ClassId ida(in, 1); - ArrayND data, over; - ArrayND::restore(ida, in, &data); - ArrayND::restore(ida, in, &over); - CPP11_auto_ptr > result( - new HistoND(axes, title.c_str(), - accumulatedDataLabel.c_str())); - result->data_ = data; - result->overflow_ = over; - result->fillCount_ = fillCount; - result->overCount_ = overCount; - return result.release(); - } - - template - void convertHistoToDensity(Histo* h, const bool knownNonNegative) - { - assert(h); - if (!knownNonNegative) - (const_cast&>(h->binContents())).makeNonNegative(); - const double integ = h->integral(); - *h /= integ; - } - - template - std::vector densityScanHistoMap(const Histo& histo) - { - std::vector result; - const unsigned d = histo.dim(); - result.reserve(d); - for (unsigned i=0; i - std::vector convolutionHistoMap( - const Histo& histo, const bool doubleRange) - { - std::vector result; - const unsigned d = histo.dim(); - result.reserve(d); - for (unsigned i=0; i + template + void HistoND::fillC(const double* coords, const unsigned coordLength, const Num2& w) { + if (coordLength != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoND::fillC: " + "incompatible input point dimensionality"); + if (coordLength) { + assert(coords); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + unsigned* over = idx + dim_; + const Axis* ax = &axes_[0]; + unsigned overflown = 0U; + for (unsigned i = 0; i < dim_; ++i) { + over[i] = ax[i].overflowIndexWeighted(coords[i], idx + i, wg + i); + overflown |= (over[i] - 1U); + } + if (overflown) { + overflow_.value(over, dim_) += w; + ++overCount_; + } else + fillPreservingCentroid(w); + } else + data_() += w; + ++fillCount_; + ++modCount_; + } + + template + template + inline void HistoND::fill(const Num2& w) { + if (dim_) + Private::h_badargs("fill"); + data_() += w; + ++fillCount_; + ++modCount_; + } + + template + template + inline void HistoND::dispatch(Num2& w, Functor& f) { + if (dim_) + Private::h_badargs("dispatch"); + f(data_(), w); + ++modCount_; + } + + template + template + inline void HistoND::fillC(const Num2& w) { + if (dim_) + Private::h_badargs("fillC"); + data_() += w; + ++fillCount_; + ++modCount_; + } + + template + inline const Numeric& HistoND::examine() const { + if (dim_) + Private::h_badargs("examine"); + return data_(); + } + + template + inline const Numeric& HistoND::closestBin() const { + if (dim_) + Private::h_badargs("closestBin"); + return data_(); + } + + template + template + void HistoND::fill(const double x0, const Num2& w) { + if (dim_ != 1U) + Private::h_badargs("fill"); + unsigned i0 = 0; + const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); + if (ov0 == 1U) + data_(i0) += w; + else { + overflow_(ov0) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, Num2& w, Functor& f) { + if (dim_ != 1U) + Private::h_badargs("dispatch"); + unsigned i0 = 0; + const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); + if (ov0 == 1U) + f(data_(i0), w); + else + f(overflow_(ov0), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, const Num2& w) { + if (dim_ != 1U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const unsigned ov0 = axes_[0].overflowIndexWeighted(x0, idx, wg); + if (ov0 == 1U) + fillPreservingCentroid(w); + else { + overflow_(ov0) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + inline const Numeric& HistoND::examine(const double x0) const { + if (dim_ != 1U) + Private::h_badargs("examine"); + unsigned i0 = 0; + const unsigned ov0 = axes_[0].overflowIndex(x0, &i0); + if (ov0 == 1U) + return data_(i0); + else + return overflow_(ov0); + } + + template + inline const Numeric& HistoND::closestBin(const double x0) const { + if (dim_ != 1U) + Private::h_badargs("closestBin"); + const unsigned i0 = axes_[0].closestValidBin(x0); + return data_(i0); + } + + template + template + void HistoND::fill(const double x0, const double x1, const Num2& w) { + if (dim_ != 2U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + if (o0 == 1U && o1 == 1U) + data_(i0, i1) += w; + else { + overflow_(o0, o1) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, const double x1, Num2& w, Functor& f) { + if (dim_ != 2U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + if (o0 == 1U && o1 == 1U) + f(data_(i0, i1), w); + else + f(overflow_(o0, o1), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, const double x1, const Num2& w) { + if (dim_ != 2U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + if (o0 == 1U && o1 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, const double x1) const { + if (dim_ != 2U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + if (o0 == 1U && o1 == 1U) + return data_(i0, i1); + else + return overflow_(o0, o1); + } + + template + const Numeric& HistoND::closestBin(const double x0, const double x1) const { + if (dim_ != 2U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + return data_(i0, i1); + } + + template + template + void HistoND::fill(const double x0, const double x1, const double x2, const Num2& w) { + if (dim_ != 3U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + if (o0 == 1U && o1 == 1U && o2 == 1U) + data_(i0, i1, i2) += w; + else { + overflow_(o0, o1, o2) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, const double x1, const double x2, Num2& w, Functor& f) { + if (dim_ != 3U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + if (o0 == 1U && o1 == 1U && o2 == 1U) + f(data_(i0, i1, i2), w); + else + f(overflow_(o0, o1, o2), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, const double x1, const double x2, const Num2& w) { + if (dim_ != 3U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + if (o0 == 1U && o1 == 1U && o2 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, const double x1, const double x2) const { + if (dim_ != 3U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + if (o0 == 1U && o1 == 1U && o2 == 1U) + return data_(i0, i1, i2); + else + return overflow_(o0, o1, o2); + } + + template + const Numeric& HistoND::closestBin(const double x0, const double x1, const double x2) const { + if (dim_ != 3U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + return data_(i0, i1, i2); + } + + template + template + void HistoND::fill(const double x0, const double x1, const double x2, const double x3, const Num2& w) { + if (dim_ != 4U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) + data_(i0, i1, i2, i3) += w; + else { + overflow_(o0, o1, o2, o3) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch( + const double x0, const double x1, const double x2, const double x3, Num2& w, Functor& f) { + if (dim_ != 4U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) + f(data_(i0, i1, i2, i3), w); + else + f(overflow_(o0, o1, o2, o3), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, const double x1, const double x2, const double x3, const Num2& w) { + if (dim_ != 4U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, + const double x1, + const double x2, + const double x3) const { + if (dim_ != 4U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U) + return data_(i0, i1, i2, i3); + else + return overflow_(o0, o1, o2, o3); + } + + template + const Numeric& HistoND::closestBin(const double x0, + const double x1, + const double x2, + const double x3) const { + if (dim_ != 4U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + return data_(i0, i1, i2, i3); + } + + template + template + void HistoND::fill( + const double x0, const double x1, const double x2, const double x3, const double x4, const Num2& w) { + if (dim_ != 5U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) + data_(i0, i1, i2, i3, i4) += w; + else { + overflow_(o0, o1, o2, o3, o4) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch( + const double x0, const double x1, const double x2, const double x3, const double x4, Num2& w, Functor& f) { + if (dim_ != 5U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) + f(data_(i0, i1, i2, i3, i4), w); + else + f(overflow_(o0, o1, o2, o3, o4), w); + ++modCount_; + } + + template + template + void HistoND::fillC( + const double x0, const double x1, const double x2, const double x3, const double x4, const Num2& w) { + if (dim_ != 5U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine( + const double x0, const double x1, const double x2, const double x3, const double x4) const { + if (dim_ != 5U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U) + return data_(i0, i1, i2, i3, i4); + else + return overflow_(o0, o1, o2, o3, o4); + } + + template + const Numeric& HistoND::closestBin( + const double x0, const double x1, const double x2, const double x3, const double x4) const { + if (dim_ != 5U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + return data_(i0, i1, i2, i3, i4); + } + + template + template + void HistoND::fill(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const Num2& w) { + if (dim_ != 6U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U) + data_(i0, i1, i2, i3, i4, i5) += w; + else { + overflow_(o0, o1, o2, o3, o4, o5) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + Num2& w, + Functor& f) { + if (dim_ != 6U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U) + f(data_(i0, i1, i2, i3, i4, i5), w); + else + f(overflow_(o0, o1, o2, o3, o4, o5), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const Num2& w) { + if (dim_ != 6U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx + 5, wg + 5); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4, o5) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine( + const double x0, const double x1, const double x2, const double x3, const double x4, const double x5) const { + if (dim_ != 6U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U) + return data_(i0, i1, i2, i3, i4, i5); + else + return overflow_(o0, o1, o2, o3, o4, o5); + } + + template + const Numeric& HistoND::closestBin( + const double x0, const double x1, const double x2, const double x3, const double x4, const double x5) const { + if (dim_ != 6U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + const unsigned i5 = ax[5].closestValidBin(x5); + return data_(i0, i1, i2, i3, i4, i5); + } + + template + template + void HistoND::fill(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const Num2& w) { + if (dim_ != 7U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) + data_(i0, i1, i2, i3, i4, i5, i6) += w; + else { + overflow_(o0, o1, o2, o3, o4, o5, o6) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + Num2& w, + Functor& f) { + if (dim_ != 7U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) + f(data_(i0, i1, i2, i3, i4, i5, i6), w); + else + f(overflow_(o0, o1, o2, o3, o4, o5, o6), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const Num2& w) { + if (dim_ != 7U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx + 5, wg + 5); + const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx + 6, wg + 6); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4, o5, o6) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6) const { + if (dim_ != 7U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U) + return data_(i0, i1, i2, i3, i4, i5, i6); + else + return overflow_(o0, o1, o2, o3, o4, o5, o6); + } + + template + const Numeric& HistoND::closestBin(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6) const { + if (dim_ != 7U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + const unsigned i5 = ax[5].closestValidBin(x5); + const unsigned i6 = ax[6].closestValidBin(x6); + return data_(i0, i1, i2, i3, i4, i5, i6); + } + + template + template + void HistoND::fill(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const Num2& w) { + if (dim_ != 8U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) + data_(i0, i1, i2, i3, i4, i5, i6, i7) += w; + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + Num2& w, + Functor& f) { + if (dim_ != 8U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) + f(data_(i0, i1, i2, i3, i4, i5, i6, i7), w); + else + f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const Num2& w) { + if (dim_ != 8U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx + 5, wg + 5); + const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx + 6, wg + 6); + const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx + 7, wg + 7); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7) const { + if (dim_ != 8U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U) + return data_(i0, i1, i2, i3, i4, i5, i6, i7); + else + return overflow_(o0, o1, o2, o3, o4, o5, o6, o7); + } + + template + const Numeric& HistoND::closestBin(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7) const { + if (dim_ != 8U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + const unsigned i5 = ax[5].closestValidBin(x5); + const unsigned i6 = ax[6].closestValidBin(x6); + const unsigned i7 = ax[7].closestValidBin(x7); + return data_(i0, i1, i2, i3, i4, i5, i6, i7); + } + + template + template + void HistoND::fill(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const Num2& w) { + if (dim_ != 9U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) + data_(i0, i1, i2, i3, i4, i5, i6, i7, i8) += w; + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + Num2& w, + Functor& f) { + if (dim_ != 9U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) + f(data_(i0, i1, i2, i3, i4, i5, i6, i7, i8), w); + else + f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const Num2& w) { + if (dim_ != 9U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx + 5, wg + 5); + const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx + 6, wg + 6); + const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx + 7, wg + 7); + const unsigned o8 = ax[8].overflowIndexWeighted(x8, idx + 8, wg + 8); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8) const { + if (dim_ != 9U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U) + return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8); + else + return overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8); + } + + template + const Numeric& HistoND::closestBin(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8) const { + if (dim_ != 9U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + const unsigned i5 = ax[5].closestValidBin(x5); + const unsigned i6 = ax[6].closestValidBin(x6); + const unsigned i7 = ax[7].closestValidBin(x7); + const unsigned i8 = ax[8].closestValidBin(x8); + return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8); + } + + template + template + void HistoND::fill(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9, + const Num2& w) { + if (dim_ != 10U) + Private::h_badargs("fill"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + const unsigned o9 = ax[9].overflowIndex(x9, &i9); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && + o9 == 1U) + data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) += w; + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + template + void HistoND::dispatch(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9, + Num2& w, + Functor& f) { + if (dim_ != 10U) + Private::h_badargs("dispatch"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + const unsigned o9 = ax[9].overflowIndex(x9, &i9); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && + o9 == 1U) + f(data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9), w); + else + f(overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9), w); + ++modCount_; + } + + template + template + void HistoND::fillC(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9, + const Num2& w) { + if (dim_ != 10U) + Private::h_badargs("fillC"); + double* wg = &weightBuf_[0]; + unsigned* idx = &indexBuf_[0]; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndexWeighted(x0, idx + 0, wg + 0); + const unsigned o1 = ax[1].overflowIndexWeighted(x1, idx + 1, wg + 1); + const unsigned o2 = ax[2].overflowIndexWeighted(x2, idx + 2, wg + 2); + const unsigned o3 = ax[3].overflowIndexWeighted(x3, idx + 3, wg + 3); + const unsigned o4 = ax[4].overflowIndexWeighted(x4, idx + 4, wg + 4); + const unsigned o5 = ax[5].overflowIndexWeighted(x5, idx + 5, wg + 5); + const unsigned o6 = ax[6].overflowIndexWeighted(x6, idx + 6, wg + 6); + const unsigned o7 = ax[7].overflowIndexWeighted(x7, idx + 7, wg + 7); + const unsigned o8 = ax[8].overflowIndexWeighted(x8, idx + 8, wg + 8); + const unsigned o9 = ax[9].overflowIndexWeighted(x9, idx + 9, wg + 9); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && + o9 == 1U) + fillPreservingCentroid(w); + else { + overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9) += w; + ++overCount_; + } + ++fillCount_; + ++modCount_; + } + + template + const Numeric& HistoND::examine(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9) const { + if (dim_ != 10U) + Private::h_badargs("examine"); + unsigned i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0, i8 = 0, i9 = 0; + const Axis* ax = &axes_[0]; + const unsigned o0 = ax[0].overflowIndex(x0, &i0); + const unsigned o1 = ax[1].overflowIndex(x1, &i1); + const unsigned o2 = ax[2].overflowIndex(x2, &i2); + const unsigned o3 = ax[3].overflowIndex(x3, &i3); + const unsigned o4 = ax[4].overflowIndex(x4, &i4); + const unsigned o5 = ax[5].overflowIndex(x5, &i5); + const unsigned o6 = ax[6].overflowIndex(x6, &i6); + const unsigned o7 = ax[7].overflowIndex(x7, &i7); + const unsigned o8 = ax[8].overflowIndex(x8, &i8); + const unsigned o9 = ax[9].overflowIndex(x9, &i9); + if (o0 == 1U && o1 == 1U && o2 == 1U && o3 == 1U && o4 == 1U && o5 == 1U && o6 == 1U && o7 == 1U && o8 == 1U && + o9 == 1U) + return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9); + else + return overflow_(o0, o1, o2, o3, o4, o5, o6, o7, o8, o9); + } + + template + const Numeric& HistoND::closestBin(const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9) const { + if (dim_ != 10U) + Private::h_badargs("closestBin"); + const Axis* ax = &axes_[0]; + const unsigned i0 = ax[0].closestValidBin(x0); + const unsigned i1 = ax[1].closestValidBin(x1); + const unsigned i2 = ax[2].closestValidBin(x2); + const unsigned i3 = ax[3].closestValidBin(x3); + const unsigned i4 = ax[4].closestValidBin(x4); + const unsigned i5 = ax[5].closestValidBin(x5); + const unsigned i6 = ax[6].closestValidBin(x6); + const unsigned i7 = ax[7].closestValidBin(x7); + const unsigned i8 = ax[8].closestValidBin(x8); + const unsigned i9 = ax[9].closestValidBin(x9); + return data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9); + } + + template + template + inline void HistoND::setBin(const unsigned* index, const unsigned indexLen, const Num2& v) { + data_.value(index, indexLen) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned* index, const unsigned indexLen, const Num2& v) { + data_.valueAt(index, indexLen) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const Num2& v) { + data_() = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const Num2& v) { + data_.at() = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, const Num2& v) { + data_(i0) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, const Num2& v) { + data_.at(i0) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, const unsigned i1, const Num2& v) { + data_(i0, i1) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, const unsigned i1, const Num2& v) { + data_.at(i0, i1) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, const unsigned i1, const unsigned i2, const Num2& v) { + data_(i0, i1, i2) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const Num2& v) { + data_(i0, i1, i2, i3) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4, const Num2& v) { + data_(i0, i1, i2, i3, i4) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const Num2& v) { + data_(i0, i1, i2, i3, i4, i5) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const Num2& v) { + data_(i0, i1, i2, i3, i4, i5, i6) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const Num2& v) { + data_(i0, i1, i2, i3, i4, i5, i6, i7) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const Num2& v) { + data_(i0, i1, i2, i3, i4, i5, i6, i7, i8) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBin(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9, + const Num2& v) { + data_(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, const unsigned i1, const unsigned i2, const Num2& v) { + data_.at(i0, i1, i2) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const Num2& v) { + data_.at(i0, i1, i2, i3) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt( + const unsigned i0, const unsigned i1, const unsigned i2, const unsigned i3, const unsigned i4, const Num2& v) { + data_.at(i0, i1, i2, i3, i4) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const Num2& v) { + data_.at(i0, i1, i2, i3, i4, i5) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const Num2& v) { + data_.at(i0, i1, i2, i3, i4, i5, i6) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const Num2& v) { + data_.at(i0, i1, i2, i3, i4, i5, i6, i7) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const Num2& v) { + data_.at(i0, i1, i2, i3, i4, i5, i6, i7, i8) = v; + ++modCount_; + } + + template + template + inline void HistoND::setBinAt(const unsigned i0, + const unsigned i1, + const unsigned i2, + const unsigned i3, + const unsigned i4, + const unsigned i5, + const unsigned i6, + const unsigned i7, + const unsigned i8, + const unsigned i9, + const Num2& v) { + data_.at(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9) = v; + ++modCount_; + } + + template + template + inline HistoND& HistoND::operator+=(const HistoND& r) { + data_ += r.data_; + overflow_ += r.overflow_; + fillCount_ += r.fillCount_; + overCount_ += r.overCount_; + ++modCount_; + return *this; + } + + template + template + inline HistoND& HistoND::operator-=(const HistoND& r) { + data_ -= r.data_; + overflow_ -= r.overflow_; + + // Subtraction does not make much sense for fill counts. + // We will assume that what we want should be equivalent + // to the in-place multiplication of the other histogram + // by -1 and then adding. + // + fillCount_ += r.fillCount_; + overCount_ += r.overCount_; + + ++modCount_; + return *this; + } + + template + template + inline HistoND& HistoND::operator*=(const Num2& r) { + data_ *= r; + overflow_ *= r; + ++modCount_; + return *this; + } + + template + template + inline HistoND& HistoND::operator/=(const Num2& r) { + data_ /= r; + overflow_ /= r; + ++modCount_; + return *this; + } + + template + HistoND::HistoND(const HistoND& r, const unsigned ax1, const unsigned ax2) + : title_(r.title_), + accumulatedDataLabel_(r.accumulatedDataLabel_), + data_(r.data_.transpose(ax1, ax2)), + overflow_(r.overflow_.transpose(ax1, ax2)), + axes_(r.axes_), + weightBuf_(r.weightBuf_), + indexBuf_(r.indexBuf_), + fillCount_(r.fillCount_), + overCount_(r.overCount_), + modCount_(0UL), + dim_(r.dim_) { + std::swap(axes_[ax1], axes_[ax2]); + } + + template + HistoND::HistoND(const HistoND& r) + : title_(r.title_), + accumulatedDataLabel_(r.accumulatedDataLabel_), + data_(r.data_), + overflow_(r.overflow_), + axes_(r.axes_), + weightBuf_(r.weightBuf_), + indexBuf_(r.indexBuf_), + fillCount_(r.fillCount_), + overCount_(r.overCount_), + modCount_(0UL), + dim_(r.dim_) {} + + template + HistoND& HistoND::operator=(const HistoND& r) { + if (&r != this) { + title_ = r.title_; + accumulatedDataLabel_ = r.accumulatedDataLabel_; + data_.uninitialize(); + data_ = r.data_; + overflow_.uninitialize(); + overflow_ = r.overflow_; + axes_ = r.axes_; + weightBuf_ = r.weightBuf_; + indexBuf_ = r.indexBuf_; + fillCount_ = r.fillCount_; + overCount_ = r.overCount_; + dim_ = r.dim_; + ++modCount_; + } + return *this; + } + + template + HistoND HistoND::transpose(const unsigned axisNum1, const unsigned axisNum2) const { + if (axisNum1 >= dim_ || axisNum2 >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::HistoND::transpose: " + "axis number is out of range"); + if (axisNum1 == axisNum2) + // Just make a copy + return *this; + else + return HistoND(*this, axisNum1, axisNum2); + } + + template + template + void HistoND::addToBinContents(const Num2& weight) { + const unsigned long nDat = data_.length(); + Numeric* data = const_cast(data_.data()); + for (unsigned long i = 0; i < nDat; ++i) + data[i] += weight; + fillCount_ += nDat; + ++modCount_; + } + + template + template + void HistoND::addToOverflows(const Num2& weight) { + const unsigned long nOver = overflow_.length(); + Numeric* data = const_cast(overflow_.data()); + for (unsigned long i = 0; i < nOver; ++i) + data[i] += weight; + overCount_ += nOver; + fillCount_ += nOver; + ++modCount_; + } + + template + template + void HistoND::addToBinContents(const Num2* data, const unsigned long dataLength) { + if (dataLength != data_.length()) + throw npstat::NpstatInvalidArgument("In npstat::HistoND::addToBinContents: incompatible data length"); + assert(data); + Numeric* dat = const_cast(data_.data()); + for (unsigned long i = 0; i < dataLength; ++i) + dat[i] += data[i]; + fillCount_ += dataLength; + ++modCount_; + } + + template + template + void HistoND::addToOverflows(const Num2* data, const unsigned long dataLength) { + if (dataLength != overflow_.length()) + throw npstat::NpstatInvalidArgument("In npstat::HistoND::addToOverflows: incompatible data length"); + assert(data); + Numeric* dat = const_cast(overflow_.data()); + for (unsigned long i = 0; i < dataLength; ++i) + dat[i] += data[i]; + overCount_ += dataLength; + fillCount_ += dataLength; + ++modCount_; + } + + template + template + void HistoND::scaleBinContents(const Num2* data, const unsigned long dataLength) { + if (dataLength != data_.length()) + throw npstat::NpstatInvalidArgument("In npstat::HistoND::scaleBinContents: incompatible data length"); + assert(data); + Numeric* dat = const_cast(data_.data()); + for (unsigned long i = 0; i < dataLength; ++i) + dat[i] *= data[i]; + ++modCount_; + } + + template + template + void HistoND::scaleOverflows(const Num2* data, const unsigned long dataLength) { + if (dataLength != overflow_.length()) + throw npstat::NpstatInvalidArgument("In npstat::HistoND::scaleOverflows: incompatible data length"); + assert(data); + Numeric* dat = const_cast(overflow_.data()); + for (unsigned long i = 0; i < dataLength; ++i) + dat[i] *= data[i]; + ++modCount_; + } + + template + template + inline void HistoND::setBinContents(const Num2* data, + const unsigned long dataLength, + const bool clearOverflowsNow) { + data_.setData(data, dataLength); + if (clearOverflowsNow) + clearOverflows(); + ++modCount_; + } + + template + template + inline void HistoND::setOverflows(const Num2* data, const unsigned long dataLength) { + overflow_.setData(data, dataLength); + ++modCount_; + } + + template + inline void HistoND::recalculateNFillsFromData() { + const long double nOver = overflow_.template sum(); + const long double nData = data_.template sum(); + overCount_ = static_cast(nOver); + fillCount_ = static_cast(nData + nOver); + ++modCount_; + } + + template + template + inline void HistoND::addToProjection(HistoND* projection, + AbsArrayProjector& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + data_.addToProjection(&projection->data_, projector, projectedIndices, nProjectedIndices); + projection->fillCount_ += projection->nBins(); + projection->modCount_++; + } + + template + template + inline void HistoND::addToProjection(HistoND* projection, + AbsVisitor& projector, + const unsigned* projectedIndices, + const unsigned nProjectedIndices) const { + assert(projection); + data_.addToProjection(&projection->data_, projector, projectedIndices, nProjectedIndices); + projection->fillCount_ += projection->nBins(); + projection->modCount_++; + } + + template + const char* HistoND::classname() { + static const std::string myClass(gs::template_class_name("npstat::HistoND")); + return myClass.c_str(); + } + + template + bool HistoND::write(std::ostream& of) const { + gs::write_pod(of, title_); + gs::write_pod(of, accumulatedDataLabel_); + gs::write_pod(of, fillCount_); + gs::write_pod(of, overCount_); + + return !of.fail() && gs::write_obj_vector(of, axes_) && data_.classId().write(of) && data_.write(of) && + overflow_.write(of); + } + + template + HistoND* HistoND::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + std::string title; + gs::read_pod(in, &title); + + std::string accumulatedDataLabel; + gs::read_pod(in, &accumulatedDataLabel); + + unsigned long fillCount = 0, overCount = 0; + gs::read_pod(in, &fillCount); + gs::read_pod(in, &overCount); + if (in.fail()) + throw gs::IOReadFailure("In npstat::HistoND::read: input stream failure"); + + std::vector axes; + gs::read_heap_obj_vector_as_placed(in, &axes); + gs::ClassId ida(in, 1); + ArrayND data, over; + ArrayND::restore(ida, in, &data); + ArrayND::restore(ida, in, &over); + CPP11_auto_ptr > result( + new HistoND(axes, title.c_str(), accumulatedDataLabel.c_str())); + result->data_ = data; + result->overflow_ = over; + result->fillCount_ = fillCount; + result->overCount_ = overCount; + return result.release(); + } + + template + void convertHistoToDensity(Histo* h, const bool knownNonNegative) { + assert(h); + if (!knownNonNegative) + (const_cast&>(h->binContents())).makeNonNegative(); + const double integ = h->integral(); + *h /= integ; + } + + template + std::vector densityScanHistoMap(const Histo& histo) { + std::vector result; + const unsigned d = histo.dim(); + result.reserve(d); + for (unsigned i = 0; i < d; ++i) { + const LinearMapper1d& m = histo.axis(i).binNumberMapper(false); + result.push_back(m.inverse()); + } + return result; + } + + template + std::vector convolutionHistoMap(const Histo& histo, const bool doubleRange) { + std::vector result; + const unsigned d = histo.dim(); + result.reserve(d); + for (unsigned i = 0; i < d; ++i) + result.push_back(histo.axis(i).kernelScanMapper(doubleRange)); + return result; + } +} // namespace npstat + +#endif // NPSTAT_HISTOND_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/HistoNDFunctorInstances.h b/JetMETCorrections/InterpolationTables/interface/HistoNDFunctorInstances.h index e8e706abb8774..2d1ebca7d894b 100644 --- a/JetMETCorrections/InterpolationTables/interface/HistoNDFunctorInstances.h +++ b/JetMETCorrections/InterpolationTables/interface/HistoNDFunctorInstances.h @@ -15,18 +15,17 @@ #include "JetMETCorrections/InterpolationTables/interface/DualHistoAxis.h" namespace npstat { - typedef StorableHistoNDFunctor DoubleHistoNDFunctor; + typedef StorableHistoNDFunctor DoubleHistoNDFunctor; - typedef StorableHistoNDFunctor DoubleUAHistoNDFunctor; + typedef StorableHistoNDFunctor DoubleUAHistoNDFunctor; - typedef StorableHistoNDFunctor DoubleNUHistoNDFunctor; + typedef StorableHistoNDFunctor DoubleNUHistoNDFunctor; - typedef StorableHistoNDFunctor FloatHistoNDFunctor; + typedef StorableHistoNDFunctor FloatHistoNDFunctor; - typedef StorableHistoNDFunctor FloatUAHistoNDFunctor; + typedef StorableHistoNDFunctor FloatUAHistoNDFunctor; - typedef StorableHistoNDFunctor FloatNUHistoNDFunctor; -} - -#endif // NPSTAT_HISTONDFUNCTORINSTANCES_HH_ + typedef StorableHistoNDFunctor FloatNUHistoNDFunctor; +} // namespace npstat +#endif // NPSTAT_HISTONDFUNCTORINSTANCES_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/InterpolationFunctorInstances.h b/JetMETCorrections/InterpolationTables/interface/InterpolationFunctorInstances.h index 056b63a8262fb..4dd89983851a6 100644 --- a/JetMETCorrections/InterpolationTables/interface/InterpolationFunctorInstances.h +++ b/JetMETCorrections/InterpolationTables/interface/InterpolationFunctorInstances.h @@ -16,24 +16,17 @@ #include "JetMETCorrections/InterpolationTables/interface/DualAxis.h" namespace npstat { - typedef StorableInterpolationFunctor - DoubleInterpolationFunctor; + typedef StorableInterpolationFunctor DoubleInterpolationFunctor; - typedef StorableInterpolationFunctor - DoubleUAInterpolationFunctor; + typedef StorableInterpolationFunctor DoubleUAInterpolationFunctor; - typedef StorableInterpolationFunctor - DoubleNUInterpolationFunctor; + typedef StorableInterpolationFunctor DoubleNUInterpolationFunctor; - typedef StorableInterpolationFunctor - FloatInterpolationFunctor; + typedef StorableInterpolationFunctor FloatInterpolationFunctor; - typedef StorableInterpolationFunctor - FloatUAInterpolationFunctor; + typedef StorableInterpolationFunctor FloatUAInterpolationFunctor; - typedef StorableInterpolationFunctor - FloatNUInterpolationFunctor; -} - -#endif // NPSTAT_INTERPOLATIONFUNCTORINSTANCES_HH_ + typedef StorableInterpolationFunctor FloatNUInterpolationFunctor; +} // namespace npstat +#endif // NPSTAT_INTERPOLATIONFUNCTORINSTANCES_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/Interval.h b/JetMETCorrections/InterpolationTables/interface/Interval.h index cc54a60e20625..4337841625df9 100644 --- a/JetMETCorrections/InterpolationTables/interface/Interval.h +++ b/JetMETCorrections/InterpolationTables/interface/Interval.h @@ -15,313 +15,275 @@ #include namespace npstat { - /** + /** // Representation of 1-d intervals. The following invariant // is maintained: min() will not exceed max(). // // See BoxND class for rectangles, boxes, and hyperboxes. */ - template - class Interval - { - public: - /** Both lower and upper interval bounds are set to Numeric() */ - inline Interval() : min_(Numeric()), max_(Numeric()) {} - - /** + template + class Interval { + public: + /** Both lower and upper interval bounds are set to Numeric() */ + inline Interval() : min_(Numeric()), max_(Numeric()) {} + + /** // Minimum is set to Numeric(), maximum to the given argument. // An exception is thrown if the argument is smaller than Numeric(). */ - inline explicit Interval(const Numeric max) - : min_(Numeric()), max_(max) - { - if (min_ > max_) throw npstat::NpstatInvalidArgument( - "In npstat::Interval constructor: invalid limits"); - } - - /** + inline explicit Interval(const Numeric max) : min_(Numeric()), max_(max) { + if (min_ > max_) + throw npstat::NpstatInvalidArgument("In npstat::Interval constructor: invalid limits"); + } + + /** // Constructor from both bounds. Set "swapIfOutOfOrder" argument // to "true" if the minimum can be larger than the maximum (in this // case the bounds will be swapped internally). */ - inline Interval(const Numeric min, const Numeric max, - const bool swapIfOutOfOrder = false) - : min_(min), max_(max) - { - if (min_ > max_) - { - if (swapIfOutOfOrder) - std::swap(min_, max_); - else - throw npstat::NpstatInvalidArgument( - "In npstat::Interval constructor: invalid limits"); - } - } - - /** Set the lower interval bound */ - inline void setMin(const Numeric value) - { - if (value > max_) throw npstat::NpstatInvalidArgument( - "In npstat::Interval::setMin: argument above max"); - min_ = value; - } - - /** Set the upper interval bound */ - inline void setMax(const Numeric value) - { - if (value < min_) throw npstat::NpstatInvalidArgument( - "In npstat::Interval::setMax: argument below min"); - max_ = value; - } - - /** Set both interval bounds */ - inline void setBounds(const Numeric minval, const Numeric maxval, - const bool swapIfOutOfOrder = false) - { - if (maxval < minval && !swapIfOutOfOrder) - throw npstat::NpstatInvalidArgument( - "In npstat::Interval::setBounds: invalid limits"); - min_ = minval; - max_ = maxval; - if (swapIfOutOfOrder && min_ > max_) - std::swap(min_, max_); - } - - /** Return the lower bound */ - inline const Numeric min() const {return min_;} - - /** Return the upper bound */ - inline const Numeric max() const {return max_;} - - /** Return both bounds */ - inline void getBounds(Numeric* pmin, Numeric* pmax) const - {*pmin = min_; *pmax = max_;} - - /** Interval length */ - inline Numeric length() const {return max_ - min_;} - - /** The middle point of the interval */ - inline Numeric midpoint() const - {return static_cast((max_ + min_)*0.5);} - - /** Is the point inside the interval or on the lower boundary? */ - inline bool isInsideLower(const Numeric value) const - {return value >= min_ && value < max_;} - - /** Is the point inside the interval or on the upper boundary? */ - inline bool isInsideUpper(const Numeric value) const - {return value > min_ && value <= max_;} - - /** Is the point inside the interval or on one of the boundaries? */ - inline bool isInsideWithBounds(const Numeric value) const - {return value >= min_ && value <= max_;} - - /** + inline Interval(const Numeric min, const Numeric max, const bool swapIfOutOfOrder = false) : min_(min), max_(max) { + if (min_ > max_) { + if (swapIfOutOfOrder) + std::swap(min_, max_); + else + throw npstat::NpstatInvalidArgument("In npstat::Interval constructor: invalid limits"); + } + } + + /** Set the lower interval bound */ + inline void setMin(const Numeric value) { + if (value > max_) + throw npstat::NpstatInvalidArgument("In npstat::Interval::setMin: argument above max"); + min_ = value; + } + + /** Set the upper interval bound */ + inline void setMax(const Numeric value) { + if (value < min_) + throw npstat::NpstatInvalidArgument("In npstat::Interval::setMax: argument below min"); + max_ = value; + } + + /** Set both interval bounds */ + inline void setBounds(const Numeric minval, const Numeric maxval, const bool swapIfOutOfOrder = false) { + if (maxval < minval && !swapIfOutOfOrder) + throw npstat::NpstatInvalidArgument("In npstat::Interval::setBounds: invalid limits"); + min_ = minval; + max_ = maxval; + if (swapIfOutOfOrder && min_ > max_) + std::swap(min_, max_); + } + + /** Return the lower bound */ + inline const Numeric min() const { return min_; } + + /** Return the upper bound */ + inline const Numeric max() const { return max_; } + + /** Return both bounds */ + inline void getBounds(Numeric* pmin, Numeric* pmax) const { + *pmin = min_; + *pmax = max_; + } + + /** Interval length */ + inline Numeric length() const { return max_ - min_; } + + /** The middle point of the interval */ + inline Numeric midpoint() const { return static_cast((max_ + min_) * 0.5); } + + /** Is the point inside the interval or on the lower boundary? */ + inline bool isInsideLower(const Numeric value) const { return value >= min_ && value < max_; } + + /** Is the point inside the interval or on the upper boundary? */ + inline bool isInsideUpper(const Numeric value) const { return value > min_ && value <= max_; } + + /** Is the point inside the interval or on one of the boundaries? */ + inline bool isInsideWithBounds(const Numeric value) const { return value >= min_ && value <= max_; } + + /** // Is the point completely inside the interval // (and does not coincide with any bound)? */ - inline bool isInside(const Numeric value) const - {return value > min_ && value < max_;} + inline bool isInside(const Numeric value) const { return value > min_ && value < max_; } - //@{ - /** + //@{ + /** // Scaling of both the minimum and the maximum by a constant. // Minimum and maximum will be swapped internally in case the // constant is negative. */ - Interval& operator*=(double r); - Interval& operator/=(double r); - //@} + Interval& operator*=(double r); + Interval& operator/=(double r); + //@} - //@{ - /** Shift both interval bounds by a constant */ - Interval& operator+=(const Numeric value); - Interval& operator-=(const Numeric value); - //@} + //@{ + /** Shift both interval bounds by a constant */ + Interval& operator+=(const Numeric value); + Interval& operator-=(const Numeric value); + //@} - /** Move the interval so that the midpoint ends up at 0 */ - Interval& moveMidpointTo0(); + /** Move the interval so that the midpoint ends up at 0 */ + Interval& moveMidpointTo0(); - //@{ - /** + //@{ + /** // Scaling the bounds by a constant in such a way // that the midpoint remains unchanged */ - Interval& expand(double r); - //@} + Interval& expand(double r); + //@} - /** + /** // The following function returns default-constructed empty interval // in case this interval and the argument interval do not overlap */ - Interval overlap(const Interval& r) const; + Interval overlap(const Interval& r) const; - /** Same as overlap.length() but a tad faster */ - Numeric overlapLength(const Interval& r) const; + /** Same as overlap.length() but a tad faster */ + Numeric overlapLength(const Interval& r) const; - /** Same as overlapLength(r)/length() but a tad faster */ - double overlapFraction(const Interval& r) const; + /** Same as overlapLength(r)/length() but a tad faster */ + double overlapFraction(const Interval& r) const; - /** + /** // Derive the coefficients a and b such that the linear // mapping y = a*x + b maps the lower limit of this interval // into the lower limit of the argument interval and the // upper limit of this interval into the upper limit of the // argument interval */ - template - void linearMap(const Interval &r, double* a, double* b) const; + template + void linearMap(const Interval& r, double* a, double* b) const; - private: - Numeric min_; - Numeric max_; - }; -} + private: + Numeric min_; + Numeric max_; + }; +} // namespace npstat //@{ /** Binary comparison for equality */ template -bool operator==(const npstat::Interval& l,const npstat::Interval& r); +bool operator==(const npstat::Interval& l, const npstat::Interval& r); template -bool operator!=(const npstat::Interval& l,const npstat::Interval& r); +bool operator!=(const npstat::Interval& l, const npstat::Interval& r); //@} #include #include namespace npstat { - template - inline Interval Interval::overlap( - const Interval& r) const - { - Interval over; - if (max_ == r.min_) - over.setBounds(max_, max_); - else if (r.max_ == min_) - over.setBounds(min_, min_); - else if (max_ > r.min_ && r.max_ > min_) - { - over.min_ = min_ < r.min_ ? r.min_ : min_; - over.max_ = max_ < r.max_ ? max_ : r.max_; - } - return over; + template + inline Interval Interval::overlap(const Interval& r) const { + Interval over; + if (max_ == r.min_) + over.setBounds(max_, max_); + else if (r.max_ == min_) + over.setBounds(min_, min_); + else if (max_ > r.min_ && r.max_ > min_) { + over.min_ = min_ < r.min_ ? r.min_ : min_; + over.max_ = max_ < r.max_ ? max_ : r.max_; } - - template - inline Numeric Interval::overlapLength(const Interval& r) const - { - if (max_ > r.min_ && r.max_ > min_) - { - const Numeric mn = min_ < r.min_ ? r.min_ : min_; - const Numeric mx = max_ < r.max_ ? max_ : r.max_; - return mx - mn; - } - else - return Numeric(); - } - - template - inline double Interval::overlapFraction(const Interval& r) const - { - if (max_ > r.min_ && r.max_ > min_) - { - const Numeric mn = min_ < r.min_ ? r.min_ : min_; - const Numeric mx = max_ < r.max_ ? max_ : r.max_; - return (mx - mn)*1.0/(max_ - min_); - } - else - return 0.0; - } - - template - inline Interval& Interval::operator*=(const double r) - { - min_ *= r; - max_ *= r; - if (max_ < min_) - std::swap(min_, max_); - return *this; - } - - template - inline Interval& Interval::moveMidpointTo0() - { - const Numeric len = max_ - min_; - max_ = len/static_cast(2); - min_ = -max_; - return *this; - } - - template - inline Interval& Interval::expand(const double ir) - { - const double r = fabs(ir); - if (r != 1.0) - { - const Numeric center(static_cast((max_ + min_)*0.5)); - min_ = center + (min_ - center)*r; - max_ = center + (max_ - center)*r; - } - return *this; + return over; + } + + template + inline Numeric Interval::overlapLength(const Interval& r) const { + if (max_ > r.min_ && r.max_ > min_) { + const Numeric mn = min_ < r.min_ ? r.min_ : min_; + const Numeric mx = max_ < r.max_ ? max_ : r.max_; + return mx - mn; + } else + return Numeric(); + } + + template + inline double Interval::overlapFraction(const Interval& r) const { + if (max_ > r.min_ && r.max_ > min_) { + const Numeric mn = min_ < r.min_ ? r.min_ : min_; + const Numeric mx = max_ < r.max_ ? max_ : r.max_; + return (mx - mn) * 1.0 / (max_ - min_); + } else + return 0.0; + } + + template + inline Interval& Interval::operator*=(const double r) { + min_ *= r; + max_ *= r; + if (max_ < min_) + std::swap(min_, max_); + return *this; + } + + template + inline Interval& Interval::moveMidpointTo0() { + const Numeric len = max_ - min_; + max_ = len / static_cast(2); + min_ = -max_; + return *this; + } + + template + inline Interval& Interval::expand(const double ir) { + const double r = fabs(ir); + if (r != 1.0) { + const Numeric center(static_cast((max_ + min_) * 0.5)); + min_ = center + (min_ - center) * r; + max_ = center + (max_ - center) * r; } - - template - inline Interval& Interval::operator/=(const double r) - { - if (!r) throw npstat::NpstatDomainError( - "In npstat::Interval::operator/=: division by zero"); - min_ /= r; - max_ /= r; - if (max_ < min_) - std::swap(min_, max_); - return *this; - } - - template - inline Interval& Interval::operator+=(const Numeric r) - { - min_ += r; - max_ += r; - return *this; - } - - template - inline Interval& Interval::operator-=(const Numeric r) - { - min_ -= r; - max_ -= r; - return *this; - } - - template - template - void Interval::linearMap( - const Interval &r, double* a, double* b) const - { - if (max_ == min_) throw npstat::NpstatDomainError( - "In npstat::Interval::linearMap: zero length interval"); - assert(a); - assert(b); - const Num2 rmax(r.max()); - const Num2 rmin(r.min()); - *a = static_cast((rmax - rmin)*1.0/(max_ - min_)); - *b = static_cast((rmax + rmin) - *a*(max_ + min_))/2.0; - } -} + return *this; + } + + template + inline Interval& Interval::operator/=(const double r) { + if (!r) + throw npstat::NpstatDomainError("In npstat::Interval::operator/=: division by zero"); + min_ /= r; + max_ /= r; + if (max_ < min_) + std::swap(min_, max_); + return *this; + } + + template + inline Interval& Interval::operator+=(const Numeric r) { + min_ += r; + max_ += r; + return *this; + } + + template + inline Interval& Interval::operator-=(const Numeric r) { + min_ -= r; + max_ -= r; + return *this; + } + + template + template + void Interval::linearMap(const Interval& r, double* a, double* b) const { + if (max_ == min_) + throw npstat::NpstatDomainError("In npstat::Interval::linearMap: zero length interval"); + assert(a); + assert(b); + const Num2 rmax(r.max()); + const Num2 rmin(r.min()); + *a = static_cast((rmax - rmin) * 1.0 / (max_ - min_)); + *b = static_cast((rmax + rmin) - *a * (max_ + min_)) / 2.0; + } +} // namespace npstat template -bool operator==(const npstat::Interval& l,const npstat::Interval& r) -{ - return r.min() == l.min() && r.max() == l.max(); +bool operator==(const npstat::Interval& l, const npstat::Interval& r) { + return r.min() == l.min() && r.max() == l.max(); } template -bool operator!=(const npstat::Interval& l,const npstat::Interval& r) -{ - return !(l == r); +bool operator!=(const npstat::Interval& l, const npstat::Interval& r) { + return !(l == r); } - -#endif // NPSTAT_INTERVAL_HH_ - +#endif // NPSTAT_INTERVAL_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/LinInterpolatedTableND.h b/JetMETCorrections/InterpolationTables/interface/LinInterpolatedTableND.h index c72e8dd39f35d..41b0811a90550 100644 --- a/JetMETCorrections/InterpolationTables/interface/LinInterpolatedTableND.h +++ b/JetMETCorrections/InterpolationTables/interface/LinInterpolatedTableND.h @@ -21,23 +21,22 @@ #include "JetMETCorrections/InterpolationTables/interface/UniformAxis.h" namespace npstat { - /** + /** // Template for multilinear interpolation/extrapolation of values provided // on a rectangular coordinate grid. "Numeric" is the type stored in // the table. "Axis" should be one of GridAxis, UniformAxis, or DualAxis // classes or a user-provided class with a similar set of methods. */ - template - class LinInterpolatedTableND - { - template - friend class LinInterpolatedTableND; + template + class LinInterpolatedTableND { + template + friend class LinInterpolatedTableND; - public: - typedef Numeric value_type; - typedef Axis axis_type; + public: + typedef Numeric value_type; + typedef Axis axis_type; - /** + /** // Main constructor for arbitrary-dimensional interpolators. // // "axes" are the axes of the rectangular coordinate grid. @@ -51,120 +50,139 @@ namespace npstat { // "functionLabel" is an arbitrary string which can potentially // be used by plotting programs and such. */ - LinInterpolatedTableND( - const std::vector& axes, - const std::vector >& extrapolationType, - const char* functionLabel=nullptr); - - /** Convenience constructor for 1-d interpolators */ - LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, - const char* functionLabel=nullptr); - - /** Convenience constructor for 2-d interpolators */ - LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const char* functionLabel=nullptr); - - /** Convenience constructor for 3-d interpolators */ - LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const char* functionLabel=nullptr); - - /** Convenience constructor for 4-d interpolators */ - LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const char* functionLabel=nullptr); - - /** Convenience constructor for 5-d interpolators */ - LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const Axis& vAxis, bool leftV, bool rightV, - const char* functionLabel=nullptr); - - /** + LinInterpolatedTableND(const std::vector& axes, + const std::vector >& extrapolationType, + const char* functionLabel = nullptr); + + /** Convenience constructor for 1-d interpolators */ + LinInterpolatedTableND(const Axis& xAxis, bool leftX, bool rightX, const char* functionLabel = nullptr); + + /** Convenience constructor for 2-d interpolators */ + LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const char* functionLabel = nullptr); + + /** Convenience constructor for 3-d interpolators */ + LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const char* functionLabel = nullptr); + + /** Convenience constructor for 4-d interpolators */ + LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const char* functionLabel = nullptr); + + /** Convenience constructor for 5-d interpolators */ + LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const Axis& vAxis, + bool leftV, + bool rightV, + const char* functionLabel = nullptr); + + /** // Converting copy constructor from interpolator // with another storage type */ - template - LinInterpolatedTableND(const LinInterpolatedTableND&); + template + LinInterpolatedTableND(const LinInterpolatedTableND&); - /** + /** // Basic interpolation result. Argument point dimensionality must be // compatible with the interpolator dimensionality. */ - Numeric operator()(const double* point, unsigned dim) const; - - //@{ - /** Convenience function for low-dimensional interpolators */ - Numeric operator()(const double& x0) const; - Numeric operator()(const double& x0, const double& x1) const; - Numeric operator()(const double& x0, const double& x1, - const double& x2) const; - Numeric operator()(const double& x0, const double& x1, - const double& x2, const double& x3) const; - Numeric operator()(const double& x0, const double& x1, - const double& x2, const double& x3, - const double& x4) const; - //@} - - //@{ - /** Examine interpolator contents */ - inline unsigned dim() const {return dim_;} - inline const std::vector& axes() const {return axes_;} - inline const Axis& axis(const unsigned i) const - {return axes_.at(i);} - inline unsigned long length() const {return data_.length();} - bool leftInterpolationLinear(unsigned i) const; - bool rightInterpolationLinear(unsigned i) const; - std::vector > interpolationType() const; - inline const std::string& functionLabel() const - {return functionLabel_;} - //@} - - //@{ - /** Access the interpolator table data */ - inline const ArrayND& table() const {return data_;} - inline ArrayND& table() {return data_;} - //@} - - /** Convenience function for getting coordinates of the grid points */ - void getCoords(unsigned long linearIndex, - double* coords, unsigned coordsBufferSize) const; - - /** + Numeric operator()(const double* point, unsigned dim) const; + + //@{ + /** Convenience function for low-dimensional interpolators */ + Numeric operator()(const double& x0) const; + Numeric operator()(const double& x0, const double& x1) const; + Numeric operator()(const double& x0, const double& x1, const double& x2) const; + Numeric operator()(const double& x0, const double& x1, const double& x2, const double& x3) const; + Numeric operator()(const double& x0, const double& x1, const double& x2, const double& x3, const double& x4) const; + //@} + + //@{ + /** Examine interpolator contents */ + inline unsigned dim() const { return dim_; } + inline const std::vector& axes() const { return axes_; } + inline const Axis& axis(const unsigned i) const { return axes_.at(i); } + inline unsigned long length() const { return data_.length(); } + bool leftInterpolationLinear(unsigned i) const; + bool rightInterpolationLinear(unsigned i) const; + std::vector > interpolationType() const; + inline const std::string& functionLabel() const { return functionLabel_; } + //@} + + //@{ + /** Access the interpolator table data */ + inline const ArrayND& table() const { return data_; } + inline ArrayND& table() { return data_; } + //@} + + /** Convenience function for getting coordinates of the grid points */ + void getCoords(unsigned long linearIndex, double* coords, unsigned coordsBufferSize) const; + + /** // This method returns "true" if the method isUniform() // of each interpolator axis returns "true" */ - bool isUniformlyBinned() const; + bool isUniformlyBinned() const; - /** + /** // This method will return "true" if the point // is inside the grid limits or on the boundary */ - bool isWithinLimits(const double* point, unsigned dim) const; + bool isWithinLimits(const double* point, unsigned dim) const; - /** Modifier for the function label */ - inline void setFunctionLabel(const char* newlabel) - {functionLabel_ = newlabel ? newlabel : "";} + /** Modifier for the function label */ + inline void setFunctionLabel(const char* newlabel) { functionLabel_ = newlabel ? newlabel : ""; } - /** + /** // Invert the function w.r.t. the variable represented by one of // the axes. The function values must change monotonously along // the chosen axis. Note that this operation is meaningful only // in case "Numeric" type is either float or double. */ - template - CPP11_auto_ptr invertWRTAxis( - ConvertibleToUnsigned axisNumber, const Axis& replacementAxis, - bool newAxisLeftLinear, bool newAxisRightLinear, - const char* functionLabel=nullptr) const; + template + CPP11_auto_ptr invertWRTAxis(ConvertibleToUnsigned axisNumber, + const Axis& replacementAxis, + bool newAxisLeftLinear, + bool newAxisRightLinear, + const char* functionLabel = nullptr) const; - /** + /** // This method inverts the ratio response. // That is, we assume that the table encodes r(x) for // some function f(x) = x*r(x). We also assume that the @@ -186,66 +204,66 @@ namespace npstat { // h(f(x)). Naturally, this whole operation is meaningful // only in case "Numeric" type is either float or double. */ - template - CPP11_auto_ptr invertRatioResponse( - unsigned axisNumber, const Axis& replacementAxis, - bool newAxisLeftLinear, bool newAxisRightLinear, - Functor1 invg, Functor2 invh, - const char* functionLabel=nullptr) const; - - /** Comparison for equality */ - bool operator==(const LinInterpolatedTableND&) const; - - /** Logical negation of operator== */ - inline bool operator!=(const LinInterpolatedTableND& r) const - {return !(*this == r);} - - //@{ - // Method related to "geners" I/O - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static const char* classname(); - static inline unsigned version() {return 1;} - static LinInterpolatedTableND* read( - const gs::ClassId& id, std::istream& in); - - private: - LinInterpolatedTableND() = delete; - - LinInterpolatedTableND( - const ArrayND& data, - const std::vector& axes, - const char* leftInterpolation, - const char* rightInterpolation, - const std::string& label); - - bool allConstInterpolated() const; - - ArrayND data_; - std::vector axes_; - std::string functionLabel_; - char leftInterpolationLinear_[CHAR_BIT*sizeof(unsigned long)]; - char rightInterpolationLinear_[CHAR_BIT*sizeof(unsigned long)]; - unsigned dim_; - bool allConstInterpolated_; - - template - static double solveForRatioArg(double xmin, double xmax, - double rmin, double rmax, - double fval, Functor1 invg); - - template - static void invert1DResponse(const ArrayND& fromSlice, - const Axis& fromAxis, const Axis& toAxis, - bool newLeftLinear, bool newRightLinear, - Functor1 invg, - const double* rawx, const double* rawf, - double* workspace, - ArrayND* toSlice); - }; -} + template + CPP11_auto_ptr invertRatioResponse(unsigned axisNumber, + const Axis& replacementAxis, + bool newAxisLeftLinear, + bool newAxisRightLinear, + Functor1 invg, + Functor2 invh, + const char* functionLabel = nullptr) const; + + /** Comparison for equality */ + bool operator==(const LinInterpolatedTableND&) const; + + /** Logical negation of operator== */ + inline bool operator!=(const LinInterpolatedTableND& r) const { return !(*this == r); } + + //@{ + // Method related to "geners" I/O + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static const char* classname(); + static inline unsigned version() { return 1; } + static LinInterpolatedTableND* read(const gs::ClassId& id, std::istream& in); + + private: + LinInterpolatedTableND() = delete; + + LinInterpolatedTableND(const ArrayND& data, + const std::vector& axes, + const char* leftInterpolation, + const char* rightInterpolation, + const std::string& label); + + bool allConstInterpolated() const; + + ArrayND data_; + std::vector axes_; + std::string functionLabel_; + char leftInterpolationLinear_[CHAR_BIT * sizeof(unsigned long)]; + char rightInterpolationLinear_[CHAR_BIT * sizeof(unsigned long)]; + unsigned dim_; + bool allConstInterpolated_; + + template + static double solveForRatioArg(double xmin, double xmax, double rmin, double rmax, double fval, Functor1 invg); + + template + static void invert1DResponse(const ArrayND& fromSlice, + const Axis& fromAxis, + const Axis& toAxis, + bool newLeftLinear, + bool newRightLinear, + Functor1 invg, + const double* rawx, + const double* rawf, + double* workspace, + ArrayND* toSlice); + }; +} // namespace npstat #include #include @@ -259,990 +277,874 @@ namespace npstat { #include "JetMETCorrections/InterpolationTables/interface/isMonotonous.h" namespace npstat { - namespace Private { - template - ArrayShape makeTableShape(const std::vector& axes) - { - const unsigned n = axes.size(); - ArrayShape result; - result.reserve(n); - for (unsigned i=0; i - ArrayShape makeTableShape(const Axis& xAxis) - { - ArrayShape result; - result.reserve(1U); - result.push_back(xAxis.nCoords()); - return result; - } - - template - ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis) - { - ArrayShape result; - result.reserve(2U); - result.push_back(xAxis.nCoords()); - result.push_back(yAxis.nCoords()); - return result; - } - - template - ArrayShape makeTableShape(const Axis& xAxis, - const Axis& yAxis, - const Axis& zAxis) - { - ArrayShape result; - result.reserve(3U); - result.push_back(xAxis.nCoords()); - result.push_back(yAxis.nCoords()); - result.push_back(zAxis.nCoords()); - return result; - } - - template - ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis) - { - ArrayShape result; - result.reserve(4U); - result.push_back(xAxis.nCoords()); - result.push_back(yAxis.nCoords()); - result.push_back(zAxis.nCoords()); - result.push_back(tAxis.nCoords()); - return result; - } - - template - ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis, - const Axis& zAxis, const Axis& tAxis, - const Axis& vAxis) - { - ArrayShape result; - result.reserve(5U); - result.push_back(xAxis.nCoords()); - result.push_back(yAxis.nCoords()); - result.push_back(zAxis.nCoords()); - result.push_back(tAxis.nCoords()); - result.push_back(vAxis.nCoords()); - return result; - } - - inline double lind_interpolateSimple( - const double x0, const double x1, - const double y0, const double y1, - const double x) - { - return y0 + (y1 - y0)*((x - x0)/(x1 - x0)); - } - - template - void lind_invert1DSlice( - const ArrayND& fromSlice, - const Axis& fromAxis, const Axis& toAxis, - const bool leftLinear, const bool rightLinear, - ArrayND* toSlice) - { - assert(toSlice); - assert(fromSlice.rank() == 1U); - assert(toSlice->rank() == 1U); - - const Numeric* fromData = fromSlice.data(); - const unsigned fromLen = fromSlice.length(); - assert(fromLen > 1U); - assert(fromLen == fromAxis.nCoords()); - const Numeric* fromDataEnd = fromData + fromLen; - if (!isStrictlyMonotonous(fromData, fromDataEnd)) - throw npstat::NpstatInvalidArgument( - "In npstat::Private::lind_invert1DSlice: " - "slice data is not monotonous and can not be inverted"); - - const Numeric yfirst = fromData[0]; - const Numeric ylast = fromData[fromLen - 1U]; - const bool increasing = yfirst < ylast; - - Numeric* toD = const_cast(toSlice->data()); - const unsigned nAxisPoints = toAxis.nCoords(); - assert(toSlice->length() == nAxisPoints); - - for (unsigned ipt=0; ipt(toAxis.coordinate(ipt)); - if (increasing) - { - if (y <= yfirst) - { - if (leftLinear) - toD[ipt] = Private::lind_interpolateSimple( - yfirst, fromData[1], fromAxis.coordinate(0), - fromAxis.coordinate(1), y); - else - toD[ipt] = fromAxis.coordinate(0); - } - else if (y >= ylast) - { - if (rightLinear) - toD[ipt] = Private::lind_interpolateSimple( - ylast, fromData[fromLen - 2U], - fromAxis.coordinate(fromLen - 1U), - fromAxis.coordinate(fromLen - 2U), y); - else - toD[ipt] = fromAxis.coordinate(fromLen - 1U); - } - else - { - const unsigned i = std::lower_bound(fromData,fromDataEnd,y)- - fromData; - toD[ipt] = Private::lind_interpolateSimple( - fromData[i-1U], fromData[i], - fromAxis.coordinate(i-1U), - fromAxis.coordinate(i), y); - } - } - else - { - // The role of left and right are exchanged - // with respect to first and last point - if (y <= ylast) - { - if (leftLinear) - toD[ipt] = Private::lind_interpolateSimple( - ylast, fromData[fromLen - 2U], - fromAxis.coordinate(fromLen - 1U), - fromAxis.coordinate(fromLen - 2U), y); - else - toD[ipt] = fromAxis.coordinate(fromLen - 1U); - } - else if (y >= yfirst) - { - if (rightLinear) - toD[ipt] = Private::lind_interpolateSimple( - yfirst, fromData[1], - fromAxis.coordinate(0), - fromAxis.coordinate(1), y); - else - toD[ipt] = fromAxis.coordinate(0); - } - else - { - const unsigned i = std::lower_bound(fromData,fromDataEnd, - y,std::greater())-fromData; - toD[ipt] = Private::lind_interpolateSimple( - fromData[i-1U], fromData[i], - fromAxis.coordinate(i-1U), - fromAxis.coordinate(i), y); - } - } - } - } + namespace Private { + template + ArrayShape makeTableShape(const std::vector& axes) { + const unsigned n = axes.size(); + ArrayShape result; + result.reserve(n); + for (unsigned i = 0; i < n; ++i) + result.push_back(axes[i].nCoords()); + return result; } - template - bool LinInterpolatedTableND::allConstInterpolated() const - { - for (unsigned i=0; i + ArrayShape makeTableShape(const Axis& xAxis) { + ArrayShape result; + result.reserve(1U); + result.push_back(xAxis.nCoords()); + return result; } - template - bool LinInterpolatedTableND::operator==( - const LinInterpolatedTableND& r) const - { - if (dim_ != r.dim_) - return false; - for (unsigned i=0; i - const char* LinInterpolatedTableND::classname() - { - static const std::string myClass(gs::template_class_name( - "npstat::LinInterpolatedTableND")); - return myClass.c_str(); - } - - template - bool LinInterpolatedTableND::write(std::ostream& of) const - { - const bool status = data_.classId().write(of) && - data_.write(of) && - gs::write_obj_vector(of, axes_); - if (status) - { - gs::write_pod_array(of, leftInterpolationLinear_, dim_); - gs::write_pod_array(of, rightInterpolationLinear_, dim_); - gs::write_pod(of, functionLabel_); - } - return status && !of.fail(); + template + ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis) { + ArrayShape result; + result.reserve(2U); + result.push_back(xAxis.nCoords()); + result.push_back(yAxis.nCoords()); + return result; } - template - LinInterpolatedTableND* - LinInterpolatedTableND::read( - const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current( - gs::ClassId::makeId >()); - current.ensureSameId(id); - - gs::ClassId ida(in, 1); - ArrayND data; - ArrayND::restore(ida, in, &data); - std::vector axes; - gs::read_heap_obj_vector_as_placed(in, &axes); - const unsigned dim = axes.size(); - if (dim > CHAR_BIT*sizeof(unsigned long) || data.rank() != dim) - throw gs::IOInvalidData( - "In npstat::LinInterpolatedTableND::read: " - "read back invalid dimensionality"); - char leftInterpolation[CHAR_BIT*sizeof(unsigned long)]; - gs::read_pod_array(in, leftInterpolation, dim); - char rightInterpolation[CHAR_BIT*sizeof(unsigned long)]; - gs::read_pod_array(in, rightInterpolation, dim); - std::string label; - gs::read_pod(in, &label); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::LinInterpolatedTableND::read: input stream failure"); - return new LinInterpolatedTableND( - data, axes, leftInterpolation, rightInterpolation, label); + template + ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis, const Axis& zAxis) { + ArrayShape result; + result.reserve(3U); + result.push_back(xAxis.nCoords()); + result.push_back(yAxis.nCoords()); + result.push_back(zAxis.nCoords()); + return result; } - template - bool LinInterpolatedTableND::leftInterpolationLinear( - const unsigned i) const - { - if (i >= dim_) throw npstat::NpstatOutOfRange( - "In npstat::LinInterpolatedTableND::leftInterpolationLinear: " - "index out of range"); - return leftInterpolationLinear_[i]; + template + ArrayShape makeTableShape(const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const Axis& tAxis) { + ArrayShape result; + result.reserve(4U); + result.push_back(xAxis.nCoords()); + result.push_back(yAxis.nCoords()); + result.push_back(zAxis.nCoords()); + result.push_back(tAxis.nCoords()); + return result; } - template - bool LinInterpolatedTableND::rightInterpolationLinear( - const unsigned i) const - { - if (i >= dim_) throw npstat::NpstatOutOfRange( - "In npstat::LinInterpolatedTableND::rightInterpolationLinear: " - "index out of range"); - return rightInterpolationLinear_[i]; + template + ArrayShape makeTableShape( + const Axis& xAxis, const Axis& yAxis, const Axis& zAxis, const Axis& tAxis, const Axis& vAxis) { + ArrayShape result; + result.reserve(5U); + result.push_back(xAxis.nCoords()); + result.push_back(yAxis.nCoords()); + result.push_back(zAxis.nCoords()); + result.push_back(tAxis.nCoords()); + result.push_back(vAxis.nCoords()); + return result; } - template - bool LinInterpolatedTableND::isUniformlyBinned() const - { - for (unsigned i=0; i - std::vector > - LinInterpolatedTableND::interpolationType() const - { - std::vector > vec; - vec.reserve(dim_); - for (unsigned i=0; i(leftInterpolationLinear_[i], - rightInterpolationLinear_[i])); - return vec; - } - - template - LinInterpolatedTableND::LinInterpolatedTableND( - const std::vector& axes, - const std::vector >& interpolationType, - const char* label) - : data_(Private::makeTableShape(axes)), - axes_(axes), - functionLabel_(label ? label : ""), - dim_(axes.size()) - { - if (dim_ == 0 || dim_ >= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND constructor: requested " - "table dimensionality is not supported"); - if (dim_ != interpolationType.size()) - throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND constructor: " - "incompatible number of interpolation specifications"); - for (unsigned i=0; i& pair(interpolationType[i]); - leftInterpolationLinear_[i] = pair.first; - rightInterpolationLinear_[i] = pair.second; - } - - allConstInterpolated_ = allConstInterpolated(); - } - - template - template - LinInterpolatedTableND::LinInterpolatedTableND( - const LinInterpolatedTableND& r) - : data_(r.data_), - axes_(r.axes_), - functionLabel_(r.functionLabel_), - dim_(r.dim_), - allConstInterpolated_(r.allConstInterpolated_) - { - for (unsigned i=0; i - LinInterpolatedTableND::LinInterpolatedTableND( - const ArrayND& data, - const std::vector& axes, - const char* leftInterpolation, - const char* rightInterpolation, - const std::string& label) - : data_(data), - axes_(axes), - functionLabel_(label), - dim_(data.rank()) - { - for (unsigned i=0; i + void lind_invert1DSlice(const ArrayND& fromSlice, + const Axis& fromAxis, + const Axis& toAxis, + const bool leftLinear, + const bool rightLinear, + ArrayND* toSlice) { + assert(toSlice); + assert(fromSlice.rank() == 1U); + assert(toSlice->rank() == 1U); + + const Numeric* fromData = fromSlice.data(); + const unsigned fromLen = fromSlice.length(); + assert(fromLen > 1U); + assert(fromLen == fromAxis.nCoords()); + const Numeric* fromDataEnd = fromData + fromLen; + if (!isStrictlyMonotonous(fromData, fromDataEnd)) + throw npstat::NpstatInvalidArgument( + "In npstat::Private::lind_invert1DSlice: " + "slice data is not monotonous and can not be inverted"); + + const Numeric yfirst = fromData[0]; + const Numeric ylast = fromData[fromLen - 1U]; + const bool increasing = yfirst < ylast; + + Numeric* toD = const_cast(toSlice->data()); + const unsigned nAxisPoints = toAxis.nCoords(); + assert(toSlice->length() == nAxisPoints); + + for (unsigned ipt = 0; ipt < nAxisPoints; ++ipt) { + const Numeric y = static_cast(toAxis.coordinate(ipt)); + if (increasing) { + if (y <= yfirst) { + if (leftLinear) + toD[ipt] = Private::lind_interpolateSimple( + yfirst, fromData[1], fromAxis.coordinate(0), fromAxis.coordinate(1), y); + else + toD[ipt] = fromAxis.coordinate(0); + } else if (y >= ylast) { + if (rightLinear) + toD[ipt] = Private::lind_interpolateSimple(ylast, + fromData[fromLen - 2U], + fromAxis.coordinate(fromLen - 1U), + fromAxis.coordinate(fromLen - 2U), + y); + else + toD[ipt] = fromAxis.coordinate(fromLen - 1U); + } else { + const unsigned i = std::lower_bound(fromData, fromDataEnd, y) - fromData; + toD[ipt] = Private::lind_interpolateSimple( + fromData[i - 1U], fromData[i], fromAxis.coordinate(i - 1U), fromAxis.coordinate(i), y); + } + } else { + // The role of left and right are exchanged + // with respect to first and last point + if (y <= ylast) { + if (leftLinear) + toD[ipt] = Private::lind_interpolateSimple(ylast, + fromData[fromLen - 2U], + fromAxis.coordinate(fromLen - 1U), + fromAxis.coordinate(fromLen - 2U), + y); + else + toD[ipt] = fromAxis.coordinate(fromLen - 1U); + } else if (y >= yfirst) { + if (rightLinear) + toD[ipt] = Private::lind_interpolateSimple( + yfirst, fromData[1], fromAxis.coordinate(0), fromAxis.coordinate(1), y); + else + toD[ipt] = fromAxis.coordinate(0); + } else { + const unsigned i = std::lower_bound(fromData, fromDataEnd, y, std::greater()) - fromData; + toD[ipt] = Private::lind_interpolateSimple( + fromData[i - 1U], fromData[i], fromAxis.coordinate(i - 1U), fromAxis.coordinate(i), y); + } } - allConstInterpolated_ = allConstInterpolated(); + } } - - template - LinInterpolatedTableND::LinInterpolatedTableND( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const Axis& vAxis, bool leftV, bool rightV, - const char* label) - : data_(Private::makeTableShape(xAxis, yAxis, zAxis, tAxis, vAxis)), - functionLabel_(label ? label : ""), - dim_(5U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - axes_.push_back(tAxis); - axes_.push_back(vAxis); - - unsigned i = 0; - leftInterpolationLinear_[i] = leftX; - rightInterpolationLinear_[i++] = rightX; - leftInterpolationLinear_[i] = leftY; - rightInterpolationLinear_[i++] = rightY; - leftInterpolationLinear_[i] = leftZ; - rightInterpolationLinear_[i++] = rightZ; - leftInterpolationLinear_[i] = leftT; - rightInterpolationLinear_[i++] = rightT; - leftInterpolationLinear_[i] = leftV; - rightInterpolationLinear_[i++] = rightV; - assert(i == dim_); - - allConstInterpolated_ = allConstInterpolated(); + } // namespace Private + + template + bool LinInterpolatedTableND::allConstInterpolated() const { + for (unsigned i = 0; i < dim_; ++i) + if (leftInterpolationLinear_[i] || rightInterpolationLinear_[i]) + return false; + return true; + } + + template + bool LinInterpolatedTableND::operator==(const LinInterpolatedTableND& r) const { + if (dim_ != r.dim_) + return false; + for (unsigned i = 0; i < dim_; ++i) { + if (leftInterpolationLinear_[i] != r.leftInterpolationLinear_[i]) + return false; + if (rightInterpolationLinear_[i] != r.rightInterpolationLinear_[i]) + return false; } - - template - LinInterpolatedTableND::LinInterpolatedTableND( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const char* label) - : data_(Private::makeTableShape(xAxis, yAxis, zAxis, tAxis)), - functionLabel_(label ? label : ""), - dim_(4U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - axes_.push_back(tAxis); - - unsigned i = 0; - leftInterpolationLinear_[i] = leftX; - rightInterpolationLinear_[i++] = rightX; - leftInterpolationLinear_[i] = leftY; - rightInterpolationLinear_[i++] = rightY; - leftInterpolationLinear_[i] = leftZ; - rightInterpolationLinear_[i++] = rightZ; - leftInterpolationLinear_[i] = leftT; - rightInterpolationLinear_[i++] = rightT; - assert(i == dim_); - - allConstInterpolated_ = allConstInterpolated(); + return data_ == r.data_ && axes_ == r.axes_ && functionLabel_ == r.functionLabel_; + } + + template + const char* LinInterpolatedTableND::classname() { + static const std::string myClass(gs::template_class_name("npstat::LinInterpolatedTableND")); + return myClass.c_str(); + } + + template + bool LinInterpolatedTableND::write(std::ostream& of) const { + const bool status = data_.classId().write(of) && data_.write(of) && gs::write_obj_vector(of, axes_); + if (status) { + gs::write_pod_array(of, leftInterpolationLinear_, dim_); + gs::write_pod_array(of, rightInterpolationLinear_, dim_); + gs::write_pod(of, functionLabel_); } - - template - LinInterpolatedTableND::LinInterpolatedTableND( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const char* label) - : data_(Private::makeTableShape(xAxis, yAxis, zAxis)), - functionLabel_(label ? label : ""), - dim_(3U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - axes_.push_back(zAxis); - - unsigned i = 0; - leftInterpolationLinear_[i] = leftX; - rightInterpolationLinear_[i++] = rightX; - leftInterpolationLinear_[i] = leftY; - rightInterpolationLinear_[i++] = rightY; - leftInterpolationLinear_[i] = leftZ; - rightInterpolationLinear_[i++] = rightZ; - assert(i == dim_); - - allConstInterpolated_ = allConstInterpolated(); + return status && !of.fail(); + } + + template + LinInterpolatedTableND* LinInterpolatedTableND::read(const gs::ClassId& id, + std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + gs::ClassId ida(in, 1); + ArrayND data; + ArrayND::restore(ida, in, &data); + std::vector axes; + gs::read_heap_obj_vector_as_placed(in, &axes); + const unsigned dim = axes.size(); + if (dim > CHAR_BIT * sizeof(unsigned long) || data.rank() != dim) + throw gs::IOInvalidData( + "In npstat::LinInterpolatedTableND::read: " + "read back invalid dimensionality"); + char leftInterpolation[CHAR_BIT * sizeof(unsigned long)]; + gs::read_pod_array(in, leftInterpolation, dim); + char rightInterpolation[CHAR_BIT * sizeof(unsigned long)]; + gs::read_pod_array(in, rightInterpolation, dim); + std::string label; + gs::read_pod(in, &label); + if (in.fail()) + throw gs::IOReadFailure("In npstat::LinInterpolatedTableND::read: input stream failure"); + return new LinInterpolatedTableND(data, axes, leftInterpolation, rightInterpolation, label); + } + + template + bool LinInterpolatedTableND::leftInterpolationLinear(const unsigned i) const { + if (i >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::LinInterpolatedTableND::leftInterpolationLinear: " + "index out of range"); + return leftInterpolationLinear_[i]; + } + + template + bool LinInterpolatedTableND::rightInterpolationLinear(const unsigned i) const { + if (i >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::LinInterpolatedTableND::rightInterpolationLinear: " + "index out of range"); + return rightInterpolationLinear_[i]; + } + + template + bool LinInterpolatedTableND::isUniformlyBinned() const { + for (unsigned i = 0; i < dim_; ++i) + if (!axes_[i].isUniform()) + return false; + return true; + } + + template + std::vector > LinInterpolatedTableND::interpolationType() const { + std::vector > vec; + vec.reserve(dim_); + for (unsigned i = 0; i < dim_; ++i) + vec.push_back(std::pair(leftInterpolationLinear_[i], rightInterpolationLinear_[i])); + return vec; + } + + template + LinInterpolatedTableND::LinInterpolatedTableND( + const std::vector& axes, const std::vector >& interpolationType, const char* label) + : data_(Private::makeTableShape(axes)), axes_(axes), functionLabel_(label ? label : ""), dim_(axes.size()) { + if (dim_ == 0 || dim_ >= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND constructor: requested " + "table dimensionality is not supported"); + if (dim_ != interpolationType.size()) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND constructor: " + "incompatible number of interpolation specifications"); + for (unsigned i = 0; i < dim_; ++i) { + const std::pair& pair(interpolationType[i]); + leftInterpolationLinear_[i] = pair.first; + rightInterpolationLinear_[i] = pair.second; } - template - LinInterpolatedTableND::LinInterpolatedTableND( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const char* label) - : data_(Private::makeTableShape(xAxis, yAxis)), - functionLabel_(label ? label : ""), - dim_(2U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - axes_.push_back(yAxis); - - unsigned i = 0; - leftInterpolationLinear_[i] = leftX; - rightInterpolationLinear_[i++] = rightX; - leftInterpolationLinear_[i] = leftY; - rightInterpolationLinear_[i++] = rightY; - assert(i == dim_); - - allConstInterpolated_ = allConstInterpolated(); + allConstInterpolated_ = allConstInterpolated(); + } + + template + template + LinInterpolatedTableND::LinInterpolatedTableND(const LinInterpolatedTableND& r) + : data_(r.data_), + axes_(r.axes_), + functionLabel_(r.functionLabel_), + dim_(r.dim_), + allConstInterpolated_(r.allConstInterpolated_) { + for (unsigned i = 0; i < dim_; ++i) { + leftInterpolationLinear_[i] = r.leftInterpolationLinear_[i]; + rightInterpolationLinear_[i] = r.rightInterpolationLinear_[i]; } - - template - LinInterpolatedTableND::LinInterpolatedTableND( - const Axis& xAxis, bool leftX, bool rightX, - const char* label) - : data_(Private::makeTableShape(xAxis)), - functionLabel_(label ? label : ""), - dim_(1U) - { - axes_.reserve(dim_); - axes_.push_back(xAxis); - - leftInterpolationLinear_[0] = leftX; - rightInterpolationLinear_[0] = rightX; - - allConstInterpolated_ = allConstInterpolated(); - } - - template - template - CPP11_auto_ptr > - LinInterpolatedTableND::invertWRTAxis( - const ConvertibleToUnsigned axisNumC, const Axis& replacementAxis, - const bool leftLinear, const bool rightLinear, - const char* functionLabel) const - { - const unsigned axisNumber = static_cast(axisNumC); - - if (axisNumber >= dim_) - throw npstat::NpstatOutOfRange( - "In npstat::LinInterpolatedTableND::invertAxis: " - "axis number is out of range"); - - // Generate the new set of axes - std::vector newAxes(axes_); - newAxes[axisNumber] = replacementAxis; - - std::vector > iType(interpolationType()); - iType[axisNumber] = std::pair(leftLinear, rightLinear); - - // Create the new table - CPP11_auto_ptr pTable( - new LinInterpolatedTableND(newAxes, iType, functionLabel)); - - if (dim_ > 1U) - { - // Prepare array slices - unsigned sliceIndex[CHAR_BIT*sizeof(unsigned long)]; - unsigned fixedIndices[CHAR_BIT*sizeof(unsigned long)]; - unsigned count = 0; - for (unsigned i=0; i parentSlice(data_, fixedIndices, count); - ArrayND dauSlice(pTable->data_, fixedIndices, count); - - // Cycle over the slices - for (ArrayNDScanner scan(sliceIndex,count); scan.isValid(); ++scan) - { - scan.getIndex(sliceIndex, count); - data_.exportSlice(&parentSlice, fixedIndices, - sliceIndex, count); - Private::lind_invert1DSlice( - parentSlice, axes_[axisNumber], replacementAxis, - leftLinear, rightLinear, &dauSlice); - pTable->data_.importSlice(dauSlice, fixedIndices, - sliceIndex, count); - } - } - else - Private::lind_invert1DSlice( - data_, axes_[0], replacementAxis, - leftLinear, rightLinear, &pTable->data_); - return pTable; + } + + template + LinInterpolatedTableND::LinInterpolatedTableND(const ArrayND& data, + const std::vector& axes, + const char* leftInterpolation, + const char* rightInterpolation, + const std::string& label) + : data_(data), axes_(axes), functionLabel_(label), dim_(data.rank()) { + for (unsigned i = 0; i < dim_; ++i) { + leftInterpolationLinear_[i] = leftInterpolation[i]; + rightInterpolationLinear_[i] = rightInterpolation[i]; } - - template - template - CPP11_auto_ptr > - LinInterpolatedTableND::invertRatioResponse( - const unsigned axisNumber, const Axis& replacementAxis, - const bool leftLinear, const bool rightLinear, - Functor1 invg, Functor2 invh, - const char* functionLabel) const - { - if (axisNumber >= dim_) - throw npstat::NpstatOutOfRange( - "In npstat::LinInterpolatedTableND::invertRatioResponse: " - "axis number is out of range"); - - // Generate the new set of axes - std::vector newAxes(axes_); - newAxes[axisNumber] = replacementAxis; - - std::vector > iType(interpolationType()); - iType[axisNumber] = std::pair(leftLinear, rightLinear); - - // Transform the original axis to the raw x values - const Axis& oldAxis(axes_[axisNumber]); - std::vector rawx; - const unsigned nCoords = oldAxis.nCoords(); - rawx.reserve(nCoords); - for (unsigned i=0; i rawf; - const unsigned nFuncs = replacementAxis.nCoords(); - rawf.reserve(nFuncs); - for (unsigned i=0; i + LinInterpolatedTableND::LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const Axis& vAxis, + bool leftV, + bool rightV, + const char* label) + : data_(Private::makeTableShape(xAxis, yAxis, zAxis, tAxis, vAxis)), + functionLabel_(label ? label : ""), + dim_(5U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + axes_.push_back(tAxis); + axes_.push_back(vAxis); + + unsigned i = 0; + leftInterpolationLinear_[i] = leftX; + rightInterpolationLinear_[i++] = rightX; + leftInterpolationLinear_[i] = leftY; + rightInterpolationLinear_[i++] = rightY; + leftInterpolationLinear_[i] = leftZ; + rightInterpolationLinear_[i++] = rightZ; + leftInterpolationLinear_[i] = leftT; + rightInterpolationLinear_[i++] = rightT; + leftInterpolationLinear_[i] = leftV; + rightInterpolationLinear_[i++] = rightV; + assert(i == dim_); + + allConstInterpolated_ = allConstInterpolated(); + } + + template + LinInterpolatedTableND::LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const char* label) + : data_(Private::makeTableShape(xAxis, yAxis, zAxis, tAxis)), functionLabel_(label ? label : ""), dim_(4U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + axes_.push_back(tAxis); + + unsigned i = 0; + leftInterpolationLinear_[i] = leftX; + rightInterpolationLinear_[i++] = rightX; + leftInterpolationLinear_[i] = leftY; + rightInterpolationLinear_[i++] = rightY; + leftInterpolationLinear_[i] = leftZ; + rightInterpolationLinear_[i++] = rightZ; + leftInterpolationLinear_[i] = leftT; + rightInterpolationLinear_[i++] = rightT; + assert(i == dim_); + + allConstInterpolated_ = allConstInterpolated(); + } + + template + LinInterpolatedTableND::LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const char* label) + : data_(Private::makeTableShape(xAxis, yAxis, zAxis)), functionLabel_(label ? label : ""), dim_(3U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + axes_.push_back(zAxis); + + unsigned i = 0; + leftInterpolationLinear_[i] = leftX; + rightInterpolationLinear_[i++] = rightX; + leftInterpolationLinear_[i] = leftY; + rightInterpolationLinear_[i++] = rightY; + leftInterpolationLinear_[i] = leftZ; + rightInterpolationLinear_[i++] = rightZ; + assert(i == dim_); + + allConstInterpolated_ = allConstInterpolated(); + } + + template + LinInterpolatedTableND::LinInterpolatedTableND( + const Axis& xAxis, bool leftX, bool rightX, const Axis& yAxis, bool leftY, bool rightY, const char* label) + : data_(Private::makeTableShape(xAxis, yAxis)), functionLabel_(label ? label : ""), dim_(2U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + axes_.push_back(yAxis); + + unsigned i = 0; + leftInterpolationLinear_[i] = leftX; + rightInterpolationLinear_[i++] = rightX; + leftInterpolationLinear_[i] = leftY; + rightInterpolationLinear_[i++] = rightY; + assert(i == dim_); + + allConstInterpolated_ = allConstInterpolated(); + } + + template + LinInterpolatedTableND::LinInterpolatedTableND(const Axis& xAxis, + bool leftX, + bool rightX, + const char* label) + : data_(Private::makeTableShape(xAxis)), functionLabel_(label ? label : ""), dim_(1U) { + axes_.reserve(dim_); + axes_.push_back(xAxis); + + leftInterpolationLinear_[0] = leftX; + rightInterpolationLinear_[0] = rightX; + + allConstInterpolated_ = allConstInterpolated(); + } + + template + template + CPP11_auto_ptr > LinInterpolatedTableND::invertWRTAxis( + const ConvertibleToUnsigned axisNumC, + const Axis& replacementAxis, + const bool leftLinear, + const bool rightLinear, + const char* functionLabel) const { + const unsigned axisNumber = static_cast(axisNumC); + + if (axisNumber >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::LinInterpolatedTableND::invertAxis: " + "axis number is out of range"); + + // Generate the new set of axes + std::vector newAxes(axes_); + newAxes[axisNumber] = replacementAxis; + + std::vector > iType(interpolationType()); + iType[axisNumber] = std::pair(leftLinear, rightLinear); + + // Create the new table + CPP11_auto_ptr pTable(new LinInterpolatedTableND(newAxes, iType, functionLabel)); + + if (dim_ > 1U) { + // Prepare array slices + unsigned sliceIndex[CHAR_BIT * sizeof(unsigned long)]; + unsigned fixedIndices[CHAR_BIT * sizeof(unsigned long)]; + unsigned count = 0; + for (unsigned i = 0; i < dim_; ++i) + if (i != axisNumber) { + sliceIndex[count] = data_.span(i); + fixedIndices[count++] = i; } - - // Workspace needed for the inversion code - std::vector workspace(nCoords); - - // Create the new table - CPP11_auto_ptr pTable( - new LinInterpolatedTableND(newAxes, iType, functionLabel)); - - if (dim_ > 1U) - { - // Prepare array slices - unsigned sliceIndex[CHAR_BIT*sizeof(unsigned long)]; - unsigned fixedIndices[CHAR_BIT*sizeof(unsigned long)]; - unsigned count = 0; - for (unsigned i=0; i parentSlice(data_, fixedIndices, count); - ArrayND dauSlice(pTable->data_, fixedIndices, count); - - // Cycle over the slices - for (ArrayNDScanner scan(sliceIndex,count); scan.isValid(); ++scan) - { - scan.getIndex(sliceIndex, count); - data_.exportSlice(&parentSlice, fixedIndices, - sliceIndex, count); - invert1DResponse(parentSlice, oldAxis, - replacementAxis, leftLinear, rightLinear, - invg, &rawx[0], &rawf[0], &workspace[0], - &dauSlice); - pTable->data_.importSlice(dauSlice, fixedIndices, - sliceIndex, count); - } - } - else - invert1DResponse(data_, oldAxis, replacementAxis, leftLinear, - rightLinear, invg, &rawx[0], &rawf[0], - &workspace[0], &pTable->data_); - return pTable; + ArrayND parentSlice(data_, fixedIndices, count); + ArrayND dauSlice(pTable->data_, fixedIndices, count); + + // Cycle over the slices + for (ArrayNDScanner scan(sliceIndex, count); scan.isValid(); ++scan) { + scan.getIndex(sliceIndex, count); + data_.exportSlice(&parentSlice, fixedIndices, sliceIndex, count); + Private::lind_invert1DSlice( + parentSlice, axes_[axisNumber], replacementAxis, leftLinear, rightLinear, &dauSlice); + pTable->data_.importSlice(dauSlice, fixedIndices, sliceIndex, count); + } + } else + Private::lind_invert1DSlice(data_, axes_[0], replacementAxis, leftLinear, rightLinear, &pTable->data_); + return pTable; + } + + template + template + CPP11_auto_ptr > LinInterpolatedTableND::invertRatioResponse( + const unsigned axisNumber, + const Axis& replacementAxis, + const bool leftLinear, + const bool rightLinear, + Functor1 invg, + Functor2 invh, + const char* functionLabel) const { + if (axisNumber >= dim_) + throw npstat::NpstatOutOfRange( + "In npstat::LinInterpolatedTableND::invertRatioResponse: " + "axis number is out of range"); + + // Generate the new set of axes + std::vector newAxes(axes_); + newAxes[axisNumber] = replacementAxis; + + std::vector > iType(interpolationType()); + iType[axisNumber] = std::pair(leftLinear, rightLinear); + + // Transform the original axis to the raw x values + const Axis& oldAxis(axes_[axisNumber]); + std::vector rawx; + const unsigned nCoords = oldAxis.nCoords(); + rawx.reserve(nCoords); + for (unsigned i = 0; i < nCoords; ++i) { + const double x = invg(oldAxis.coordinate(i)); + if (x < 0.0) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::invertRatioResponse: " + "invalid original axis definition (negative transformed " + "coordinate)"); + rawx.push_back(x); } - template - void LinInterpolatedTableND::getCoords( - const unsigned long linearIndex, - double* coords, const unsigned coordsBufferSize) const - { - if (coordsBufferSize < dim_) throw npstat::NpstatInvalidArgument( - "In LinInterpolatedTableND::getCoords: " - "insufficient buffer size"); - assert(coords); - unsigned index[CHAR_BIT*sizeof(unsigned long)]; - data_.convertLinearIndex(linearIndex, index, dim_); - for (unsigned i=0; i rawf; + const unsigned nFuncs = replacementAxis.nCoords(); + rawf.reserve(nFuncs); + for (unsigned i = 0; i < nFuncs; ++i) { + const double f = invh(replacementAxis.coordinate(i)); + if (f < 0.0) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::invertRatioResponse: " + "invalid new axis definition (negative transformed " + "coordinate)"); + rawf.push_back(f); } - template - bool LinInterpolatedTableND::isWithinLimits( - const double* point, const unsigned len) const - { - if (len != dim_) - throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::isWithinLimits: " - "incompatible point dimensionality"); - assert(point); - - for (unsigned i=0; i axes_[i].max()) - return false; - return true; - } - - template - Numeric LinInterpolatedTableND::operator()( - const double* point, const unsigned len) const - { - typedef typename ProperDblFromCmpl::type proper_double; - - if (len != dim_) - throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): " - "incompatible point dimensionality"); - assert(point); - - bool interpolateArray = true; - if (!allConstInterpolated_) - for (unsigned i=0; i axes_[i].max())) - { - interpolateArray = false; - break; - } - - if (interpolateArray) - { - // Translate coordinates into the array system and - // simply use the ArrayND interpolation facilities - double buf[CHAR_BIT*sizeof(unsigned long)]; - for (unsigned i=0; i& pair = - axes_[i].getInterval(point[i]); - buf[i] = pair.first + 1U - pair.second; - } - return data_.interpolate1(buf, dim_); + // Workspace needed for the inversion code + std::vector workspace(nCoords); + + // Create the new table + CPP11_auto_ptr pTable(new LinInterpolatedTableND(newAxes, iType, functionLabel)); + + if (dim_ > 1U) { + // Prepare array slices + unsigned sliceIndex[CHAR_BIT * sizeof(unsigned long)]; + unsigned fixedIndices[CHAR_BIT * sizeof(unsigned long)]; + unsigned count = 0; + for (unsigned i = 0; i < dim_; ++i) + if (i != axisNumber) { + sliceIndex[count] = data_.span(i); + fixedIndices[count++] = i; } - else - { - unsigned ix[CHAR_BIT*sizeof(unsigned long)]; - double weight[CHAR_BIT*sizeof(unsigned long)]; - for (unsigned i=0; i axes_[i].max()); - const std::pair& pair = linear ? - axes_[i].linearInterval(point[i]) : - axes_[i].getInterval(point[i]); - ix[i] = pair.first; - weight[i] = pair.second; - } - - Numeric sum = Numeric(); - const unsigned long maxcycle = 1UL << dim_; - const unsigned long* strides = data_.strides(); - const Numeric* dat = data_.data(); - for (unsigned long icycle=0UL; icycle(w); - } - return sum; + ArrayND parentSlice(data_, fixedIndices, count); + ArrayND dauSlice(pTable->data_, fixedIndices, count); + + // Cycle over the slices + for (ArrayNDScanner scan(sliceIndex, count); scan.isValid(); ++scan) { + scan.getIndex(sliceIndex, count); + data_.exportSlice(&parentSlice, fixedIndices, sliceIndex, count); + invert1DResponse(parentSlice, + oldAxis, + replacementAxis, + leftLinear, + rightLinear, + invg, + &rawx[0], + &rawf[0], + &workspace[0], + &dauSlice); + pTable->data_.importSlice(dauSlice, fixedIndices, sliceIndex, count); + } + } else + invert1DResponse(data_, + oldAxis, + replacementAxis, + leftLinear, + rightLinear, + invg, + &rawx[0], + &rawf[0], + &workspace[0], + &pTable->data_); + return pTable; + } + + template + void LinInterpolatedTableND::getCoords(const unsigned long linearIndex, + double* coords, + const unsigned coordsBufferSize) const { + if (coordsBufferSize < dim_) + throw npstat::NpstatInvalidArgument( + "In LinInterpolatedTableND::getCoords: " + "insufficient buffer size"); + assert(coords); + unsigned index[CHAR_BIT * sizeof(unsigned long)]; + data_.convertLinearIndex(linearIndex, index, dim_); + for (unsigned i = 0; i < dim_; ++i) + coords[i] = axes_[i].coordinate(index[i]); + } + + template + bool LinInterpolatedTableND::isWithinLimits(const double* point, const unsigned len) const { + if (len != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::isWithinLimits: " + "incompatible point dimensionality"); + assert(point); + + for (unsigned i = 0; i < dim_; ++i) + if (point[i] < axes_[i].min() || point[i] > axes_[i].max()) + return false; + return true; + } + + template + Numeric LinInterpolatedTableND::operator()(const double* point, const unsigned len) const { + typedef typename ProperDblFromCmpl::type proper_double; + + if (len != dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): " + "incompatible point dimensionality"); + assert(point); + + bool interpolateArray = true; + if (!allConstInterpolated_) + for (unsigned i = 0; i < dim_; ++i) + if ((leftInterpolationLinear_[i] && point[i] < axes_[i].min()) || + (rightInterpolationLinear_[i] && point[i] > axes_[i].max())) { + interpolateArray = false; + break; } - } - template - Numeric LinInterpolatedTableND::operator()( - const double& x0) const - { - const unsigned nArgs = 1U; - if (dim_ != nArgs) throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): number of " - "arguments, 1, is incompatible with the interpolator dimensionality"); - double tmp[nArgs]; - tmp[0] = x0; - return operator()(tmp, nArgs); - } - - template - Numeric LinInterpolatedTableND::operator()( - const double& x0, const double& x1) const - { - const unsigned nArgs = 2U; - if (dim_ != nArgs) throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): number of " - "arguments, 2, is incompatible with the interpolator dimensionality"); - double tmp[nArgs]; - tmp[0] = x0; - tmp[1] = x1; - return operator()(tmp, nArgs); + if (interpolateArray) { + // Translate coordinates into the array system and + // simply use the ArrayND interpolation facilities + double buf[CHAR_BIT * sizeof(unsigned long)]; + for (unsigned i = 0; i < dim_; ++i) { + const std::pair& pair = axes_[i].getInterval(point[i]); + buf[i] = pair.first + 1U - pair.second; + } + return data_.interpolate1(buf, dim_); + } else { + unsigned ix[CHAR_BIT * sizeof(unsigned long)]; + double weight[CHAR_BIT * sizeof(unsigned long)]; + for (unsigned i = 0; i < dim_; ++i) { + const bool linear = (leftInterpolationLinear_[i] && point[i] < axes_[i].min()) || + (rightInterpolationLinear_[i] && point[i] > axes_[i].max()); + const std::pair& pair = + linear ? axes_[i].linearInterval(point[i]) : axes_[i].getInterval(point[i]); + ix[i] = pair.first; + weight[i] = pair.second; + } + + Numeric sum = Numeric(); + const unsigned long maxcycle = 1UL << dim_; + const unsigned long* strides = data_.strides(); + const Numeric* dat = data_.data(); + for (unsigned long icycle = 0UL; icycle < maxcycle; ++icycle) { + double w = 1.0; + unsigned long icell = 0UL; + for (unsigned i = 0; i < dim_; ++i) { + if (icycle & (1UL << i)) { + w *= (1.0 - weight[i]); + icell += strides[i] * (ix[i] + 1U); + } else { + w *= weight[i]; + icell += strides[i] * ix[i]; + } + } + sum += dat[icell] * static_cast(w); + } + return sum; } - - template - Numeric LinInterpolatedTableND::operator()( - const double& x0, const double& x1, const double& x2) const - { - const unsigned nArgs = 3U; - if (dim_ != nArgs) throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): number of " - "arguments, 3, is incompatible with the interpolator dimensionality"); - double tmp[nArgs]; - tmp[0] = x0; - tmp[1] = x1; - tmp[2] = x2; - return operator()(tmp, nArgs); + } + + template + Numeric LinInterpolatedTableND::operator()(const double& x0) const { + const unsigned nArgs = 1U; + if (dim_ != nArgs) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): number of " + "arguments, 1, is incompatible with the interpolator dimensionality"); + double tmp[nArgs]; + tmp[0] = x0; + return operator()(tmp, nArgs); + } + + template + Numeric LinInterpolatedTableND::operator()(const double& x0, const double& x1) const { + const unsigned nArgs = 2U; + if (dim_ != nArgs) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): number of " + "arguments, 2, is incompatible with the interpolator dimensionality"); + double tmp[nArgs]; + tmp[0] = x0; + tmp[1] = x1; + return operator()(tmp, nArgs); + } + + template + Numeric LinInterpolatedTableND::operator()(const double& x0, + const double& x1, + const double& x2) const { + const unsigned nArgs = 3U; + if (dim_ != nArgs) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): number of " + "arguments, 3, is incompatible with the interpolator dimensionality"); + double tmp[nArgs]; + tmp[0] = x0; + tmp[1] = x1; + tmp[2] = x2; + return operator()(tmp, nArgs); + } + + template + Numeric LinInterpolatedTableND::operator()(const double& x0, + const double& x1, + const double& x2, + const double& x3) const { + const unsigned nArgs = 4U; + if (dim_ != nArgs) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): number of " + "arguments, 4, is incompatible with the interpolator dimensionality"); + double tmp[nArgs]; + tmp[0] = x0; + tmp[1] = x1; + tmp[2] = x2; + tmp[3] = x3; + return operator()(tmp, nArgs); + } + + template + Numeric LinInterpolatedTableND::operator()( + const double& x0, const double& x1, const double& x2, const double& x3, const double& x4) const { + const unsigned nArgs = 5U; + if (dim_ != nArgs) + throw npstat::NpstatInvalidArgument( + "In npstat::LinInterpolatedTableND::operator(): number of " + "arguments, 5, is incompatible with the interpolator dimensionality"); + double tmp[nArgs]; + tmp[0] = x0; + tmp[1] = x1; + tmp[2] = x2; + tmp[3] = x3; + tmp[4] = x4; + return operator()(tmp, nArgs); + } + + template + template + double LinInterpolatedTableND::solveForRatioArg( + const double xmin, const double xmax, const double rmin, const double rmax, const double fval, Functor1 invg) { + // Find two values of x so that f(x0) <= fval <= f(x1) + double x0 = xmin; + double x1 = xmax; + double fmin = invg(xmin) * rmin; + double fmax = invg(xmax) * rmax; + const double step = xmax - xmin; + assert(fmin < fmax); + assert(step > 0.0); + + unsigned stepcount = 0; + const unsigned maxSteps = 1000U; + for (double stepfactor = 1.0; (fval < fmin || fval > fmax) && stepcount < maxSteps; stepfactor *= 2.0, ++stepcount) + if (fval < fmin) { + x1 = x0; + fmax = fmin; + x0 -= stepfactor * step; + fmin = invg(x0) * Private::lind_interpolateSimple(xmin, xmax, rmin, rmax, x0); + } else { + x0 = x1; + fmin = fmax; + x1 += stepfactor * step; + fmax = invg(x1) * Private::lind_interpolateSimple(xmin, xmax, rmin, rmax, x1); + } + if (stepcount == maxSteps) + throw npstat::NpstatRuntimeError( + "In LinInterpolatedTableND::solveForRatioArg: " + "faled to bracket the root"); + + assert(x1 >= x0); + while ((x1 - x0) / (std::abs(x1) + std::abs(x0) + DBL_EPSILON) > 4.0 * DBL_EPSILON) { + const double xhalf = (x1 + x0) / 2.0; + const double fhalf = invg(xhalf) * Private::lind_interpolateSimple(xmin, xmax, rmin, rmax, xhalf); + if (fval < fhalf) { + x1 = xhalf; + fmax = fhalf; + } else { + x0 = xhalf; + fmin = fhalf; + } } - - template - Numeric LinInterpolatedTableND::operator()( - const double& x0, const double& x1, - const double& x2, const double& x3) const - { - const unsigned nArgs = 4U; - if (dim_ != nArgs) throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): number of " - "arguments, 4, is incompatible with the interpolator dimensionality"); - double tmp[nArgs]; - tmp[0] = x0; - tmp[1] = x1; - tmp[2] = x2; - tmp[3] = x3; - return operator()(tmp, nArgs); + return (x1 + x0) / 2.0; + } + + template + template + void LinInterpolatedTableND::invert1DResponse(const ArrayND& fromSlice, + const Axis& fromAxis, + const Axis& toAxis, + const bool newLeftLinear, + const bool newRightLinear, + Functor1 invg, + const double* rawx, + const double* rawf, + double* workspace, + ArrayND* toSlice) { + assert(toSlice); + assert(fromSlice.rank() == 1U); + assert(toSlice->rank() == 1U); + + const Numeric zero = Numeric(); + const Numeric* fromData = fromSlice.data(); + const unsigned fromLen = fromSlice.length(); + assert(fromLen > 1U); + assert(fromLen == fromAxis.nCoords()); + Numeric* toD = const_cast(toSlice->data()); + const unsigned nAxisPoints = toAxis.nCoords(); + assert(toSlice->length() == nAxisPoints); + + for (unsigned i = 0; i < fromLen; ++i) { + if (fromData[i] <= zero) + throw npstat::NpstatDomainError( + "In LinInterpolatedTableND::invert1DResponse: " + "non-positive response found. This ratio " + "response table is not invertible."); + workspace[i] = rawx[i] * fromData[i]; } - template - Numeric LinInterpolatedTableND::operator()( - const double& x0, const double& x1, const double& x2, - const double& x3, const double& x4) const - { - const unsigned nArgs = 5U; - if (dim_ != nArgs) throw npstat::NpstatInvalidArgument( - "In npstat::LinInterpolatedTableND::operator(): number of " - "arguments, 5, is incompatible with the interpolator dimensionality"); - double tmp[nArgs]; - tmp[0] = x0; - tmp[1] = x1; - tmp[2] = x2; - tmp[3] = x3; - tmp[4] = x4; - return operator()(tmp, nArgs); - } - - template - template - double LinInterpolatedTableND::solveForRatioArg( - const double xmin, const double xmax, - const double rmin, const double rmax, - const double fval, Functor1 invg) - { - // Find two values of x so that f(x0) <= fval <= f(x1) - double x0 = xmin; - double x1 = xmax; - double fmin = invg(xmin)*rmin; - double fmax = invg(xmax)*rmax; - const double step = xmax - xmin; - assert(fmin < fmax); - assert(step > 0.0); - - unsigned stepcount = 0; - const unsigned maxSteps = 1000U; - for (double stepfactor = 1.0; (fval < fmin || fval > fmax) && - stepcount < maxSteps; stepfactor *= 2.0, ++stepcount) - if (fval < fmin) - { - x1 = x0; - fmax = fmin; - x0 -= stepfactor*step; - fmin = invg(x0)*Private::lind_interpolateSimple( - xmin, xmax, rmin, rmax, x0); - } - else - { - x0 = x1; - fmin = fmax; - x1 += stepfactor*step; - fmax = invg(x1)*Private::lind_interpolateSimple( - xmin, xmax, rmin, rmax, x1); - } - if (stepcount == maxSteps) throw npstat::NpstatRuntimeError( - "In LinInterpolatedTableND::solveForRatioArg: " - "faled to bracket the root"); - - assert(x1 >= x0); - while ((x1 - x0)/(std::abs(x1) + std::abs(x0) + DBL_EPSILON) > 4.0*DBL_EPSILON) - { - const double xhalf = (x1 + x0)/2.0; - const double fhalf = invg(xhalf)*Private::lind_interpolateSimple( - xmin, xmax, rmin, rmax, xhalf); - if (fval < fhalf) - { - x1 = xhalf; - fmax = fhalf; - } - else - { - x0 = xhalf; - fmin = fhalf; - } - } - return (x1 + x0)/2.0; + const double yfirst = workspace[0]; + const double ylast = workspace[fromLen - 1U]; + + bool adjustZero = false; + unsigned nBelow = 0; + for (unsigned ipt = 0; ipt < nAxisPoints; ++ipt) { + const double y = rawf[ipt]; + unsigned i0 = 0; + bool solve = false; + if (y == 0.0) { + assert(ipt == 0U); + if (newLeftLinear) + adjustZero = true; + } else if (y <= yfirst) { + ++nBelow; + solve = newLeftLinear; + } else if (y >= ylast) { + solve = newRightLinear; + i0 = solve ? fromLen - 2 : fromLen - 1; + } else { + solve = true; + i0 = static_cast(std::lower_bound(workspace, workspace + fromLen, y) - workspace) - 1U; + } + if (solve) { + const double x = solveForRatioArg( + fromAxis.coordinate(i0), fromAxis.coordinate(i0 + 1), fromData[i0], fromData[i0 + 1], y, invg); + toD[ipt] = invg(x) / y; + } else + toD[ipt] = 1.0 / fromData[i0]; } + if (adjustZero && nBelow) + toD[0] = toD[1]; + } +} // namespace npstat - template - template - void LinInterpolatedTableND::invert1DResponse( - const ArrayND& fromSlice, - const Axis& fromAxis, const Axis& toAxis, - const bool newLeftLinear, const bool newRightLinear, - Functor1 invg, const double* rawx, const double* rawf, - double* workspace, - ArrayND* toSlice) - { - assert(toSlice); - assert(fromSlice.rank() == 1U); - assert(toSlice->rank() == 1U); - - const Numeric zero = Numeric(); - const Numeric* fromData = fromSlice.data(); - const unsigned fromLen = fromSlice.length(); - assert(fromLen > 1U); - assert(fromLen == fromAxis.nCoords()); - Numeric* toD = const_cast(toSlice->data()); - const unsigned nAxisPoints = toAxis.nCoords(); - assert(toSlice->length() == nAxisPoints); - - for (unsigned i=0; i= ylast) - { - solve = newRightLinear; - i0 = solve ? fromLen-2 : fromLen-1; - } - else - { - solve = true; - i0 = static_cast(std::lower_bound( - workspace,workspace+fromLen,y) - workspace) - 1U; - } - if (solve) - { - const double x = solveForRatioArg(fromAxis.coordinate(i0), - fromAxis.coordinate(i0+1), - fromData[i0], fromData[i0+1], - y, invg); - toD[ipt] = invg(x)/y; - } - else - toD[ipt] = 1.0/fromData[i0]; - } - if (adjustZero && nBelow) - toD[0] = toD[1]; - } -} - - -#endif // NPSTAT_LININTERPOLATEDTABLEND_HH_ - +#endif // NPSTAT_LININTERPOLATEDTABLEND_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/LinearMapper1d.h b/JetMETCorrections/InterpolationTables/interface/LinearMapper1d.h index bc77a1653e05f..a0ecf52042cda 100644 --- a/JetMETCorrections/InterpolationTables/interface/LinearMapper1d.h +++ b/JetMETCorrections/InterpolationTables/interface/LinearMapper1d.h @@ -14,62 +14,55 @@ #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" namespace npstat { - /** Functor which performs linear mapping in 1-d */ - class LinearMapper1d - { - public: - /** Default constructor builds an identity transformation */ - inline LinearMapper1d() : a_(1.0), b_(0.0) {} + /** Functor which performs linear mapping in 1-d */ + class LinearMapper1d { + public: + /** Default constructor builds an identity transformation */ + inline LinearMapper1d() : a_(1.0), b_(0.0) {} - /** + /** // Transform definition from two points. The point at x0 // is mapped into y0, the point at x1 is mapped into y1. // The linear transformation is thus fully defined. */ - inline LinearMapper1d(const double x0, const double y0, - const double x1, const double y1) - { - const double dx = x1 - x0; - if (!dx) throw npstat::NpstatInvalidArgument( - "In npstat::LinearMapper1d constructor: " - "invalid arguments (x0 == x1)"); - a_ = (y1 - y0)/dx; - b_ = ((y0 + y1) - a_*(x0 + x1))/2.0; - } + inline LinearMapper1d(const double x0, const double y0, const double x1, const double y1) { + const double dx = x1 - x0; + if (!dx) + throw npstat::NpstatInvalidArgument( + "In npstat::LinearMapper1d constructor: " + "invalid arguments (x0 == x1)"); + a_ = (y1 - y0) / dx; + b_ = ((y0 + y1) - a_ * (x0 + x1)) / 2.0; + } - /** Explicitly provide the transform coefficients as in y = ca*x + cb */ - inline LinearMapper1d(const double ca, const double cb) - : a_(ca), b_(cb) {} + /** Explicitly provide the transform coefficients as in y = ca*x + cb */ + inline LinearMapper1d(const double ca, const double cb) : a_(ca), b_(cb) {} - /** Perform the transformation */ - inline double operator()(const double& x) const {return a_*x + b_;} + /** Perform the transformation */ + inline double operator()(const double& x) const { return a_ * x + b_; } - /** Get the linear coefficient of the transform */ - inline double a() const {return a_;} + /** Get the linear coefficient of the transform */ + inline double a() const { return a_; } - /** Get the transform constant */ - inline double b() const {return b_;} + /** Get the transform constant */ + inline double b() const { return b_; } - /** Create the inverse transform */ - inline LinearMapper1d inverse() const - { - if (!a_) throw npstat::NpstatInvalidArgument( - "In npstat::LinearMapper1d::inverse: " - "mapping is not invertible"); - return LinearMapper1d(1.0/a_, -b_/a_); - } + /** Create the inverse transform */ + inline LinearMapper1d inverse() const { + if (!a_) + throw npstat::NpstatInvalidArgument( + "In npstat::LinearMapper1d::inverse: " + "mapping is not invertible"); + return LinearMapper1d(1.0 / a_, -b_ / a_); + } - /** Sequence of two transforms: the one on the right is applied first */ - inline LinearMapper1d operator*(const LinearMapper1d& r) const - { - return LinearMapper1d(a_*r.a_, a_*r.b_ + b_); - } + /** Sequence of two transforms: the one on the right is applied first */ + inline LinearMapper1d operator*(const LinearMapper1d& r) const { return LinearMapper1d(a_ * r.a_, a_ * r.b_ + b_); } - private: - double a_; - double b_; - }; -} - -#endif // NPSTAT_LINEARMAPPER1D_HH_ + private: + double a_; + double b_; + }; +} // namespace npstat +#endif // NPSTAT_LINEARMAPPER1D_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h b/JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h index 053766156ae57..d3f00dc03bc0d 100644 --- a/JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h @@ -18,126 +18,115 @@ #include "JetMETCorrections/InterpolationTables/interface/Interval.h" namespace npstat { - template class HistoND; - class DualHistoAxis; + template + class HistoND; + class DualHistoAxis; - /** + /** // This class can be used to create histograms with non-uniform binning */ - class NUHistoAxis - { - public: - /** + class NUHistoAxis { + public: + /** // The number of bin edges provided must be at least 2. Edge // coordinates will be sorted internally in the increasing order. // The number of bins will be less by 1 than the number of edges. */ - NUHistoAxis(const std::vector& binEdges, const char* label = nullptr); - - //@{ - /** Examine axis properties */ - inline double min() const {return min_;} - inline double max() const {return max_;} - inline Interval interval() const - {return Interval(min_, max_);} - inline double length() const {return max_ - min_;} - inline unsigned nBins() const {return nBins_;} - inline double binWidth(const int binNum) const - {return binEdges_.at(binNum+1) - binEdges_.at(binNum);} - inline const std::string& label() const {return label_;} - inline bool isUniform() const {return uniform_;} - //@} - - /** Return the coordinate of the given bin left edge */ - inline double leftBinEdge(const int binNum) const - {return binEdges_.at(binNum);} - - /** Return the coordinate of the given bin right edge */ - inline double rightBinEdge(const int binNum) const - {return binEdges_.at(binNum + 1);} - - /** Return the coordinate of the given bin center */ - inline double binCenter(const int binNum) const - {return 0.5*(binEdges_.at(binNum) + binEdges_.at(binNum + 1));} - - /** Return the coordinate interval occupied by the given bin */ - inline Interval binInterval(const int binNum) const - {return Interval(binEdges_.at(binNum), - binEdges_.at(binNum + 1));} - - /** Change the axis label */ - inline void setLabel(const char* newlabel) - {label_ = newlabel ? newlabel : "";} - - /** + NUHistoAxis(const std::vector& binEdges, const char* label = nullptr); + + //@{ + /** Examine axis properties */ + inline double min() const { return min_; } + inline double max() const { return max_; } + inline Interval interval() const { return Interval(min_, max_); } + inline double length() const { return max_ - min_; } + inline unsigned nBins() const { return nBins_; } + inline double binWidth(const int binNum) const { return binEdges_.at(binNum + 1) - binEdges_.at(binNum); } + inline const std::string& label() const { return label_; } + inline bool isUniform() const { return uniform_; } + //@} + + /** Return the coordinate of the given bin left edge */ + inline double leftBinEdge(const int binNum) const { return binEdges_.at(binNum); } + + /** Return the coordinate of the given bin right edge */ + inline double rightBinEdge(const int binNum) const { return binEdges_.at(binNum + 1); } + + /** Return the coordinate of the given bin center */ + inline double binCenter(const int binNum) const { return 0.5 * (binEdges_.at(binNum) + binEdges_.at(binNum + 1)); } + + /** Return the coordinate interval occupied by the given bin */ + inline Interval binInterval(const int binNum) const { + return Interval(binEdges_.at(binNum), binEdges_.at(binNum + 1)); + } + + /** Change the axis label */ + inline void setLabel(const char* newlabel) { label_ = newlabel ? newlabel : ""; } + + /** // This method returns -1 for values below the lower limit and // "nBins()" for values equal to or above the upper limit */ - int binNumber(double x) const; + int binNumber(double x) const; - /** + /** // Floating point bin number given the coordinate. Useful for // interpolation methods and such. */ - double fltBinNumber(double x, bool mapLeftEdgeTo0=true) const; + double fltBinNumber(double x, bool mapLeftEdgeTo0 = true) const; - /** + /** // This method returns the closest valid bin number // (above 0 and below nBins() ) */ - unsigned closestValidBin(double x) const; - - bool operator==(const NUHistoAxis&) const; - bool operator!=(const NUHistoAxis&) const; - - /** Comparison of axis coordinates within given tolerance */ - bool isClose(const NUHistoAxis&, double tol) const; - - /** Return uniformly rebinned axis */ - NUHistoAxis rebin(unsigned newBins) const; - - //@{ - /** Method related to "geners" I/O */ - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - //@} - - static inline const char* classname() {return "npstat::NUHistoAxis";} - static inline unsigned version() {return 1;} - static NUHistoAxis* read(const gs::ClassId& id, std::istream& in); - - private: - NUHistoAxis(unsigned nBins, double min, double max, - const char* label = nullptr); - - double min_; - double max_; - std::vector binEdges_; - std::string label_; - unsigned nBins_; - bool uniform_; - - template friend class HistoND; - friend class DualHistoAxis; - - inline unsigned overflowIndex( - const double x, unsigned* binNum) const - { - if (x < min_) - return 0U; - else if (x >= max_) - return 2U; - else - { - *binNum = binNumber(x); - return 1U; - } - } - - inline NUHistoAxis() : min_(0.0), max_(0.0), - nBins_(0), uniform_(false) {} - }; -} - -#endif // NPSTAT_NUHISTOAXIS_HH_ - + unsigned closestValidBin(double x) const; + + bool operator==(const NUHistoAxis&) const; + bool operator!=(const NUHistoAxis&) const; + + /** Comparison of axis coordinates within given tolerance */ + bool isClose(const NUHistoAxis&, double tol) const; + + /** Return uniformly rebinned axis */ + NUHistoAxis rebin(unsigned newBins) const; + + //@{ + /** Method related to "geners" I/O */ + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + //@} + + static inline const char* classname() { return "npstat::NUHistoAxis"; } + static inline unsigned version() { return 1; } + static NUHistoAxis* read(const gs::ClassId& id, std::istream& in); + + private: + NUHistoAxis(unsigned nBins, double min, double max, const char* label = nullptr); + + double min_; + double max_; + std::vector binEdges_; + std::string label_; + unsigned nBins_; + bool uniform_; + + template + friend class HistoND; + friend class DualHistoAxis; + + inline unsigned overflowIndex(const double x, unsigned* binNum) const { + if (x < min_) + return 0U; + else if (x >= max_) + return 2U; + else { + *binNum = binNumber(x); + return 1U; + } + } + + inline NUHistoAxis() : min_(0.0), max_(0.0), nBins_(0), uniform_(false) {} + }; +} // namespace npstat + +#endif // NPSTAT_NUHISTOAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/NpstatException.h b/JetMETCorrections/InterpolationTables/interface/NpstatException.h index 7d68bfb26f532..7c96e4a853d84 100644 --- a/JetMETCorrections/InterpolationTables/interface/NpstatException.h +++ b/JetMETCorrections/InterpolationTables/interface/NpstatException.h @@ -16,59 +16,48 @@ #include "FWCore/Utilities/interface/Exception.h" namespace npstat { - /** Base class for the exceptions specific to the npstat namespace */ - struct NpstatException : public cms::Exception - { - inline NpstatException() : cms::Exception("npstat::NpstatException") {} + /** Base class for the exceptions specific to the npstat namespace */ + struct NpstatException : public cms::Exception { + inline NpstatException() : cms::Exception("npstat::NpstatException") {} - inline explicit NpstatException(const std::string& description) - : cms::Exception(description) {} + inline explicit NpstatException(const std::string& description) : cms::Exception(description) {} - inline explicit NpstatException(const char* description) - : cms::Exception(description) {} + inline explicit NpstatException(const char* description) : cms::Exception(description) {} - ~NpstatException() throw() override {} - }; + ~NpstatException() throw() override {} + }; - struct NpstatOutOfRange : public NpstatException - { - inline NpstatOutOfRange() : NpstatException("npstat::NpstatOutOfRange") {} + struct NpstatOutOfRange : public NpstatException { + inline NpstatOutOfRange() : NpstatException("npstat::NpstatOutOfRange") {} - inline explicit NpstatOutOfRange(const std::string& description) - : NpstatException(description) {} + inline explicit NpstatOutOfRange(const std::string& description) : NpstatException(description) {} - ~NpstatOutOfRange() throw() override {} - }; + ~NpstatOutOfRange() throw() override {} + }; - struct NpstatInvalidArgument : public NpstatException - { - inline NpstatInvalidArgument() : NpstatException("npstat::NpstatInvalidArgument") {} + struct NpstatInvalidArgument : public NpstatException { + inline NpstatInvalidArgument() : NpstatException("npstat::NpstatInvalidArgument") {} - inline explicit NpstatInvalidArgument(const std::string& description) - : NpstatException(description) {} + inline explicit NpstatInvalidArgument(const std::string& description) : NpstatException(description) {} - ~NpstatInvalidArgument() throw() override {} - }; + ~NpstatInvalidArgument() throw() override {} + }; - struct NpstatRuntimeError : public NpstatException - { - inline NpstatRuntimeError() : NpstatException("npstat::NpstatRuntimeError") {} + struct NpstatRuntimeError : public NpstatException { + inline NpstatRuntimeError() : NpstatException("npstat::NpstatRuntimeError") {} - inline explicit NpstatRuntimeError(const std::string& description) - : NpstatException(description) {} + inline explicit NpstatRuntimeError(const std::string& description) : NpstatException(description) {} - ~NpstatRuntimeError() throw() override {} - }; + ~NpstatRuntimeError() throw() override {} + }; - struct NpstatDomainError : public NpstatException - { - inline NpstatDomainError() : NpstatException("npstat::NpstatDomainError") {} + struct NpstatDomainError : public NpstatException { + inline NpstatDomainError() : NpstatException("npstat::NpstatDomainError") {} - inline explicit NpstatDomainError(const std::string& description) - : NpstatException(description) {} + inline explicit NpstatDomainError(const std::string& description) : NpstatException(description) {} - ~NpstatDomainError() throw() override {} - }; -} + ~NpstatDomainError() throw() override {} + }; +} // namespace npstat -#endif // NPSTAT_EXCEPTION_HH_ +#endif // NPSTAT_EXCEPTION_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/PreciseType.h b/JetMETCorrections/InterpolationTables/interface/PreciseType.h index 760d44f3ab749..96ad27d36a0fc 100644 --- a/JetMETCorrections/InterpolationTables/interface/PreciseType.h +++ b/JetMETCorrections/InterpolationTables/interface/PreciseType.h @@ -16,53 +16,45 @@ #include "Alignment/Geners/interface/IOIsNumber.hh" namespace npstat { - template - struct PreciseTypeHelper - { - typedef T type; - }; + template + struct PreciseTypeHelper { + typedef T type; + }; - template - struct PreciseTypeHelper - { - typedef long double type; - }; + template + struct PreciseTypeHelper { + typedef long double type; + }; - /** + /** // Use "long double" as the most precise type among various simple // numeric types, std::complex for complex types, and // the type itself for other types. */ - template - struct PreciseType - { - typedef typename PreciseTypeHelper::value>::type type; - }; - - template - struct PreciseType > - { - typedef std::complex type; - }; - - template - struct PreciseType > - { - typedef std::complex type; - }; - - template - struct PreciseType > - { - typedef std::complex type; - }; - - template - struct PreciseType > - { - typedef std::complex type; - }; -} - -#endif // NPSTAT_PRECISETYPE_HH_ - + template + struct PreciseType { + typedef typename PreciseTypeHelper::value>::type type; + }; + + template + struct PreciseType > { + typedef std::complex type; + }; + + template + struct PreciseType > { + typedef std::complex type; + }; + + template + struct PreciseType > { + typedef std::complex type; + }; + + template + struct PreciseType > { + typedef std::complex type; + }; +} // namespace npstat + +#endif // NPSTAT_PRECISETYPE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h b/JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h index 52fc1f6af7c55..93b4e060483b3 100644 --- a/JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h +++ b/JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h @@ -15,36 +15,30 @@ #include namespace npstat { - template - struct ProperDblFromCmpl - { - typedef double type; - }; - - template - struct ProperDblFromCmpl > - { - typedef T type; - }; - - template - struct ProperDblFromCmpl > - { - typedef T type; - }; - - template - struct ProperDblFromCmpl > - { - typedef T type; - }; - - template - struct ProperDblFromCmpl > - { - typedef T type; - }; -} - -#endif // NPSTAT_PROPERDBLFROMCMPL_HH_ - + template + struct ProperDblFromCmpl { + typedef double type; + }; + + template + struct ProperDblFromCmpl > { + typedef T type; + }; + + template + struct ProperDblFromCmpl > { + typedef T type; + }; + + template + struct ProperDblFromCmpl > { + typedef T type; + }; + + template + struct ProperDblFromCmpl > { + typedef T type; + }; +} // namespace npstat + +#endif // NPSTAT_PROPERDBLFROMCMPL_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/SimpleFunctors.h b/JetMETCorrections/InterpolationTables/interface/SimpleFunctors.h index e36070f59adc3..ec210431f256d 100644 --- a/JetMETCorrections/InterpolationTables/interface/SimpleFunctors.h +++ b/JetMETCorrections/InterpolationTables/interface/SimpleFunctors.h @@ -13,437 +13,368 @@ */ namespace npstat { - /** Base class for a functor that takes no arguments */ - template - struct Functor0 - { - typedef Result result_type; - - inline virtual ~Functor0() {} - virtual Result operator()() const = 0; - }; - - /** Base class for a functor that takes a single argument */ - template - struct Functor1 - { - typedef Result result_type; - typedef Arg1 first_argument_type; - - inline virtual ~Functor1() {} - virtual Result operator()(const Arg1&) const = 0; - }; - - /** Base class for a functor that takes two arguments */ - template - struct Functor2 - { - typedef Result result_type; - typedef Arg1 first_argument_type; - typedef Arg2 second_argument_type; - - inline virtual ~Functor2() {} - virtual Result operator()(const Arg1&, const Arg2&) const = 0; - }; - - /** Base class for a functor that takes three arguments */ - template - struct Functor3 - { - typedef Result result_type; - typedef Arg1 first_argument_type; - typedef Arg2 second_argument_type; - typedef Arg3 third_argument_type; - - inline virtual ~Functor3() {} - virtual Result operator()(const Arg1&,const Arg2&,const Arg3&) const=0; - }; - - /** A simple functor which returns a copy of its argument */ - template - struct Same : public Functor1 - { - inline Result operator()(const Result& a) const override {return a;} - }; - - /** A simple functor which returns a reference to its argument */ - template - struct SameRef : public Functor1 - { - inline const Result& operator()(const Result& a) const {return a;} - }; - - /** + /** Base class for a functor that takes no arguments */ + template + struct Functor0 { + typedef Result result_type; + + inline virtual ~Functor0() {} + virtual Result operator()() const = 0; + }; + + /** Base class for a functor that takes a single argument */ + template + struct Functor1 { + typedef Result result_type; + typedef Arg1 first_argument_type; + + inline virtual ~Functor1() {} + virtual Result operator()(const Arg1&) const = 0; + }; + + /** Base class for a functor that takes two arguments */ + template + struct Functor2 { + typedef Result result_type; + typedef Arg1 first_argument_type; + typedef Arg2 second_argument_type; + + inline virtual ~Functor2() {} + virtual Result operator()(const Arg1&, const Arg2&) const = 0; + }; + + /** Base class for a functor that takes three arguments */ + template + struct Functor3 { + typedef Result result_type; + typedef Arg1 first_argument_type; + typedef Arg2 second_argument_type; + typedef Arg3 third_argument_type; + + inline virtual ~Functor3() {} + virtual Result operator()(const Arg1&, const Arg2&, const Arg3&) const = 0; + }; + + /** A simple functor which returns a copy of its argument */ + template + struct Same : public Functor1 { + inline Result operator()(const Result& a) const override { return a; } + }; + + /** A simple functor which returns a reference to its argument */ + template + struct SameRef : public Functor1 { + inline const Result& operator()(const Result& a) const { return a; } + }; + + /** // Simple functor which ignores is arguments and instead // builds the result using the default constructor of the result type */ - template - struct DefaultConstructor0 : public Functor0 - { - inline Result operator()() const {return Result();} - }; + template + struct DefaultConstructor0 : public Functor0 { + inline Result operator()() const { return Result(); } + }; - /** + /** // Simple functor which ignores is arguments and instead // builds the result using the default constructor of the result type */ - template - struct DefaultConstructor1 : public Functor1 - { - inline Result operator()(const Arg1&) const {return Result();} - }; + template + struct DefaultConstructor1 : public Functor1 { + inline Result operator()(const Arg1&) const { return Result(); } + }; - /** + /** // Simple functor which ignores is arguments and instead // builds the result using the default constructor of the result type */ - template - struct DefaultConstructor2 : public Functor2 - { - inline Result operator()(const Arg1&, const Arg2&) const - {return Result();} - }; - - /** + template + struct DefaultConstructor2 : public Functor2 { + inline Result operator()(const Arg1&, const Arg2&) const { return Result(); } + }; + + /** // Simple functor which ignores is arguments and instead // builds the result using the default constructor of the result type */ - template - struct DefaultConstructor3 : public Functor3 - { - inline Result operator()(const Arg1&, const Arg2&, const Arg3&) const - {return Result();} - }; - - /** + template + struct DefaultConstructor3 : public Functor3 { + inline Result operator()(const Arg1&, const Arg2&, const Arg3&) const { return Result(); } + }; + + /** // Sometimes it becomes necessary to perform an explicit cast for proper // overload resolution of a converting copy constructor */ - template - struct CastingCopyConstructor : public Functor1 - { - inline Result operator()(const Arg1& a) const - {return Result(static_cast(a));} - }; - - /** + template + struct CastingCopyConstructor : public Functor1 { + inline Result operator()(const Arg1& a) const { return Result(static_cast(a)); } + }; + + /** // Adaptation for using functors without arguments with simple // cmath-style functions. Do not use this struct as a base class. */ - template - struct FcnFunctor0 : public Functor0 - { - inline explicit FcnFunctor0(Result (*fcn)()) : fcn_(fcn) {} + template + struct FcnFunctor0 : public Functor0 { + inline explicit FcnFunctor0(Result (*fcn)()) : fcn_(fcn) {} - inline Result operator()() const {return fcn_();} + inline Result operator()() const { return fcn_(); } - private: - FcnFunctor0() = delete; - Result (*fcn_)(); - }; + private: + FcnFunctor0() = delete; + Result (*fcn_)(); + }; - /** + /** // Adaptation for using single-argument functors with simple // cmath-style functions. Do not use this struct as a base class. */ - template - struct FcnFunctor1 : public Functor1 - { - inline explicit FcnFunctor1(Result (*fcn)(Arg1)) : fcn_(fcn) {} + template + struct FcnFunctor1 : public Functor1 { + inline explicit FcnFunctor1(Result (*fcn)(Arg1)) : fcn_(fcn) {} - inline Result operator()(const Arg1& a) const {return fcn_(a);} + inline Result operator()(const Arg1& a) const { return fcn_(a); } - private: - FcnFunctor1() = delete; - Result (*fcn_)(Arg1); - }; + private: + FcnFunctor1() = delete; + Result (*fcn_)(Arg1); + }; - /** + /** // Adaptation for using two-argument functors with simple // cmath-style functions. Do not use this struct as a base class. */ - template - struct FcnFunctor2 : public Functor2 - { - inline explicit FcnFunctor2(Result (*fcn)(Arg1, Arg2)) : fcn_(fcn) {} + template + struct FcnFunctor2 : public Functor2 { + inline explicit FcnFunctor2(Result (*fcn)(Arg1, Arg2)) : fcn_(fcn) {} - inline Result operator()(const Arg1& x, const Arg2& y) const - {return fcn_(x, y);} + inline Result operator()(const Arg1& x, const Arg2& y) const { return fcn_(x, y); } - private: - FcnFunctor2() = delete; - Result (*fcn_)(Arg1, Arg2); - }; + private: + FcnFunctor2() = delete; + Result (*fcn_)(Arg1, Arg2); + }; - /** + /** // Adaptation for using three-argument functors with simple // cmath-style functions. Do not use this struct as a base class. */ - template - struct FcnFunctor3 : public Functor3 - { - inline explicit FcnFunctor3(Result (*fcn)(Arg1,Arg2,Arg3)):fcn_(fcn) {} + template + struct FcnFunctor3 : public Functor3 { + inline explicit FcnFunctor3(Result (*fcn)(Arg1, Arg2, Arg3)) : fcn_(fcn) {} - inline Result operator()(const Arg1&x,const Arg2&y,const Arg3&z) const - {return fcn_(x, y, z);} + inline Result operator()(const Arg1& x, const Arg2& y, const Arg3& z) const { return fcn_(x, y, z); } - private: - FcnFunctor3() = delete; - Result (*fcn_)(Arg1, Arg2, Arg3); - }; + private: + FcnFunctor3() = delete; + Result (*fcn_)(Arg1, Arg2, Arg3); + }; - /** + /** // Functor which extracts a given element from a random access linear // container without bounds checking */ - template - struct Element1D : public Functor1 - { - inline explicit Element1D(const unsigned long index) : idx(index) {} + template + struct Element1D : public Functor1 { + inline explicit Element1D(const unsigned long index) : idx(index) {} - inline Result operator()(const Container& c) const {return c[idx];} + inline Result operator()(const Container& c) const { return c[idx]; } - private: - Element1D() = delete; - unsigned long idx; - }; + private: + Element1D() = delete; + unsigned long idx; + }; - /** + /** // Functor which extracts a given element from a random access linear // container with bounds checking */ - template - struct Element1DAt : public Functor1 - { - inline explicit Element1DAt(const unsigned long index) : idx(index) {} + template + struct Element1DAt : public Functor1 { + inline explicit Element1DAt(const unsigned long index) : idx(index) {} - inline Result operator()(const Container& c) const {return c.at(idx);} + inline Result operator()(const Container& c) const { return c.at(idx); } - private: - Element1DAt() = delete; - unsigned long idx; - }; + private: + Element1DAt() = delete; + unsigned long idx; + }; - /** + /** // Left assignment functor. Works just like normal binary // assignment operator in places where functor is needed. */ - template - struct assign_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left = right;} - }; - - /** + template + struct assign_left { + inline T1& operator()(T1& left, const T2& right) const { return left = right; } + }; + + /** // Right assignment functor. Reverses the assignment direction // in comparison with the normal binary assignment operator. */ - template - struct assign_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right = left;} - }; - - /** In-place addition on the left side */ - template - struct pluseq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left += right;} - }; - - /** In-place addition on the right side */ - template - struct pluseq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right += left;} - }; - - /** + template + struct assign_right { + inline T2& operator()(const T1& left, T2& right) const { return right = left; } + }; + + /** In-place addition on the left side */ + template + struct pluseq_left { + inline T1& operator()(T1& left, const T2& right) const { return left += right; } + }; + + /** In-place addition on the right side */ + template + struct pluseq_right { + inline T2& operator()(const T1& left, T2& right) const { return right += left; } + }; + + /** // In-place addition on the left side preceded by // multiplication of the right argument by a double */ - template - struct addmul_left - { - inline explicit addmul_left(const double weight) : w_(weight) {} + template + struct addmul_left { + inline explicit addmul_left(const double weight) : w_(weight) {} - inline T1& operator()(T1& left, const T2& right) const - {return left += w_*right;} + inline T1& operator()(T1& left, const T2& right) const { return left += w_ * right; } - private: - addmul_left() = delete; - double w_; - }; + private: + addmul_left() = delete; + double w_; + }; - /** + /** // In-place addition on the right side preceded by // multiplication of the left argument by a double */ - template - struct addmul_right - { - inline explicit addmul_right(const double weight) : w_(weight) {} - - inline T1& operator()(T1& left, const T2& right) const - {return right += w_*left;} - - private: - addmul_right() = delete; - double w_; - }; - - /** In-place subtraction on the left side */ - template - struct minuseq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left -= right;} - }; - - /** In-place subtraction on the right side */ - template - struct minuseq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right -= left;} - }; - - /** In-place multiplication on the left side */ - template - struct multeq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left *= right;} - }; - - /** In-place multiplication on the right side */ - template - struct multeq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right *= left;} - }; - - /** In-place division on the left side withot checking for division by 0 */ - template - struct diveq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left /= right;} - }; - - /** In-place division on the right side withot checking for division by 0 */ - template - struct diveq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right /= left;} - }; - - /** In-place division on the left side. Allow 0/0 = const. */ - template - struct diveq_left_0by0isC - { - inline diveq_left_0by0isC() : - C(T1()), leftZero(T1()), rightZero(T2()) {} - inline explicit diveq_left_0by0isC(const T1& value) : - C(value), leftZero(T1()), rightZero(T2()) {} - - inline T1& operator()(T1& left, const T2& right) const - { - if (right == rightZero) - if (left == leftZero) - { - left = C; - return left; - } - return left /= right; + template + struct addmul_right { + inline explicit addmul_right(const double weight) : w_(weight) {} + + inline T1& operator()(T1& left, const T2& right) const { return right += w_ * left; } + + private: + addmul_right() = delete; + double w_; + }; + + /** In-place subtraction on the left side */ + template + struct minuseq_left { + inline T1& operator()(T1& left, const T2& right) const { return left -= right; } + }; + + /** In-place subtraction on the right side */ + template + struct minuseq_right { + inline T2& operator()(const T1& left, T2& right) const { return right -= left; } + }; + + /** In-place multiplication on the left side */ + template + struct multeq_left { + inline T1& operator()(T1& left, const T2& right) const { return left *= right; } + }; + + /** In-place multiplication on the right side */ + template + struct multeq_right { + inline T2& operator()(const T1& left, T2& right) const { return right *= left; } + }; + + /** In-place division on the left side withot checking for division by 0 */ + template + struct diveq_left { + inline T1& operator()(T1& left, const T2& right) const { return left /= right; } + }; + + /** In-place division on the right side withot checking for division by 0 */ + template + struct diveq_right { + inline T2& operator()(const T1& left, T2& right) const { return right /= left; } + }; + + /** In-place division on the left side. Allow 0/0 = const. */ + template + struct diveq_left_0by0isC { + inline diveq_left_0by0isC() : C(T1()), leftZero(T1()), rightZero(T2()) {} + inline explicit diveq_left_0by0isC(const T1& value) : C(value), leftZero(T1()), rightZero(T2()) {} + + inline T1& operator()(T1& left, const T2& right) const { + if (right == rightZero) + if (left == leftZero) { + left = C; + return left; } - - private: - T1 C; - T1 leftZero; - T2 rightZero; - }; - - /** In-place division on the right side. Allow 0/0 = const. */ - template - struct diveq_right_0by0isC - { - inline diveq_right_0by0isC() : - C(T2()), leftZero(T1()), rightZero(T2()) {} - inline explicit diveq_right_0by0isC(const T2& value) : - C(value), leftZero(T1()), rightZero(T2()) {} - - inline T2& operator()(const T1& left, T2& right) const - { - if (left == leftZero) - if (right == rightZero) - { - right = C; - return right; - } - return right /= left; + return left /= right; + } + + private: + T1 C; + T1 leftZero; + T2 rightZero; + }; + + /** In-place division on the right side. Allow 0/0 = const. */ + template + struct diveq_right_0by0isC { + inline diveq_right_0by0isC() : C(T2()), leftZero(T1()), rightZero(T2()) {} + inline explicit diveq_right_0by0isC(const T2& value) : C(value), leftZero(T1()), rightZero(T2()) {} + + inline T2& operator()(const T1& left, T2& right) const { + if (left == leftZero) + if (right == rightZero) { + right = C; + return right; } - - private: - T2 C; - T1 leftZero; - T2 rightZero; - }; - - /** Left assignment functor preceded by a static cast */ - template - struct scast_assign_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left = static_cast(right);} - }; - - /** Right assignment functor preceded by a static cast */ - template - struct scast_assign_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right = static_cast(left);} - }; - - /** In-place addition on the left side preceded by a static cast */ - template - struct scast_pluseq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left += static_cast(right);} - }; - - /** In-place addition on the right side preceded by a static cast */ - template - struct scast_pluseq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right += static_cast(left);} - }; - - /** In-place subtraction on the left side preceded by a static cast */ - template - struct scast_minuseq_left - { - inline T1& operator()(T1& left, const T2& right) const - {return left -= static_cast(right);} - }; - - /** In-place subtraction on the right side preceded by a static cast */ - template - struct scast_minuseq_right - { - inline T2& operator()(const T1& left, T2& right) const - {return right -= static_cast(left);} - }; -} - -#endif // NPSTAT_SIMPLEFUNCTORS_HH_ - + return right /= left; + } + + private: + T2 C; + T1 leftZero; + T2 rightZero; + }; + + /** Left assignment functor preceded by a static cast */ + template + struct scast_assign_left { + inline T1& operator()(T1& left, const T2& right) const { return left = static_cast(right); } + }; + + /** Right assignment functor preceded by a static cast */ + template + struct scast_assign_right { + inline T2& operator()(const T1& left, T2& right) const { return right = static_cast(left); } + }; + + /** In-place addition on the left side preceded by a static cast */ + template + struct scast_pluseq_left { + inline T1& operator()(T1& left, const T2& right) const { return left += static_cast(right); } + }; + + /** In-place addition on the right side preceded by a static cast */ + template + struct scast_pluseq_right { + inline T2& operator()(const T1& left, T2& right) const { return right += static_cast(left); } + }; + + /** In-place subtraction on the left side preceded by a static cast */ + template + struct scast_minuseq_left { + inline T1& operator()(T1& left, const T2& right) const { return left -= static_cast(right); } + }; + + /** In-place subtraction on the right side preceded by a static cast */ + template + struct scast_minuseq_right { + inline T2& operator()(const T1& left, T2& right) const { return right -= static_cast(left); } + }; +} // namespace npstat + +#endif // NPSTAT_SIMPLEFUNCTORS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/StorableHistoNDFunctor.h b/JetMETCorrections/InterpolationTables/interface/StorableHistoNDFunctor.h index fc3bce227ed70..0caa91db932ec 100644 --- a/JetMETCorrections/InterpolationTables/interface/StorableHistoNDFunctor.h +++ b/JetMETCorrections/InterpolationTables/interface/StorableHistoNDFunctor.h @@ -18,191 +18,163 @@ #include "JetMETCorrections/InterpolationTables/interface/HistoND.h" namespace npstat { - /** + /** // This class adapts HistoND template together with various histogram // interpolation functions to the StorableMultivariateFunctor interface */ - template - < - class Numeric, - class Axis = HistoAxis, - class Converter = Same - > - class StorableHistoNDFunctor : public StorableMultivariateFunctor - { - template - friend class StorableHistoNDFunctor; - - public: - typedef HistoND Table; - - //@{ - /** + template > + class StorableHistoNDFunctor : public StorableMultivariateFunctor { + template + friend class StorableHistoNDFunctor; + + public: + typedef HistoND Table; + + //@{ + /** // Constructor from a pre-existing histogram. The "degree" // argument specifies the interpolation degree which can be // 0, 1, or 3. */ - template - inline StorableHistoNDFunctor( - const HistoND& table, const unsigned degree=1) - : StorableMultivariateFunctor(), table_(table), deg_(degree) - {validateInterDegree(degree, table.isUniformlyBinned());} - - template - inline StorableHistoNDFunctor( - const HistoND& table, - const unsigned degree, - const std::string& descr) - : StorableMultivariateFunctor(descr), table_(table), deg_(degree) - {validateInterDegree(degree, table.isUniformlyBinned());} - //@} - - /** Converting copy constructor */ - template - inline StorableHistoNDFunctor( - const StorableHistoNDFunctor& tab) - : StorableMultivariateFunctor(tab.description()), - table_(tab.table_, Same(), tab.title().c_str(), - tab.accumulatedDataLabel().c_str()), deg_(tab.deg_) {} - - ~StorableHistoNDFunctor() override {} - - unsigned minDim() const override {return table_.dim();}; - - double operator()(const double* point, unsigned dim) const override; - - /** Retrieve interpolation degree */ - inline unsigned interpolationDegree() const {return deg_;} - - /** Set interpolation degree (0, 1, or 3) */ - void setInterpolationDegree(const unsigned deg); - - //@{ - /** Retrieve the underlying HistoND object */ - inline Table& interpolator() {return table_;} - inline const Table& interpolator() const {return table_;} - //@} - - //@{ - /** Retrieve the tabulated data */ - inline ArrayND& table() - {return const_cast&>(table_.binContents());} - - inline const ArrayND& table() const - {return table_.binContents();} - //@} - - /** Change the coordinate converter */ - inline void setConverter(const Converter& conv) {conv_ = conv;} - - //@{ - // Method related to "geners" I/O - gs::ClassId classId() const override {return gs::ClassId(*this);} - bool write(std::ostream& of) const override; - //@} - - // I/O methods needed for reading - static inline const char* classname(); - static inline unsigned version() {return 1;} - static StorableHistoNDFunctor* read( - const gs::ClassId& id, std::istream& in); - - protected: - bool isEqual(const StorableMultivariateFunctor& other) const override - { - // Note the use of static_cast rather than dynamic_cast below. - // static_cast works faster and it is guaranteed to succeed here. - const StorableHistoNDFunctor& r = - static_cast(other); - return table_ == r.table_ && deg_ == r.deg_ && - this->description() == other.description(); - } - - private: - StorableHistoNDFunctor() = delete; - - Table table_; - unsigned deg_; - Converter conv_; - - static void validateInterDegree(unsigned deg, bool isUniform); - }; -} + template + inline StorableHistoNDFunctor(const HistoND& table, const unsigned degree = 1) + : StorableMultivariateFunctor(), table_(table), deg_(degree) { + validateInterDegree(degree, table.isUniformlyBinned()); + } -#include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" + template + inline StorableHistoNDFunctor(const HistoND& table, const unsigned degree, const std::string& descr) + : StorableMultivariateFunctor(descr), table_(table), deg_(degree) { + validateInterDegree(degree, table.isUniformlyBinned()); + } + //@} -#include "Alignment/Geners/interface/binaryIO.hh" -#include "Alignment/Geners/interface/CPP11_auto_ptr.hh" -#include "Alignment/Geners/interface/IOException.hh" + /** Converting copy constructor */ + template + inline StorableHistoNDFunctor(const StorableHistoNDFunctor& tab) + : StorableMultivariateFunctor(tab.description()), + table_(tab.table_, Same(), tab.title().c_str(), tab.accumulatedDataLabel().c_str()), + deg_(tab.deg_) {} -#include "JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h" + ~StorableHistoNDFunctor() override {} -namespace npstat { - template - double StorableHistoNDFunctor::operator()( - const double* point, const unsigned dim) const - { - return conv_(interpolateHistoND(table_, point, dim, deg_)); - } + unsigned minDim() const override { return table_.dim(); }; - template - const char* StorableHistoNDFunctor::classname() - { - static const std::string myClass(gs::template_class_name( - "npstat::StorableHistoNDFunctor")); - return myClass.c_str(); - } + double operator()(const double* point, unsigned dim) const override; - template - bool StorableHistoNDFunctor::write(std::ostream& of) const - { - gs::write_pod(of, this->description()); - gs::write_pod(of, deg_); - return table_.classId().write(of) && table_.write(of); - } + /** Retrieve interpolation degree */ + inline unsigned interpolationDegree() const { return deg_; } - template - StorableHistoNDFunctor* - StorableHistoNDFunctor::read( - const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current( - gs::ClassId::makeId >()); - current.ensureSameId(id); - - std::string descr; - gs::read_pod(in, &descr); - unsigned deg; - gs::read_pod(in, °); - gs::ClassId tabid(in, 1); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::StorableHistoNDFunctor::read: " - "input stream failure"); - CPP11_auto_ptr tab(Table::read(tabid, in)); - return new StorableHistoNDFunctor(*tab, deg, descr); - } + /** Set interpolation degree (0, 1, or 3) */ + void setInterpolationDegree(const unsigned deg); - template - inline void StorableHistoNDFunctor::setInterpolationDegree( - const unsigned deg) - { - validateInterDegree(deg, table_.isUniformlyBinned()); - deg_ = deg; - } + //@{ + /** Retrieve the underlying HistoND object */ + inline Table& interpolator() { return table_; } + inline const Table& interpolator() const { return table_; } + //@} + + //@{ + /** Retrieve the tabulated data */ + inline ArrayND& table() { return const_cast&>(table_.binContents()); } + + inline const ArrayND& table() const { return table_.binContents(); } + //@} + + /** Change the coordinate converter */ + inline void setConverter(const Converter& conv) { conv_ = conv; } - template - inline void StorableHistoNDFunctor::validateInterDegree( - const unsigned deg, const bool isUniform) - { - const bool ok = isUniform ? (deg == 0 || deg == 1 || deg == 3) : - (deg == 0 || deg == 1); - if (!ok) - throw npstat::NpstatInvalidArgument( - "In npstat::StorableHistoNDFunctor::validateInterDegree: " - "unsupported interpolation degree"); + //@{ + // Method related to "geners" I/O + gs::ClassId classId() const override { return gs::ClassId(*this); } + bool write(std::ostream& of) const override; + //@} + + // I/O methods needed for reading + static inline const char* classname(); + static inline unsigned version() { return 1; } + static StorableHistoNDFunctor* read(const gs::ClassId& id, std::istream& in); + + protected: + bool isEqual(const StorableMultivariateFunctor& other) const override { + // Note the use of static_cast rather than dynamic_cast below. + // static_cast works faster and it is guaranteed to succeed here. + const StorableHistoNDFunctor& r = static_cast(other); + return table_ == r.table_ && deg_ == r.deg_ && this->description() == other.description(); } -} + private: + StorableHistoNDFunctor() = delete; + + Table table_; + unsigned deg_; + Converter conv_; + + static void validateInterDegree(unsigned deg, bool isUniform); + }; +} // namespace npstat -#endif // NPSTAT_STORABLEHISTONDFUNCTOR_HH_ +#include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" + +#include "Alignment/Geners/interface/binaryIO.hh" +#include "Alignment/Geners/interface/CPP11_auto_ptr.hh" +#include "Alignment/Geners/interface/IOException.hh" + +#include "JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h" +namespace npstat { + template + double StorableHistoNDFunctor::operator()(const double* point, const unsigned dim) const { + return conv_(interpolateHistoND(table_, point, dim, deg_)); + } + + template + const char* StorableHistoNDFunctor::classname() { + static const std::string myClass(gs::template_class_name("npstat::StorableHistoNDFunctor")); + return myClass.c_str(); + } + + template + bool StorableHistoNDFunctor::write(std::ostream& of) const { + gs::write_pod(of, this->description()); + gs::write_pod(of, deg_); + return table_.classId().write(of) && table_.write(of); + } + + template + StorableHistoNDFunctor* StorableHistoNDFunctor::read( + const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + std::string descr; + gs::read_pod(in, &descr); + unsigned deg; + gs::read_pod(in, °); + gs::ClassId tabid(in, 1); + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::StorableHistoNDFunctor::read: " + "input stream failure"); + CPP11_auto_ptr
tab(Table::read(tabid, in)); + return new StorableHistoNDFunctor(*tab, deg, descr); + } + + template + inline void StorableHistoNDFunctor::setInterpolationDegree(const unsigned deg) { + validateInterDegree(deg, table_.isUniformlyBinned()); + deg_ = deg; + } + + template + inline void StorableHistoNDFunctor::validateInterDegree(const unsigned deg, + const bool isUniform) { + const bool ok = isUniform ? (deg == 0 || deg == 1 || deg == 3) : (deg == 0 || deg == 1); + if (!ok) + throw npstat::NpstatInvalidArgument( + "In npstat::StorableHistoNDFunctor::validateInterDegree: " + "unsupported interpolation degree"); + } +} // namespace npstat + +#endif // NPSTAT_STORABLEHISTONDFUNCTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/StorableInterpolationFunctor.h b/JetMETCorrections/InterpolationTables/interface/StorableInterpolationFunctor.h index 4a0f4c2b4f88c..301d87a55ca1e 100644 --- a/JetMETCorrections/InterpolationTables/interface/StorableInterpolationFunctor.h +++ b/JetMETCorrections/InterpolationTables/interface/StorableInterpolationFunctor.h @@ -17,203 +17,203 @@ #include "JetMETCorrections/InterpolationTables/interface/SimpleFunctors.h" namespace npstat { - /** + /** // This class adapts LinInterpolatedTableND template to the // StorableMultivariateFunctor interface */ - template - < - class Numeric, - class Axis = UniformAxis, - class Converter = Same - > - class StorableInterpolationFunctor : public StorableMultivariateFunctor - { - template - friend class StorableInterpolationFunctor; - - public: - typedef LinInterpolatedTableND Table; - - //@{ - /** Constructor from a pre-existing table */ - template - inline StorableInterpolationFunctor( - const LinInterpolatedTableND& table) - : StorableMultivariateFunctor(), table_(table) {} - - template - inline StorableInterpolationFunctor( - const LinInterpolatedTableND& table, - const std::string& descr) - : StorableMultivariateFunctor(descr), table_(table) {} - //@} - - /** Converting copy constructor */ - template - inline StorableInterpolationFunctor( - const StorableInterpolationFunctor& tab) - : StorableMultivariateFunctor(tab.description()), - table_(tab.table_) {} - - //@{ - /** + template > + class StorableInterpolationFunctor : public StorableMultivariateFunctor { + template + friend class StorableInterpolationFunctor; + + public: + typedef LinInterpolatedTableND Table; + + //@{ + /** Constructor from a pre-existing table */ + template + inline StorableInterpolationFunctor(const LinInterpolatedTableND& table) + : StorableMultivariateFunctor(), table_(table) {} + + template + inline StorableInterpolationFunctor(const LinInterpolatedTableND& table, const std::string& descr) + : StorableMultivariateFunctor(descr), table_(table) {} + //@} + + /** Converting copy constructor */ + template + inline StorableInterpolationFunctor(const StorableInterpolationFunctor& tab) + : StorableMultivariateFunctor(tab.description()), table_(tab.table_) {} + + //@{ + /** // Constructor which builds the table in place. // It basically passses its arguments to the // corresponding constructor of LinInterpolatedTableND. */ - inline StorableInterpolationFunctor( - const std::vector& axes, - const std::vector >& interpolationType, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(axes, interpolationType, functionLabel) {} - - inline StorableInterpolationFunctor( - const Axis& xAxis, bool leftX, bool rightX, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(xAxis, leftX, rightX, functionLabel) {} - - inline StorableInterpolationFunctor( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(xAxis, leftX, rightX, - yAxis, leftY, rightY, functionLabel) {} - - inline StorableInterpolationFunctor( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(xAxis, leftX, rightX, - yAxis, leftY, rightY, - zAxis, leftZ, rightZ, functionLabel) {} - - inline StorableInterpolationFunctor( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(xAxis, leftX, rightX, - yAxis, leftY, rightY, - zAxis, leftZ, rightZ, - tAxis, leftT, rightT, functionLabel) {} - - inline StorableInterpolationFunctor( - const Axis& xAxis, bool leftX, bool rightX, - const Axis& yAxis, bool leftY, bool rightY, - const Axis& zAxis, bool leftZ, bool rightZ, - const Axis& tAxis, bool leftT, bool rightT, - const Axis& vAxis, bool leftV, bool rightV, - const char* functionLabel=nullptr) - : StorableMultivariateFunctor(), - table_(xAxis, leftX, rightX, - yAxis, leftY, rightY, - zAxis, leftZ, rightZ, - tAxis, leftT, rightT, - vAxis, leftV, rightV, functionLabel) {} - //@} - - ~StorableInterpolationFunctor() override {} - - unsigned minDim() const override {return table_.dim();}; - - double operator()(const double* point, unsigned dim) const override - {return conv_(table_(point, dim));} - - //@{ - /** Retrieve the underlying LinInterpolatedTableND object */ - inline Table& interpolator() {return table_;} - inline const Table& interpolator() const {return table_;} - //@} - - //@{ - /** Retrieve the tabulated data */ - inline ArrayND& table() {return table_.table();} - inline const ArrayND& table() const {return table_.table();} - //@} - - /** Change the coordinate converter */ - inline void setConverter(const Converter& conv) {conv_ = conv;} - - //@{ - // Method related to "geners" I/O - gs::ClassId classId() const override {return gs::ClassId(*this);} - bool write(std::ostream& of) const override; - //@} - - // I/O methods needed for reading - static inline const char* classname(); - static inline unsigned version() {return 1;} - static StorableInterpolationFunctor* read( - const gs::ClassId& id, std::istream& in); - - protected: - bool isEqual(const StorableMultivariateFunctor& other) const override - { - // Note the use of static_cast rather than dynamic_cast below. - // static_cast works faster and it is guaranteed to succeed here. - const StorableInterpolationFunctor& r = - static_cast(other); - return table_ == r.table_ && - this->description() == other.description(); - } - - private: - StorableInterpolationFunctor() = delete; - - Table table_; - Converter conv_; - }; -} + inline StorableInterpolationFunctor(const std::vector& axes, + const std::vector >& interpolationType, + const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), table_(axes, interpolationType, functionLabel) {} + + inline StorableInterpolationFunctor(const Axis& xAxis, bool leftX, bool rightX, const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), table_(xAxis, leftX, rightX, functionLabel) {} + + inline StorableInterpolationFunctor(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), table_(xAxis, leftX, rightX, yAxis, leftY, rightY, functionLabel) {} + + inline StorableInterpolationFunctor(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), + table_(xAxis, leftX, rightX, yAxis, leftY, rightY, zAxis, leftZ, rightZ, functionLabel) {} + + inline StorableInterpolationFunctor(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), + table_( + xAxis, leftX, rightX, yAxis, leftY, rightY, zAxis, leftZ, rightZ, tAxis, leftT, rightT, functionLabel) {} + + inline StorableInterpolationFunctor(const Axis& xAxis, + bool leftX, + bool rightX, + const Axis& yAxis, + bool leftY, + bool rightY, + const Axis& zAxis, + bool leftZ, + bool rightZ, + const Axis& tAxis, + bool leftT, + bool rightT, + const Axis& vAxis, + bool leftV, + bool rightV, + const char* functionLabel = nullptr) + : StorableMultivariateFunctor(), + table_(xAxis, + leftX, + rightX, + yAxis, + leftY, + rightY, + zAxis, + leftZ, + rightZ, + tAxis, + leftT, + rightT, + vAxis, + leftV, + rightV, + functionLabel) {} + //@} + + ~StorableInterpolationFunctor() override {} + + unsigned minDim() const override { return table_.dim(); }; + + double operator()(const double* point, unsigned dim) const override { return conv_(table_(point, dim)); } + + //@{ + /** Retrieve the underlying LinInterpolatedTableND object */ + inline Table& interpolator() { return table_; } + inline const Table& interpolator() const { return table_; } + //@} + + //@{ + /** Retrieve the tabulated data */ + inline ArrayND& table() { return table_.table(); } + inline const ArrayND& table() const { return table_.table(); } + //@} + + /** Change the coordinate converter */ + inline void setConverter(const Converter& conv) { conv_ = conv; } + + //@{ + // Method related to "geners" I/O + gs::ClassId classId() const override { return gs::ClassId(*this); } + bool write(std::ostream& of) const override; + //@} + + // I/O methods needed for reading + static inline const char* classname(); + static inline unsigned version() { return 1; } + static StorableInterpolationFunctor* read(const gs::ClassId& id, std::istream& in); + + protected: + bool isEqual(const StorableMultivariateFunctor& other) const override { + // Note the use of static_cast rather than dynamic_cast below. + // static_cast works faster and it is guaranteed to succeed here. + const StorableInterpolationFunctor& r = static_cast(other); + return table_ == r.table_ && this->description() == other.description(); + } + + private: + StorableInterpolationFunctor() = delete; + + Table table_; + Converter conv_; + }; +} // namespace npstat #include "Alignment/Geners/interface/binaryIO.hh" #include "Alignment/Geners/interface/CPP11_auto_ptr.hh" #include "Alignment/Geners/interface/IOException.hh" namespace npstat { - template - const char* StorableInterpolationFunctor::classname() - { - static const std::string myClass(gs::template_class_name( - "npstat::StorableInterpolationFunctor")); - return myClass.c_str(); - } - - template - bool StorableInterpolationFunctor::write( - std::ostream& of) const - { - gs::write_pod(of, this->description()); - return table_.classId().write(of) && table_.write(of); - } - - template - StorableInterpolationFunctor* - StorableInterpolationFunctor::read( - const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current( - gs::ClassId::makeId >()); - current.ensureSameId(id); - - std::string descr; - gs::read_pod(in, &descr); - gs::ClassId tabid(in, 1); - if (in.fail()) throw gs::IOReadFailure( - "In npstat::StorableInterpolationFunctor::read: " - "input stream failure"); - CPP11_auto_ptr
tab(Table::read(tabid, in)); - return new StorableInterpolationFunctor(*tab, descr); - } -} - - -#endif // NPSTAT_STORABLEINTERPOLATIONFUNCTOR_HH_ - + template + const char* StorableInterpolationFunctor::classname() { + static const std::string myClass(gs::template_class_name("npstat::StorableInterpolationFunctor")); + return myClass.c_str(); + } + + template + bool StorableInterpolationFunctor::write(std::ostream& of) const { + gs::write_pod(of, this->description()); + return table_.classId().write(of) && table_.write(of); + } + + template + StorableInterpolationFunctor* StorableInterpolationFunctor::read( + const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId >()); + current.ensureSameId(id); + + std::string descr; + gs::read_pod(in, &descr); + gs::ClassId tabid(in, 1); + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::StorableInterpolationFunctor::read: " + "input stream failure"); + CPP11_auto_ptr
tab(Table::read(tabid, in)); + return new StorableInterpolationFunctor(*tab, descr); + } +} // namespace npstat + +#endif // NPSTAT_STORABLEINTERPOLATIONFUNCTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctor.h b/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctor.h index ae6c3822d0629..88d2995a305d4 100644 --- a/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctor.h +++ b/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctor.h @@ -19,69 +19,64 @@ #include "JetMETCorrections/InterpolationTables/interface/AbsMultivariateFunctor.h" namespace npstat { - /** Base class for storable multivariate functors */ - class StorableMultivariateFunctor : public AbsMultivariateFunctor - { - public: - inline StorableMultivariateFunctor() {} + /** Base class for storable multivariate functors */ + class StorableMultivariateFunctor : public AbsMultivariateFunctor { + public: + inline StorableMultivariateFunctor() {} - /** Functor description can be an arbitrary string */ - inline explicit StorableMultivariateFunctor(const std::string& descr) - : AbsMultivariateFunctor(), description_(descr) {} + /** Functor description can be an arbitrary string */ + inline explicit StorableMultivariateFunctor(const std::string& descr) + : AbsMultivariateFunctor(), description_(descr) {} - inline ~StorableMultivariateFunctor() override {} + inline ~StorableMultivariateFunctor() override {} - /** Retrieve the functor description */ - inline const std::string& description() const {return description_;} + /** Retrieve the functor description */ + inline const std::string& description() const { return description_; } - /** Change the functor description */ - inline void setDescription(const std::string& newDescription) - {description_ = newDescription;} + /** Change the functor description */ + inline void setDescription(const std::string& newDescription) { description_ = newDescription; } - /** + /** // This method will throw npstat::NpstatRuntimeError in case // functor description is different from the provided argument */ - void validateDescription(const std::string& description) const; + void validateDescription(const std::string& description) const; - //@{ - /** + //@{ + /** // Do not override comparison operators in the derived classes, // override the method "isEqual" instead. */ - inline bool operator==(const StorableMultivariateFunctor& r) const - {return (typeid(*this) == typeid(r)) && this->isEqual(r);} - inline bool operator!=(const StorableMultivariateFunctor& r) const - {return !(*this == r);} - //@} - - //@{ - /** Method related to "geners" I/O */ - virtual gs::ClassId classId() const = 0; - virtual bool write(std::ostream& of) const = 0; - //@} - - // I/O methods needed for reading - static inline const char* classname() - {return "npstat::StorableMultivariateFunctor";} - static inline unsigned version() {return 1;} - static StorableMultivariateFunctor* read( - const gs::ClassId& id, std::istream& in); - - protected: - /** + inline bool operator==(const StorableMultivariateFunctor& r) const { + return (typeid(*this) == typeid(r)) && this->isEqual(r); + } + inline bool operator!=(const StorableMultivariateFunctor& r) const { return !(*this == r); } + //@} + + //@{ + /** Method related to "geners" I/O */ + virtual gs::ClassId classId() const = 0; + virtual bool write(std::ostream& of) const = 0; + //@} + + // I/O methods needed for reading + static inline const char* classname() { return "npstat::StorableMultivariateFunctor"; } + static inline unsigned version() { return 1; } + static StorableMultivariateFunctor* read(const gs::ClassId& id, std::istream& in); + + protected: + /** // Method needed to compare objects for equality. // Must be overriden by derived classes. It is left // up to the derived classes to decide whether they // should compare description strings in order to // establish equality. */ - virtual bool isEqual(const StorableMultivariateFunctor&) const = 0; - - private: - std::string description_; - }; -} + virtual bool isEqual(const StorableMultivariateFunctor&) const = 0; -#endif // NPSTAT_STORABLEMULTIVARIATEFUNCTOR_HH_ + private: + std::string description_; + }; +} // namespace npstat +#endif // NPSTAT_STORABLEMULTIVARIATEFUNCTOR_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h b/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h index 7020f4aef7ff9..0a48e0037cd0a 100644 --- a/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h +++ b/JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h @@ -16,22 +16,18 @@ #include "JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctor.h" namespace npstat { - /** + /** // Note that this class does not have any public constructors. // All application usage is through the gs::StaticReader wrapper. */ - class StorableMultivariateFunctorReader : - public gs::DefaultReader - { - typedef gs::DefaultReader Base; - friend class gs::StaticReader; - StorableMultivariateFunctorReader(); //NOLINT - }; - - /** The reader factory for descendants of StorableMultivariateFunctor */ - typedef gs::StaticReader - StaticStorableMultivariateFunctorReader; -} + class StorableMultivariateFunctorReader : public gs::DefaultReader { + typedef gs::DefaultReader Base; + friend class gs::StaticReader; + StorableMultivariateFunctorReader(); //NOLINT + }; -#endif // NPSTAT_READER_FOR_STORABLEMULTIVARIATEFUNCTOR + /** The reader factory for descendants of StorableMultivariateFunctor */ + typedef gs::StaticReader StaticStorableMultivariateFunctorReader; +} // namespace npstat +#endif // NPSTAT_READER_FOR_STORABLEMULTIVARIATEFUNCTOR diff --git a/JetMETCorrections/InterpolationTables/interface/UniformAxis.h b/JetMETCorrections/InterpolationTables/interface/UniformAxis.h index b635eebba3e8e..c6412f18d3628 100644 --- a/JetMETCorrections/InterpolationTables/interface/UniformAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/UniformAxis.h @@ -20,78 +20,73 @@ #include "Alignment/Geners/interface/ClassId.hh" namespace npstat { - /** + /** // This class contains the info needed to define an axis of a rectangular // grid. The distance between grid points is uniform. */ - class UniformAxis - { - public: - // The number of coordinates must be at least 2 - UniformAxis(unsigned nCoords, double min, double max, - const char* label=nullptr); - - // Basic accessors - inline unsigned nCoords() const {return npt_;} - inline double min() const {return min_;} - inline double max() const {return max_;} - inline const std::string& label() const {return label_;} - inline bool usesLogSpace() const {return false;} - - // The following function returns the grid interval number and - // the weight of the point at the left side of the interval. - // The weight will be set to 1 if the given coordinate coincides - // with the grid point and will decay to 0 linearly as the - // coordinate moves towards the next point on the right. - // - // The coordinates below the leftmost grid point are mapped - // into the 0th interval with weight 1. The coordinates above - // the rightmost grid point are mapped into the last interval - // with weight 0 for the left point (it is expected that weight 1 - // will then be assigned to the right point). - std::pair getInterval(double coordinate) const; - - // Similar function which calculates the weights including - // the points outside of the axis boundaries - std::pair linearInterval(double coordinate) const; - - // Convenience methods - std::vector coords() const; - double coordinate(unsigned i) const; - inline double length() const {return max_ - min_;} - inline bool isUniform() const {return true;} - inline unsigned nIntervals() const {return npt_ - 1;} - inline double intervalWidth(unsigned) const {return bw_;} - - bool operator==(const UniformAxis& r) const; - inline bool operator!=(const UniformAxis& r) const - {return !(*this == r);} - - // Closeness within tolerance - bool isClose(const UniformAxis& r, double tol) const; - - // Modify the label - inline void setLabel(const char* newlabel) - {label_ = newlabel ? newlabel : "";} - - // Methods related to I/O - inline gs::ClassId classId() const {return gs::ClassId(*this);} - bool write(std::ostream& of) const; - - static inline const char* classname() {return "npstat::UniformAxis";} - static inline unsigned version() {return 1;} - static UniformAxis* read(const gs::ClassId& id, std::istream& in); - - private: - double min_; - double max_; - double bw_; - std::string label_; - unsigned npt_; - - inline UniformAxis() : min_(0.), max_(0.), bw_(0.), npt_(0) {} - }; -} - -#endif // NPSTAT_UNIFORMAXIS_HH_ - + class UniformAxis { + public: + // The number of coordinates must be at least 2 + UniformAxis(unsigned nCoords, double min, double max, const char* label = nullptr); + + // Basic accessors + inline unsigned nCoords() const { return npt_; } + inline double min() const { return min_; } + inline double max() const { return max_; } + inline const std::string& label() const { return label_; } + inline bool usesLogSpace() const { return false; } + + // The following function returns the grid interval number and + // the weight of the point at the left side of the interval. + // The weight will be set to 1 if the given coordinate coincides + // with the grid point and will decay to 0 linearly as the + // coordinate moves towards the next point on the right. + // + // The coordinates below the leftmost grid point are mapped + // into the 0th interval with weight 1. The coordinates above + // the rightmost grid point are mapped into the last interval + // with weight 0 for the left point (it is expected that weight 1 + // will then be assigned to the right point). + std::pair getInterval(double coordinate) const; + + // Similar function which calculates the weights including + // the points outside of the axis boundaries + std::pair linearInterval(double coordinate) const; + + // Convenience methods + std::vector coords() const; + double coordinate(unsigned i) const; + inline double length() const { return max_ - min_; } + inline bool isUniform() const { return true; } + inline unsigned nIntervals() const { return npt_ - 1; } + inline double intervalWidth(unsigned) const { return bw_; } + + bool operator==(const UniformAxis& r) const; + inline bool operator!=(const UniformAxis& r) const { return !(*this == r); } + + // Closeness within tolerance + bool isClose(const UniformAxis& r, double tol) const; + + // Modify the label + inline void setLabel(const char* newlabel) { label_ = newlabel ? newlabel : ""; } + + // Methods related to I/O + inline gs::ClassId classId() const { return gs::ClassId(*this); } + bool write(std::ostream& of) const; + + static inline const char* classname() { return "npstat::UniformAxis"; } + static inline unsigned version() { return 1; } + static UniformAxis* read(const gs::ClassId& id, std::istream& in); + + private: + double min_; + double max_; + double bw_; + std::string label_; + unsigned npt_; + + inline UniformAxis() : min_(0.), max_(0.), bw_(0.), npt_(0) {} + }; +} // namespace npstat + +#endif // NPSTAT_UNIFORMAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/absDifference.h b/JetMETCorrections/InterpolationTables/interface/absDifference.h index 70a6aba491447..6149dd5c2c4ef 100644 --- a/JetMETCorrections/InterpolationTables/interface/absDifference.h +++ b/JetMETCorrections/InterpolationTables/interface/absDifference.h @@ -18,86 +18,70 @@ #include "Alignment/Geners/interface/IOIsUnsigned.hh" namespace npstat { - namespace Private { - template - struct AbsReturnType - { - typedef T type; - }; - - template - struct AbsReturnType > - { - typedef T type; - }; - - template - struct AbsReturnType > - { - typedef T type; - }; - - template - struct AbsReturnType > - { - typedef T type; - }; - - template - struct AbsReturnType > - { - typedef T type; - }; - - // Signed type - template - struct AbsHelper - { - typedef typename Private::AbsReturnType::type return_type; - - inline static return_type delta(const T& v1, const T& v2) - {return std::abs(v1 - v2);} - - inline static return_type value(const T& v1) - {return std::abs(v1);} - }; - - // Unsigned type - template - struct AbsHelper - { - typedef typename Private::AbsReturnType::type return_type; - - inline static return_type delta(const T& v1, const T& v2) - {return v1 > v2 ? v1 - v2 : v2 - v1;} - - inline static return_type value(const T& v1) - {return v1;} - }; - } - - /** + namespace Private { + template + struct AbsReturnType { + typedef T type; + }; + + template + struct AbsReturnType > { + typedef T type; + }; + + template + struct AbsReturnType > { + typedef T type; + }; + + template + struct AbsReturnType > { + typedef T type; + }; + + template + struct AbsReturnType > { + typedef T type; + }; + + // Signed type + template + struct AbsHelper { + typedef typename Private::AbsReturnType::type return_type; + + inline static return_type delta(const T& v1, const T& v2) { return std::abs(v1 - v2); } + + inline static return_type value(const T& v1) { return std::abs(v1); } + }; + + // Unsigned type + template + struct AbsHelper { + typedef typename Private::AbsReturnType::type return_type; + + inline static return_type delta(const T& v1, const T& v2) { return v1 > v2 ? v1 - v2 : v2 - v1; } + + inline static return_type value(const T& v1) { return v1; } + }; + } // namespace Private + + /** // Absolute value of the difference between two numbers. // Works for all standard numeric types, including unsigned and complex. */ - template - inline typename Private::AbsReturnType::type - absDifference(const T& v1, const T& v2) - { - return Private::AbsHelper::value>::delta(v1, v2); - } - - /** + template + inline typename Private::AbsReturnType::type absDifference(const T& v1, const T& v2) { + return Private::AbsHelper::value>::delta(v1, v2); + } + + /** // Absolute value of a number. // Works for all standard numeric types, including unsigned and complex. */ - template - inline typename Private::AbsReturnType::type - absValue(const T& v1) - { - return Private::AbsHelper::value>::value(v1); - } -} - -#endif // NPSTAT_ABSDIFFERENCE_HH_ + template + inline typename Private::AbsReturnType::type absValue(const T& v1) { + return Private::AbsHelper::value>::value(v1); + } +} // namespace npstat +#endif // NPSTAT_ABSDIFFERENCE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/allocators.h b/JetMETCorrections/InterpolationTables/interface/allocators.h index dd55fb0dd582a..14de565b9d062 100644 --- a/JetMETCorrections/InterpolationTables/interface/allocators.h +++ b/JetMETCorrections/InterpolationTables/interface/allocators.h @@ -14,100 +14,83 @@ #include namespace npstat { - /** + /** // Function for allocating memory buffers if their size // exceeds the size of the buffer available on the stack */ - template - inline T* makeBuffer(unsigned sizeNeeded, T* stackBuffer, - unsigned sizeofStackBuffer) - { - if (sizeNeeded > sizeofStackBuffer || stackBuffer == nullptr) - return new T[sizeNeeded]; - else - return stackBuffer; - } + template + inline T* makeBuffer(unsigned sizeNeeded, T* stackBuffer, unsigned sizeofStackBuffer) { + if (sizeNeeded > sizeofStackBuffer || stackBuffer == nullptr) + return new T[sizeNeeded]; + else + return stackBuffer; + } - /** Function for freeing memory buffers allocated by "makeBuffer" */ - template - inline void destroyBuffer(T* thisBuffer, const T* stackBuffer) - { - if (thisBuffer != stackBuffer) - delete [] thisBuffer; - } + /** Function for freeing memory buffers allocated by "makeBuffer" */ + template + inline void destroyBuffer(T* thisBuffer, const T* stackBuffer) { + if (thisBuffer != stackBuffer) + delete[] thisBuffer; + } - /** Copy a buffer (with possible type conversion on the fly) */ - template - inline void copyBuffer(T1* dest, const T2* source, const unsigned long len) - { - if (len) - { - assert(dest); - assert(source); - for (unsigned long i=0; i(*source++); - } + /** Copy a buffer (with possible type conversion on the fly) */ + template + inline void copyBuffer(T1* dest, const T2* source, const unsigned long len) { + if (len) { + assert(dest); + assert(source); + for (unsigned long i = 0; i < len; ++i) + *dest++ = static_cast(*source++); } + } - /** + /** // Copy a buffer (with possible type conversion on the fly) // transposing it in the process (treating as a square matrix) */ - template - inline void transposeBuffer(T1* dest, const T2* source, - const unsigned long dim) - { - if (dim) - { - assert(dest); - assert(source); - for (unsigned long i=0; i(*source++); - ++dest; - } - } + template + inline void transposeBuffer(T1* dest, const T2* source, const unsigned long dim) { + if (dim) { + assert(dest); + assert(source); + for (unsigned long i = 0; i < dim; ++i) { + for (unsigned long j = 0; j < dim; ++j) + dest[j * dim] = static_cast(*source++); + ++dest; + } } + } - /** + /** // Copy a buffer (with possible type conversion on the fly) // transposing it in the process (treating as an M x N matrix) */ - template - inline void transposeBuffer(T1* dest, const T2* source, - const unsigned long M, - const unsigned long N) - { - if (M && N) - { - assert(dest); - assert(source); - for (unsigned long i=0; i(*source++); - ++dest; - } - } + template + inline void transposeBuffer(T1* dest, const T2* source, const unsigned long M, const unsigned long N) { + if (M && N) { + assert(dest); + assert(source); + for (unsigned long i = 0; i < M; ++i) { + for (unsigned long j = 0; j < N; ++j) + dest[j * M] = static_cast(*source++); + ++dest; + } } + } - /** + /** // Clear a buffer (set all elements to the value produced by the // default constructor) */ - template - inline void clearBuffer(T* buf, const unsigned long len) - { - if (len) - { - assert(buf); - const T zero = T(); - for (unsigned long i=0; i + inline void clearBuffer(T* buf, const unsigned long len) { + if (len) { + assert(buf); + const T zero = T(); + for (unsigned long i = 0; i < len; ++i) + *buf++ = zero; } -} - -#endif // NPSTAT_ALLOCATORS_HH_ + } +} // namespace npstat +#endif // NPSTAT_ALLOCATORS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h b/JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h index 080b0eefb6100..c8bb6c0d0ab8c 100644 --- a/JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h +++ b/JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h @@ -17,23 +17,21 @@ #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" namespace npstat { - /** + /** // Check if two doubles are within certain relative tolerance from // each other. The "tol" argument which specifies the tolerance // must be non-negative. */ - inline bool closeWithinTolerance(const double& a, const double& b, - const double& tol) - { - if (tol < 0.0) - throw npstat::NpstatInvalidArgument("In npstat::closeWithinTolerance: " - "negative tolerance is not allowed"); - if (a == b) - return true; - else - return fabs(a - b)/std::max(fabs(a), fabs(b)) <= tol; - } -} - -#endif // NPSTAT_CLOSEWITHINTOLERANCE_HH_ + inline bool closeWithinTolerance(const double& a, const double& b, const double& tol) { + if (tol < 0.0) + throw npstat::NpstatInvalidArgument( + "In npstat::closeWithinTolerance: " + "negative tolerance is not allowed"); + if (a == b) + return true; + else + return fabs(a - b) / std::max(fabs(a), fabs(b)) <= tol; + } +} // namespace npstat +#endif // NPSTAT_CLOSEWITHINTOLERANCE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/convertAxis.h b/JetMETCorrections/InterpolationTables/interface/convertAxis.h index a5e070b8505ed..446eb66b785c5 100644 --- a/JetMETCorrections/InterpolationTables/interface/convertAxis.h +++ b/JetMETCorrections/InterpolationTables/interface/convertAxis.h @@ -22,28 +22,27 @@ #include "JetMETCorrections/InterpolationTables/interface/NUHistoAxis.h" namespace npstat { - /** Convert uniform grid axis to uniform histogram axis */ - HistoAxis convertToHistoAxis(const UniformAxis& gridAxis); + /** Convert uniform grid axis to uniform histogram axis */ + HistoAxis convertToHistoAxis(const UniformAxis& gridAxis); - /** Convert uniform histogram to uniform grid axis axis */ - UniformAxis convertToGridAxis(const HistoAxis& histoAxis); + /** Convert uniform histogram to uniform grid axis axis */ + UniformAxis convertToGridAxis(const HistoAxis& histoAxis); - /** + /** // Note that conversion from non-uniform histogram axis into // the grid axis is always possible, but it is loosing information // (we are writing the positions of bin centers only, not edges) */ - GridAxis convertToGridAxis(const NUHistoAxis& histoAxis); + GridAxis convertToGridAxis(const NUHistoAxis& histoAxis); - /** + /** // The conversion from non-uniform grid axis to non-uniform // histogram axis is only unambiguous when some additional // info is available. Here, in particular, we are asking for // the position of the axis minimum. This function will throw // npstat::NpstatInvalidArgument in case the conversion is impossible. */ - NUHistoAxis convertToHistoAxis(const GridAxis& gridAxis, double xMin); -} - -#endif // NPSTAT_CONVERTAXIS_HH_ + NUHistoAxis convertToHistoAxis(const GridAxis& gridAxis, double xMin); +} // namespace npstat +#endif // NPSTAT_CONVERTAXIS_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/interpolate.h b/JetMETCorrections/InterpolationTables/interface/interpolate.h index e6b874c5d6cb8..3297946a13331 100644 --- a/JetMETCorrections/InterpolationTables/interface/interpolate.h +++ b/JetMETCorrections/InterpolationTables/interface/interpolate.h @@ -15,45 +15,39 @@ #include "JetMETCorrections/InterpolationTables/interface/ProperDblFromCmpl.h" namespace npstat { - /** + /** // Linear interpolation. Assumes that // the function values are given at 0 and 1. */ - template - inline T interpolate_linear(const double x, const T& f0, const T& f1) - { - const typename ProperDblFromCmpl::type dx = 1.0 - x; - return f0*dx + f1*static_cast::type>(x); - } + template + inline T interpolate_linear(const double x, const T& f0, const T& f1) { + const typename ProperDblFromCmpl::type dx = 1.0 - x; + return f0 * dx + f1 * static_cast::type>(x); + } - /** + /** // Quadratic interpolation. Assume that // the function values are given at 0, 1, and 2. */ - template - inline T interpolate_quadratic(const double x, const T& f0, - const T& f1, const T& f2) - { - static const typename ProperDblFromCmpl::type two = 2.0; - const typename ProperDblFromCmpl::type dx = x - 1.0; - return f1 + ((f2 - f0)/two + ((f2 - f1) + (f0 - f1))*(dx/two))*dx; - } + template + inline T interpolate_quadratic(const double x, const T& f0, const T& f1, const T& f2) { + static const typename ProperDblFromCmpl::type two = 2.0; + const typename ProperDblFromCmpl::type dx = x - 1.0; + return f1 + ((f2 - f0) / two + ((f2 - f1) + (f0 - f1)) * (dx / two)) * dx; + } - /** + /** // Cubic interpolation. Assume that // the function values are given at 0, 1, 2, and 3. */ - template - inline T interpolate_cubic(const double x, const T& f0, const T& f1, - const T& f2, const T& f3) - { - return interpolate_linear(x*(3.0 - x)/2.0, - interpolate_linear(x/3.0, f0, f3), - interpolate_linear(x - 1.0, f1, f2)); - } + template + inline T interpolate_cubic(const double x, const T& f0, const T& f1, const T& f2, const T& f3) { + return interpolate_linear( + x * (3.0 - x) / 2.0, interpolate_linear(x / 3.0, f0, f3), interpolate_linear(x - 1.0, f1, f2)); + } - //@{ - /** + //@{ + /** // Get the coefficients of the interpolating polynomial. // The interpolated function values are provided at 0, 1, ... // The return value of the function is the number of @@ -63,63 +57,54 @@ namespace npstat { // The length of the provided buffer must be sufficient // to hold all these coefficients. */ - template - unsigned interpolation_coefficients(T* buffer, unsigned bufLen, - const T& f0, const T& f1); - template - unsigned interpolation_coefficients(T* buffer, unsigned bufLen, - const T& f0, const T& f1, const T& f2); - template - unsigned interpolation_coefficients(T* buffer, unsigned bufLen, - const T& f0, const T& f1, - const T& f2, const T& f3); - //@} -} + template + unsigned interpolation_coefficients(T* buffer, unsigned bufLen, const T& f0, const T& f1); + template + unsigned interpolation_coefficients(T* buffer, unsigned bufLen, const T& f0, const T& f1, const T& f2); + template + unsigned interpolation_coefficients(T* buffer, unsigned bufLen, const T& f0, const T& f1, const T& f2, const T& f3); + //@} +} // namespace npstat #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" namespace npstat { - template - unsigned interpolation_coefficients(T* buffer, const unsigned bufLen, - const T& f0, const T& f1) - { - if (bufLen <= 1U) throw npstat::NpstatInvalidArgument( - "In npstat::interpolation_coefficients: " - "insufficient length of the output buffer"); - buffer[0] = f0; - buffer[1] = f1 - f0; - return 2U; - } + template + unsigned interpolation_coefficients(T* buffer, const unsigned bufLen, const T& f0, const T& f1) { + if (bufLen <= 1U) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolation_coefficients: " + "insufficient length of the output buffer"); + buffer[0] = f0; + buffer[1] = f1 - f0; + return 2U; + } - template - unsigned interpolation_coefficients(T* buffer, const unsigned bufLen, - const T& f0, const T& f1, const T& f2) - { - if (bufLen <= 2U) throw npstat::NpstatInvalidArgument( - "In npstat::interpolation_coefficients: " - "insufficient length of the output buffer"); - buffer[0] = f0; - buffer[1] = static_cast((f1 - f2 + 3*(f1 - f0))/2.0); - buffer[2] = static_cast(((f0 - f1) + (f2 - f1))/2.0); - return 3U; - } + template + unsigned interpolation_coefficients(T* buffer, const unsigned bufLen, const T& f0, const T& f1, const T& f2) { + if (bufLen <= 2U) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolation_coefficients: " + "insufficient length of the output buffer"); + buffer[0] = f0; + buffer[1] = static_cast((f1 - f2 + 3 * (f1 - f0)) / 2.0); + buffer[2] = static_cast(((f0 - f1) + (f2 - f1)) / 2.0); + return 3U; + } - template - unsigned interpolation_coefficients(T* buffer, const unsigned bufLen, - const T& f0, const T& f1, - const T& f2, const T& f3) - { - if (bufLen <= 3U) throw npstat::NpstatInvalidArgument( - "In npstat::interpolation_coefficients: " - "insufficient length of the output buffer"); - buffer[0] = f0; - buffer[1] = static_cast((11*(f1 - f0)+7*(f1 - f2)+2*(f3 - f2))/6.0); - buffer[2] = static_cast((2*(f0 - f1)+3*(f2 - f1)+(f2 - f3))/2.0); - buffer[3] = static_cast(((f3 - f0) + 3*(f1 - f2))/6.0); - return 4U; - } -} - - -#endif // NPSTAT_INTERPOLATE_HH_ + template + unsigned interpolation_coefficients( + T* buffer, const unsigned bufLen, const T& f0, const T& f1, const T& f2, const T& f3) { + if (bufLen <= 3U) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolation_coefficients: " + "insufficient length of the output buffer"); + buffer[0] = f0; + buffer[1] = static_cast((11 * (f1 - f0) + 7 * (f1 - f2) + 2 * (f3 - f2)) / 6.0); + buffer[2] = static_cast((2 * (f0 - f1) + 3 * (f2 - f1) + (f2 - f3)) / 2.0); + buffer[3] = static_cast(((f3 - f0) + 3 * (f1 - f2)) / 6.0); + return 4U; + } +} // namespace npstat +#endif // NPSTAT_INTERPOLATE_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h b/JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h index 266c837386ad9..0b45e86c6246d 100644 --- a/JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h +++ b/JetMETCorrections/InterpolationTables/interface/interpolateHistoND.h @@ -24,439 +24,441 @@ #include "JetMETCorrections/InterpolationTables/interface/HistoND.h" namespace npstat { - /** + /** // The interpolation degree in this method can be set to 0, 1, or 3 // which results, respectively, in closest bin lookup, multilinear // interpolation, or multicubic interpolation. Value of the closest // bin inside the histogram range is used if some coordinate is outside // of the corresponding axis limits. */ - template - Float interpolateHistoND(const HistoND& histo, - const double *coords, unsigned coordsDim, - unsigned interpolationDegree); - //@{ - /** + template + Float interpolateHistoND(const HistoND& histo, + const double* coords, + unsigned coordsDim, + unsigned interpolationDegree); + //@{ + /** // Convenience function for interpolating histograms, with // an explicit coordinate argument for each histogram dimension */ - template - Float interpolateHistoND(const HistoND& histo, - double x0, unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, double x0, unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, - unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, double x0, double x1, unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, - unsigned interpolationDegree); + template + Float interpolateHistoND( + const HistoND& histo, double x0, double x1, double x2, unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - unsigned interpolationDegree); + template + Float interpolateHistoND( + const HistoND& histo, double x0, double x1, double x2, double x3, unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, double x5, - unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, double x5, double x6, - unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8, unsigned interpolationDegree); + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + unsigned interpolationDegree); - template - Float interpolateHistoND(const HistoND& histo, - double x0, double x1, double x2, double x3, - double x4, double x5, double x6, double x7, - double x8, double x9, - unsigned interpolationDegree); - //@} -} + template + Float interpolateHistoND(const HistoND& histo, + double x0, + double x1, + double x2, + double x3, + double x4, + double x5, + double x6, + double x7, + double x8, + double x9, + unsigned interpolationDegree); + //@} +} // namespace npstat #include #include "JetMETCorrections/InterpolationTables/interface/NpstatException.h" namespace npstat { - namespace Private { - template - void iHND_checkArgs(const HistoND& histo, - const unsigned xDim, - const unsigned interpolationDegree) - { - if (xDim != histo.dim()) throw npstat::NpstatInvalidArgument( - "In npstat::interpolateHistoND: incompatible " - "dimensionality of input coordinates"); - if (xDim == 0U) throw npstat::NpstatInvalidArgument( - "In npstat::interpolateHistoND: can not interpolate " - "zero-dimensional histograms"); - if (!(interpolationDegree == 0U || - interpolationDegree == 1U || - interpolationDegree == 3U)) throw npstat::NpstatInvalidArgument( - "In npstat::interpolateHistoND: " - "unsupported interpolation degree"); - if (interpolationDegree == 3U && !histo.isUniformlyBinned()) - throw npstat::NpstatInvalidArgument( - "In npstat::interpolateHistoND: unsupported " - "interpolation degree for non-uniform binning"); - } - } - + namespace Private { template - Float interpolateHistoND(const HistoND& histo, - const double *x, const unsigned xDim, - const unsigned interpolationDegree) - { - Private::iHND_checkArgs(histo, xDim, interpolationDegree); - assert(x); - const Axis* ax = &histo.axes()[0]; - double coords[CHAR_BIT*sizeof(unsigned long)]; - for (unsigned i=0; i& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, xDim); - case 3U: - return bins.interpolate3(coords, xDim); - default: - return bins.closest(coords, xDim); - } + void iHND_checkArgs(const HistoND& histo, const unsigned xDim, const unsigned interpolationDegree) { + if (xDim != histo.dim()) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolateHistoND: incompatible " + "dimensionality of input coordinates"); + if (xDim == 0U) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolateHistoND: can not interpolate " + "zero-dimensional histograms"); + if (!(interpolationDegree == 0U || interpolationDegree == 1U || interpolationDegree == 3U)) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolateHistoND: " + "unsupported interpolation degree"); + if (interpolationDegree == 3U && !histo.isUniformlyBinned()) + throw npstat::NpstatInvalidArgument( + "In npstat::interpolateHistoND: unsupported " + "interpolation degree for non-uniform binning"); } + } // namespace Private - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const unsigned interpolationDegree) - { - const unsigned expDim = 1U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const double coords = histo.axis(0).fltBinNumber(x0, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(&coords, expDim); - case 3U: - return bins.interpolate3(&coords, expDim); - default: - return bins.closest(&coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double* x, + const unsigned xDim, + const unsigned interpolationDegree) { + Private::iHND_checkArgs(histo, xDim, interpolationDegree); + assert(x); + const Axis* ax = &histo.axes()[0]; + double coords[CHAR_BIT * sizeof(unsigned long)]; + for (unsigned i = 0; i < xDim; ++i) + coords[i] = ax[i].fltBinNumber(x[i], false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, xDim); + case 3U: + return bins.interpolate3(coords, xDim); + default: + return bins.closest(coords, xDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const unsigned interpolationDegree) - { - const unsigned expDim = 2U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, const double x0, const unsigned interpolationDegree) { + const unsigned expDim = 1U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const double coords = histo.axis(0).fltBinNumber(x0, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(&coords, expDim); + case 3U: + return bins.interpolate3(&coords, expDim); + default: + return bins.closest(&coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const unsigned interpolationDegree) - { - const unsigned expDim = 3U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const unsigned interpolationDegree) { + const unsigned expDim = 2U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const unsigned interpolationDegree) - { - const unsigned expDim = 4U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const unsigned interpolationDegree) { + const unsigned expDim = 3U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const unsigned interpolationDegree) - { - const unsigned expDim = 5U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const unsigned interpolationDegree) { + const unsigned expDim = 4U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const unsigned interpolationDegree) - { - const unsigned expDim = 6U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - coords[5] = ax[5].fltBinNumber(x5, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const unsigned interpolationDegree) { + const unsigned expDim = 5U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const unsigned interpolationDegree) - { - const unsigned expDim = 7U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - coords[5] = ax[5].fltBinNumber(x5, false); - coords[6] = ax[6].fltBinNumber(x6, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const unsigned interpolationDegree) { + const unsigned expDim = 6U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + coords[5] = ax[5].fltBinNumber(x5, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7, - const unsigned interpolationDegree) - { - const unsigned expDim = 8U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - coords[5] = ax[5].fltBinNumber(x5, false); - coords[6] = ax[6].fltBinNumber(x6, false); - coords[7] = ax[7].fltBinNumber(x7, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const unsigned interpolationDegree) { + const unsigned expDim = 7U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + coords[5] = ax[5].fltBinNumber(x5, false); + coords[6] = ax[6].fltBinNumber(x6, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7, - const double x8, - const unsigned interpolationDegree) - { - const unsigned expDim = 9U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - coords[5] = ax[5].fltBinNumber(x5, false); - coords[6] = ax[6].fltBinNumber(x6, false); - coords[7] = ax[7].fltBinNumber(x7, false); - coords[8] = ax[8].fltBinNumber(x8, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const unsigned interpolationDegree) { + const unsigned expDim = 8U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + coords[5] = ax[5].fltBinNumber(x5, false); + coords[6] = ax[6].fltBinNumber(x6, false); + coords[7] = ax[7].fltBinNumber(x7, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } + } - template - Float interpolateHistoND(const HistoND& histo, - const double x0, - const double x1, - const double x2, - const double x3, - const double x4, - const double x5, - const double x6, - const double x7, - const double x8, - const double x9, - const unsigned interpolationDegree) - { - const unsigned expDim = 10U; - Private::iHND_checkArgs(histo, expDim, interpolationDegree); - const Axis* ax = &histo.axes()[0]; - double coords[expDim]; - coords[0] = ax[0].fltBinNumber(x0, false); - coords[1] = ax[1].fltBinNumber(x1, false); - coords[2] = ax[2].fltBinNumber(x2, false); - coords[3] = ax[3].fltBinNumber(x3, false); - coords[4] = ax[4].fltBinNumber(x4, false); - coords[5] = ax[5].fltBinNumber(x5, false); - coords[6] = ax[6].fltBinNumber(x6, false); - coords[7] = ax[7].fltBinNumber(x7, false); - coords[8] = ax[8].fltBinNumber(x8, false); - coords[9] = ax[9].fltBinNumber(x9, false); - const ArrayND& bins(histo.binContents()); - switch (interpolationDegree) - { - case 1U: - return bins.interpolate1(coords, expDim); - case 3U: - return bins.interpolate3(coords, expDim); - default: - return bins.closest(coords, expDim); - } + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const unsigned interpolationDegree) { + const unsigned expDim = 9U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + coords[5] = ax[5].fltBinNumber(x5, false); + coords[6] = ax[6].fltBinNumber(x6, false); + coords[7] = ax[7].fltBinNumber(x7, false); + coords[8] = ax[8].fltBinNumber(x8, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); } -} - + } -#endif // NPSTAT_INTERPOLATEHISTOND_HH_ + template + Float interpolateHistoND(const HistoND& histo, + const double x0, + const double x1, + const double x2, + const double x3, + const double x4, + const double x5, + const double x6, + const double x7, + const double x8, + const double x9, + const unsigned interpolationDegree) { + const unsigned expDim = 10U; + Private::iHND_checkArgs(histo, expDim, interpolationDegree); + const Axis* ax = &histo.axes()[0]; + double coords[expDim]; + coords[0] = ax[0].fltBinNumber(x0, false); + coords[1] = ax[1].fltBinNumber(x1, false); + coords[2] = ax[2].fltBinNumber(x2, false); + coords[3] = ax[3].fltBinNumber(x3, false); + coords[4] = ax[4].fltBinNumber(x4, false); + coords[5] = ax[5].fltBinNumber(x5, false); + coords[6] = ax[6].fltBinNumber(x6, false); + coords[7] = ax[7].fltBinNumber(x7, false); + coords[8] = ax[8].fltBinNumber(x8, false); + coords[9] = ax[9].fltBinNumber(x9, false); + const ArrayND& bins(histo.binContents()); + switch (interpolationDegree) { + case 1U: + return bins.interpolate1(coords, expDim); + case 3U: + return bins.interpolate3(coords, expDim); + default: + return bins.closest(coords, expDim); + } + } +} // namespace npstat +#endif // NPSTAT_INTERPOLATEHISTOND_HH_ diff --git a/JetMETCorrections/InterpolationTables/interface/isMonotonous.h b/JetMETCorrections/InterpolationTables/interface/isMonotonous.h index 7aaf848bc0e50..4d8498fa25ec2 100644 --- a/JetMETCorrections/InterpolationTables/interface/isMonotonous.h +++ b/JetMETCorrections/InterpolationTables/interface/isMonotonous.h @@ -13,80 +13,72 @@ */ namespace npstat { - /** Check if the sequence of values is strictly increasing */ - template - inline bool isStrictlyIncreasing(Iter begin, Iter const end) - { - if (begin == end) - return false; - Iter first(begin); - bool status = ++begin != end; - for (; begin != end && status; ++begin, ++first) - if (!(*first < *begin)) - status = false; - return status; - } + /** Check if the sequence of values is strictly increasing */ + template + inline bool isStrictlyIncreasing(Iter begin, Iter const end) { + if (begin == end) + return false; + Iter first(begin); + bool status = ++begin != end; + for (; begin != end && status; ++begin, ++first) + if (!(*first < *begin)) + status = false; + return status; + } - /** Check if the sequence of values is strictly decreasing */ - template - inline bool isStrictlyDecreasing(Iter begin, Iter const end) - { - if (begin == end) - return false; - Iter first(begin); - bool status = ++begin != end; - for (; begin != end && status; ++begin, ++first) - if (!(*begin < *first)) - status = false; - return status; - } + /** Check if the sequence of values is strictly decreasing */ + template + inline bool isStrictlyDecreasing(Iter begin, Iter const end) { + if (begin == end) + return false; + Iter first(begin); + bool status = ++begin != end; + for (; begin != end && status; ++begin, ++first) + if (!(*begin < *first)) + status = false; + return status; + } - /** Check if the sequence of values is strictly increasing or decreasing */ - template - inline bool isStrictlyMonotonous(Iter const begin, Iter const end) - { - return isStrictlyIncreasing(begin, end) || - isStrictlyDecreasing(begin, end); - } + /** Check if the sequence of values is strictly increasing or decreasing */ + template + inline bool isStrictlyMonotonous(Iter const begin, Iter const end) { + return isStrictlyIncreasing(begin, end) || isStrictlyDecreasing(begin, end); + } - /** Check if the sequence of values is not decreasing */ - template - inline bool isNonDecreasing(Iter begin, Iter const end) - { - if (begin == end) - return false; - Iter first(begin); - bool status = ++begin != end; - for (; begin != end && status; ++begin, ++first) - if (*begin < *first) - status = false; - return status; - } + /** Check if the sequence of values is not decreasing */ + template + inline bool isNonDecreasing(Iter begin, Iter const end) { + if (begin == end) + return false; + Iter first(begin); + bool status = ++begin != end; + for (; begin != end && status; ++begin, ++first) + if (*begin < *first) + status = false; + return status; + } - /** Check if the sequence of values is not increasing */ - template - inline bool isNonIncreasing(Iter begin, Iter const end) - { - if (begin == end) - return false; - Iter first(begin); - bool status = ++begin != end; - for (; begin != end && status; ++begin, ++first) - if (*begin > *first) - status = false; - return status; - } + /** Check if the sequence of values is not increasing */ + template + inline bool isNonIncreasing(Iter begin, Iter const end) { + if (begin == end) + return false; + Iter first(begin); + bool status = ++begin != end; + for (; begin != end && status; ++begin, ++first) + if (*begin > *first) + status = false; + return status; + } - /** + /** // Check if the sequence of values is either non-increasing // or non-decreasing */ - template - inline bool isMonotonous(Iter const begin, Iter const end) - { - return isNonDecreasing(begin, end) || isNonIncreasing(begin, end); - } -} - -#endif // NPSTAT_ISMONOTONOUS_HH_ + template + inline bool isMonotonous(Iter const begin, Iter const end) { + return isNonDecreasing(begin, end) || isNonIncreasing(begin, end); + } +} // namespace npstat +#endif // NPSTAT_ISMONOTONOUS_HH_ diff --git a/JetMETCorrections/InterpolationTables/src/ArrayNDScanner.cc b/JetMETCorrections/InterpolationTables/src/ArrayNDScanner.cc index 5460b1a136c1b..19707ea8c53e2 100644 --- a/JetMETCorrections/InterpolationTables/src/ArrayNDScanner.cc +++ b/JetMETCorrections/InterpolationTables/src/ArrayNDScanner.cc @@ -4,44 +4,40 @@ #include "JetMETCorrections/InterpolationTables/interface/ArrayNDScanner.h" namespace npstat { - void ArrayNDScanner::initialize( - const unsigned* shape, const unsigned lenShape) - { - // Check argument validity - if (lenShape == 0U || lenShape >= CHAR_BIT*sizeof(unsigned long)) - throw npstat::NpstatInvalidArgument( - "In npstat::ArrayNDScanner::initialize: invalid scan shape"); - assert(shape); - for (unsigned j=0; j= CHAR_BIT * sizeof(unsigned long)) + throw npstat::NpstatInvalidArgument("In npstat::ArrayNDScanner::initialize: invalid scan shape"); + assert(shape); + for (unsigned j = 0; j < lenShape; ++j) + if (!shape[j]) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayNDScanner::initialize: " + "number of scans must be positive in each dimension"); - // Initialize the scanner data - state_ = 0UL; - dim_ = lenShape; - strides_[dim_ - 1] = 1UL; - for (unsigned j=dim_ - 1; j>0; --j) - strides_[j - 1] = strides_[j]*shape[j]; - maxState_ = strides_[0]*shape[0]; - } + // Initialize the scanner data + state_ = 0UL; + dim_ = lenShape; + strides_[dim_ - 1] = 1UL; + for (unsigned j = dim_ - 1; j > 0; --j) + strides_[j - 1] = strides_[j] * shape[j]; + maxState_ = strides_[0] * shape[0]; + } - void ArrayNDScanner::getIndex( - unsigned* ix, const unsigned indexBufferLen) const - { - if (indexBufferLen < dim_) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayNDScanner::getIndex: " - "insufficient length of the output buffer"); - if (state_ >= maxState_) throw npstat::NpstatRuntimeError( - "In npstat::ArrayNDScanner::getIndex: invalid scanner state"); - assert(ix); + void ArrayNDScanner::getIndex(unsigned* ix, const unsigned indexBufferLen) const { + if (indexBufferLen < dim_) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayNDScanner::getIndex: " + "insufficient length of the output buffer"); + if (state_ >= maxState_) + throw npstat::NpstatRuntimeError("In npstat::ArrayNDScanner::getIndex: invalid scanner state"); + assert(ix); - unsigned long l = state_; - for (unsigned i=0; i(idx); - l -= (idx * strides_[i]); - } + unsigned long l = state_; + for (unsigned i = 0; i < dim_; ++i) { + unsigned long idx = l / strides_[i]; + ix[i] = static_cast(idx); + l -= (idx * strides_[i]); } -} + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/ArrayRange.cc b/JetMETCorrections/InterpolationTables/src/ArrayRange.cc index 9258a430be8e5..0c0b1285f4a22 100644 --- a/JetMETCorrections/InterpolationTables/src/ArrayRange.cc +++ b/JetMETCorrections/InterpolationTables/src/ArrayRange.cc @@ -2,145 +2,126 @@ #include "JetMETCorrections/InterpolationTables/interface/ArrayRange.h" namespace npstat { - ArrayRange::ArrayRange(const unsigned* ishape, const unsigned imax) - { - if (imax) - { - assert(ishape); - this->reserve(imax); - for (unsigned i=0; ipush_back(Interval(ishape[i])); - } + ArrayRange::ArrayRange(const unsigned* ishape, const unsigned imax) { + if (imax) { + assert(ishape); + this->reserve(imax); + for (unsigned i = 0; i < imax; ++i) + this->push_back(Interval(ishape[i])); } + } - bool ArrayRange::isCompatible(const ArrayShape& ishape) const - { - const unsigned imax = ishape.size(); - return isCompatible(imax ? &ishape[0] : (unsigned*)nullptr, imax); - } + bool ArrayRange::isCompatible(const ArrayShape& ishape) const { + const unsigned imax = ishape.size(); + return isCompatible(imax ? &ishape[0] : (unsigned*)nullptr, imax); + } - bool ArrayRange::isCompatible(const unsigned* ishape, - const unsigned imax) const - { - if (this->size() != imax) - return false; - if (imax) - { - assert(ishape); - for (unsigned i=0; i ishape[i]) - return false; - } - return true; + bool ArrayRange::isCompatible(const unsigned* ishape, const unsigned imax) const { + if (this->size() != imax) + return false; + if (imax) { + assert(ishape); + for (unsigned i = 0; i < imax; ++i) + if ((*this)[i].length() == 0U) + return true; + for (unsigned i = 0; i < imax; ++i) + if ((*this)[i].max() > ishape[i]) + return false; } + return true; + } - bool ArrayRange::operator<(const ArrayRange& r) const - { - const unsigned mysize = this->size(); - const unsigned othersize = r.size(); - if (mysize < othersize) - return true; - if (mysize > othersize) - return false; - for (unsigned i=0; i& left((*this)[i]); - const Interval& right(r[i]); - if (left.min() < right.min()) - return true; - if (left.min() > right.min()) - return false; - if (left.max() < right.max()) - return true; - if (left.max() > right.max()) - return false; - } + bool ArrayRange::operator<(const ArrayRange& r) const { + const unsigned mysize = this->size(); + const unsigned othersize = r.size(); + if (mysize < othersize) + return true; + if (mysize > othersize) + return false; + for (unsigned i = 0; i < mysize; ++i) { + const Interval& left((*this)[i]); + const Interval& right(r[i]); + if (left.min() < right.min()) + return true; + if (left.min() > right.min()) + return false; + if (left.max() < right.max()) + return true; + if (left.max() > right.max()) return false; } + return false; + } - ArrayRange& ArrayRange::stripOuterLayer() - { - const unsigned mysize = this->size(); - for (unsigned i=0; isize(); + for (unsigned i = 0; i < mysize; ++i) { + (*this)[i].setMin((*this)[i].min() + 1U); + const unsigned uplim = (*this)[i].max(); + if (uplim) + (*this)[i].setMax(uplim - 1U); } + return *this; + } - unsigned long ArrayRange::rangeSize() const - { - unsigned long result = 0UL; - const unsigned imax = this->size(); - if (imax) - { - result = 1UL; - for (unsigned i=0; isize(); + if (imax) { + result = 1UL; + for (unsigned i = 0; i < imax; ++i) + result *= (*this)[i].length(); } + return result; + } - ArrayShape ArrayRange::shape() const - { - const unsigned imax = this->size(); - ArrayShape oshape(imax); - for (unsigned i=0; isize(); + ArrayShape oshape(imax); + for (unsigned i = 0; i < imax; ++i) + oshape[i] = (*this)[i].length(); + return oshape; + } - void ArrayRange::lowerLimits(unsigned* limits, - const unsigned limitsLen) const - { - const unsigned imax = this->size(); - if (limitsLen < imax) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayRange::lowerLimits: " - "insufficient size of the output buffer"); - if (imax) - { - assert(limits); - const Interval* data = &(*this)[0]; - for (unsigned i=0; isize(); + if (limitsLen < imax) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayRange::lowerLimits: " + "insufficient size of the output buffer"); + if (imax) { + assert(limits); + const Interval* data = &(*this)[0]; + for (unsigned i = 0; i < imax; ++i) + limits[i] = data[i].min(); } + } - void ArrayRange::upperLimits(unsigned* limits, - const unsigned limitsLen) const - { - const unsigned imax = this->size(); - if (limitsLen < imax) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayRange::upperLimits: " - "insufficient size of the output buffer"); - if (imax) - { - assert(limits); - const Interval* data = &(*this)[0]; - for (unsigned i=0; isize(); + if (limitsLen < imax) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayRange::upperLimits: " + "insufficient size of the output buffer"); + if (imax) { + assert(limits); + const Interval* data = &(*this)[0]; + for (unsigned i = 0; i < imax; ++i) + limits[i] = data[i].max(); } + } - void ArrayRange::rangeLength(unsigned* limits, - const unsigned limitsLen) const - { - const unsigned imax = this->size(); - if (limitsLen < imax) throw npstat::NpstatInvalidArgument( - "In npstat::ArrayRange::rangeLength: " - "insufficient size of the output buffer"); - if (imax) - { - assert(limits); - const Interval* data = &(*this)[0]; - for (unsigned i=0; isize(); + if (limitsLen < imax) + throw npstat::NpstatInvalidArgument( + "In npstat::ArrayRange::rangeLength: " + "insufficient size of the output buffer"); + if (imax) { + assert(limits); + const Interval* data = &(*this)[0]; + for (unsigned i = 0; i < imax; ++i) + limits[i] = data[i].length(); } -} + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/ArrayShape.cc b/JetMETCorrections/InterpolationTables/src/ArrayShape.cc index 126b874ac18d4..f7bc7a64fed00 100644 --- a/JetMETCorrections/InterpolationTables/src/ArrayShape.cc +++ b/JetMETCorrections/InterpolationTables/src/ArrayShape.cc @@ -4,185 +4,175 @@ #include "JetMETCorrections/InterpolationTables/interface/ArrayShape.h" namespace npstat { - ArrayShape makeShape() - { - return ArrayShape(); + ArrayShape makeShape() { return ArrayShape(); } + + ArrayShape makeShape(unsigned i0) { return ArrayShape(1, i0); } + + ArrayShape makeShape(unsigned i0, unsigned i1) { + ArrayShape s; + s.reserve(2); + s.push_back(i0); + s.push_back(i1); + return s; + } + + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2) { + ArrayShape s; + s.reserve(3); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + return s; + } + + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3) { + ArrayShape s; + s.reserve(4); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + return s; + } + + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4) { + ArrayShape s; + s.reserve(5); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + return s; + } + + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5) { + ArrayShape s; + s.reserve(6); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + s.push_back(i5); + return s; + } + + ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6) { + ArrayShape s; + s.reserve(7); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + s.push_back(i5); + s.push_back(i6); + return s; + } + + ArrayShape makeShape( + unsigned i0, unsigned i1, unsigned i2, unsigned i3, unsigned i4, unsigned i5, unsigned i6, unsigned i7) { + ArrayShape s; + s.reserve(8); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + s.push_back(i5); + s.push_back(i6); + s.push_back(i7); + return s; + } + + ArrayShape makeShape(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8) { + ArrayShape s; + s.reserve(9); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + s.push_back(i5); + s.push_back(i6); + s.push_back(i7); + s.push_back(i8); + return s; + } + + ArrayShape makeShape(unsigned i0, + unsigned i1, + unsigned i2, + unsigned i3, + unsigned i4, + unsigned i5, + unsigned i6, + unsigned i7, + unsigned i8, + unsigned i9) { + ArrayShape s; + s.reserve(10); + s.push_back(i0); + s.push_back(i1); + s.push_back(i2); + s.push_back(i3); + s.push_back(i4); + s.push_back(i5); + s.push_back(i6); + s.push_back(i7); + s.push_back(i8); + s.push_back(i9); + return s; + } + + ArrayShape makeShape(const unsigned* indices, const unsigned nIndices) { + ArrayShape s; + if (nIndices) { + assert(indices); + s.reserve(nIndices); + for (unsigned i = 0; i < nIndices; ++i) + s.push_back(indices[i]); } - - ArrayShape makeShape(unsigned i0) - { - return ArrayShape(1, i0); - } - - ArrayShape makeShape(unsigned i0, unsigned i1) - { - ArrayShape s; - s.reserve(2); - s.push_back(i0); - s.push_back(i1); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2) - { - ArrayShape s; - s.reserve(3); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3) - { - ArrayShape s; - s.reserve(4); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4) - { - ArrayShape s; - s.reserve(5); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5) - { - ArrayShape s; - s.reserve(6); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - s.push_back(i5); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6) - { - ArrayShape s; - s.reserve(7); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - s.push_back(i5); - s.push_back(i6); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7) - { - ArrayShape s; - s.reserve(8); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - s.push_back(i5); - s.push_back(i6); - s.push_back(i7); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8) - { - ArrayShape s; - s.reserve(9); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - s.push_back(i5); - s.push_back(i6); - s.push_back(i7); - s.push_back(i8); - return s; - } - - ArrayShape makeShape(unsigned i0, unsigned i1, unsigned i2, unsigned i3, - unsigned i4, unsigned i5, unsigned i6, unsigned i7, - unsigned i8, unsigned i9) - { - ArrayShape s; - s.reserve(10); - s.push_back(i0); - s.push_back(i1); - s.push_back(i2); - s.push_back(i3); - s.push_back(i4); - s.push_back(i5); - s.push_back(i6); - s.push_back(i7); - s.push_back(i8); - s.push_back(i9); - return s; - } - - ArrayShape makeShape(const unsigned* indices, const unsigned nIndices) - { - ArrayShape s; - if (nIndices) - { - assert(indices); - s.reserve(nIndices); - for (unsigned i=0; i sh2[i]) - return false; - return true; + return s; + } + + ArrayShape doubleShape(const ArrayShape& inputShape) { + ArrayShape s(inputShape); + const unsigned len = s.size(); + for (unsigned i = 0; i < len; ++i) + s[i] *= 2U; + return s; + } + + ArrayShape halfShape(const ArrayShape& inputShape) { + ArrayShape s(inputShape); + const unsigned len = s.size(); + for (unsigned i = 0; i < len; ++i) { + if (!(s[i] % 2U == 0)) + throw npstat::NpstatInvalidArgument( + "In npstat::halfShape: array span must be " + "even in each dimension"); + s[i] /= 2U; } -} + return s; + } + + bool isSubShape(const ArrayShape& sh1, const ArrayShape& sh2) { + const unsigned len = sh1.size(); + if (len != sh2.size()) + return false; + for (unsigned i = 0; i < len; ++i) + if (sh1[i] > sh2[i]) + return false; + return true; + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/DualAxis.cc b/JetMETCorrections/InterpolationTables/src/DualAxis.cc index 7fad0e91e53b7..dd6eb623f9806 100644 --- a/JetMETCorrections/InterpolationTables/src/DualAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/DualAxis.cc @@ -5,36 +5,32 @@ #include "Alignment/Geners/interface/CPP11_auto_ptr.hh" namespace npstat { - bool DualAxis::write(std::ostream& of) const - { - unsigned char c = uniform_; - gs::write_pod(of, c); - if (uniform_) - return !of.fail() && u_.classId().write(of) && u_.write(of); - else - return !of.fail() && a_.classId().write(of) && a_.write(of); - } + bool DualAxis::write(std::ostream& of) const { + unsigned char c = uniform_; + gs::write_pod(of, c); + if (uniform_) + return !of.fail() && u_.classId().write(of) && u_.write(of); + else + return !of.fail() && a_.classId().write(of) && a_.write(of); + } - DualAxis* DualAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); + DualAxis* DualAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); - unsigned char c; - gs::read_pod(in, &c); - gs::ClassId clid(in, 1); - if (in.fail()) - throw gs::IOReadFailure("In npstat::DualAxis::read: " - "input stream failure"); - if (c) - { - CPP11_auto_ptr axis(UniformAxis::read(clid, in)); - return new DualAxis(*axis); - } - else - { - CPP11_auto_ptr axis(GridAxis::read(clid, in)); - return new DualAxis(*axis); - } + unsigned char c; + gs::read_pod(in, &c); + gs::ClassId clid(in, 1); + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::DualAxis::read: " + "input stream failure"); + if (c) { + CPP11_auto_ptr axis(UniformAxis::read(clid, in)); + return new DualAxis(*axis); + } else { + CPP11_auto_ptr axis(GridAxis::read(clid, in)); + return new DualAxis(*axis); } -} + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/DualHistoAxis.cc b/JetMETCorrections/InterpolationTables/src/DualHistoAxis.cc index 575fa38447cff..ec1f4e39e41b3 100644 --- a/JetMETCorrections/InterpolationTables/src/DualHistoAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/DualHistoAxis.cc @@ -5,36 +5,32 @@ #include "Alignment/Geners/interface/CPP11_auto_ptr.hh" namespace npstat { - bool DualHistoAxis::write(std::ostream& of) const - { - unsigned char c = uniform_; - gs::write_pod(of, c); - if (uniform_) - return !of.fail() && u_.classId().write(of) && u_.write(of); - else - return !of.fail() && a_.classId().write(of) && a_.write(of); - } + bool DualHistoAxis::write(std::ostream& of) const { + unsigned char c = uniform_; + gs::write_pod(of, c); + if (uniform_) + return !of.fail() && u_.classId().write(of) && u_.write(of); + else + return !of.fail() && a_.classId().write(of) && a_.write(of); + } - DualHistoAxis* DualHistoAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); + DualHistoAxis* DualHistoAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); - unsigned char c; - gs::read_pod(in, &c); - gs::ClassId clid(in, 1); - if (in.fail()) - throw gs::IOReadFailure("In npstat::DualHistoAxis::read: " - "input stream failure"); - if (c) - { - CPP11_auto_ptr axis(HistoAxis::read(clid, in)); - return new DualHistoAxis(*axis); - } - else - { - CPP11_auto_ptr axis(NUHistoAxis::read(clid, in)); - return new DualHistoAxis(*axis); - } + unsigned char c; + gs::read_pod(in, &c); + gs::ClassId clid(in, 1); + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::DualHistoAxis::read: " + "input stream failure"); + if (c) { + CPP11_auto_ptr axis(HistoAxis::read(clid, in)); + return new DualHistoAxis(*axis); + } else { + CPP11_auto_ptr axis(NUHistoAxis::read(clid, in)); + return new DualHistoAxis(*axis); } -} + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/EquidistantSequence.cc b/JetMETCorrections/InterpolationTables/src/EquidistantSequence.cc index d8a0b555c8ccf..338bdbc8745b3 100644 --- a/JetMETCorrections/InterpolationTables/src/EquidistantSequence.cc +++ b/JetMETCorrections/InterpolationTables/src/EquidistantSequence.cc @@ -4,72 +4,58 @@ #include "JetMETCorrections/InterpolationTables/interface/EquidistantSequence.h" namespace npstat { - EquidistantInLinearSpace::EquidistantInLinearSpace( - const double minScale, const double maxScale, const unsigned nScales) - : std::vector() - { - switch (nScales) - { - case 0: + EquidistantInLinearSpace::EquidistantInLinearSpace(const double minScale, + const double maxScale, + const unsigned nScales) + : std::vector() { + switch (nScales) { + case 0: break; - case 1: - { - this->reserve(nScales); - const double sc = (minScale == maxScale ? minScale : - (minScale + maxScale)/2.0); - push_back(sc); - } - break; + case 1: { + this->reserve(nScales); + const double sc = (minScale == maxScale ? minScale : (minScale + maxScale) / 2.0); + push_back(sc); + } break; - default: - { - this->reserve(nScales); - const double step = (maxScale - minScale)/(nScales - 1); - push_back(minScale); - for (unsigned i=1; ireserve(nScales); + const double step = (maxScale - minScale) / (nScales - 1); + push_back(minScale); + for (unsigned i = 1; i < nScales - 1; ++i) + push_back(minScale + i * step); + push_back(maxScale); + } break; } + } - EquidistantInLogSpace::EquidistantInLogSpace( - const double minScale, const double maxScale, const unsigned nScales) - : std::vector() - { - if (nScales) - if (!(minScale > 0.0 && maxScale > 0.0)) - throw npstat::NpstatInvalidArgument( - "In npstat::EquidistantInLogSpace constructor: " - "minimum and maximum scales must be positive"); - switch (nScales) - { - case 0: + EquidistantInLogSpace::EquidistantInLogSpace(const double minScale, const double maxScale, const unsigned nScales) + : std::vector() { + if (nScales) + if (!(minScale > 0.0 && maxScale > 0.0)) + throw npstat::NpstatInvalidArgument( + "In npstat::EquidistantInLogSpace constructor: " + "minimum and maximum scales must be positive"); + switch (nScales) { + case 0: break; - case 1: - { - this->reserve(nScales); - const double sc = (minScale == maxScale ? minScale : - sqrt(minScale*maxScale)); - push_back(sc); - } - break; + case 1: { + this->reserve(nScales); + const double sc = (minScale == maxScale ? minScale : sqrt(minScale * maxScale)); + push_back(sc); + } break; - default: - { - this->reserve(nScales); - const double logmax = log(maxScale); - const double logmin = log(minScale); - const double logstep = (logmax - logmin)/(nScales - 1); - push_back(minScale); - for (unsigned i=1; ireserve(nScales); + const double logmax = log(maxScale); + const double logmin = log(minScale); + const double logstep = (logmax - logmin) / (nScales - 1); + push_back(minScale); + for (unsigned i = 1; i < nScales - 1; ++i) + push_back(exp(logmin + i * logstep)); + push_back(maxScale); + } break; } -} + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/GridAxis.cc b/JetMETCorrections/InterpolationTables/src/GridAxis.cc index 2d8f979a909c1..08ca29e2816fa 100644 --- a/JetMETCorrections/InterpolationTables/src/GridAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/GridAxis.cc @@ -9,186 +9,144 @@ #include "JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h" namespace npstat { - void GridAxis::initialize() - { - if (npt_ <= 1U) throw npstat::NpstatInvalidArgument( - "In npstat::GridAxis::initialize: insufficient number " - "of coordinates (at least 2 are required)"); - std::sort(coords_.begin(), coords_.end()); - const double* c = &coords_[0]; - if (useLogSpace_) - { - logs_.reserve(npt_); - for (unsigned i=0; i& coords, - const bool useLogSpace) - : coords_(coords), - npt_(coords_.size()), - useLogSpace_(useLogSpace) - { - initialize(); + // Can't have duplicate coordinates + for (unsigned i = 1; i < npt_; ++i) + if (c[i] <= c[i - 1U]) + throw npstat::NpstatInvalidArgument( + "In npstat::GridAxis::initialize: " + "all coordinates must be distinct"); + } + + GridAxis::GridAxis(const std::vector& coords, const bool useLogSpace) + : coords_(coords), npt_(coords_.size()), useLogSpace_(useLogSpace) { + initialize(); + } + + GridAxis::GridAxis(const std::vector& coords, const char* label, const bool useLogSpace) + : coords_(coords), label_(label ? label : ""), npt_(coords_.size()), useLogSpace_(useLogSpace) { + initialize(); + } + + std::pair GridAxis::getInterval(const double x) const { + if (useLogSpace_) + if (x <= 0.0) + throw npstat::NpstatDomainError("In GridAxis::getInterval: argument must be positive"); + const double* c = &coords_[0]; + if (x <= c[0]) + return std::pair(0U, 1.0); + else if (x >= c[npt_ - 1U]) + return std::pair(npt_ - 2U, 0.0); + else { + unsigned ibnd = lower_bound(coords_.begin(), coords_.end(), x) - coords_.begin(); + --ibnd; + if (useLogSpace_) { + const double* l = &logs_[0]; + const double w = 1.0 - (log(x) - l[ibnd]) / (l[ibnd + 1U] - l[ibnd]); + return std::pair(ibnd, w); + } else { + const double w = 1.0 - (x - c[ibnd]) / (c[ibnd + 1U] - c[ibnd]); + return std::pair(ibnd, w); + } } - - GridAxis::GridAxis(const std::vector& coords, - const char* label, - const bool useLogSpace) - : coords_(coords), - label_(label ? label : ""), - npt_(coords_.size()), - useLogSpace_(useLogSpace) - { - initialize(); - } - - std::pair GridAxis::getInterval(const double x) const - { - if (useLogSpace_) - if (x <= 0.0) throw npstat::NpstatDomainError( - "In GridAxis::getInterval: argument must be positive"); - const double* c = &coords_[0]; - if (x <= c[0]) - return std::pair(0U, 1.0); - else if (x >= c[npt_ - 1U]) - return std::pair(npt_ - 2U, 0.0); - else - { - unsigned ibnd = lower_bound - (coords_.begin(), coords_.end(), x) - coords_.begin(); - --ibnd; - if (useLogSpace_) - { - const double* l = &logs_[0]; - const double w = 1.0 - (log(x) - l[ibnd])/ - (l[ibnd + 1U] - l[ibnd]); - return std::pair(ibnd, w); - } - else - { - const double w = 1.0 - (x - c[ibnd])/(c[ibnd + 1U] - c[ibnd]); - return std::pair(ibnd, w); - } - } - } - - std::pair GridAxis::linearInterval(const double x) const - { - if (useLogSpace_) - if (x <= 0.0) throw npstat::NpstatDomainError( - "In GridAxis::linearInterval: argument must be positive"); - const double* c = &coords_[0]; - if (x <= c[0]) - { - if (useLogSpace_) - { - const double* l = &logs_[0]; - const double bw = l[1] - l[0]; - return std::pair(0U, 1.0 - (log(x) - l[0])/bw); - } - else - { - const double bw = c[1] - c[0]; - return std::pair(0U, 1.0 - (x - c[0])/bw); - } - } - else if (x >= c[npt_ - 1U]) - { - if (useLogSpace_) - { - const double* l = &logs_[0]; - const double bw = l[npt_ - 1U] - l[npt_ - 2U]; - return std::pair( - npt_ - 2U, (l[npt_ - 1U] - log(x))/bw); - } - else - { - const double bw = c[npt_ - 1U] - c[npt_ - 2U]; - return std::pair( - npt_ - 2U, (c[npt_ - 1U] - x)/bw); - } - } - else - { - unsigned ibnd = lower_bound - (coords_.begin(), coords_.end(), x) - coords_.begin(); - --ibnd; - if (useLogSpace_) - { - const double* l = &logs_[0]; - const double w = 1.0 - (log(x) - l[ibnd])/ - (l[ibnd + 1U] - l[ibnd]); - return std::pair(ibnd, w); - } - else - { - const double w = 1.0 - (x - c[ibnd])/(c[ibnd + 1U] - c[ibnd]); - return std::pair(ibnd, w); - } - } - } - - bool GridAxis::write(std::ostream& of) const - { - // It is unlikely that this object will be written in isolation. - // So, do not bother with too many checks. - gs::write_pod_vector(of, coords_); - gs::write_pod(of, label_); - gs::write_pod(of, useLogSpace_); - return !of.fail(); - } - - GridAxis* GridAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); - - std::vector coords; - gs::read_pod_vector(in, &coords); - - std::string label; - gs::read_pod(in, &label); - - bool useLogSpace; - gs::read_pod(in, &useLogSpace); - - if (in.fail()) - throw gs::IOReadFailure("In npstat::GridAxis::read: " - "input stream failure"); - return new GridAxis(coords, label.c_str(), useLogSpace); - } - - bool GridAxis::operator==(const GridAxis& r) const - { - return useLogSpace_ == r.useLogSpace_ && - coords_ == r.coords_ && - label_ == r.label_; - } - - bool GridAxis::isClose(const GridAxis& r, const double tol) const - { - if (!(useLogSpace_ == r.useLogSpace_ && - label_ == r.label_)) - return false; - const unsigned long n = coords_.size(); - if (n != r.coords_.size()) - return false; - for (unsigned long i=0; i GridAxis::linearInterval(const double x) const { + if (useLogSpace_) + if (x <= 0.0) + throw npstat::NpstatDomainError("In GridAxis::linearInterval: argument must be positive"); + const double* c = &coords_[0]; + if (x <= c[0]) { + if (useLogSpace_) { + const double* l = &logs_[0]; + const double bw = l[1] - l[0]; + return std::pair(0U, 1.0 - (log(x) - l[0]) / bw); + } else { + const double bw = c[1] - c[0]; + return std::pair(0U, 1.0 - (x - c[0]) / bw); + } + } else if (x >= c[npt_ - 1U]) { + if (useLogSpace_) { + const double* l = &logs_[0]; + const double bw = l[npt_ - 1U] - l[npt_ - 2U]; + return std::pair(npt_ - 2U, (l[npt_ - 1U] - log(x)) / bw); + } else { + const double bw = c[npt_ - 1U] - c[npt_ - 2U]; + return std::pair(npt_ - 2U, (c[npt_ - 1U] - x) / bw); + } + } else { + unsigned ibnd = lower_bound(coords_.begin(), coords_.end(), x) - coords_.begin(); + --ibnd; + if (useLogSpace_) { + const double* l = &logs_[0]; + const double w = 1.0 - (log(x) - l[ibnd]) / (l[ibnd + 1U] - l[ibnd]); + return std::pair(ibnd, w); + } else { + const double w = 1.0 - (x - c[ibnd]) / (c[ibnd + 1U] - c[ibnd]); + return std::pair(ibnd, w); + } } -} + } + + bool GridAxis::write(std::ostream& of) const { + // It is unlikely that this object will be written in isolation. + // So, do not bother with too many checks. + gs::write_pod_vector(of, coords_); + gs::write_pod(of, label_); + gs::write_pod(of, useLogSpace_); + return !of.fail(); + } + + GridAxis* GridAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); + + std::vector coords; + gs::read_pod_vector(in, &coords); + + std::string label; + gs::read_pod(in, &label); + + bool useLogSpace; + gs::read_pod(in, &useLogSpace); + + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::GridAxis::read: " + "input stream failure"); + return new GridAxis(coords, label.c_str(), useLogSpace); + } + + bool GridAxis::operator==(const GridAxis& r) const { + return useLogSpace_ == r.useLogSpace_ && coords_ == r.coords_ && label_ == r.label_; + } + + bool GridAxis::isClose(const GridAxis& r, const double tol) const { + if (!(useLogSpace_ == r.useLogSpace_ && label_ == r.label_)) + return false; + const unsigned long n = coords_.size(); + if (n != r.coords_.size()) + return false; + for (unsigned long i = 0; i < n; ++i) + if (!closeWithinTolerance(coords_[i], r.coords_[i], tol)) + return false; + return true; + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/HistoAxis.cc b/JetMETCorrections/InterpolationTables/src/HistoAxis.cc index 0f3156cdb70e2..1949a879e8f40 100644 --- a/JetMETCorrections/InterpolationTables/src/HistoAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/HistoAxis.cc @@ -10,163 +10,132 @@ #include "JetMETCorrections/InterpolationTables/interface/HistoAxis.h" namespace npstat { - HistoAxis::HistoAxis(const unsigned nbins, const double min, - const double max, const char* label) - : min_(min), max_(max), label_(label ? label : ""), nBins_(nbins) - { - if (!(nBins_ && nBins_ < UINT_MAX/2U - 1U)) - throw npstat::NpstatInvalidArgument("In npstat::HistoAxis constructor: " - "number of bins is out of range"); - if (min_ > max_) - std::swap(min_, max_); - bw_ = (max_ - min_)/nBins_; + HistoAxis::HistoAxis(const unsigned nbins, const double min, const double max, const char* label) + : min_(min), max_(max), label_(label ? label : ""), nBins_(nbins) { + if (!(nBins_ && nBins_ < UINT_MAX / 2U - 1U)) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoAxis constructor: " + "number of bins is out of range"); + if (min_ > max_) + std::swap(min_, max_); + bw_ = (max_ - min_) / nBins_; + } + + HistoAxis HistoAxis::rebin(const unsigned nbins) const { return HistoAxis(nbins, min_, max_, label_.c_str()); } + + bool HistoAxis::isClose(const HistoAxis& r, const double tol) const { + return closeWithinTolerance(min_, r.min_, tol) && closeWithinTolerance(max_, r.max_, tol) && label_ == r.label_ && + nBins_ == r.nBins_; + } + + bool HistoAxis::operator==(const HistoAxis& r) const { + return min_ == r.min_ && max_ == r.max_ && label_ == r.label_ && nBins_ == r.nBins_; + } + + bool HistoAxis::operator!=(const HistoAxis& r) const { return !(*this == r); } + + int HistoAxis::binNumber(const double x) const { + if (bw_) { + int binnum = static_cast(floor((x - min_) / bw_)); + if (x >= max_) { + if (binnum < static_cast(nBins_)) + binnum = nBins_; + } else { + if (binnum >= static_cast(nBins_)) + binnum = nBins_ - 1U; + } + return binnum; + } else { + if (x < min_) + return -1; + else + return nBins_; } - - HistoAxis HistoAxis::rebin(const unsigned nbins) const - { - return HistoAxis(nbins, min_, max_, label_.c_str()); - } - - bool HistoAxis::isClose(const HistoAxis& r, const double tol) const - { - return closeWithinTolerance(min_, r.min_, tol) && - closeWithinTolerance(max_, r.max_, tol) && - label_ == r.label_ && - nBins_ == r.nBins_; - } - - bool HistoAxis::operator==(const HistoAxis& r) const - { - return min_ == r.min_ && - max_ == r.max_ && - label_ == r.label_ && - nBins_ == r.nBins_; - } - - bool HistoAxis::operator!=(const HistoAxis& r) const - { - return !(*this == r); - } - - int HistoAxis::binNumber(const double x) const - { - if (bw_) - { - int binnum = static_cast(floor((x - min_)/bw_)); - if (x >= max_) - { - if (binnum < static_cast(nBins_)) - binnum = nBins_; - } - else - { - if (binnum >= static_cast(nBins_)) - binnum = nBins_ - 1U; - } - return binnum; - } - else - { - if (x < min_) - return -1; - else - return nBins_; - } - } - - unsigned HistoAxis::closestValidBin(const double x) const - { - if (x <= min_) - return 0U; - else if (bw_ && x < max_) - { - const unsigned binnum = static_cast(floor((x-min_)/bw_)); - if (binnum < nBins_) - return binnum; - } - return nBins_ - 1U; - } - - LinearMapper1d HistoAxis::binNumberMapper(const bool mapLeftEdgeTo0) const - { - if (!bw_) throw npstat::NpstatDomainError( - "In npstat::HistoAxis::binNumberMapper: " - "bin width is zero. Mapper can not be constructed."); - const double base = mapLeftEdgeTo0 ? min_/bw_ : min_/bw_ + 0.5; - return LinearMapper1d(1.0/bw_, -base); - } - - CircularMapper1d HistoAxis::kernelScanMapper(const bool doubleRange) const - { - if (!bw_) throw npstat::NpstatDomainError( - "In npstat::HistoAxis::kernelScanMapper: " - "bin width is zero. Mapper can not be constructed."); - double range = max_ - min_; - if (doubleRange) - range *= 2.0; - return CircularMapper1d(bw_, 0.0, range); + } + + unsigned HistoAxis::closestValidBin(const double x) const { + if (x <= min_) + return 0U; + else if (bw_ && x < max_) { + const unsigned binnum = static_cast(floor((x - min_) / bw_)); + if (binnum < nBins_) + return binnum; } - - unsigned HistoAxis::overflowIndexWeighted( - const double x, unsigned* binNumber, double *weight) const - { - if (x < min_) - return 0U; - else if (x >= max_) - return 2U; - else - { - if (nBins_ <= 1U) throw npstat::NpstatInvalidArgument( - "In npstat::HistoAxis::overflowIndexWeighted: " - "must have more than one bin"); - const double dbin = (x - min_)/bw_; - if (dbin <= 0.5) - { - *binNumber = 0; - *weight = 1.0; - } - else if (dbin >= nBins_ - 0.5) - { - *binNumber = nBins_ - 2; - *weight = 0.0; - } - else - { - const unsigned bin = static_cast(dbin - 0.5); - *binNumber = bin >= nBins_ - 1U ? nBins_ - 2U : bin; - *weight = 1.0 - (dbin - 0.5 - *binNumber); - } - return 1U; - } - } - - bool HistoAxis::write(std::ostream& of) const - { - gs::write_pod(of, min_); - gs::write_pod(of, max_); - gs::write_pod(of, label_); - gs::write_pod(of, nBins_); - return !of.fail(); - } - - HistoAxis* HistoAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); - - double min = 0.0, max = 0.0; - std::string label; - unsigned nBins = 0; - - gs::read_pod(in, &min); - gs::read_pod(in, &max); - gs::read_pod(in, &label); - gs::read_pod(in, &nBins); - - if (!in.fail()) - return new HistoAxis(nBins, min, max, label.c_str()); - else - throw gs::IOReadFailure("In npstat::HistoAxis::read: " - "input stream failure"); + return nBins_ - 1U; + } + + LinearMapper1d HistoAxis::binNumberMapper(const bool mapLeftEdgeTo0) const { + if (!bw_) + throw npstat::NpstatDomainError( + "In npstat::HistoAxis::binNumberMapper: " + "bin width is zero. Mapper can not be constructed."); + const double base = mapLeftEdgeTo0 ? min_ / bw_ : min_ / bw_ + 0.5; + return LinearMapper1d(1.0 / bw_, -base); + } + + CircularMapper1d HistoAxis::kernelScanMapper(const bool doubleRange) const { + if (!bw_) + throw npstat::NpstatDomainError( + "In npstat::HistoAxis::kernelScanMapper: " + "bin width is zero. Mapper can not be constructed."); + double range = max_ - min_; + if (doubleRange) + range *= 2.0; + return CircularMapper1d(bw_, 0.0, range); + } + + unsigned HistoAxis::overflowIndexWeighted(const double x, unsigned* binNumber, double* weight) const { + if (x < min_) + return 0U; + else if (x >= max_) + return 2U; + else { + if (nBins_ <= 1U) + throw npstat::NpstatInvalidArgument( + "In npstat::HistoAxis::overflowIndexWeighted: " + "must have more than one bin"); + const double dbin = (x - min_) / bw_; + if (dbin <= 0.5) { + *binNumber = 0; + *weight = 1.0; + } else if (dbin >= nBins_ - 0.5) { + *binNumber = nBins_ - 2; + *weight = 0.0; + } else { + const unsigned bin = static_cast(dbin - 0.5); + *binNumber = bin >= nBins_ - 1U ? nBins_ - 2U : bin; + *weight = 1.0 - (dbin - 0.5 - *binNumber); + } + return 1U; } -} + } + + bool HistoAxis::write(std::ostream& of) const { + gs::write_pod(of, min_); + gs::write_pod(of, max_); + gs::write_pod(of, label_); + gs::write_pod(of, nBins_); + return !of.fail(); + } + + HistoAxis* HistoAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); + + double min = 0.0, max = 0.0; + std::string label; + unsigned nBins = 0; + + gs::read_pod(in, &min); + gs::read_pod(in, &max); + gs::read_pod(in, &label); + gs::read_pod(in, &nBins); + + if (!in.fail()) + return new HistoAxis(nBins, min, max, label.c_str()); + else + throw gs::IOReadFailure( + "In npstat::HistoAxis::read: " + "input stream failure"); + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/NUHistoAxis.cc b/JetMETCorrections/InterpolationTables/src/NUHistoAxis.cc index 15b2093442f39..a5f6631ea155d 100644 --- a/JetMETCorrections/InterpolationTables/src/NUHistoAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/NUHistoAxis.cc @@ -12,178 +12,149 @@ #include "JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h" namespace npstat { - NUHistoAxis::NUHistoAxis(const std::vector& binEdges, - const char* label) - : binEdges_(binEdges), nBins_(binEdges.size() - 1U), uniform_(false) - { - if (!(binEdges_.size() > 1U && binEdges_.size() < UINT_MAX/2U)) - throw npstat::NpstatInvalidArgument("In npstat::NUHistoAxis constructor: " - "number of bin edges is out of range"); - std::sort(binEdges_.begin(), binEdges_.end()); - min_ = binEdges_[0]; - max_ = binEdges_[nBins_]; - if (label) - label_ = std::string(label); + NUHistoAxis::NUHistoAxis(const std::vector& binEdges, const char* label) + : binEdges_(binEdges), nBins_(binEdges.size() - 1U), uniform_(false) { + if (!(binEdges_.size() > 1U && binEdges_.size() < UINT_MAX / 2U)) + throw npstat::NpstatInvalidArgument( + "In npstat::NUHistoAxis constructor: " + "number of bin edges is out of range"); + std::sort(binEdges_.begin(), binEdges_.end()); + min_ = binEdges_[0]; + max_ = binEdges_[nBins_]; + if (label) + label_ = std::string(label); + } + + NUHistoAxis::NUHistoAxis(const unsigned nBins, const double min, const double max, const char* label) + : min_(min), max_(max), nBins_(nBins), uniform_(true) { + if (!(nBins_ && nBins_ < UINT_MAX / 2U - 1U)) + throw npstat::NpstatInvalidArgument( + "In npstat::NUHistoAxis constructor: " + "number of bins is out of range"); + if (min_ > max_) + std::swap(min_, max_); + binEdges_ = EquidistantInLinearSpace(min_, max_, nBins + 1U); + if (label) + label_ = std::string(label); + } + + NUHistoAxis NUHistoAxis::rebin(const unsigned newBins) const { + return NUHistoAxis(newBins, min_, max_, label_.c_str()); + } + + bool NUHistoAxis::isClose(const NUHistoAxis& r, const double tol) const { + if (!(closeWithinTolerance(min_, r.min_, tol) && closeWithinTolerance(max_, r.max_, tol) && label_ == r.label_ && + nBins_ == r.nBins_ && uniform_ == r.uniform_)) + return false; + for (unsigned i = 0; i < nBins_; ++i) + if (!closeWithinTolerance(binEdges_[i], r.binEdges_[i], tol)) + return false; + return true; + } + + bool NUHistoAxis::operator==(const NUHistoAxis& r) const { + return min_ == r.min_ && max_ == r.max_ && label_ == r.label_ && nBins_ == r.nBins_ && binEdges_ == r.binEdges_ && + uniform_ == r.uniform_; + } + + bool NUHistoAxis::operator!=(const NUHistoAxis& r) const { return !(*this == r); } + + int NUHistoAxis::binNumber(const double x) const { + const int delta = std::upper_bound(binEdges_.begin(), binEdges_.end(), x) - binEdges_.begin(); + return delta - 1; + } + + double NUHistoAxis::fltBinNumber(const double x, const bool mapLeftEdgeTo0) const { + const int delta = std::upper_bound(binEdges_.begin(), binEdges_.end(), x) - binEdges_.begin(); + const int binnum = delta - 1; + + if (binnum < 0) { + const double left = binEdges_[0]; + const double right = binEdges_[1]; + double bval = (x - left) / (right - left); + if (!mapLeftEdgeTo0) + bval -= 0.5; + if (bval < -1.0) + bval = -1.0; + return bval; + } else if (static_cast(binnum) >= nBins_) { + const double left = binEdges_[nBins_ - 1U]; + const double right = binEdges_[nBins_]; + double bval = nBins_ - 1U + (x - left) / (right - left); + if (!mapLeftEdgeTo0) + bval -= 0.5; + if (bval > static_cast(nBins_)) + bval = nBins_; + return bval; + } else { + const double left = binEdges_[binnum]; + const double right = binEdges_[delta]; + if (mapLeftEdgeTo0) + return binnum + (x - left) / (right - left); + else { + // It is not obvious what is best to do here. + // The following works to preserve interpolation + // of 0th order. The commented out snippet below + // would instead connect bin centers by straight + // lines during interpolation. + return binnum + (x - left) / (right - left) - 0.5; + + // Bin center is mapped to binnum. + // Bin center of the next bin is mapped to binnum + 1. + // Bin center of the previous bin is mapped to binnum - 1. + // + // const double binCenter = (left + right)/2.0; + // if ((binnum == 0 && x <= binCenter) || + // (static_cast(binnum) == nBins_ - 1 && x >= binCenter)) + // return binnum + (x - left)/(right - left) - 0.5; + // else if (x <= binCenter) + // { + // const double otherBinCenter = (left + binEdges_[binnum - 1])/2.0; + // return binnum + (x - binCenter)/(binCenter - otherBinCenter); + // } + // else + // { + // const double otherBinCenter = (right + binEdges_[binnum + 2])/2.0; + // return binnum + (x - binCenter)/(otherBinCenter - binCenter); + // } + } } - - NUHistoAxis::NUHistoAxis(const unsigned nBins, - const double min, const double max, - const char* label) - : min_(min), max_(max), nBins_(nBins), uniform_(true) - { - if (!(nBins_ && nBins_ < UINT_MAX/2U - 1U)) - throw npstat::NpstatInvalidArgument("In npstat::NUHistoAxis constructor: " - "number of bins is out of range"); - if (min_ > max_) - std::swap(min_, max_); - binEdges_ = EquidistantInLinearSpace(min_, max_, nBins+1U); - if (label) - label_ = std::string(label); - } - - NUHistoAxis NUHistoAxis::rebin(const unsigned newBins) const - { - return NUHistoAxis(newBins, min_, max_, label_.c_str()); - } - - bool NUHistoAxis::isClose(const NUHistoAxis& r, const double tol) const - { - if (!(closeWithinTolerance(min_, r.min_, tol) && - closeWithinTolerance(max_, r.max_, tol) && - label_ == r.label_ && - nBins_ == r.nBins_ && - uniform_ == r.uniform_)) - return false; - for (unsigned i=0; i(binnum) >= nBins_) - { - const double left = binEdges_[nBins_ - 1U]; - const double right = binEdges_[nBins_]; - double bval = nBins_ - 1U + (x - left)/(right - left); - if (!mapLeftEdgeTo0) - bval -= 0.5; - if (bval > static_cast(nBins_)) - bval = nBins_; - return bval; - } - else - { - const double left = binEdges_[binnum]; - const double right = binEdges_[delta]; - if (mapLeftEdgeTo0) - return binnum + (x - left)/(right - left); - else - { - // It is not obvious what is best to do here. - // The following works to preserve interpolation - // of 0th order. The commented out snippet below - // would instead connect bin centers by straight - // lines during interpolation. - return binnum + (x - left)/(right - left) - 0.5; - - // Bin center is mapped to binnum. - // Bin center of the next bin is mapped to binnum + 1. - // Bin center of the previous bin is mapped to binnum - 1. - // - // const double binCenter = (left + right)/2.0; - // if ((binnum == 0 && x <= binCenter) || - // (static_cast(binnum) == nBins_ - 1 && x >= binCenter)) - // return binnum + (x - left)/(right - left) - 0.5; - // else if (x <= binCenter) - // { - // const double otherBinCenter = (left + binEdges_[binnum - 1])/2.0; - // return binnum + (x - binCenter)/(binCenter - otherBinCenter); - // } - // else - // { - // const double otherBinCenter = (right + binEdges_[binnum + 2])/2.0; - // return binnum + (x - binCenter)/(otherBinCenter - binCenter); - // } - } - } - } - - unsigned NUHistoAxis::closestValidBin(const double x) const - { - const int delta = std::upper_bound(binEdges_.begin(), binEdges_.end(), x) - - binEdges_.begin(); - int binnum = delta - 1; - if (binnum < 0) - binnum = 0; - else if (static_cast(binnum) >= nBins_) - binnum = nBins_ - 1U; - return binnum; - } - - bool NUHistoAxis::write(std::ostream& of) const - { - gs::write_pod_vector(of, binEdges_); - gs::write_pod(of, label_); - unsigned char c = uniform_; - gs::write_pod(of, c); - return !of.fail(); - } - - NUHistoAxis* NUHistoAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); - - std::vector binEdges; - std::string label; - unsigned char unif; - gs::read_pod_vector(in, &binEdges); - gs::read_pod(in, &label); - gs::read_pod(in, &unif); - if (in.fail()) - throw gs::IOReadFailure("In npstat::UHistoAxis::read: " - "input stream failure"); - NUHistoAxis* result = new NUHistoAxis(binEdges, label.c_str()); - result->uniform_ = unif; - return result; - } -} + } + + unsigned NUHistoAxis::closestValidBin(const double x) const { + const int delta = std::upper_bound(binEdges_.begin(), binEdges_.end(), x) - binEdges_.begin(); + int binnum = delta - 1; + if (binnum < 0) + binnum = 0; + else if (static_cast(binnum) >= nBins_) + binnum = nBins_ - 1U; + return binnum; + } + + bool NUHistoAxis::write(std::ostream& of) const { + gs::write_pod_vector(of, binEdges_); + gs::write_pod(of, label_); + unsigned char c = uniform_; + gs::write_pod(of, c); + return !of.fail(); + } + + NUHistoAxis* NUHistoAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); + + std::vector binEdges; + std::string label; + unsigned char unif; + gs::read_pod_vector(in, &binEdges); + gs::read_pod(in, &label); + gs::read_pod(in, &unif); + if (in.fail()) + throw gs::IOReadFailure( + "In npstat::UHistoAxis::read: " + "input stream failure"); + NUHistoAxis* result = new NUHistoAxis(binEdges, label.c_str()); + result->uniform_ = unif; + return result; + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc b/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc index d81384807d3da..9d8889c87eef2 100644 --- a/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc +++ b/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctor.cc @@ -3,25 +3,20 @@ #include "JetMETCorrections/InterpolationTables/interface/StorableMultivariateFunctorReader.h" namespace npstat { - void StorableMultivariateFunctor::validateDescription( - const std::string& description) const - { - if (description_ != description) - { - std::string mesage = - "In StorableMultivariateFunctor::validateDescription: " - "argument description string \""; - mesage += description; - mesage += "\" is different from the object description string \""; - mesage += description_; - mesage += "\""; - throw npstat::NpstatRuntimeError(mesage); - } + void StorableMultivariateFunctor::validateDescription(const std::string& description) const { + if (description_ != description) { + std::string mesage = + "In StorableMultivariateFunctor::validateDescription: " + "argument description string \""; + mesage += description; + mesage += "\" is different from the object description string \""; + mesage += description_; + mesage += "\""; + throw npstat::NpstatRuntimeError(mesage); } + } - StorableMultivariateFunctor* StorableMultivariateFunctor::read( - const gs::ClassId& id, std::istream& in) - { - return StaticStorableMultivariateFunctorReader::instance().read(id, in); - } -} + StorableMultivariateFunctor* StorableMultivariateFunctor::read(const gs::ClassId& id, std::istream& in) { + return StaticStorableMultivariateFunctorReader::instance().read(id, in); + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctorReader.cc b/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctorReader.cc index 2acd3d0c37eee..3ed3610bea3a8 100644 --- a/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctorReader.cc +++ b/JetMETCorrections/InterpolationTables/src/StorableMultivariateFunctorReader.cc @@ -6,29 +6,28 @@ #include "JetMETCorrections/InterpolationTables/interface/InterpolationFunctorInstances.h" #include "JetMETCorrections/InterpolationTables/interface/HistoNDFunctorInstances.h" -// Simple macro for adding a reader for a class derived from +// Simple macro for adding a reader for a class derived from // StorableMultivariateFunctor -#define add_reader(Derived) do { \ - const gs::ClassId& id(gs::ClassId::makeId()); \ - (*this)[id.name()] = \ - new gs::ConcreteReader(); \ -} while(0); +#define add_reader(Derived) \ + do { \ + const gs::ClassId& id(gs::ClassId::makeId()); \ + (*this)[id.name()] = new gs::ConcreteReader(); \ + } while (0); namespace npstat { - StorableMultivariateFunctorReader::StorableMultivariateFunctorReader() - { - add_reader(DoubleInterpolationFunctor); - add_reader(DoubleUAInterpolationFunctor); - add_reader(DoubleNUInterpolationFunctor); - add_reader(FloatInterpolationFunctor); - add_reader(FloatUAInterpolationFunctor); - add_reader(FloatNUInterpolationFunctor); + StorableMultivariateFunctorReader::StorableMultivariateFunctorReader() { + add_reader(DoubleInterpolationFunctor); + add_reader(DoubleUAInterpolationFunctor); + add_reader(DoubleNUInterpolationFunctor); + add_reader(FloatInterpolationFunctor); + add_reader(FloatUAInterpolationFunctor); + add_reader(FloatNUInterpolationFunctor); - add_reader(DoubleHistoNDFunctor); - add_reader(DoubleUAHistoNDFunctor); - add_reader(DoubleNUHistoNDFunctor); - add_reader(FloatHistoNDFunctor); - add_reader(FloatUAHistoNDFunctor); - add_reader(FloatNUHistoNDFunctor); - } -} + add_reader(DoubleHistoNDFunctor); + add_reader(DoubleUAHistoNDFunctor); + add_reader(DoubleNUHistoNDFunctor); + add_reader(FloatHistoNDFunctor); + add_reader(FloatUAHistoNDFunctor); + add_reader(FloatNUHistoNDFunctor); + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/UniformAxis.cc b/JetMETCorrections/InterpolationTables/src/UniformAxis.cc index fdc860ea85d14..ca8fe3e744aa9 100644 --- a/JetMETCorrections/InterpolationTables/src/UniformAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/UniformAxis.cc @@ -10,128 +10,111 @@ #include "JetMETCorrections/InterpolationTables/interface/closeWithinTolerance.h" namespace npstat { - UniformAxis::UniformAxis(const unsigned nCoords, - const double min, const double max, - const char* label) - : min_(min), max_(max), label_(label ? label : ""), npt_(nCoords) - { - if (!(npt_ > 1U && npt_ < UINT_MAX/2U - 1U)) - throw npstat::NpstatInvalidArgument("In npstat::UniformAxis constructor: " - "number of points is out of range"); - if (min_ > max_) - std::swap(min_, max_); - bw_ = (max_ - min_)/(npt_ - 1U); - if (max_ == min_) - throw npstat::NpstatInvalidArgument( - "In npstat::UniformAxis constructor: " - "minimum and maximum must be distinct"); - } + UniformAxis::UniformAxis(const unsigned nCoords, const double min, const double max, const char* label) + : min_(min), max_(max), label_(label ? label : ""), npt_(nCoords) { + if (!(npt_ > 1U && npt_ < UINT_MAX / 2U - 1U)) + throw npstat::NpstatInvalidArgument( + "In npstat::UniformAxis constructor: " + "number of points is out of range"); + if (min_ > max_) + std::swap(min_, max_); + bw_ = (max_ - min_) / (npt_ - 1U); + if (max_ == min_) + throw npstat::NpstatInvalidArgument( + "In npstat::UniformAxis constructor: " + "minimum and maximum must be distinct"); + } - std::pair UniformAxis::getInterval(const double x) const - { - if (x <= min_) - return std::pair(0U, 1.0); - else if (x >= max_) - return std::pair(npt_ - 2U, 0.0); - else - { - unsigned binnum = static_cast(floor((x - min_)/bw_)); - if (binnum > npt_ - 2U) - binnum = npt_ - 2U; - double w = binnum + 1.0 - (x - min_)/bw_; - if (w < 0.0) - w = 0.0; - else if (w > 1.0) - w = 1.0; - return std::pair(binnum, w); - } + std::pair UniformAxis::getInterval(const double x) const { + if (x <= min_) + return std::pair(0U, 1.0); + else if (x >= max_) + return std::pair(npt_ - 2U, 0.0); + else { + unsigned binnum = static_cast(floor((x - min_) / bw_)); + if (binnum > npt_ - 2U) + binnum = npt_ - 2U; + double w = binnum + 1.0 - (x - min_) / bw_; + if (w < 0.0) + w = 0.0; + else if (w > 1.0) + w = 1.0; + return std::pair(binnum, w); } + } - std::pair UniformAxis::linearInterval(const double x) const - { - if (x <= min_) - return std::pair(0U, 1.0 - (x - min_)/bw_); - else if (x >= max_) - return std::pair(npt_ - 2U, (max_ - x)/bw_); - else - { - unsigned binnum = static_cast(floor((x - min_)/bw_)); - if (binnum > npt_ - 2U) - binnum = npt_ - 2U; - double w = binnum + 1.0 - (x - min_)/bw_; - if (w < 0.0) - w = 0.0; - else if (w > 1.0) - w = 1.0; - return std::pair(binnum, w); - } + std::pair UniformAxis::linearInterval(const double x) const { + if (x <= min_) + return std::pair(0U, 1.0 - (x - min_) / bw_); + else if (x >= max_) + return std::pair(npt_ - 2U, (max_ - x) / bw_); + else { + unsigned binnum = static_cast(floor((x - min_) / bw_)); + if (binnum > npt_ - 2U) + binnum = npt_ - 2U; + double w = binnum + 1.0 - (x - min_) / bw_; + if (w < 0.0) + w = 0.0; + else if (w > 1.0) + w = 1.0; + return std::pair(binnum, w); } + } - std::vector UniformAxis::coords() const - { - std::vector vec; - vec.reserve(npt_); - const unsigned nptm1 = npt_ - 1U; - for (unsigned i=0; i UniformAxis::coords() const { + std::vector vec; + vec.reserve(npt_); + const unsigned nptm1 = npt_ - 1U; + for (unsigned i = 0; i < nptm1; ++i) + vec.push_back(min_ + bw_ * i); + vec.push_back(max_); + return vec; + } - double UniformAxis::coordinate(const unsigned i) const - { - if (i >= npt_) - throw npstat::NpstatOutOfRange( - "In npstat::UniformAxis::coordinate: index out of range"); - if (i == npt_ - 1U) - return max_; - else - return min_ + bw_*i; - } + double UniformAxis::coordinate(const unsigned i) const { + if (i >= npt_) + throw npstat::NpstatOutOfRange("In npstat::UniformAxis::coordinate: index out of range"); + if (i == npt_ - 1U) + return max_; + else + return min_ + bw_ * i; + } - bool UniformAxis::isClose(const UniformAxis& r, const double tol) const - { - return closeWithinTolerance(min_, r.min_, tol) && - closeWithinTolerance(max_, r.max_, tol) && - label_ == r.label_ && - npt_ == r.npt_; - } + bool UniformAxis::isClose(const UniformAxis& r, const double tol) const { + return closeWithinTolerance(min_, r.min_, tol) && closeWithinTolerance(max_, r.max_, tol) && label_ == r.label_ && + npt_ == r.npt_; + } - bool UniformAxis::operator==(const UniformAxis& r) const - { - return min_ == r.min_ && - max_ == r.max_ && - label_ == r.label_ && - npt_ == r.npt_; - } + bool UniformAxis::operator==(const UniformAxis& r) const { + return min_ == r.min_ && max_ == r.max_ && label_ == r.label_ && npt_ == r.npt_; + } - bool UniformAxis::write(std::ostream& of) const - { - gs::write_pod(of, min_); - gs::write_pod(of, max_); - gs::write_pod(of, label_); - gs::write_pod(of, npt_); - return !of.fail(); - } + bool UniformAxis::write(std::ostream& of) const { + gs::write_pod(of, min_); + gs::write_pod(of, max_); + gs::write_pod(of, label_); + gs::write_pod(of, npt_); + return !of.fail(); + } - UniformAxis* UniformAxis::read(const gs::ClassId& id, std::istream& in) - { - static const gs::ClassId current(gs::ClassId::makeId()); - current.ensureSameId(id); + UniformAxis* UniformAxis::read(const gs::ClassId& id, std::istream& in) { + static const gs::ClassId current(gs::ClassId::makeId()); + current.ensureSameId(id); - double min = 0.0, max = 0.0; - std::string label; - unsigned nBins = 0; + double min = 0.0, max = 0.0; + std::string label; + unsigned nBins = 0; - gs::read_pod(in, &min); - gs::read_pod(in, &max); - gs::read_pod(in, &label); - gs::read_pod(in, &nBins); + gs::read_pod(in, &min); + gs::read_pod(in, &max); + gs::read_pod(in, &label); + gs::read_pod(in, &nBins); - if (!in.fail()) - return new UniformAxis(nBins, min, max, label.c_str()); - else - throw gs::IOReadFailure("In npstat::UniformAxis::read: " - "input stream failure"); - } -} + if (!in.fail()) + return new UniformAxis(nBins, min, max, label.c_str()); + else + throw gs::IOReadFailure( + "In npstat::UniformAxis::read: " + "input stream failure"); + } +} // namespace npstat diff --git a/JetMETCorrections/InterpolationTables/src/convertAxis.cc b/JetMETCorrections/InterpolationTables/src/convertAxis.cc index 5683b34800253..2c17f8fef9173 100644 --- a/JetMETCorrections/InterpolationTables/src/convertAxis.cc +++ b/JetMETCorrections/InterpolationTables/src/convertAxis.cc @@ -3,53 +3,49 @@ #include "JetMETCorrections/InterpolationTables/interface/convertAxis.h" namespace npstat { - HistoAxis convertToHistoAxis(const UniformAxis& gridAxis) - { - const unsigned nBins = gridAxis.nCoords(); - const double xmin = gridAxis.min(); - const double xmax = gridAxis.max(); - const double hbw = 0.5*(xmax - xmin)/(nBins - 1U); - HistoAxis ax(nBins, xmin-hbw, xmax+hbw, gridAxis.label().c_str()); - return ax; - } - - UniformAxis convertToGridAxis(const HistoAxis& histoAxis) - { - const unsigned nBins = histoAxis.nBins(); - const double xmin = histoAxis.binCenter(0); - const double xmax = histoAxis.binCenter(nBins - 1); - UniformAxis ax(nBins, xmin, xmax, histoAxis.label().c_str()); - return ax; - } + HistoAxis convertToHistoAxis(const UniformAxis& gridAxis) { + const unsigned nBins = gridAxis.nCoords(); + const double xmin = gridAxis.min(); + const double xmax = gridAxis.max(); + const double hbw = 0.5 * (xmax - xmin) / (nBins - 1U); + HistoAxis ax(nBins, xmin - hbw, xmax + hbw, gridAxis.label().c_str()); + return ax; + } - NUHistoAxis convertToHistoAxis(const GridAxis& gridAxis, double xMin) - { - const unsigned nCoords = gridAxis.nCoords(); - std::vector binEdges; - binEdges.reserve(nCoords + 1U); - binEdges.push_back(xMin); - for (unsigned i=0; i coords; - coords.reserve(nBins); - for (unsigned i=0; i binEdges; + binEdges.reserve(nCoords + 1U); + binEdges.push_back(xMin); + for (unsigned i = 0; i < nCoords; ++i) { + const double x = gridAxis.coordinate(i); + if (x <= xMin) + throw npstat::NpstatInvalidArgument( + "In npstat::convertToHistoAxis: " + "conversion is impossible"); + const double halfbin = x - xMin; + xMin = x + halfbin; + binEdges.push_back(xMin); } -} + NUHistoAxis ax(binEdges, gridAxis.label().c_str()); + return ax; + } + + GridAxis convertToGridAxis(const NUHistoAxis& histoAxis) { + const unsigned nBins = histoAxis.nBins(); + std::vector coords; + coords.reserve(nBins); + for (unsigned i = 0; i < nBins; ++i) + coords.push_back(histoAxis.binCenter(i)); + GridAxis ax(coords, histoAxis.label().c_str()); + return ax; + } +} // namespace npstat diff --git a/JetMETCorrections/IsolatedParticles/test/TestIsoSimTracks.cc b/JetMETCorrections/IsolatedParticles/test/TestIsoSimTracks.cc index 9549a91c095cc..a3d0f843de9f1 100644 --- a/JetMETCorrections/IsolatedParticles/test/TestIsoSimTracks.cc +++ b/JetMETCorrections/IsolatedParticles/test/TestIsoSimTracks.cc @@ -15,7 +15,6 @@ // Original Author: Sergey Petrushanko // - // system include files #include @@ -67,7 +66,6 @@ #include "Geometry/CommonDetUnit/interface/GeomDet.h" - #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" @@ -81,215 +79,205 @@ #include class TestIsoSimTracks : public edm::EDAnalyzer { - public: - explicit TestIsoSimTracks(const edm::ParameterSet&); - virtual ~TestIsoSimTracks(){}; +public: + explicit TestIsoSimTracks(const edm::ParameterSet&); + virtual ~TestIsoSimTracks(){}; - virtual void analyze (const edm::Event&, const edm::EventSetup&); - void endJob(void); + virtual void analyze(const edm::Event&, const edm::EventSetup&); + void endJob(void); - private: +private: TFile* m_Hfile; - struct{ - TH1F* eta; - TH1F* phi; - TH1F* p; - TH1F* pt; - TH1F* isomult; - } IsoHists; - TrackDetectorAssociator trackAssociator_; - TrackAssociatorParameters trackAssociatorParameters_; - - edm::EDGetTokenT simTracksToken_; - edm::EDGetTokenT simVerticesToken_; + struct { + TH1F* eta; + TH1F* phi; + TH1F* p; + TH1F* pt; + TH1F* isomult; + } IsoHists; + TrackDetectorAssociator trackAssociator_; + TrackAssociatorParameters trackAssociatorParameters_; + + edm::EDGetTokenT simTracksToken_; + edm::EDGetTokenT simVerticesToken_; }; -TestIsoSimTracks::TestIsoSimTracks(const edm::ParameterSet& iConfig) : - simTracksToken_(consumes(iConfig.getParameter("simTracksTag"))), - simVerticesToken_(consumes(iConfig.getParameter("simVerticesTag"))) -{ - // Fill data labels - //std::vector labels = iConfig.getParameter >("labels"); - //boost::regex regExp1 ("([^\\s,]+)[\\s,]+([^\\s,]+)$"); - //boost::regex regExp2 ("([^\\s,]+)[\\s,]+([^\\s,]+)[\\s,]+([^\\s,]+)$"); - //boost::smatch matches; - - m_Hfile=new TFile("IsoHists.root","RECREATE"); - IsoHists.eta = new TH1F("Eta","Track eta",100,-5.,5.); - IsoHists.phi = new TH1F("Phi","Track phi",100,-3.5,3.5); - IsoHists.p = new TH1F("Momentum","Track momentum",100,0.,20.); - IsoHists.pt = new TH1F("pt","Track pt",100,0.,10.); - IsoHists.isomult = new TH1F("IsoMult","Iso Mult",10,-0.5,9.5); - - //for(std::vector::const_iterator label = labels.begin(); label != labels.end(); label++) { - // if (boost::regex_match(*label,matches,regExp1)) -// trackAssociator_.addDataLabels(matches[1],matches[2]); - // else if (boost::regex_match(*label,matches,regExp2)) -// trackAssociator_.addDataLabels(matches[1],matches[2],matches[3]); - // else -// edm::LogError("ConfigurationError") << "Failed to parse label:\n" << *label << "Skipped.\n"; - // } - - // trackAssociator_.addDataLabels("EBRecHitCollection","ecalrechit","EcalRecHitsEB"); - // trackAssociator_.addDataLabels("CaloTowerCollection","towermaker"); - // trackAssociator_.addDataLabels("DTRecSegment4DCollection","recseg4dbuilder"); - - // Load TrackDetectorAssociator parameters - edm::ParameterSet parameters = iConfig.getParameter("TrackAssociatorParameters"); - edm::ConsumesCollector iC = consumesCollector(); - trackAssociatorParameters_.loadParameters( parameters, iC ); - trackAssociator_.useDefaultPropagator(); +TestIsoSimTracks::TestIsoSimTracks(const edm::ParameterSet& iConfig) + : simTracksToken_(consumes(iConfig.getParameter("simTracksTag"))), + simVerticesToken_(consumes(iConfig.getParameter("simVerticesTag"))) { + // Fill data labels + //std::vector labels = iConfig.getParameter >("labels"); + //boost::regex regExp1 ("([^\\s,]+)[\\s,]+([^\\s,]+)$"); + //boost::regex regExp2 ("([^\\s,]+)[\\s,]+([^\\s,]+)[\\s,]+([^\\s,]+)$"); + //boost::smatch matches; + + m_Hfile = new TFile("IsoHists.root", "RECREATE"); + IsoHists.eta = new TH1F("Eta", "Track eta", 100, -5., 5.); + IsoHists.phi = new TH1F("Phi", "Track phi", 100, -3.5, 3.5); + IsoHists.p = new TH1F("Momentum", "Track momentum", 100, 0., 20.); + IsoHists.pt = new TH1F("pt", "Track pt", 100, 0., 10.); + IsoHists.isomult = new TH1F("IsoMult", "Iso Mult", 10, -0.5, 9.5); + + //for(std::vector::const_iterator label = labels.begin(); label != labels.end(); label++) { + // if (boost::regex_match(*label,matches,regExp1)) + // trackAssociator_.addDataLabels(matches[1],matches[2]); + // else if (boost::regex_match(*label,matches,regExp2)) + // trackAssociator_.addDataLabels(matches[1],matches[2],matches[3]); + // else + // edm::LogError("ConfigurationError") << "Failed to parse label:\n" << *label << "Skipped.\n"; + // } + + // trackAssociator_.addDataLabels("EBRecHitCollection","ecalrechit","EcalRecHitsEB"); + // trackAssociator_.addDataLabels("CaloTowerCollection","towermaker"); + // trackAssociator_.addDataLabels("DTRecSegment4DCollection","recseg4dbuilder"); + + // Load TrackDetectorAssociator parameters + edm::ParameterSet parameters = iConfig.getParameter("TrackAssociatorParameters"); + edm::ConsumesCollector iC = consumesCollector(); + trackAssociatorParameters_.loadParameters(parameters, iC); + trackAssociator_.useDefaultPropagator(); } -void TestIsoSimTracks::analyze( const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - using namespace edm; +void TestIsoSimTracks::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + using namespace edm; -// mine! b + // mine! b - std::vector AllTracks; - std::vector AllTracks1; + std::vector AllTracks; + std::vector AllTracks1; -// mine! e + // mine! e - // get list of tracks and their vertices - Handle simTracks; - iEvent.getByToken(simTracksToken_, simTracks); + // get list of tracks and their vertices + Handle simTracks; + iEvent.getByToken(simTracksToken_, simTracks); - Handle simVertices; - iEvent.getByToken(simVerticesToken_, simVertices); - if (! simVertices.isValid() ) throw cms::Exception("FatalError") << "No vertices found\n"; + Handle simVertices; + iEvent.getByToken(simVerticesToken_, simVertices); + if (!simVertices.isValid()) + throw cms::Exception("FatalError") << "No vertices found\n"; - // loop over simulated tracks - std::cout << "Number of simulated tracks found in the event: " << simTracks->size() << std::endl; - for(SimTrackContainer::const_iterator tracksCI = simTracks->begin(); - tracksCI != simTracks->end(); tracksCI++){ + // loop over simulated tracks + std::cout << "Number of simulated tracks found in the event: " << simTracks->size() << std::endl; + for (SimTrackContainer::const_iterator tracksCI = simTracks->begin(); tracksCI != simTracks->end(); tracksCI++) { + // skip low Pt tracks + if (tracksCI->momentum().Pt() < 0.7) { + // std::cout << "Skipped low Pt track (Pt: " << tracksCI->momentum().perp() << ")" <momentum().Pt() < 0.7) { -// std::cout << "Skipped low Pt track (Pt: " << tracksCI->momentum().perp() << ")" <vertIndex(); + // uint trackIndex = tracksCI->genpartIndex(); + + SimVertex vertex(math::XYZVectorD(0., 0., 0.), 0); + if (vertexIndex >= 0) + vertex = (*simVertices)[vertexIndex]; + + // skip tracks originated away from the IP + // if (vertex.position().rho() > 50) { + // std::cout << "Skipped track originated away from IP: " <momentum().Pt() << " , " << tracksCI->momentum().eta() << " , " << tracksCI->momentum().phi() + << std::endl; + + // Simply get ECAL energy of the crossed crystals + // std::cout << "ECAL energy of crossed crystals: " << + // trackAssociator_.getEcalEnergy(iEvent, iSetup, + // trackAssociator_.getFreeTrajectoryState(iSetup, *tracksCI, vertex) ) + // << " GeV" << std::endl; + + // std::cout << "Details:\n" <momentum().x() * tracksCI->momentum().x() + tracksCI->momentum().y() * tracksCI->momentum().y() + + tracksCI->momentum().z() * tracksCI->momentum().z()); + + if (info.isGoodEcal == 1 && fabs(info.trkGlobPosAtEcal.eta()) < 2.6) { + AllTracks.push_back(GlobalPoint( + info.trkGlobPosAtEcal.x() / rfa, info.trkGlobPosAtEcal.y() / rfa, info.trkGlobPosAtEcal.z() / rfa)); + if (tracksCI->momentum().Pt() > 2. && fabs(info.trkGlobPosAtEcal.eta()) < 2.1) { + AllTracks1.push_back(GlobalPoint( + info.trkGlobPosAtEcal.x() / rfa, info.trkGlobPosAtEcal.y() / rfa, info.trkGlobPosAtEcal.z() / rfa)); } + } - // get vertex - int vertexIndex = tracksCI->vertIndex(); - // uint trackIndex = tracksCI->genpartIndex(); - - SimVertex vertex(math::XYZVectorD(0.,0.,0.),0); - if (vertexIndex >= 0) vertex = (*simVertices)[vertexIndex]; - - // skip tracks originated away from the IP -// if (vertex.position().rho() > 50) { -// std::cout << "Skipped track originated away from IP: " <momentum().Pt() << " , " << - tracksCI->momentum().eta() << " , " << tracksCI->momentum().phi() << std::endl; - - // Simply get ECAL energy of the crossed crystals -// std::cout << "ECAL energy of crossed crystals: " << -// trackAssociator_.getEcalEnergy(iEvent, iSetup, -// trackAssociator_.getFreeTrajectoryState(iSetup, *tracksCI, vertex) ) -// << " GeV" << std::endl; - -// std::cout << "Details:\n" <momentum().x()*tracksCI->momentum().x() + - tracksCI->momentum().y()*tracksCI->momentum().y() + - tracksCI->momentum().z()*tracksCI->momentum().z()); - - if (info.isGoodEcal==1 && fabs(info.trkGlobPosAtEcal.eta()) < 2.6){ - AllTracks.push_back(GlobalPoint(info.trkGlobPosAtEcal.x()/rfa, info.trkGlobPosAtEcal.y()/rfa, info.trkGlobPosAtEcal.z()/rfa)); - if (tracksCI->momentum().Pt() > 2. && fabs(info.trkGlobPosAtEcal.eta()) < 2.1) - { - AllTracks1.push_back(GlobalPoint(info.trkGlobPosAtEcal.x()/rfa, info.trkGlobPosAtEcal.y()/rfa, info.trkGlobPosAtEcal.z()/rfa)); - } - } - -// mine! e - -// std::cout << "HCAL, if track reach HCAL: " << info.isGoodHcal << std::endl; -// std::cout << "HCAL, number of crossed towers: " << info.crossedTowers.size() << std::endl; -// std::cout << "HCAL, energy of crossed towers: " << info.hcalEnergy() << " GeV" << std::endl; -// std::cout << "HCAL, number of towers in the cone: " << info.towers.size() << std::endl; -// std::cout << "HCAL, energy in the cone: " << info.hcalConeEnergy() << " GeV" << std::endl; -// std::cout << "HCAL, trajectory point (z,R,eta,phi): " << info.trkGlobPosAtHcal.z() << ", " -// << info.trkGlobPosAtHcal.R() << " , " << info.trkGlobPosAtHcal.eta() << " , " -// << info.trkGlobPosAtHcal.phi()<< std::endl; - - } - -// mine! b - - std::cout << " NUMBER of tracks " << AllTracks.size() << " and candidates for iso tracks " << AllTracks1.size() < 3.141592) delta_phi = 6.283184 - delta_phi; - double delta_eta = fabs(AllTracks1[ia1].eta() - AllTracks[ia].eta()); - double delta_actual = sqrt( delta_phi*delta_phi + delta_eta*delta_eta ); - - if (delta_actual < delta_min && delta_actual != 0.) delta_min = delta_actual; - - } + // mine! e - if (delta_min > 0.5) { - - std::cout << "FIND ISOLATED TRACK " << AllTracks1[ia1].mag() << " " << AllTracks1[ia1].eta()<< " "<< AllTracks1[ia1].phi()<< std::endl; + // std::cout << "HCAL, if track reach HCAL: " << info.isGoodHcal << std::endl; + // std::cout << "HCAL, number of crossed towers: " << info.crossedTowers.size() << std::endl; + // std::cout << "HCAL, energy of crossed towers: " << info.hcalEnergy() << " GeV" << std::endl; + // std::cout << "HCAL, number of towers in the cone: " << info.towers.size() << std::endl; + // std::cout << "HCAL, energy in the cone: " << info.hcalConeEnergy() << " GeV" << std::endl; + // std::cout << "HCAL, trajectory point (z,R,eta,phi): " << info.trkGlobPosAtHcal.z() << ", " + // << info.trkGlobPosAtHcal.R() << " , " << info.trkGlobPosAtHcal.eta() << " , " + // << info.trkGlobPosAtHcal.phi()<< std::endl; + } - IsoHists.eta->Fill(AllTracks1[ia1].eta()); - IsoHists.phi->Fill(AllTracks1[ia1].phi()); - IsoHists.p->Fill(AllTracks1[ia1].mag()); - IsoHists.pt->Fill(AllTracks1[ia1].perp()); - imult = imult+1.; + // mine! b - } - } - IsoHists.isomult->Fill(imult); + std::cout << " NUMBER of tracks " << AllTracks.size() << " and candidates for iso tracks " << AllTracks1.size() + << std::endl; -// mine! e + double imult = 0.; -} + for (unsigned int ia1 = 0; ia1 < AllTracks1.size(); ia1++) { + double delta_min = 3.141592; + for (unsigned int ia = 0; ia < AllTracks.size(); ia++) { + double delta_phi = fabs(AllTracks1[ia1].phi() - AllTracks[ia].phi()); + if (delta_phi > 3.141592) + delta_phi = 6.283184 - delta_phi; + double delta_eta = fabs(AllTracks1[ia1].eta() - AllTracks[ia].eta()); + double delta_actual = sqrt(delta_phi * delta_phi + delta_eta * delta_eta); -void TestIsoSimTracks::endJob(void) { + if (delta_actual < delta_min && delta_actual != 0.) + delta_min = delta_actual; + } - m_Hfile->cd(); - IsoHists.eta->Write(); - IsoHists.phi->Write(); - IsoHists.p->Write(); - IsoHists.pt->Write(); - IsoHists.isomult->Write(); - m_Hfile->Close(); + if (delta_min > 0.5) { + std::cout << "FIND ISOLATED TRACK " << AllTracks1[ia1].mag() << " " << AllTracks1[ia1].eta() << " " + << AllTracks1[ia1].phi() << std::endl; + + IsoHists.eta->Fill(AllTracks1[ia1].eta()); + IsoHists.phi->Fill(AllTracks1[ia1].phi()); + IsoHists.p->Fill(AllTracks1[ia1].mag()); + IsoHists.pt->Fill(AllTracks1[ia1].perp()); + imult = imult + 1.; + } + } + IsoHists.isomult->Fill(imult); + // mine! e } - +void TestIsoSimTracks::endJob(void) { + m_Hfile->cd(); + IsoHists.eta->Write(); + IsoHists.phi->Write(); + IsoHists.p->Write(); + IsoHists.pt->Write(); + IsoHists.isomult->Write(); + m_Hfile->Close(); +} //define this as a plug-in DEFINE_FWK_MODULE(TestIsoSimTracks); diff --git a/JetMETCorrections/IsolatedParticles/test/TestIsoTracks.cc b/JetMETCorrections/IsolatedParticles/test/TestIsoTracks.cc index d943316f65400..9e79485883660 100644 --- a/JetMETCorrections/IsolatedParticles/test/TestIsoTracks.cc +++ b/JetMETCorrections/IsolatedParticles/test/TestIsoTracks.cc @@ -15,7 +15,6 @@ // Original Author: Sergey Petrushanko // - // system include files #include @@ -67,7 +66,6 @@ #include "Geometry/CommonDetUnit/interface/GeomDet.h" - #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" @@ -94,231 +92,218 @@ using namespace std; using namespace reco; - class TestIsoTracks : public edm::EDAnalyzer { - public: - explicit TestIsoTracks(const edm::ParameterSet&); - virtual ~TestIsoTracks(){}; +public: + explicit TestIsoTracks(const edm::ParameterSet&); + virtual ~TestIsoTracks(){}; - void setPrimaryVertex(const reco::Vertex & a){theRecVertex = a;} - void setTracksFromPrimaryVertex(vector & a){theTrack = a;} - virtual void analyze (const edm::Event&, const edm::EventSetup&); - void endJob(void); + void setPrimaryVertex(const reco::Vertex& a) { theRecVertex = a; } + void setTracksFromPrimaryVertex(vector& a) { theTrack = a; } + virtual void analyze(const edm::Event&, const edm::EventSetup&); + void endJob(void); - private: +private: TFile* m_Hfile; - struct{ - TH1F* eta; - TH1F* phi; - TH1F* p; - TH1F* pt; - TH1F* isomult; - } IsoHists; - - edm::EDGetTokenT mInputPVfCTF; - edm::EDGetTokenT m_inputTrackToken; + struct { + TH1F* eta; + TH1F* phi; + TH1F* p; + TH1F* pt; + TH1F* isomult; + } IsoHists; + edm::EDGetTokenT mInputPVfCTF; + edm::EDGetTokenT m_inputTrackToken; double theRvert; reco::Vertex theRecVertex; vector theTrack; - TrackDetectorAssociator trackAssociator_; - TrackAssociatorParameters trackAssociatorParameters_; + TrackDetectorAssociator trackAssociator_; + TrackAssociatorParameters trackAssociatorParameters_; - edm::EDGetTokenT simTracksToken_; - edm::EDGetTokenT simVerticesToken_; + edm::EDGetTokenT simTracksToken_; + edm::EDGetTokenT simVerticesToken_; }; -TestIsoTracks::TestIsoTracks(const edm::ParameterSet& iConfig): - mInputPVfCTF(consumes(iConfig.getParameter("src3"))), - m_inputTrackToken(consumes(edm::InputTag(iConfig.getUntrackedParameter("inputTrackLabel","ctfWithMaterialTracks")))), - theRvert(iConfig.getParameter("rvert")), - simTracksToken_(consumes(iConfig.getParameter("simTracksTag"))), - simVerticesToken_(consumes(iConfig.getParameter("simVerticesTag"))) -{ - m_Hfile=new TFile("IsoHists.root","RECREATE"); - IsoHists.eta = new TH1F("Eta","Track eta",50,-2.5,2.5); - IsoHists.phi = new TH1F("Phi","Track phi",50,-3.2,3.2); - IsoHists.p = new TH1F("Momentum","Track momentum",100,0.,20.); - IsoHists.pt = new TH1F("pt","Track pt",100,0.,10.); - IsoHists.isomult = new TH1F("IsoMult","Iso Mult",10,-0.5,9.5); - - // Load TrackDetectorAssociator parameters - edm::ParameterSet parameters = iConfig.getParameter("TrackAssociatorParameters"); - edm::ConsumesCollector iC = consumesCollector(); - trackAssociatorParameters_.loadParameters( parameters, iC ); - trackAssociator_.useDefaultPropagator(); +TestIsoTracks::TestIsoTracks(const edm::ParameterSet& iConfig) + : mInputPVfCTF(consumes(iConfig.getParameter("src3"))), + m_inputTrackToken(consumes( + edm::InputTag(iConfig.getUntrackedParameter("inputTrackLabel", "ctfWithMaterialTracks")))), + theRvert(iConfig.getParameter("rvert")), + simTracksToken_(consumes(iConfig.getParameter("simTracksTag"))), + simVerticesToken_(consumes(iConfig.getParameter("simVerticesTag"))) { + m_Hfile = new TFile("IsoHists.root", "RECREATE"); + IsoHists.eta = new TH1F("Eta", "Track eta", 50, -2.5, 2.5); + IsoHists.phi = new TH1F("Phi", "Track phi", 50, -3.2, 3.2); + IsoHists.p = new TH1F("Momentum", "Track momentum", 100, 0., 20.); + IsoHists.pt = new TH1F("pt", "Track pt", 100, 0., 10.); + IsoHists.isomult = new TH1F("IsoMult", "Iso Mult", 10, -0.5, 9.5); + + // Load TrackDetectorAssociator parameters + edm::ParameterSet parameters = iConfig.getParameter("TrackAssociatorParameters"); + edm::ConsumesCollector iC = consumesCollector(); + trackAssociatorParameters_.loadParameters(parameters, iC); + trackAssociator_.useDefaultPropagator(); } -void TestIsoTracks::analyze( const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - using namespace edm; - -// mine! b - - std::vector AllTracks; - std::vector AllTracks1; - -// mine! e - -// Take Reco Vertex collection - edm::Handle primary_vertices; //Define Inputs (vertices) - iEvent.getByToken(mInputPVfCTF, primary_vertices); //Get Inputs (vertices) - - // Take Reco Track Collection - edm::Handle trackCollection; - iEvent.getByToken(m_inputTrackToken,trackCollection); - const reco::TrackCollection tC = *(trackCollection.product()); - - // get list of tracks and their vertices - Handle simTracks; - iEvent.getByToken(simTracksToken_, simTracks); - - Handle simVertices; - iEvent.getByToken(simVerticesToken_, simVertices); - if (! simVertices.isValid() ) throw cms::Exception("FatalError") << "No vertices found\n"; - - - // loop over tracks - - std::cout << "Number of tracks found in the event: " << trackCollection->size() << std::endl; - -// for(SimTrackContainer::const_iterator tracksCI = simTracks->begin(); -// tracksCI != simTracks->end(); tracksCI++){ - - for(reco::TrackCollection::const_iterator tracksCI=tC.begin(); tracksCI!=tC.end(); tracksCI++){ +void TestIsoTracks::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + using namespace edm; - double mome_pt = sqrt ( tracksCI->momentum().x()*tracksCI->momentum().x() + - tracksCI->momentum().y()*tracksCI->momentum().y()); + // mine! b - // skip low Pt tracks - if (mome_pt < 0.5) { - std::cout << "Skipped low Pt track (Pt: " << mome_pt << ")" < AllTracks; + std::vector AllTracks1; - // get vertex -// int vertexIndex = tracksCI->vertIndex(); - // uint trackIndex = tracksCI->genpartIndex(); + // mine! e -// SimVertex vertex(Hep3Vector(0.,0.,0.),0); -// if (vertexIndex >= 0) vertex = (*simVertices)[vertexIndex]; + // Take Reco Vertex collection + edm::Handle primary_vertices; //Define Inputs (vertices) + iEvent.getByToken(mInputPVfCTF, primary_vertices); //Get Inputs (vertices) - // skip tracks originated away from the IP -// if (vertex.position().rho() > 50) { -// std::cout << "Skipped track originated away from IP: " < trackCollection; + iEvent.getByToken(m_inputTrackToken, trackCollection); + const reco::TrackCollection tC = *(trackCollection.product()); - std::cout << "\n-------------------------------------------------------\n Track (pt,eta,phi): " << mome_pt << " , " << - tracksCI->momentum().eta() << " , " << tracksCI->momentum().phi() << std::endl; + // get list of tracks and their vertices + Handle simTracks; + iEvent.getByToken(simTracksToken_, simTracks); - // Simply get ECAL energy of the crossed crystals -// std::cout << "ECAL energy of crossed crystals: " << -// trackAssociator_.getEcalEnergy(iEvent, iSetup, -// trackAssociator_.getFreeTrajectoryState(iSetup, *tracksCI, vertex) ) -// << " GeV" << std::endl; + Handle simVertices; + iEvent.getByToken(simVerticesToken_, simVertices); + if (!simVertices.isValid()) + throw cms::Exception("FatalError") << "No vertices found\n"; -// std::cout << "Details:\n" <size() << std::endl; - double rfa = sqrt (info.trkGlobPosAtEcal.x()*info.trkGlobPosAtEcal.x() + - info.trkGlobPosAtEcal.y()*info.trkGlobPosAtEcal.y() + - info.trkGlobPosAtEcal.z()*info.trkGlobPosAtEcal.z()) / - sqrt ( tracksCI->momentum().x()*tracksCI->momentum().x() + - tracksCI->momentum().y()*tracksCI->momentum().y() + - tracksCI->momentum().z()*tracksCI->momentum().z()); + // for(SimTrackContainer::const_iterator tracksCI = simTracks->begin(); + // tracksCI != simTracks->end(); tracksCI++){ - if (info.isGoodEcal==1 && fabs(info.trkGlobPosAtEcal.eta()) < 2.6){ - AllTracks.push_back(GlobalPoint(info.trkGlobPosAtEcal.x()/rfa, info.trkGlobPosAtEcal.y()/rfa, info.trkGlobPosAtEcal.z()/rfa)); - if (mome_pt > 2. && fabs(info.trkGlobPosAtEcal.eta()) < 2.1) - if (fabs(info.trkGlobPosAtEcal.eta()) < 2.1) - { - AllTracks1.push_back(GlobalPoint(info.trkGlobPosAtEcal.x()/rfa, info.trkGlobPosAtEcal.y()/rfa, info.trkGlobPosAtEcal.z()/rfa)); - } - } + for (reco::TrackCollection::const_iterator tracksCI = tC.begin(); tracksCI != tC.end(); tracksCI++) { + double mome_pt = + sqrt(tracksCI->momentum().x() * tracksCI->momentum().x() + tracksCI->momentum().y() * tracksCI->momentum().y()); -// mine! e - -// std::cout << "HCAL, if track reach HCAL: " << info.isGoodHcal << std::endl; -// std::cout << "HCAL, number of crossed towers: " << info.crossedTowers.size() << std::endl; -// std::cout << "HCAL, energy of crossed towers: " << info.hcalEnergy() << " GeV" << std::endl; -// std::cout << "HCAL, number of towers in the cone: " << info.towers.size() << std::endl; -// std::cout << "HCAL, energy in the cone: " << info.hcalConeEnergy() << " GeV" << std::endl; -// std::cout << "HCAL, trajectory point (z,R,eta,phi): " << info.trkGlobPosAtHcal.z() << ", " -// << info.trkGlobPosAtHcal.R() << " , " << info.trkGlobPosAtHcal.eta() << " , " -// << info.trkGlobPosAtHcal.phi()<< std::endl; + // skip low Pt tracks + if (mome_pt < 0.5) { + std::cout << "Skipped low Pt track (Pt: " << mome_pt << ")" << std::endl; + continue; + } - } + // get vertex + // int vertexIndex = tracksCI->vertIndex(); + // uint trackIndex = tracksCI->genpartIndex(); + + // SimVertex vertex(Hep3Vector(0.,0.,0.),0); + // if (vertexIndex >= 0) vertex = (*simVertices)[vertexIndex]; + + // skip tracks originated away from the IP + // if (vertex.position().rho() > 50) { + // std::cout << "Skipped track originated away from IP: " <momentum().eta() << " , " << tracksCI->momentum().phi() << std::endl; + + // Simply get ECAL energy of the crossed crystals + // std::cout << "ECAL energy of crossed crystals: " << + // trackAssociator_.getEcalEnergy(iEvent, iSetup, + // trackAssociator_.getFreeTrajectoryState(iSetup, *tracksCI, vertex) ) + // << " GeV" << std::endl; + + // std::cout << "Details:\n" <momentum().x() * tracksCI->momentum().x() + tracksCI->momentum().y() * tracksCI->momentum().y() + + tracksCI->momentum().z() * tracksCI->momentum().z()); + + if (info.isGoodEcal == 1 && fabs(info.trkGlobPosAtEcal.eta()) < 2.6) { + AllTracks.push_back(GlobalPoint( + info.trkGlobPosAtEcal.x() / rfa, info.trkGlobPosAtEcal.y() / rfa, info.trkGlobPosAtEcal.z() / rfa)); + if (mome_pt > 2. && fabs(info.trkGlobPosAtEcal.eta()) < 2.1) + if (fabs(info.trkGlobPosAtEcal.eta()) < 2.1) { + AllTracks1.push_back(GlobalPoint( + info.trkGlobPosAtEcal.x() / rfa, info.trkGlobPosAtEcal.y() / rfa, info.trkGlobPosAtEcal.z() / rfa)); + } + } -// mine! b + // mine! e - std::cout << " NUMBER of tracks " << AllTracks.size() << " and candidates for iso tracks " << AllTracks1.size() < 3.141592) delta_phi = 6.283184 - delta_phi; - double delta_eta = fabs(AllTracks1[ia1].eta() - AllTracks[ia].eta()); - double delta_actual = sqrt( delta_phi*delta_phi + delta_eta*delta_eta ); + for (unsigned int ia1 = 0; ia1 < AllTracks1.size(); ia1++) { + double delta_min = 3.141592; - if (delta_actual < delta_min && delta_actual != 0.) delta_min = delta_actual; + for (unsigned int ia = 0; ia < AllTracks.size(); ia++) { + double delta_phi = fabs(AllTracks1[ia1].phi() - AllTracks[ia].phi()); + if (delta_phi > 3.141592) + delta_phi = 6.283184 - delta_phi; + double delta_eta = fabs(AllTracks1[ia1].eta() - AllTracks[ia].eta()); + double delta_actual = sqrt(delta_phi * delta_phi + delta_eta * delta_eta); - } + if (delta_actual < delta_min && delta_actual != 0.) + delta_min = delta_actual; + } if (delta_min > 0.5) { + std::cout << "FIND ISOLATED TRACK " << AllTracks1[ia1].mag() << " " << AllTracks1[ia1].eta() << " " + << AllTracks1[ia1].phi() << std::endl; - std::cout << "FIND ISOLATED TRACK " << AllTracks1[ia1].mag() << " " << AllTracks1[ia1].eta()<< " "<< AllTracks1[ia1].phi()<< std::endl; - - IsoHists.eta->Fill(AllTracks1[ia1].eta()); - IsoHists.phi->Fill(AllTracks1[ia1].phi()); - IsoHists.p->Fill(AllTracks1[ia1].mag()); - IsoHists.pt->Fill(AllTracks1[ia1].perp()); - - imult = imult+1.; + IsoHists.eta->Fill(AllTracks1[ia1].eta()); + IsoHists.phi->Fill(AllTracks1[ia1].phi()); + IsoHists.p->Fill(AllTracks1[ia1].mag()); + IsoHists.pt->Fill(AllTracks1[ia1].perp()); + imult = imult + 1.; } } - IsoHists.isomult->Fill(imult); - -// mine! e + IsoHists.isomult->Fill(imult); + // mine! e } - void TestIsoTracks::endJob(void) { - - m_Hfile->cd(); - IsoHists.eta->Write(); - IsoHists.phi->Write(); - IsoHists.p->Write(); - IsoHists.pt->Write(); - IsoHists.isomult->Write(); - m_Hfile->Close(); - + m_Hfile->cd(); + IsoHists.eta->Write(); + IsoHists.phi->Write(); + IsoHists.p->Write(); + IsoHists.pt->Write(); + IsoHists.isomult->Write(); + m_Hfile->Close(); } - - //define this as a plug-in DEFINE_FWK_MODULE(TestIsoTracks); diff --git a/JetMETCorrections/JetParton/interface/JetPartonCorrector.h b/JetMETCorrections/JetParton/interface/JetPartonCorrector.h index d310df3bc31a8..644de9f5c3f5e 100644 --- a/JetMETCorrections/JetParton/interface/JetPartonCorrector.h +++ b/JetMETCorrections/JetParton/interface/JetPartonCorrector.h @@ -14,29 +14,26 @@ namespace edm { } namespace JetPartonNamespace { -class ParametrizationJetParton; -class UserPartonMixture; -} + class ParametrizationJetParton; + class UserPartonMixture; +} // namespace JetPartonNamespace -class JetPartonCorrector : public JetCorrector -{ -public: - JetPartonCorrector(const edm::ParameterSet& fConfig); +class JetPartonCorrector : public JetCorrector { +public: + JetPartonCorrector(const edm::ParameterSet& fConfig); ~JetPartonCorrector() override; - - double correction (const LorentzVector& fJet) const override; - + + double correction(const LorentzVector& fJet) const override; + void setParameters(std::string aCalibrationType, double aJetFinderRadius, int aPartonMixture); /// if correction needs event information - bool eventRequired () const override {return false;} - -private: + bool eventRequired() const override { return false; } - typedef std::map ParametersMap; +private: + typedef std::map ParametersMap; ParametersMap parametrization; int thePartonMixture; double theJetFinderRadius; - }; #endif diff --git a/JetMETCorrections/JetParton/src/JetPartonCorrector.cc b/JetMETCorrections/JetParton/src/JetPartonCorrector.cc index c8d151db6c5bc..aca8b882e626e 100644 --- a/JetMETCorrections/JetParton/src/JetPartonCorrector.cc +++ b/JetMETCorrections/JetParton/src/JetPartonCorrector.cc @@ -10,220 +10,220 @@ #include using namespace std; -namespace JetPartonNamespace{ -class UserPartonMixture{ - public: - UserPartonMixture(){} - virtual ~UserPartonMixture(){} - virtual double mixt (double et,double eta) - { - // The mixture of quark and gluons corresponds to QCD jets. - double f = 0.2+et/1000.*(1.+.13*exp(eta)); - return f; - } -}; - -class ParametrizationJetParton{ - - public: - - ParametrizationJetParton(int thePartonMixture,const vector& x, const vector& y, const vector& z) - { - type = thePartonMixture; - pq = x; - pg = y; - pqcd = z; - } - - double value(double arg1, double arg2) const; - - private: - - int type; - std::vector pq; - std::vector pg; - std::vector pqcd; - -}; - -double ParametrizationJetParton::value(double e, double eta)const{ - double enew(e); - double x = e; - double y = eta; - - if( abs(x-pq[2]) < pq[1]/pq[0] || abs(x-pg[2]) < pg[1]/pg[0] || abs(x-pqcd[2]) < pqcd[1]/pqcd[0] ) - { - return enew; - } - - double kjetq = pq[0]-pq[1]/(x-pq[2]); - double kjetg = pg[0]-pg[1]/(x-pg[2]); - double kjetqcd = pqcd[0]-pqcd[1]/(x-pqcd[2]); - - switch(type){ - case 1: - { - if( abs(kjetq) > 0.0001 ) enew=e/kjetq; - break; +namespace JetPartonNamespace { + class UserPartonMixture { + public: + UserPartonMixture() {} + virtual ~UserPartonMixture() {} + virtual double mixt(double et, double eta) { + // The mixture of quark and gluons corresponds to QCD jets. + double f = 0.2 + et / 1000. * (1. + .13 * exp(eta)); + return f; } - case 2: - { - if( abs(kjetg) > 0.0001 ) enew=e/kjetg; - break; + }; + + class ParametrizationJetParton { + public: + ParametrizationJetParton(int thePartonMixture, + const vector& x, + const vector& y, + const vector& z) { + type = thePartonMixture; + pq = x; + pg = y; + pqcd = z; } - case 3: - { - if( abs(kjetqcd) > 0.0001 ) enew=e/kjetqcd; - break; - } - case 4: - { - cout<<"[Jets] JetPartonCorrector: Warning! Calibration to b-quark - does not implemented yet. Light quark calibration is used instead "< 0.0001 ) enew=e/kjetq; - break; + + double value(double arg1, double arg2) const; + + private: + int type; + std::vector pq; + std::vector pg; + std::vector pqcd; + }; + + double ParametrizationJetParton::value(double e, double eta) const { + double enew(e); + double x = e; + double y = eta; + + if (abs(x - pq[2]) < pq[1] / pq[0] || abs(x - pg[2]) < pg[1] / pg[0] || abs(x - pqcd[2]) < pqcd[1] / pqcd[0]) { + return enew; } - case 100: - { - UserPartonMixture upm; - double f = upm.mixt(x,y); - double kjet=(f*kjetq+kjetg)/(f+1); - if( abs(kjet) > 0.0001 ) enew=e/kjet; - break; + + double kjetq = pq[0] - pq[1] / (x - pq[2]); + double kjetg = pg[0] - pg[1] / (x - pg[2]); + double kjetqcd = pqcd[0] - pqcd[1] / (x - pqcd[2]); + + switch (type) { + case 1: { + if (abs(kjetq) > 0.0001) + enew = e / kjetq; + break; + } + case 2: { + if (abs(kjetg) > 0.0001) + enew = e / kjetg; + break; + } + case 3: { + if (abs(kjetqcd) > 0.0001) + enew = e / kjetqcd; + break; + } + case 4: { + cout << "[Jets] JetPartonCorrector: Warning! Calibration to b-quark - does not implemented yet. Light quark " + "calibration is used instead " + << endl; + if (abs(kjetq) > 0.0001) + enew = e / kjetq; + break; + } + case 100: { + UserPartonMixture upm; + double f = upm.mixt(x, y); + double kjet = (f * kjetq + kjetg) / (f + 1); + if (abs(kjet) > 0.0001) + enew = e / kjet; + break; + } + + default: + cerr << "[Jets] JetPartonCorrector: Error! unknown parametrization type = " << type + << " No correction applied ..." << endl; + break; } - - default: - cerr<<"[Jets] JetPartonCorrector: Error! unknown parametrization type = "<& parameters(int ieta){return pars[ieta];} - bool valid(){return !etavector.empty();} - - private: - - vector etavector; - vector typevector; - vector< vector > pars; -}; + class JetPartonCalibrationParameterSet { + public: + JetPartonCalibrationParameterSet(string tag); + int neta() { return etavector.size(); } + double eta(int ieta) { return etavector[ieta]; } + int type(int ieta) { return typevector[ieta]; } + const vector& parameters(int ieta) { return pars[ieta]; } + bool valid() { return !etavector.empty(); } -JetPartonCalibrationParameterSet::JetPartonCalibrationParameterSet(string tag){ + private: + vector etavector; + vector typevector; + vector > pars; + }; - std::string file="JetMETCorrections/JetParton/data/"+tag+".txt"; + JetPartonCalibrationParameterSet::JetPartonCalibrationParameterSet(string tag) { + std::string file = "JetMETCorrections/JetParton/data/" + tag + ".txt"; - edm::FileInPath f1(file); + edm::FileInPath f1(file); - std::ifstream in( (f1.fullPath()).c_str() ); + std::ifstream in((f1.fullPath()).c_str()); - - - // if ( f1.isLocal() ){ + // if ( f1.isLocal() ){ string line; - while( std::getline( in, line) ){ - if(line.empty() || line[0]=='#') continue; + while (std::getline(in, line)) { + if (line.empty() || line[0] == '#') + continue; istringstream linestream(line); double par; int type; - linestream>>par>>type; + linestream >> par >> type; etavector.push_back(par); typevector.push_back(type); pars.push_back(vector()); - while(linestream>>par)pars.back().push_back(par); + while (linestream >> par) + pars.back().push_back(par); } // } // else // if (tag!="no") { cout<<"The file \""<("MixtureType"); theJetFinderRadius = fConfig.getParameter("Radius"); - setParameters (fConfig.getParameter ("tagName"),theJetFinderRadius,thePartonMixture ); + setParameters(fConfig.getParameter("tagName"), theJetFinderRadius, thePartonMixture); } -JetPartonCorrector::~JetPartonCorrector() -{ - for(ParametersMap::iterator ip=parametrization.begin();ip!=parametrization.end();ip++) delete ip->second; +JetPartonCorrector::~JetPartonCorrector() { + for (ParametersMap::iterator ip = parametrization.begin(); ip != parametrization.end(); ip++) + delete ip->second; } -void JetPartonCorrector::setParameters(std::string aCalibrationType, double aJetFinderRadius, int aPartonMixture ) -{ - - theJetFinderRadius = aJetFinderRadius; - thePartonMixture = aPartonMixture; - - JetPartonNamespace::JetPartonCalibrationParameterSet pset(aCalibrationType); - - if((!pset.valid()) && (aCalibrationType != "no")) - { - edm::LogError ("JetPartonCorrector: Jet Corrections not found ") << aCalibrationType << - " not found! Cannot apply any correction ... For JetPlusTrack calibration only radii 0.5 and 0.7 are included for JetParton" << endl; - return; - } - if (aCalibrationType=="no") return; - - - map > pq; - map > pg; - map > pqcd; - int iq = 0; - int ig = 0; - int iqcd = 0; - for(int ieta=0; ieta > pq; + map > pg; + map > pqcd; + int iq = 0; + int ig = 0; + int iqcd = 0; + for (int ieta = 0; ieta < pset.neta(); ieta++) { + if (pset.type(ieta) == 1) { + pq[iq] = pset.parameters(ieta); + iq++; + }; + if (pset.type(ieta) == 2) { + pg[ig] = pset.parameters(ieta); + ig++; + }; + if (pset.type(ieta) == 3) { + pqcd[iqcd] = pset.parameters(ieta); + iqcd++; + }; + } + + for (int ieta = 0; ieta < iq; ieta++) { + parametrization[pset.eta(ieta)] = new JetPartonNamespace::ParametrizationJetParton( + thePartonMixture, (*pq.find(ieta)).second, (*pg.find(ieta)).second, (*pqcd.find(ieta)).second); + } } -double JetPartonCorrector::correction( const LorentzVector& fJet) const -{ - if(parametrization.empty()) { return 1.; } - - double et=fJet.Et(); - double eta=fabs(fJet.Eta()); - +double JetPartonCorrector::correction(const LorentzVector& fJet) const { + if (parametrization.empty()) { + return 1.; + } + + double et = fJet.Et(); + double eta = fabs(fJet.Eta()); + //if(eta<10) { eta=abs(fJet.getY()); } double etnew; - std::map::const_iterator ip=parametrization.upper_bound(eta); - if(ip==parametrization.begin()) - { - etnew=ip->second->value(et,eta); - } - else if(ip==parametrization.end()) - { - etnew=(--ip)->second->value(et,eta); - } - else - { - double eta2=ip->first; - double et2=ip->second->value(et,eta); - ip--; - double eta1=ip->first; - double et1=ip->second->value(et,eta); - - etnew=(eta2*et1 - eta1*et2 + eta*et2 - eta*et1)/(eta2-eta1); - } - cout<<" JetParton::The new energy found "<::const_iterator ip = parametrization.upper_bound(eta); + if (ip == parametrization.begin()) { + etnew = ip->second->value(et, eta); + } else if (ip == parametrization.end()) { + etnew = (--ip)->second->value(et, eta); + } else { + double eta2 = ip->first; + double et2 = ip->second->value(et, eta); + ip--; + double eta1 = ip->first; + double et1 = ip->second->value(et, eta); + + etnew = (eta2 * et1 - eta1 * et2 + eta * et2 - eta * et1) / (eta2 - eta1); + } + cout << " JetParton::The new energy found " << etnew << " " << et << endl; float mScale = 1000.; - - if( et > 0.001) mScale = etnew/et; + + if (et > 0.001) + mScale = etnew / et; return mScale; - - } diff --git a/JetMETCorrections/JetVertexAssociation/interface/JetVertexAssociation.h b/JetMETCorrections/JetVertexAssociation/interface/JetVertexAssociation.h index 83a473ee9aa7a..1917f0a537ed7 100644 --- a/JetMETCorrections/JetVertexAssociation/interface/JetVertexAssociation.h +++ b/JetMETCorrections/JetVertexAssociation/interface/JetVertexAssociation.h @@ -15,24 +15,21 @@ #include #include - namespace edm { class ParameterSet; class Event; class EventSetup; -} - -namespace cms{ +} // namespace edm - class JetVertexAssociation : public edm::EDProducer{ +namespace cms { + class JetVertexAssociation : public edm::EDProducer { public: + JetVertexAssociation(const edm::ParameterSet& ps); - JetVertexAssociation (const edm::ParameterSet& ps); - - ~JetVertexAssociation () override {} + ~JetVertexAssociation() override {} - void produce(edm::Event& e, const edm::EventSetup& c) override; + void produce(edm::Event& e, const edm::EventSetup& c) override; private: typedef std::vector ResultCollection1; @@ -42,9 +39,7 @@ namespace cms{ edm::EDGetTokenT jet_token; edm::EDGetTokenT track_token; edm::EDGetTokenT vertex_token; - }; -} - +} // namespace cms #endif diff --git a/JetMETCorrections/JetVertexAssociation/interface/JetVertexMain.h b/JetMETCorrections/JetVertexAssociation/interface/JetVertexMain.h index f7216105c9f7b..7145cb1208ad1 100644 --- a/JetMETCorrections/JetVertexAssociation/interface/JetVertexMain.h +++ b/JetMETCorrections/JetVertexAssociation/interface/JetVertexMain.h @@ -10,32 +10,29 @@ #include #include -class JetVertexMain { - +class JetVertexMain { public: - - JetVertexMain(const edm::ParameterSet & parameters ); - + JetVertexMain(const edm::ParameterSet& parameters); + ~JetVertexMain(){}; - - std::pair Main (const reco::CaloJet& jet, edm::Handle tracks, - double SIGNAL_V_Z, double SIGNAL_V_Z_Error ); - - private: + std::pair Main(const reco::CaloJet& jet, + edm::Handle tracks, + double SIGNAL_V_Z, + double SIGNAL_V_Z_Error); + +private: double DeltaR(double eta1, double eta2, double phi1, double phi2); double Track_Pt(double px, double py); -//algorithm parameters + //algorithm parameters double cutSigmaZ; double cutDeltaZ; double threshold; double cone_size; - int Algo; + int Algo; std::string cutType; bool discriminator; - }; -#endif - +#endif diff --git a/JetMETCorrections/JetVertexAssociation/src/JetVertexAssociation.cc b/JetMETCorrections/JetVertexAssociation/src/JetVertexAssociation.cc index c883fb9d4c6f5..739b93dfd4c2c 100644 --- a/JetMETCorrections/JetVertexAssociation/src/JetVertexAssociation.cc +++ b/JetMETCorrections/JetVertexAssociation/src/JetVertexAssociation.cc @@ -34,7 +34,6 @@ #include #include - #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" @@ -53,72 +52,62 @@ using namespace std; using namespace reco; -namespace cms{ - - JetVertexAssociation::JetVertexAssociation(const edm::ParameterSet& iConfig): m_algo(iConfig), - jet_token(consumes(edm::InputTag(iConfig.getParameter("JET_ALGO")))), - track_token(consumes(edm::InputTag(iConfig.getParameter("TRACK_ALGO")))), - vertex_token(consumes(edm::InputTag(iConfig.getParameter("VERTEX_ALGO")))) { - - +namespace cms { + JetVertexAssociation::JetVertexAssociation(const edm::ParameterSet& iConfig) + : m_algo(iConfig), + jet_token(consumes(edm::InputTag(iConfig.getParameter("JET_ALGO")))), + track_token(consumes(edm::InputTag(iConfig.getParameter("TRACK_ALGO")))), + vertex_token(consumes(edm::InputTag(iConfig.getParameter("VERTEX_ALGO")))) { produces("Var"); produces("JetType"); - - } - void JetVertexAssociation::produce(edm::Event& iEvent, const edm::EventSetup& iSetup){ - - edm::Handle jets; - iEvent.getByToken(jet_token, jets); - - edm::Handle tracks; - iEvent.getByToken(track_token, tracks); - - edm::Handle vertexes; - iEvent.getByToken(vertex_token, vertexes); - - double SIGNAL_V_Z = 0.; - double SIGNAL_V_Z_ERROR = 0.; - double ptmax = -100.; - - VertexCollection::const_iterator vert = vertexes->begin (); - if(!vertexes->empty() ) { - for (; vert != vertexes->end (); vert++) { - - SIGNAL_V_Z = vert->z(); - double pt = 0.; - reco::Vertex::trackRef_iterator tr = vert->tracks_begin(); - for (; tr != vert->tracks_end(); tr++) pt += (*tr)->pt(); - if( pt >= ptmax ){ - - ptmax = pt; - SIGNAL_V_Z = vert->z(); - SIGNAL_V_Z_ERROR = vert->zError(); - - } - - } - } - - pair result; - std::unique_ptr result1 (new ResultCollection1) ; - std::unique_ptr result2 (new ResultCollection2) ; - - CaloJetCollection::const_iterator jet = jets->begin (); - - if(!jets->empty() ) { - for (; jet != jets->end (); jet++) { - result = m_algo.Main(*jet, tracks, SIGNAL_V_Z, SIGNAL_V_Z_ERROR); - result1->push_back(result.first); - result2->push_back(result.second); - - } - } - - iEvent.put(std::move(result1), "Var"); - iEvent.put(std::move(result2), "JetType"); - + void JetVertexAssociation::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + edm::Handle jets; + iEvent.getByToken(jet_token, jets); + + edm::Handle tracks; + iEvent.getByToken(track_token, tracks); + + edm::Handle vertexes; + iEvent.getByToken(vertex_token, vertexes); + + double SIGNAL_V_Z = 0.; + double SIGNAL_V_Z_ERROR = 0.; + double ptmax = -100.; + + VertexCollection::const_iterator vert = vertexes->begin(); + if (!vertexes->empty()) { + for (; vert != vertexes->end(); vert++) { + SIGNAL_V_Z = vert->z(); + double pt = 0.; + reco::Vertex::trackRef_iterator tr = vert->tracks_begin(); + for (; tr != vert->tracks_end(); tr++) + pt += (*tr)->pt(); + if (pt >= ptmax) { + ptmax = pt; + SIGNAL_V_Z = vert->z(); + SIGNAL_V_Z_ERROR = vert->zError(); + } + } + } + + pair result; + std::unique_ptr result1(new ResultCollection1); + std::unique_ptr result2(new ResultCollection2); + + CaloJetCollection::const_iterator jet = jets->begin(); + + if (!jets->empty()) { + for (; jet != jets->end(); jet++) { + result = m_algo.Main(*jet, tracks, SIGNAL_V_Z, SIGNAL_V_Z_ERROR); + result1->push_back(result.first); + result2->push_back(result.second); + } + } + + iEvent.put(std::move(result1), "Var"); + iEvent.put(std::move(result2), "JetType"); } -} +} // namespace cms diff --git a/JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc b/JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc index 394c9e54351d8..7ab1a42a354b2 100644 --- a/JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc +++ b/JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc @@ -9,94 +9,88 @@ using namespace reco; using namespace edm; -JetVertexMain::JetVertexMain(const ParameterSet & parameters) { - +JetVertexMain::JetVertexMain(const ParameterSet& parameters) { cutSigmaZ = parameters.getParameter("JV_sigmaZ"); cutDeltaZ = parameters.getParameter("JV_deltaZ"); threshold = parameters.getParameter("JV_alpha_threshold"); cone_size = parameters.getParameter("JV_cone_size"); - Algo = parameters.getParameter("JV_type_Algo"); + Algo = parameters.getParameter("JV_type_Algo"); cutType = parameters.getParameter("JV_cutType"); - } +std::pair JetVertexMain::Main(const reco::CaloJet& jet, + edm::Handle tracks, + double signal_vert_Z, + double signal_vert_z_error) { + std::pair parameter; -std::pair JetVertexMain::Main(const reco::CaloJet& jet, edm::Handle tracks, - double signal_vert_Z, double signal_vert_z_error){ - - std::pair parameter; - double jet_et = jet.et(); double jet_phi = jet.phi(); double jet_eta = jet.eta(); // cout<<"JET: "<begin (); - - if (!tracks->empty() ) { - for (; track != tracks->end (); track++) { - double Vertex_Z = track->vz(); - double Vertex_Z_Error = track->dzError(); - double track_eta = track->eta(); - double track_phi = track->phi(); - - if (DeltaR(track_eta,jet_eta, track_phi, jet_phi) < cone_size) { - - double DeltaZ = Vertex_Z-signal_vert_Z; - double DeltaZ_Error = sqrt((Vertex_Z_Error*Vertex_Z_Error)+(signal_vert_z_error*signal_vert_z_error)); - Pt_jets_X_tot += track->px(); - Pt_jets_Y_tot += track->py(); - if (cutType == "sig") discriminator = (fabs(DeltaZ)/DeltaZ_Error) <= cutSigmaZ; - else discriminator = fabs(DeltaZ) < cutDeltaZ; - - if (discriminator){ - - Pt_jets_X += track->px(); - Pt_jets_Y += track->py(); - - } - - } - } -} + double Pt_jets_X = 0.; + double Pt_jets_Y = 0.; + double Pt_jets_X_tot = 0.; + double Pt_jets_Y_tot = 0.; + + TrackCollection::const_iterator track = tracks->begin(); + + if (!tracks->empty()) { + for (; track != tracks->end(); track++) { + double Vertex_Z = track->vz(); + double Vertex_Z_Error = track->dzError(); + double track_eta = track->eta(); + double track_phi = track->phi(); + + if (DeltaR(track_eta, jet_eta, track_phi, jet_phi) < cone_size) { + double DeltaZ = Vertex_Z - signal_vert_Z; + double DeltaZ_Error = sqrt((Vertex_Z_Error * Vertex_Z_Error) + (signal_vert_z_error * signal_vert_z_error)); + Pt_jets_X_tot += track->px(); + Pt_jets_Y_tot += track->py(); + if (cutType == "sig") + discriminator = (fabs(DeltaZ) / DeltaZ_Error) <= cutSigmaZ; + else + discriminator = fabs(DeltaZ) < cutDeltaZ; + + if (discriminator) { + Pt_jets_X += track->px(); + Pt_jets_Y += track->py(); + } + } + } + } double Var = -1; - - if (Algo == 1) Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/jet_et; + + if (Algo == 1) + Var = Track_Pt(Pt_jets_X, Pt_jets_Y) / jet_et; else if (Algo == 2) { - if (Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot)!=0) Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot); - else std::cout << "[Jets] JetVertexAssociation: Warning! problems for Algo = 2: possible division by zero .." << std::endl; - } - else { - - Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/jet_et; - std::cout << "[Jets] JetVertexAssociation: Warning! Algo = " << Algo << " not found; using Algo = 1" << std::endl; + if (Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot) != 0) + Var = Track_Pt(Pt_jets_X, Pt_jets_Y) / Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot); + else + std::cout << "[Jets] JetVertexAssociation: Warning! problems for Algo = 2: possible division by zero .." + << std::endl; + } else { + Var = Track_Pt(Pt_jets_X, Pt_jets_Y) / jet_et; + std::cout << "[Jets] JetVertexAssociation: Warning! Algo = " << Algo << " not found; using Algo = 1" << std::endl; } // cout<<"Var = "<= threshold) parameter = std::pair(Var, true); - else parameter = std::pair(Var, false); + if (Var >= threshold) + parameter = std::pair(Var, true); + else + parameter = std::pair(Var, false); return parameter; - } -double JetVertexMain::DeltaR(double eta1, double eta2, double phi1, double phi2){ - - double dphi = fabs(phi1-phi2); - if(dphi > M_PI) dphi = 2*M_PI - dphi; - double deta = fabs(eta1-eta2); - return sqrt(dphi*dphi + deta*deta); - +double JetVertexMain::DeltaR(double eta1, double eta2, double phi1, double phi2) { + double dphi = fabs(phi1 - phi2); + if (dphi > M_PI) + dphi = 2 * M_PI - dphi; + double deta = fabs(eta1 - eta2); + return sqrt(dphi * dphi + deta * deta); } -double JetVertexMain::Track_Pt(double px, double py){ - - return sqrt(px*px+py*py); - -} +double JetVertexMain::Track_Pt(double px, double py) { return sqrt(px * px + py * py); } diff --git a/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.cc b/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.cc index e6ba98a6e0d5c..a54f6f733387b 100644 --- a/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.cc +++ b/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.cc @@ -28,69 +28,52 @@ using namespace edm; using namespace std; using namespace reco; -AnalysisJV::AnalysisJV(const edm::ParameterSet& pset) : - fOutputFileName( pset.getUntrackedParameter("HistOutFile",std::string("jv_analysis.root"))), - fResult1Token(consumes(edm::InputTag("jetvertex","Var"))), - fResult2Token(consumes(edm::InputTag("jetvertex","JetType"))), - fCaloJetsToken(consumes(edm::InputTag("iterativeCone5CaloJets"))) -{ +AnalysisJV::AnalysisJV(const edm::ParameterSet& pset) + : fOutputFileName(pset.getUntrackedParameter("HistOutFile", std::string("jv_analysis.root"))), + fResult1Token(consumes(edm::InputTag("jetvertex", "Var"))), + fResult2Token(consumes(edm::InputTag("jetvertex", "JetType"))), + fCaloJetsToken(consumes(edm::InputTag("iterativeCone5CaloJets"))) {} +AnalysisJV::~AnalysisJV() {} -} - - -AnalysisJV::~AnalysisJV() -{ - -} +void AnalysisJV::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + cout << "----------------------------" << endl; + Handle JV_alpha; + iEvent.getByToken(fResult1Token, JV_alpha); -void AnalysisJV::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ + Handle JV_jet_type; + iEvent.getByToken(fResult2Token, JV_jet_type); - cout <<"----------------------------"< CaloIconeJetsHandle; + iEvent.getByToken(fCaloJetsToken, CaloIconeJetsHandle); - Handle JV_alpha; - iEvent.getByToken(fResult1Token,JV_alpha); - - Handle JV_jet_type; - iEvent.getByToken(fResult2Token,JV_jet_type); - - Handle CaloIconeJetsHandle; - iEvent.getByToken( fCaloJetsToken, CaloIconeJetsHandle); - - if(CaloIconeJetsHandle->size()){ + if (CaloIconeJetsHandle->size()) { ResultCollection1::const_iterator it_jv1 = JV_alpha->begin(); ResultCollection2::const_iterator it_jv2 = JV_jet_type->begin(); - for(CaloJetCollection::const_iterator it=CaloIconeJetsHandle->begin();it!=CaloIconeJetsHandle->end();it++){ - - if(*it_jv2) cout<<"Jet: Et = "<pt()<<" - true jet"<Fill(*it_jv1); - it_jv1++; - it_jv2++; - - } + for (CaloJetCollection::const_iterator it = CaloIconeJetsHandle->begin(); it != CaloIconeJetsHandle->end(); it++) { + if (*it_jv2) + cout << "Jet: Et = " << it->pt() << " - true jet" << endl; + else + cout << "Jet: Et = " << it->pt() << " - 'fake' jet" << endl; + + fHistAlpha->Fill(*it_jv1); + it_jv1++; + it_jv2++; } - + } } - - -void AnalysisJV::beginJob(){ - - fOutputFile = new TFile( fOutputFileName.c_str(), "RECREATE" ) ; - fHistAlpha = new TH1D( "HistAlpha" , "", 30, 0., 1.5 ) ; - +void AnalysisJV::beginJob() { + fOutputFile = new TFile(fOutputFileName.c_str(), "RECREATE"); + fHistAlpha = new TH1D("HistAlpha", "", 30, 0., 1.5); } void AnalysisJV::endJob() { + fOutputFile->Write(); + fOutputFile->Close(); - fOutputFile->Write() ; - fOutputFile->Close() ; - - return ; + return; } //define this as a plug-in diff --git a/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.h b/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.h index d40e04d550445..26069ca108074 100644 --- a/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.h +++ b/JetMETCorrections/JetVertexAssociation/test/AnalysisJV.h @@ -18,27 +18,24 @@ // class AnalysisJV : public edm::EDAnalyzer { - public: - explicit AnalysisJV(const edm::ParameterSet&); - ~AnalysisJV(); +public: + explicit AnalysisJV(const edm::ParameterSet&); + ~AnalysisJV(); +private: + virtual void beginJob(); + virtual void analyze(const edm::Event&, const edm::EventSetup&); + virtual void endJob(); + std::string fOutputFileName; - private: - virtual void beginJob() ; - virtual void analyze(const edm::Event&, const edm::EventSetup&); - virtual void endJob() ; - std::string fOutputFileName ; - - TFile* fOutputFile ; - TH1D* fHistAlpha ; - - typedef std::vector ResultCollection1; - typedef std::vector ResultCollection2; - - edm::EDGetTokenT fResult1Token; - edm::EDGetTokenT fResult2Token; - edm::EDGetTokenT fCaloJetsToken; + TFile* fOutputFile; + TH1D* fHistAlpha; + typedef std::vector ResultCollection1; + typedef std::vector ResultCollection2; + edm::EDGetTokenT fResult1Token; + edm::EDGetTokenT fResult2Token; + edm::EDGetTokenT fCaloJetsToken; }; #endif diff --git a/PhysicsTools/JetExamples/test/printGenJetRatio.cc b/PhysicsTools/JetExamples/test/printGenJetRatio.cc index 98205ea781327..2c6456ffadf72 100644 --- a/PhysicsTools/JetExamples/test/printGenJetRatio.cc +++ b/PhysicsTools/JetExamples/test/printGenJetRatio.cc @@ -19,20 +19,18 @@ #include "SimDataFormats/JetMatching/interface/JetFlavourMatching.h" class printGenJetRatio : public edm::EDAnalyzer { - public: - typedef reco::JetFloatAssociation::Container JetBCEnergyRatioCollection; +public: + typedef reco::JetFloatAssociation::Container JetBCEnergyRatioCollection; - explicit printGenJetRatio(const edm::ParameterSet & ); - ~printGenJetRatio() {}; - void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); - - private: - - edm::EDGetTokenT sourceBratioToken_; - edm::EDGetTokenT sourceCratioToken_; - edm::Handle theBratioValue; - edm::Handle theCratioValue; + explicit printGenJetRatio(const edm::ParameterSet&); + ~printGenJetRatio(){}; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); +private: + edm::EDGetTokenT sourceBratioToken_; + edm::EDGetTokenT sourceCratioToken_; + edm::Handle theBratioValue; + edm::Handle theCratioValue; }; // system include files @@ -45,44 +43,38 @@ using namespace std; using namespace reco; using namespace edm; -printGenJetRatio::printGenJetRatio(const edm::ParameterSet& iConfig) -{ - sourceBratioToken_ = consumes(iConfig.getParameter ("srcBratio" )); - sourceCratioToken_ = consumes(iConfig.getParameter ("srcCratio" )); +printGenJetRatio::printGenJetRatio(const edm::ParameterSet& iConfig) { + sourceBratioToken_ = consumes(iConfig.getParameter("srcBratio")); + sourceCratioToken_ = consumes(iConfig.getParameter("srcCratio")); } -void printGenJetRatio::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void printGenJetRatio::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { cout << "[printGenJetRatio] analysing event " << iEvent.id() << endl; try { - iEvent.getByToken (sourceBratioToken_ , theBratioValue); - iEvent.getByToken (sourceCratioToken_ , theCratioValue); - } catch(std::exception& ce) { + iEvent.getByToken(sourceBratioToken_, theBratioValue); + iEvent.getByToken(sourceCratioToken_, theCratioValue); + } catch (std::exception& ce) { cerr << "[printJetFlavour] caught std::exception " << ce.what() << endl; return; } cout << "-------------------- GenJet Bratio ------------------------" << endl; - for ( JetBCEnergyRatioCollection::const_iterator itB = theBratioValue->begin(); - itB != theBratioValue->end(); - itB ++) { - const Jet &jetB = *(itB->first); + for (JetBCEnergyRatioCollection::const_iterator itB = theBratioValue->begin(); itB != theBratioValue->end(); itB++) { + const Jet& jetB = *(itB->first); float cR = 0; - for ( JetBCEnergyRatioCollection::const_iterator itC = theCratioValue->begin(); - itC != theCratioValue->end(); - itC ++) { - - if( itB->first == itC->first ) cR=itC->second; + for (JetBCEnergyRatioCollection::const_iterator itC = theCratioValue->begin(); itC != theCratioValue->end(); + itC++) { + if (itB->first == itC->first) + cR = itC->second; } printf("printGenJetRatio] (pt,eta,phi) jet = %7.3f %6.3f %6.3f | bcRatio = %7.5f - %7.5f \n", - jetB.et(), - jetB.eta(), - jetB.phi(), - itB->second, - cR - ); + jetB.et(), + jetB.eta(), + jetB.phi(), + itB->second, + cR); } } -DEFINE_FWK_MODULE( printGenJetRatio ); +DEFINE_FWK_MODULE(printGenJetRatio); diff --git a/PhysicsTools/JetExamples/test/printJetFlavour.cc b/PhysicsTools/JetExamples/test/printJetFlavour.cc index 6a9ebd9b4ec4b..b6fc9978eb840 100644 --- a/PhysicsTools/JetExamples/test/printJetFlavour.cc +++ b/PhysicsTools/JetExamples/test/printJetFlavour.cc @@ -1,4 +1,4 @@ - // user include files +// user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/ESHandle.h" @@ -32,17 +32,17 @@ #include class printJetFlavour : public edm::EDAnalyzer { - public: - explicit printJetFlavour(const edm::ParameterSet & ); - ~printJetFlavour() {}; - void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); +public: + explicit printJetFlavour(const edm::ParameterSet&); + ~printJetFlavour(){}; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); - private: - edm::InputTag sourcePartons_; - edm::EDGetTokenT sourceByReferToken_; - edm::EDGetTokenT sourceByValueToken_; - edm::Handle theTagByRef; - edm::Handle theTagByValue; +private: + edm::InputTag sourcePartons_; + edm::EDGetTokenT sourceByReferToken_; + edm::EDGetTokenT sourceByValueToken_; + edm::Handle theTagByRef; + edm::Handle theTagByValue; }; using namespace std; @@ -50,101 +50,78 @@ using namespace reco; using namespace edm; using namespace ROOT::Math::VectorUtil; -printJetFlavour::printJetFlavour(const edm::ParameterSet& iConfig) -{ - sourceByReferToken_ = consumes(iConfig.getParameter ("srcByReference")); - sourceByValueToken_ = consumes(iConfig.getParameter ("srcByValue")); +printJetFlavour::printJetFlavour(const edm::ParameterSet& iConfig) { + sourceByReferToken_ = consumes(iConfig.getParameter("srcByReference")); + sourceByValueToken_ = consumes(iConfig.getParameter("srcByValue")); } -void printJetFlavour::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void printJetFlavour::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { cout << "[printJetFlavour] analysing event " << iEvent.id() << endl; try { - iEvent.getByToken (sourceByReferToken_ , theTagByRef ); - iEvent.getByToken (sourceByValueToken_ , theTagByValue ); - } catch(std::exception& ce) { + iEvent.getByToken(sourceByReferToken_, theTagByRef); + iEvent.getByToken(sourceByValueToken_, theTagByValue); + } catch (std::exception& ce) { cerr << "[printJetFlavour] caught std::exception " << ce.what() << endl; return; } cout << "-------------------- Jet Flavour by Ref From Partons--------------" << endl; - for ( JetMatchedPartonsCollection::const_iterator j = theTagByRef->begin(); - j != theTagByRef->end(); - j ++ ) { - const Jet *aJet = (*j).first.get(); + for (JetMatchedPartonsCollection::const_iterator j = theTagByRef->begin(); j != theTagByRef->end(); j++) { + const Jet* aJet = (*j).first.get(); const MatchedPartons aMatch = (*j).second; - printf("[printJetFlavour] (pt,eta,phi) jet = %7.2f %6.3f %6.3f \n", - aJet->et(), - aJet->eta(), - aJet->phi() - ); - const GenParticleRef theHeaviest = aMatch.heaviest() ; - if(theHeaviest.isNonnull()) { - float dist = DeltaR( aJet->p4(), theHeaviest.get()->p4() ); - cout << setprecision(2) << setw(6) << fixed << - " theHeaviest flav (pt,eta,phi)=" << theHeaviest.get()->pdgId() - << " (" << theHeaviest.get()->et() - << "," << theHeaviest.get()->eta() - << "," << theHeaviest.get()->phi() - << ") Dr=" << dist << endl; + printf("[printJetFlavour] (pt,eta,phi) jet = %7.2f %6.3f %6.3f \n", aJet->et(), aJet->eta(), aJet->phi()); + const GenParticleRef theHeaviest = aMatch.heaviest(); + if (theHeaviest.isNonnull()) { + float dist = DeltaR(aJet->p4(), theHeaviest.get()->p4()); + cout << setprecision(2) << setw(6) << fixed + << " theHeaviest flav (pt,eta,phi)=" << theHeaviest.get()->pdgId() << " (" + << theHeaviest.get()->et() << "," << theHeaviest.get()->eta() << "," << theHeaviest.get()->phi() + << ") Dr=" << dist << endl; } - const GenParticleRef theNearest2 = aMatch.nearest_status2() ; - if(theNearest2.isNonnull()) { - float dist = DeltaR( aJet->p4(), theNearest2.get()->p4() ); - cout << " theNearest Stat2 flav (pt,eta,phi)=" << theNearest2.get()->pdgId() - << " (" << theNearest2.get()->et() - << "," << theNearest2.get()->eta() - << "," << theNearest2.get()->phi() - << ") Dr=" << dist << endl; + const GenParticleRef theNearest2 = aMatch.nearest_status2(); + if (theNearest2.isNonnull()) { + float dist = DeltaR(aJet->p4(), theNearest2.get()->p4()); + cout << " theNearest Stat2 flav (pt,eta,phi)=" << theNearest2.get()->pdgId() << " (" + << theNearest2.get()->et() << "," << theNearest2.get()->eta() << "," << theNearest2.get()->phi() + << ") Dr=" << dist << endl; } - const GenParticleRef theNearest3 = aMatch.nearest_status3() ; - if(theNearest3.isNonnull()) { - float dist = DeltaR( aJet->p4(), theNearest3.get()->p4() ); - cout << " theNearest Stat3 flav (pt,eta,phi)=" << theNearest3.get()->pdgId() - << " (" << theNearest3.get()->et() - << "," << theNearest3.get()->eta() - << "," << theNearest3.get()->phi() - << ") Dr=" << dist << endl; + const GenParticleRef theNearest3 = aMatch.nearest_status3(); + if (theNearest3.isNonnull()) { + float dist = DeltaR(aJet->p4(), theNearest3.get()->p4()); + cout << " theNearest Stat3 flav (pt,eta,phi)=" << theNearest3.get()->pdgId() << " (" + << theNearest3.get()->et() << "," << theNearest3.get()->eta() << "," << theNearest3.get()->phi() + << ") Dr=" << dist << endl; } - const GenParticleRef thePhyDef = aMatch.physicsDefinitionParton() ; - if(thePhyDef.isNonnull()) { - float dist = DeltaR( aJet->p4(), thePhyDef.get()->p4() ); - cout << " thePhysDefinition flav (pt,eta,phi)=" << thePhyDef.get()->pdgId() - << " (" << thePhyDef.get()->et() - << "," << thePhyDef.get()->eta() - << "," << thePhyDef.get()->phi() - << ") Dr=" << dist << endl; + const GenParticleRef thePhyDef = aMatch.physicsDefinitionParton(); + if (thePhyDef.isNonnull()) { + float dist = DeltaR(aJet->p4(), thePhyDef.get()->p4()); + cout << " thePhysDefinition flav (pt,eta,phi)=" << thePhyDef.get()->pdgId() << " (" + << thePhyDef.get()->et() << "," << thePhyDef.get()->eta() << "," << thePhyDef.get()->phi() << ") Dr=" << dist + << endl; } - const GenParticleRef theAlgDef = aMatch.algoDefinitionParton() ; - if(theAlgDef.isNonnull()) { - float dist = DeltaR( aJet->p4(), theAlgDef.get()->p4() ); - cout << " theAlgoDefinition flav (pt,eta,phi)=" << theAlgDef.get()->pdgId() - << " (" << theAlgDef.get()->et() - << "," << theAlgDef.get()->eta() - << "," << theAlgDef.get()->phi() - << ") Dr=" << dist << endl; + const GenParticleRef theAlgDef = aMatch.algoDefinitionParton(); + if (theAlgDef.isNonnull()) { + float dist = DeltaR(aJet->p4(), theAlgDef.get()->p4()); + cout << " theAlgoDefinition flav (pt,eta,phi)=" << theAlgDef.get()->pdgId() << " (" + << theAlgDef.get()->et() << "," << theAlgDef.get()->eta() << "," << theAlgDef.get()->phi() << ") Dr=" << dist + << endl; } } - cout << "-------------------- Jet Flavour by Value ------------------------" << endl; - for ( JetFlavourMatchingCollection::const_iterator j = theTagByValue->begin(); - j != theTagByValue->end(); - j ++ ) { - RefToBase aJet = (*j).first; + for (JetFlavourMatchingCollection::const_iterator j = theTagByValue->begin(); j != theTagByValue->end(); j++) { + RefToBase aJet = (*j).first; const JetFlavour aFlav = (*j).second; printf("[printJetFlavour] (pt,eta,phi) jet = %7.2f %6.3f %6.3f | parton = %7.2f %6.3f %6.3f | %4d\n", - aJet.get()->et(), - aJet.get()->eta(), - aJet.get()->phi(), - aFlav.getLorentzVector().pt(), - aFlav.getLorentzVector().eta(), - aFlav.getLorentzVector().phi(), - aFlav.getFlavour() - ); + aJet.get()->et(), + aJet.get()->eta(), + aJet.get()->phi(), + aFlav.getLorentzVector().pt(), + aFlav.getLorentzVector().eta(), + aFlav.getLorentzVector().phi(), + aFlav.getFlavour()); } - } -DEFINE_FWK_MODULE( printJetFlavour ); +DEFINE_FWK_MODULE(printJetFlavour); diff --git a/PhysicsTools/JetExamples/test/printJetFlavourInfo.cc b/PhysicsTools/JetExamples/test/printJetFlavourInfo.cc index ea9287cc44fb4..23ee2a4eee7c2 100644 --- a/PhysicsTools/JetExamples/test/printJetFlavourInfo.cc +++ b/PhysicsTools/JetExamples/test/printJetFlavourInfo.cc @@ -16,170 +16,140 @@ // system include files #include - class printJetFlavourInfo : public edm::EDAnalyzer { - public: - explicit printJetFlavourInfo(const edm::ParameterSet & ); - ~printJetFlavourInfo() {}; - void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); - - private: - edm::EDGetTokenT jetFlavourInfosToken_; - edm::EDGetTokenT subjetFlavourInfosToken_; - edm::EDGetTokenT > groomedJetsToken_; - bool useSubjets_; +public: + explicit printJetFlavourInfo(const edm::ParameterSet&); + ~printJetFlavourInfo(){}; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); + +private: + edm::EDGetTokenT jetFlavourInfosToken_; + edm::EDGetTokenT subjetFlavourInfosToken_; + edm::EDGetTokenT > groomedJetsToken_; + bool useSubjets_; }; -printJetFlavourInfo::printJetFlavourInfo(const edm::ParameterSet& iConfig) -{ - jetFlavourInfosToken_ = consumes( iConfig.getParameter("jetFlavourInfos") ); - subjetFlavourInfosToken_ = mayConsume( iConfig.exists("subjetFlavourInfos") ? iConfig.getParameter("subjetFlavourInfos") : edm::InputTag() ); - groomedJetsToken_ = mayConsume >( iConfig.exists("groomedJets") ? iConfig.getParameter("groomedJets") : edm::InputTag() ); - useSubjets_ = ( iConfig.exists("subjetFlavourInfos") && iConfig.exists("groomedJets") ); +printJetFlavourInfo::printJetFlavourInfo(const edm::ParameterSet& iConfig) { + jetFlavourInfosToken_ = + consumes(iConfig.getParameter("jetFlavourInfos")); + subjetFlavourInfosToken_ = mayConsume( + iConfig.exists("subjetFlavourInfos") ? iConfig.getParameter("subjetFlavourInfos") + : edm::InputTag()); + groomedJetsToken_ = mayConsume >( + iConfig.exists("groomedJets") ? iConfig.getParameter("groomedJets") : edm::InputTag()); + useSubjets_ = (iConfig.exists("subjetFlavourInfos") && iConfig.exists("groomedJets")); } -void printJetFlavourInfo::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void printJetFlavourInfo::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { edm::Handle theJetFlavourInfos; - iEvent.getByToken(jetFlavourInfosToken_, theJetFlavourInfos ); + iEvent.getByToken(jetFlavourInfosToken_, theJetFlavourInfos); edm::Handle theSubjetFlavourInfos; edm::Handle > groomedJets; - std::vector matchedIndices; - if( useSubjets_ ) - { + std::vector matchedIndices; + if (useSubjets_) { iEvent.getByToken(subjetFlavourInfosToken_, theSubjetFlavourInfos); iEvent.getByToken(groomedJetsToken_, groomedJets); // match groomed and original jet - std::vector jetLocks(theJetFlavourInfos->size(),false); - std::vector jetIndices; + std::vector jetLocks(theJetFlavourInfos->size(), false); + std::vector jetIndices; - for(size_t gj=0; gjsize(); ++gj) - { + for (size_t gj = 0; gj < groomedJets->size(); ++gj) { double matchedDR2 = 1e9; int matchedIdx = -1; - if( groomedJets->at(gj).pt()>0. ) // skips pathological cases of groomed jets with Pt=0 + if (groomedJets->at(gj).pt() > 0.) // skips pathological cases of groomed jets with Pt=0 { - for(reco::JetFlavourInfoMatchingCollection::const_iterator j = theJetFlavourInfos->begin(); - j != theJetFlavourInfos->end(); - ++j) - { - if( jetLocks.at(j - theJetFlavourInfos->begin()) ) continue; // skip jets that have already been matched - - double tempDR2 = reco::deltaR2( j->first->rapidity(), j->first->phi(), groomedJets->at(gj).rapidity(), groomedJets->at(gj).phi() ); - if( tempDR2 < matchedDR2 ) - { + for (reco::JetFlavourInfoMatchingCollection::const_iterator j = theJetFlavourInfos->begin(); + j != theJetFlavourInfos->end(); + ++j) { + if (jetLocks.at(j - theJetFlavourInfos->begin())) + continue; // skip jets that have already been matched + + double tempDR2 = reco::deltaR2( + j->first->rapidity(), j->first->phi(), groomedJets->at(gj).rapidity(), groomedJets->at(gj).phi()); + if (tempDR2 < matchedDR2) { matchedDR2 = tempDR2; matchedIdx = (j - theJetFlavourInfos->begin()); } } } - if( matchedIdx>=0 ) jetLocks.at(matchedIdx) = true; + if (matchedIdx >= 0) + jetLocks.at(matchedIdx) = true; jetIndices.push_back(matchedIdx); } - for(size_t j=0; jsize(); ++j) - { - std::vector::iterator matchedIndex = std::find( jetIndices.begin(), jetIndices.end(), j ); + for (size_t j = 0; j < theJetFlavourInfos->size(); ++j) { + std::vector::iterator matchedIndex = std::find(jetIndices.begin(), jetIndices.end(), j); - matchedIndices.push_back( matchedIndex != jetIndices.end() ? std::distance(jetIndices.begin(),matchedIndex) : -1 ); + matchedIndices.push_back(matchedIndex != jetIndices.end() ? std::distance(jetIndices.begin(), matchedIndex) : -1); } } - for ( reco::JetFlavourInfoMatchingCollection::const_iterator j = theJetFlavourInfos->begin(); - j != theJetFlavourInfos->end(); - ++j ) { + for (reco::JetFlavourInfoMatchingCollection::const_iterator j = theJetFlavourInfos->begin(); + j != theJetFlavourInfos->end(); + ++j) { std::cout << "-------------------- Jet Flavour Info --------------------" << std::endl; - const reco::Jet *aJet = (*j).first.get(); + const reco::Jet* aJet = (*j).first.get(); reco::JetFlavourInfo aInfo = (*j).second; - std::cout << std::setprecision(2) << std::setw(6) << std::fixed - << "[printJetFlavourInfo] Jet " << (j - theJetFlavourInfos->begin()) << " pt, eta, rapidity, phi = " << aJet->pt() << ", " - << aJet->eta() << ", " - << aJet->rapidity() << ", " - << aJet->phi() - << std::endl; + std::cout << std::setprecision(2) << std::setw(6) << std::fixed << "[printJetFlavourInfo] Jet " + << (j - theJetFlavourInfos->begin()) << " pt, eta, rapidity, phi = " << aJet->pt() << ", " << aJet->eta() + << ", " << aJet->rapidity() << ", " << aJet->phi() << std::endl; // ----------------------- Hadrons ------------------------------- std::cout << " Hadron-based flavour: " << aInfo.getHadronFlavour() << std::endl; - const reco::GenParticleRefVector & bHadrons = aInfo.getbHadrons(); + const reco::GenParticleRefVector& bHadrons = aInfo.getbHadrons(); std::cout << " # of clustered b hadrons: " << bHadrons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = bHadrons.begin(); it != bHadrons.end(); ++it) - { - float dist = reco::deltaR( aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " b hadron " << (it-bHadrons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = bHadrons.begin(); it != bHadrons.end(); ++it) { + float dist = reco::deltaR(aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " b hadron " << (it - bHadrons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() << "," + << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } - const reco::GenParticleRefVector & cHadrons = aInfo.getcHadrons(); + const reco::GenParticleRefVector& cHadrons = aInfo.getcHadrons(); std::cout << " # of clustered c hadrons: " << cHadrons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = cHadrons.begin(); it != cHadrons.end(); ++it) - { - float dist = reco::deltaR( aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " c hadron " << (it-cHadrons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = cHadrons.begin(); it != cHadrons.end(); ++it) { + float dist = reco::deltaR(aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " c hadron " << (it - cHadrons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() << "," + << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } // ----------------------- Partons ------------------------------- std::cout << " Parton-based flavour: " << aInfo.getPartonFlavour() << std::endl; - const reco::GenParticleRefVector & partons = aInfo.getPartons(); + const reco::GenParticleRefVector& partons = aInfo.getPartons(); std::cout << " # of clustered partons: " << partons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = partons.begin(); it != partons.end(); ++it) - { - float dist = reco::deltaR( aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " Parton " << (it-partons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = partons.begin(); it != partons.end(); ++it) { + float dist = reco::deltaR(aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " Parton " << (it - partons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() << "," + << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } // ----------------------- Leptons ------------------------------- - const reco::GenParticleRefVector & leptons = aInfo.getLeptons(); + const reco::GenParticleRefVector& leptons = aInfo.getLeptons(); std::cout << " # of clustered leptons: " << leptons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = leptons.begin(); it != leptons.end(); ++it) - { - float dist = reco::deltaR( aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " Lepton " << (it-leptons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = leptons.begin(); it != leptons.end(); ++it) { + float dist = reco::deltaR(aJet->eta(), aJet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aJet->rapidity(), aJet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " Lepton " << (it - leptons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() << "," + << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } - if( useSubjets_ ) - { - if( matchedIndices.at(j - theJetFlavourInfos->begin())<0 ) - { + if (useSubjets_) { + if (matchedIndices.at(j - theJetFlavourInfos->begin()) < 0) { std::cout << " ----------------------- Subjet Flavour Info -----------------------" << std::endl; std::cout << " No subjets assigned to this jet" << std::endl; continue; @@ -187,97 +157,71 @@ void printJetFlavourInfo::analyze(const edm::Event& iEvent, const edm::EventSetu // loop over subjets std::cout << " ----------------------- Subjet Flavour Info -----------------------" << std::endl; - for(size_t s=0; sat(matchedIndices.at(j - theJetFlavourInfos->begin())).numberOfDaughters(); ++s) - { - const edm::Ptr & subjet = groomedJets->at(matchedIndices.at(j - theJetFlavourInfos->begin())).daughterPtr(s); - - for ( reco::JetFlavourInfoMatchingCollection::const_iterator sj = theSubjetFlavourInfos->begin(); - sj != theSubjetFlavourInfos->end(); - ++sj ) { - if( subjet != edm::Ptr((*sj).first.id(), (*sj).first.get(), (*sj).first.key()) ) continue; - - const reco::Jet *aSubjet = (*sj).first.get(); + for (size_t s = 0; s < groomedJets->at(matchedIndices.at(j - theJetFlavourInfos->begin())).numberOfDaughters(); + ++s) { + const edm::Ptr& subjet = + groomedJets->at(matchedIndices.at(j - theJetFlavourInfos->begin())).daughterPtr(s); + + for (reco::JetFlavourInfoMatchingCollection::const_iterator sj = theSubjetFlavourInfos->begin(); + sj != theSubjetFlavourInfos->end(); + ++sj) { + if (subjet != edm::Ptr((*sj).first.id(), (*sj).first.get(), (*sj).first.key())) + continue; + + const reco::Jet* aSubjet = (*sj).first.get(); aInfo = (*sj).second; - std::cout << std::setprecision(2) << std::setw(6) << std::fixed - << " [printSubjetFlavourInfo] Subjet " << s << " pt, eta, rapidity, phi, dR(eta-phi), dR(rap-phi) = " - << aSubjet->pt() << ", " - << aSubjet->eta() << ", " - << aSubjet->rapidity() << ", " - << aSubjet->phi() << ", " - << reco::deltaR( aSubjet->eta(), aSubjet->phi(), aJet->eta(), aJet->phi() ) << ", " - << reco::deltaR( aSubjet->rapidity(), aSubjet->phi(), aJet->rapidity(), aJet->phi() ) - << std::endl; + std::cout << std::setprecision(2) << std::setw(6) << std::fixed << " [printSubjetFlavourInfo] Subjet " << s + << " pt, eta, rapidity, phi, dR(eta-phi), dR(rap-phi) = " << aSubjet->pt() << ", " << aSubjet->eta() + << ", " << aSubjet->rapidity() << ", " << aSubjet->phi() << ", " + << reco::deltaR(aSubjet->eta(), aSubjet->phi(), aJet->eta(), aJet->phi()) << ", " + << reco::deltaR(aSubjet->rapidity(), aSubjet->phi(), aJet->rapidity(), aJet->phi()) << std::endl; // ----------------------- Hadrons ------------------------------- std::cout << " Hadron-based flavour: " << aInfo.getHadronFlavour() << std::endl; - const reco::GenParticleRefVector & bHadrons = aInfo.getbHadrons(); + const reco::GenParticleRefVector& bHadrons = aInfo.getbHadrons(); std::cout << " # of assigned b hadrons: " << bHadrons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = bHadrons.begin(); it != bHadrons.end(); ++it) - { - float dist = reco::deltaR( aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " b hadron " << (it-bHadrons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = bHadrons.begin(); it != bHadrons.end(); ++it) { + float dist = reco::deltaR(aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " b hadron " << (it - bHadrons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() + << "," << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } - const reco::GenParticleRefVector & cHadrons = aInfo.getcHadrons(); + const reco::GenParticleRefVector& cHadrons = aInfo.getcHadrons(); std::cout << " # of assigned c hadrons: " << cHadrons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = cHadrons.begin(); it != cHadrons.end(); ++it) - { - float dist = reco::deltaR( aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " c hadron " << (it-cHadrons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = cHadrons.begin(); it != cHadrons.end(); ++it) { + float dist = reco::deltaR(aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " c hadron " << (it - cHadrons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() + << "," << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } // ----------------------- Partons ------------------------------- std::cout << " Parton-based flavour: " << aInfo.getPartonFlavour() << std::endl; - const reco::GenParticleRefVector & partons = aInfo.getPartons(); + const reco::GenParticleRefVector& partons = aInfo.getPartons(); std::cout << " # of assigned partons: " << partons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = partons.begin(); it != partons.end(); ++it) - { - float dist = reco::deltaR( aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " Parton " << (it-partons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = partons.begin(); it != partons.end(); ++it) { + float dist = reco::deltaR(aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " Parton " << (it - partons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() + << "," << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } // ----------------------- Leptons ------------------------------- - const reco::GenParticleRefVector & leptons = aInfo.getLeptons(); + const reco::GenParticleRefVector& leptons = aInfo.getLeptons(); std::cout << " # of assigned leptons: " << leptons.size() << std::endl; - for(reco::GenParticleRefVector::const_iterator it = leptons.begin(); it != leptons.end(); ++it) - { - float dist = reco::deltaR( aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi() ); - float dist2 = reco::deltaR( aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi() ); - std::cout << " Lepton " << (it-leptons.begin()) - << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() - << ", " << (*it)->status() - << ", (" << (*it)->pt() - << "," << (*it)->eta() - << "," << (*it)->rapidity() - << "," << (*it)->phi() - << "), " << dist - << ", " << dist2 << std::endl; + for (reco::GenParticleRefVector::const_iterator it = leptons.begin(); it != leptons.end(); ++it) { + float dist = reco::deltaR(aSubjet->eta(), aSubjet->phi(), (*it)->eta(), (*it)->phi()); + float dist2 = reco::deltaR(aSubjet->rapidity(), aSubjet->phi(), (*it)->rapidity(), (*it)->phi()); + std::cout << " Lepton " << (it - leptons.begin()) + << " PdgID, status, (pt,eta,rapidity,phi), dR(eta-phi), dR(rap-phi) = " << (*it)->pdgId() << ", " + << (*it)->status() << ", (" << (*it)->pt() << "," << (*it)->eta() << "," << (*it)->rapidity() + << "," << (*it)->phi() << "), " << dist << ", " << dist2 << std::endl; } } } @@ -285,4 +229,4 @@ void printJetFlavourInfo::analyze(const edm::Event& iEvent, const edm::EventSetu } } -DEFINE_FWK_MODULE( printJetFlavourInfo ); +DEFINE_FWK_MODULE(printJetFlavourInfo); diff --git a/PhysicsTools/JetExamples/test/printPartonJet.cc b/PhysicsTools/JetExamples/test/printPartonJet.cc index 1b9f7632ac31d..7e803c030d967 100644 --- a/PhysicsTools/JetExamples/test/printPartonJet.cc +++ b/PhysicsTools/JetExamples/test/printPartonJet.cc @@ -28,30 +28,27 @@ using namespace reco; using namespace edm; class printPartonJet : public edm::EDAnalyzer { - public: - explicit printPartonJet(const edm::ParameterSet & ); - ~printPartonJet() {}; - void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); +public: + explicit printPartonJet(const edm::ParameterSet&); + ~printPartonJet(){}; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); - private: - - edm::EDGetTokenT< View > sourceToken_; - string fOutputFileName_; - Handle< View > partonJets; +private: + edm::EDGetTokenT > sourceToken_; + string fOutputFileName_; + Handle > partonJets; }; -printPartonJet::printPartonJet(const edm::ParameterSet& iConfig) -{ - sourceToken_ = consumes< View >(iConfig.getParameter ("src")); +printPartonJet::printPartonJet(const edm::ParameterSet& iConfig) { + sourceToken_ = consumes >(iConfig.getParameter("src")); } -void printPartonJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void printPartonJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { cout << "[printPartonJet] analysing event " << iEvent.id() << endl; try { - iEvent.getByToken (sourceToken_ ,partonJets); - } catch(std::exception& ce) { + iEvent.getByToken(sourceToken_, partonJets); + } catch (std::exception& ce) { cerr << "[printPartonJet] caught std::exception " << ce.what() << endl; return; } @@ -59,22 +56,16 @@ void printPartonJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iS cout << "************************" << endl; cout << "* PartonJetCollection *" << endl; cout << "************************" << endl; - for( size_t j = 0; j != partonJets->size(); ++j ) { - + for (size_t j = 0; j != partonJets->size(); ++j) { printf("[printPartonJet] (pt,eta,phi) = %7.3f %6.3f %6.3f |\n", - (*partonJets)[j].et(), - (*partonJets)[j].eta(), - (*partonJets)[j].phi() ); - for( Candidate::const_iterator itC = (*partonJets)[j].begin(); - itC != (*partonJets)[j].end(); - itC ++) { - cout << " Constituent (pt,eta,phi,pdgId): " - << itC->pt() << " " - << itC->eta() << " " - << itC->phi() << " " - << itC->pdgId() << endl; + (*partonJets)[j].et(), + (*partonJets)[j].eta(), + (*partonJets)[j].phi()); + for (Candidate::const_iterator itC = (*partonJets)[j].begin(); itC != (*partonJets)[j].end(); itC++) { + cout << " Constituent (pt,eta,phi,pdgId): " << itC->pt() << " " << itC->eta() << " " << itC->phi() + << " " << itC->pdgId() << endl; } } } -DEFINE_FWK_MODULE( printPartonJet ); +DEFINE_FWK_MODULE(printPartonJet); diff --git a/PhysicsTools/JetExamples/test/printTrackJet.cc b/PhysicsTools/JetExamples/test/printTrackJet.cc index 19a4fdec0e107..1455deb316cb0 100644 --- a/PhysicsTools/JetExamples/test/printTrackJet.cc +++ b/PhysicsTools/JetExamples/test/printTrackJet.cc @@ -21,29 +21,26 @@ using namespace reco; using namespace edm; class printTrackJet : public edm::EDAnalyzer { - public: - explicit printTrackJet(const edm::ParameterSet & ); - ~printTrackJet() {}; - void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); - - private: - - edm::EDGetTokenT sourceToken_; - edm::Handle trackJets; +public: + explicit printTrackJet(const edm::ParameterSet&); + ~printTrackJet(){}; + void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup); + +private: + edm::EDGetTokenT sourceToken_; + edm::Handle trackJets; }; -printTrackJet::printTrackJet(const edm::ParameterSet& iConfig) -{ - sourceToken_ = consumes(iConfig.getParameter ("src")); +printTrackJet::printTrackJet(const edm::ParameterSet& iConfig) { + sourceToken_ = consumes(iConfig.getParameter("src")); } -void printTrackJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ +void printTrackJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { cout << "[printTrackJet] analysing event " << iEvent.id() << endl; try { - iEvent.getByToken (sourceToken_ ,trackJets); - } catch(std::exception& ce) { + iEvent.getByToken(sourceToken_, trackJets); + } catch (std::exception& ce) { cerr << "[printTrackJet] caught std::exception " << ce.what() << endl; return; } @@ -51,24 +48,13 @@ void printTrackJet::analyze(const edm::Event& iEvent, const edm::EventSetup& iSe cout << "************************" << endl; cout << "* TrackJetCollection *" << endl; cout << "************************" << endl; - for( CandidateView::const_iterator f = trackJets->begin(); - f != trackJets->end(); - f++) { - - printf("[printTrackJet] (pt,eta,phi) = %7.3f %6.3f %6.3f |\n", - f->et(), - f->eta(), - f->phi() ); + for (CandidateView::const_iterator f = trackJets->begin(); f != trackJets->end(); f++) { + printf("[printTrackJet] (pt,eta,phi) = %7.3f %6.3f %6.3f |\n", f->et(), f->eta(), f->phi()); - for( Candidate::const_iterator c = f->begin(); - c != f->end(); - c ++) { - printf(" [Constituents] (pt,eta,phi) = %6.2f %5.2f %5.2f|\n", - c->et(), - c->eta(), - c->phi() ); - } + for (Candidate::const_iterator c = f->begin(); c != f->end(); c++) { + printf(" [Constituents] (pt,eta,phi) = %6.2f %5.2f %5.2f|\n", c->et(), c->eta(), c->phi()); + } } } -DEFINE_FWK_MODULE( printTrackJet ); +DEFINE_FWK_MODULE(printTrackJet); diff --git a/PhysicsTools/JetMCUtils/interface/CandMCTag.h b/PhysicsTools/JetMCUtils/interface/CandMCTag.h index 882b7a659ae10..a00c45a9462e9 100644 --- a/PhysicsTools/JetMCUtils/interface/CandMCTag.h +++ b/PhysicsTools/JetMCUtils/interface/CandMCTag.h @@ -11,5 +11,5 @@ namespace CandMCTagUtils { bool isParton(const reco::Candidate &c); bool isLightParton(const reco::Candidate &c); -} -#endif // CandMCTag_h +} // namespace CandMCTagUtils +#endif // CandMCTag_h diff --git a/PhysicsTools/JetMCUtils/interface/JetMCTag.h b/PhysicsTools/JetMCUtils/interface/JetMCTag.h index cca38e925d798..a59c45d4428c6 100644 --- a/PhysicsTools/JetMCUtils/interface/JetMCTag.h +++ b/PhysicsTools/JetMCUtils/interface/JetMCTag.h @@ -8,9 +8,9 @@ namespace JetMCTagUtils { double EnergyRatioFromBHadrons(const reco::Candidate &c); double EnergyRatioFromCHadrons(const reco::Candidate &c); - bool decayFromBHadron(const reco::Candidate &c); - bool decayFromCHadron(const reco::Candidate &c); + bool decayFromBHadron(const reco::Candidate &c); + bool decayFromCHadron(const reco::Candidate &c); std::string genTauDecayMode(const reco::CompositePtrCandidate &c); -} -#endif // JetMCTag_h +} // namespace JetMCTagUtils +#endif // JetMCTag_h diff --git a/PhysicsTools/JetMCUtils/interface/combination.h b/PhysicsTools/JetMCUtils/interface/combination.h index df5541218ed37..7d15b43371638 100644 --- a/PhysicsTools/JetMCUtils/interface/combination.h +++ b/PhysicsTools/JetMCUtils/interface/combination.h @@ -4,370 +4,292 @@ //======================================================= // Copyright 2003 - 2006 Wong Shao Voon // No warranty, implied or expressed, is included. -// Author is not liable for any type of loss through +// Author is not liable for any type of loss through // the use of this source code. Use it at your own risk! //======================================================= - #ifndef __COMBINATION_H__ #define __COMBINATION_H__ +namespace stdcomb { + + // Non recursive template function + template + + inline bool next_combination(BidIt n_begin, BidIt n_end, BidIt r_begin, BidIt r_end) { + bool boolmarked = false; + BidIt r_marked; -namespace stdcomb -{ - -// Non recursive template function -template - -inline bool next_combination(BidIt n_begin, BidIt n_end, -BidIt r_begin, BidIt r_end) -{ - - bool boolmarked=false; - BidIt r_marked; - - BidIt n_it1=n_end; - --n_it1; - - - BidIt tmp_r_end=r_end; - --tmp_r_end; - - for(BidIt r_it1=tmp_r_end; r_it1!=r_begin || r_it1==r_begin; --r_it1,--n_it1) - { - if(*r_it1==*n_it1 ) - { - if(r_it1!=r_begin) //to ensure not at the start of r sequence + BidIt n_it1 = n_end; + --n_it1; + + BidIt tmp_r_end = r_end; + --tmp_r_end; + + for (BidIt r_it1 = tmp_r_end; r_it1 != r_begin || r_it1 == r_begin; --r_it1, --n_it1) { + if (*r_it1 == *n_it1) { + if (r_it1 != r_begin) //to ensure not at the start of r sequence + { + boolmarked = true; + r_marked = (--r_it1); + ++r_it1; //add it back again + continue; + } else // it means it is at the start the sequence, so return false + return false; + } else //if(*r_it1!=*n_it1 ) { - boolmarked=true; - r_marked=(--r_it1); - ++r_it1;//add it back again - continue; + //marked code + if (boolmarked == true) { + //for loop to find which marked is in the first sequence + BidIt n_marked; //mark in first sequence + for (BidIt n_it2 = n_begin; n_it2 != n_end; ++n_it2) + if (*r_marked == *n_it2) { + n_marked = n_it2; + break; + } + + BidIt n_it3 = ++n_marked; + for (BidIt r_it2 = r_marked; r_it2 != r_end; ++r_it2, ++n_it3) { + *r_it2 = *n_it3; + } + return true; + } + for (BidIt n_it4 = n_begin; n_it4 != n_end; ++n_it4) + if (*r_it1 == *n_it4) { + *r_it1 = *(++n_it4); + return true; + } } - else // it means it is at the start the sequence, so return false - return false; } - else //if(*r_it1!=*n_it1 ) - { - //marked code - if(boolmarked==true) - { - //for loop to find which marked is in the first sequence - BidIt n_marked;//mark in first sequence - for (BidIt n_it2=n_begin;n_it2!=n_end;++n_it2) - if(*r_marked==*n_it2) {n_marked=n_it2;break;} - - - BidIt n_it3=++n_marked; - for (BidIt r_it2=r_marked;r_it2!=r_end;++r_it2,++n_it3) + + return true; //will never reach here + } + + // Non recursive template function with Pred + template + + inline bool next_combination(BidIt n_begin, BidIt n_end, BidIt r_begin, BidIt r_end, Prediate Equal) { + bool boolmarked = false; + BidIt r_marked; + + BidIt n_it1 = n_end; + --n_it1; + + BidIt tmp_r_end = r_end; + --tmp_r_end; + + for (BidIt r_it1 = tmp_r_end; r_it1 != r_begin || r_it1 == r_begin; --r_it1, --n_it1) { + if (Equal(*r_it1, *n_it1)) { + if (r_it1 != r_begin) //to ensure not at the start of r sequence { - *r_it2=*n_it3; + boolmarked = true; + r_marked = (--r_it1); + ++r_it1; //add it back again + continue; + } else // it means it is at the start the sequence, so return false + return false; + } else //if(*r_it1!=*n_it1 ) + { + //marked code + if (boolmarked == true) { + //for loop to find which marked is in the first sequence + BidIt n_marked; //mark in first sequence + for (BidIt n_it2 = n_begin; n_it2 != n_end; ++n_it2) + if (Equal(*r_marked, *n_it2)) { + n_marked = n_it2; + break; + } + + BidIt n_it3 = ++n_marked; + for (BidIt r_it2 = r_marked; r_it2 != r_end; ++r_it2, ++n_it3) { + *r_it2 = *n_it3; + } + return true; } - return true; + for (BidIt n_it4 = n_begin; n_it4 != n_end; ++n_it4) + if (Equal(*r_it1, *n_it4)) { + *r_it1 = *(++n_it4); + return true; + } } - for(BidIt n_it4=n_begin; n_it4!=n_end; ++n_it4) - if(*r_it1==*n_it4) - { - *r_it1=*(++n_it4); - return true; - } } - } - - return true;//will never reach here -} - -// Non recursive template function with Pred -template - -inline bool next_combination( - BidIt n_begin, - BidIt n_end, - BidIt r_begin, - BidIt r_end, - Prediate Equal) -{ - - bool boolmarked=false; - BidIt r_marked; - - BidIt n_it1=n_end; - --n_it1; - - - BidIt tmp_r_end=r_end; - --tmp_r_end; - - for(BidIt r_it1=tmp_r_end; r_it1!=r_begin || r_it1==r_begin; --r_it1,--n_it1) - { - if( Equal( *r_it1, *n_it1) ) - { - if(r_it1!=r_begin) //to ensure not at the start of r sequence - { - boolmarked=true; - r_marked=(--r_it1); - ++r_it1;//add it back again - continue; + + return true; //will never reach here + } + + // Non recursive template function + template + + inline bool prev_combination(BidIt n_begin, BidIt n_end, BidIt r_begin, BidIt r_end) { + BidIt marked; //for r + BidIt r_marked; + BidIt n_marked; + + BidIt tmp_n_end = n_end; + --tmp_n_end; + + BidIt r_it1 = r_end; + --r_it1; + + for (BidIt n_it1 = tmp_n_end; n_it1 != n_begin || n_it1 == n_begin; --n_it1) { + if (*r_it1 == *n_it1) { + r_marked = r_it1; + n_marked = n_it1; + break; } - else // it means it is at the start the sequence, so return false - return false; } - else //if(*r_it1!=*n_it1 ) - { - //marked code - if(boolmarked==true) - { - //for loop to find which marked is in the first sequence - BidIt n_marked;//mark in first sequence - for (BidIt n_it2=n_begin;n_it2!=n_end;++n_it2) - if( Equal( *r_marked, *n_it2) ) {n_marked=n_it2;break;} - - - BidIt n_it3=++n_marked; - for (BidIt r_it2=r_marked;r_it2!=r_end;++r_it2,++n_it3) - { - *r_it2=*n_it3; - } - return true; - } - for(BidIt n_it4=n_begin; n_it4!=n_end; ++n_it4) - if( Equal(*r_it1, *n_it4) ) - { - *r_it1=*(++n_it4); - return true; + + BidIt n_it2 = n_marked; + + BidIt tmp_r_end = r_end; + --tmp_r_end; + + for (BidIt r_it2 = r_marked; r_it2 != r_begin || r_it2 == r_begin; --r_it2, --n_it2) { + if (*r_it2 == *n_it2) { + if (r_it2 == r_begin && !(*r_it2 == *n_begin)) { + for (BidIt n_it3 = n_begin; n_it3 != n_end; ++n_it3) { + if (*r_it2 == *n_it3) { + marked = r_it2; + *r_it2 = *(--n_it3); + + BidIt n_it4 = n_end; + --n_it4; + for (BidIt r_it3 = tmp_r_end; (r_it3 != r_begin || r_it3 == r_begin) && r_it3 != marked; + --r_it3, --n_it4) { + *r_it3 = *n_it4; + } + return true; + } + } + } else if (r_it2 == r_begin && *r_it2 == *n_begin) { + return false; //no more previous combination; } - } - } - - return true;//will never reach here -} - - -// Non recursive template function -template - -inline bool prev_combination(BidIt n_begin, BidIt n_end, -BidIt r_begin, BidIt r_end) -{ - - BidIt marked;//for r - BidIt r_marked; - BidIt n_marked; - - - BidIt tmp_n_end=n_end; - --tmp_n_end; - - BidIt r_it1=r_end; - --r_it1; - - for(BidIt n_it1=tmp_n_end; n_it1!=n_begin || n_it1==n_begin ; --n_it1) - { - if(*r_it1==*n_it1) - { - r_marked=r_it1; - n_marked=n_it1; - break; - } - } - - BidIt n_it2=n_marked; - - - BidIt tmp_r_end=r_end; - --tmp_r_end; - - for(BidIt r_it2=r_marked; r_it2!=r_begin || r_it2==r_begin; --r_it2,--n_it2) - { - if(*r_it2==*n_it2 ) - { - if(r_it2==r_begin&& !(*r_it2==*n_begin) ) + } else //if(*r_it2!=*n_it2 ) { - for(BidIt n_it3=n_begin;n_it3!=n_end;++n_it3) - { - if(*r_it2==*n_it3) - { - marked=r_it2; - *r_it2=*(--n_it3); - - BidIt n_it4=n_end; - --n_it4; - for(BidIt r_it3=tmp_r_end; (r_it3!=r_begin || r_it3==r_begin) &&r_it3!=marked; --r_it3,--n_it4) - { - *r_it3=*n_it4; + ++r_it2; + marked = r_it2; + for (BidIt n_it5 = n_begin; n_it5 != n_end; ++n_it5) { + if (*r_it2 == *n_it5) { + *r_it2 = *(--n_it5); + + BidIt n_it6 = n_end; + --n_it6; + for (BidIt r_it4 = tmp_r_end; (r_it4 != r_begin || r_it4 == r_begin) && r_it4 != marked; --r_it4, --n_it6) { + *r_it4 = *n_it6; } return true; } } } - else if(r_it2==r_begin&&*r_it2==*n_begin) - { - return false;//no more previous combination; + } + return false; //Will never reach here, unless error + } + + // Non recursive template function with Pred + template + + inline bool prev_combination(BidIt n_begin, BidIt n_end, BidIt r_begin, BidIt r_end, Prediate Equal) { + BidIt marked; //for r + BidIt r_marked; + BidIt n_marked; + + BidIt tmp_n_end = n_end; + --tmp_n_end; + + BidIt r_it1 = r_end; + --r_it1; + + for (BidIt n_it1 = tmp_n_end; n_it1 != n_begin || n_it1 == n_begin; --n_it1) { + if (Equal(*r_it1, *n_it1)) { + r_marked = r_it1; + n_marked = n_it1; + break; } } - else //if(*r_it2!=*n_it2 ) - { - ++r_it2; - marked=r_it2; - for(BidIt n_it5=n_begin;n_it5!=n_end;++n_it5) - { - if(*r_it2==*n_it5) - { - *r_it2=*(--n_it5); - BidIt n_it6=n_end; - --n_it6; - for(BidIt r_it4=tmp_r_end; (r_it4!=r_begin || r_it4==r_begin) &&r_it4!=marked; --r_it4,--n_it6) - { - *r_it4=*n_it6; + BidIt n_it2 = n_marked; + + BidIt tmp_r_end = r_end; + --tmp_r_end; + + for (BidIt r_it2 = r_marked; r_it2 != r_begin || r_it2 == r_begin; --r_it2, --n_it2) { + if (Equal(*r_it2, *n_it2)) { + if (r_it2 == r_begin && !Equal(*r_it2, *n_begin)) { + for (BidIt n_it3 = n_begin; n_it3 != n_end; ++n_it3) { + if (Equal(*r_it2, *n_it3)) { + marked = r_it2; + *r_it2 = *(--n_it3); + + BidIt n_it4 = n_end; + --n_it4; + for (BidIt r_it3 = tmp_r_end; (r_it3 != r_begin || r_it3 == r_begin) && r_it3 != marked; + --r_it3, --n_it4) { + *r_it3 = *n_it4; + } + return true; + } } - return true; + } else if (r_it2 == r_begin && Equal(*r_it2, *n_begin)) { + return false; //no more previous combination; } - } - } - } - return false;//Will never reach here, unless error -} - - -// Non recursive template function with Pred -template - -inline bool prev_combination( - BidIt n_begin, - BidIt n_end, - BidIt r_begin, - BidIt r_end, - Prediate Equal) -{ - - BidIt marked;//for r - BidIt r_marked; - BidIt n_marked; - - - BidIt tmp_n_end=n_end; - --tmp_n_end; - - BidIt r_it1=r_end; - --r_it1; - - for(BidIt n_it1=tmp_n_end; n_it1!=n_begin || n_it1==n_begin ; --n_it1) - { - if( Equal(*r_it1, *n_it1) ) - { - r_marked=r_it1; - n_marked=n_it1; - break; - } - } - - BidIt n_it2=n_marked; - - - BidIt tmp_r_end=r_end; - --tmp_r_end; - - for(BidIt r_it2=r_marked; r_it2!=r_begin || r_it2==r_begin; --r_it2,--n_it2) - { - if( Equal(*r_it2, *n_it2) ) - { - if(r_it2==r_begin&& !Equal(*r_it2, *n_begin) ) + } else //if(*r_it2!=*n_it2 ) { - for(BidIt n_it3=n_begin;n_it3!=n_end;++n_it3) - { - if(Equal(*r_it2, *n_it3)) - { - marked=r_it2; - *r_it2=*(--n_it3); - - BidIt n_it4=n_end; - --n_it4; - for(BidIt r_it3=tmp_r_end; (r_it3!=r_begin || r_it3==r_begin) &&r_it3!=marked; --r_it3,--n_it4) - { - *r_it3=*n_it4; + ++r_it2; + marked = r_it2; + for (BidIt n_it5 = n_begin; n_it5 != n_end; ++n_it5) { + if (Equal(*r_it2, *n_it5)) { + *r_it2 = *(--n_it5); + + BidIt n_it6 = n_end; + --n_it6; + for (BidIt r_it4 = tmp_r_end; (r_it4 != r_begin || r_it4 == r_begin) && r_it4 != marked; --r_it4, --n_it6) { + *r_it4 = *n_it6; } return true; } } } - else if(r_it2==r_begin&&Equal(*r_it2, *n_begin)) - { - return false;//no more previous combination; - } } - else //if(*r_it2!=*n_it2 ) - { - ++r_it2; - marked=r_it2; - for(BidIt n_it5=n_begin;n_it5!=n_end;++n_it5) - { - if(Equal(*r_it2, *n_it5)) - { - *r_it2=*(--n_it5); + return false; //Will never reach here, unless error + } - BidIt n_it6=n_end; - --n_it6; - for(BidIt r_it4=tmp_r_end; (r_it4!=r_begin || r_it4==r_begin) &&r_it4!=marked; --r_it4,--n_it6) - { - *r_it4=*n_it6; - } - return true; - } + // Recursive template function + template + + void recursive_combination( + RanIt nbegin, RanIt nend, int n_column, RanIt rbegin, RanIt rend, int r_column, int loop, Func func) { + int r_size = rend - rbegin; + + int localloop = loop; + int local_n_column = n_column; + + //A different combination is out + if (r_column > (r_size - 1)) { + func(rbegin, rend); + return; + } + ///////////////////////////////// + + for (int i = 0; i <= loop; ++i) { + RanIt it1 = rbegin; + for (int cnt = 0; cnt < r_column; ++cnt) { + ++it1; } + + RanIt it2 = nbegin; + for (int cnt2 = 0; cnt2 < n_column + i; ++cnt2) { + ++it2; + } + + *it1 = *it2; + + ++local_n_column; + + recursive_combination(nbegin, nend, local_n_column, rbegin, rend, r_column + 1, localloop, func); + --localloop; } - } - return false;//Will never reach here, unless error -} - - -// Recursive template function -template - -void recursive_combination(RanIt nbegin, RanIt nend, int n_column, - RanIt rbegin, RanIt rend, int r_column,int loop, Func func) -{ - - int r_size=rend-rbegin; - - - int localloop=loop; - int local_n_column=n_column; - - //A different combination is out - if(r_column>(r_size-1)) - { - func(rbegin,rend); - return; - } - ///////////////////////////////// - - for(int i=0;i<=loop;++i) - { - - RanIt it1=rbegin; - for(int cnt=0;cnt CandMCTagUtils::getAncestors(const reco::Candidate &c) -{ +std::vector CandMCTagUtils::getAncestors(const reco::Candidate &c) { vector moms; - if( c.numberOfMothers() == 1 ) { - const Candidate * dau = &c; - const Candidate * mom = c.mother(); - while ( dau->numberOfMothers() == 1) { - moms.push_back( dau ); - dau = mom ; + if (c.numberOfMothers() == 1) { + const Candidate *dau = &c; + const Candidate *mom = c.mother(); + while (dau->numberOfMothers() == 1) { + moms.push_back(dau); + dau = mom; mom = dau->mother(); - } - } + } + } return moms; } - -bool CandMCTagUtils::hasBottom(const reco::Candidate &c) -{ +bool CandMCTagUtils::hasBottom(const reco::Candidate &c) { int code1; int code2; bool tmpHasBottom = false; - code1 = (int)( ( abs(c.pdgId() ) / 100)%10 ); - code2 = (int)( ( abs(c.pdgId() ) /1000)%10 ); - if ( code1 == 5 || code2 == 5) tmpHasBottom = true; + code1 = (int)((abs(c.pdgId()) / 100) % 10); + code2 = (int)((abs(c.pdgId()) / 1000) % 10); + if (code1 == 5 || code2 == 5) + tmpHasBottom = true; return tmpHasBottom; - } +} -bool CandMCTagUtils::hasCharm(const reco::Candidate &c) -{ +bool CandMCTagUtils::hasCharm(const reco::Candidate &c) { int code1; int code2; bool tmpHasCharm = false; - code1 = (int)( ( abs(c.pdgId() ) / 100)%10 ); - code2 = (int)( ( abs(c.pdgId() ) /1000)%10 ); - if ( code1 == 4 || code2 == 4) tmpHasCharm = true; + code1 = (int)((abs(c.pdgId()) / 100) % 10); + code2 = (int)((abs(c.pdgId()) / 1000) % 10); + if (code1 == 4 || code2 == 4) + tmpHasCharm = true; return tmpHasCharm; } -bool CandMCTagUtils::isParton(const reco::Candidate &c) -{ - int id = abs(c.pdgId()); +bool CandMCTagUtils::isParton(const reco::Candidate &c) { + int id = abs(c.pdgId()); - if( id == 1 || - id == 2 || - id == 3 || - id == 4 || - id == 5 || - id == 21 ) - return true; - else - return false; + if (id == 1 || id == 2 || id == 3 || id == 4 || id == 5 || id == 21) + return true; + else + return false; } -bool CandMCTagUtils::isLightParton(const reco::Candidate &c) -{ - int id = abs(c.pdgId()); +bool CandMCTagUtils::isLightParton(const reco::Candidate &c) { + int id = abs(c.pdgId()); - if( id == 1 || - id == 2 || - id == 3 || - id == 21 ) - return true; - else - return false; + if (id == 1 || id == 2 || id == 3 || id == 21) + return true; + else + return false; } diff --git a/PhysicsTools/JetMCUtils/src/JetMCTag.cc b/PhysicsTools/JetMCUtils/src/JetMCTag.cc index e8cd950b0a1fc..fefb2318992d9 100644 --- a/PhysicsTools/JetMCUtils/src/JetMCTag.cc +++ b/PhysicsTools/JetMCUtils/src/JetMCTag.cc @@ -9,133 +9,126 @@ using namespace CandMCTagUtils; /////////////////////////////////////////////////////////////////////// -double JetMCTagUtils::EnergyRatioFromBHadrons(const Candidate & c) -{ - double ratioForBjet=0; - double ratio = 0; - for( Candidate::const_iterator itC = c.begin(); - itC != c.end(); - itC ++) { - bool isFromB = decayFromBHadron(*itC); - ratio = itC->energy() / c.energy() ; - if( isFromB ) ratioForBjet += ratio; - } - return ratioForBjet; +double JetMCTagUtils::EnergyRatioFromBHadrons(const Candidate &c) { + double ratioForBjet = 0; + double ratio = 0; + for (Candidate::const_iterator itC = c.begin(); itC != c.end(); itC++) { + bool isFromB = decayFromBHadron(*itC); + ratio = itC->energy() / c.energy(); + if (isFromB) + ratioForBjet += ratio; + } + return ratioForBjet; } -double JetMCTagUtils::EnergyRatioFromCHadrons(const Candidate & c) -{ - double ratioForCjet=0; - double ratio = 0; - for( Candidate::const_iterator itC = c.begin(); - itC != c.end(); - itC ++) { - bool isFromC = decayFromCHadron(*itC); - ratio = itC->energy() / c.energy() ; - if( isFromC ) ratioForCjet += ratio; - } - return ratioForCjet; +double JetMCTagUtils::EnergyRatioFromCHadrons(const Candidate &c) { + double ratioForCjet = 0; + double ratio = 0; + for (Candidate::const_iterator itC = c.begin(); itC != c.end(); itC++) { + bool isFromC = decayFromCHadron(*itC); + ratio = itC->energy() / c.energy(); + if (isFromC) + ratioForCjet += ratio; + } + return ratioForCjet; } -bool JetMCTagUtils::decayFromBHadron(const Candidate & c) -{ - bool isFromB = false; - vector allParents = getAncestors( c ); - for( vector::const_iterator aParent = allParents.begin(); - aParent != allParents.end(); - aParent ++ ) - { - if( hasBottom(**aParent) ) isFromB = true; -/* +bool JetMCTagUtils::decayFromBHadron(const Candidate &c) { + bool isFromB = false; + vector allParents = getAncestors(c); + for (vector::const_iterator aParent = allParents.begin(); aParent != allParents.end(); aParent++) { + if (hasBottom(**aParent)) + isFromB = true; + /* cout << " particle Parent is " << (*aParent)->status() << " type " << (*aParent)->pdgId() << " pt=" << (*aParent)->pt() << " isB = " << isFromB << endl; */ - } - return isFromB; - + } + return isFromB; } -bool JetMCTagUtils::decayFromCHadron(const Candidate & c) -{ - bool isFromC = false; - vector allParents = getAncestors( c ); - for( vector::const_iterator aParent = allParents.begin(); - aParent != allParents.end(); - aParent ++ ) - { - if( hasCharm(**aParent) ) isFromC = true; -/* +bool JetMCTagUtils::decayFromCHadron(const Candidate &c) { + bool isFromC = false; + vector allParents = getAncestors(c); + for (vector::const_iterator aParent = allParents.begin(); aParent != allParents.end(); aParent++) { + if (hasCharm(**aParent)) + isFromC = true; + /* cout << " particle Parent is " << (*aParent)->status() << " type " << (*aParent)->pdgId() << " pt=" << (*aParent)->pt() << " isC = " << isFromC << endl; */ - } - return isFromC; + } + return isFromC; } std::string JetMCTagUtils::genTauDecayMode(const CompositePtrCandidate &c) { - int numElectrons = 0; int numMuons = 0; int numChargedHadrons = 0; int numNeutralHadrons = 0; int numPhotons = 0; - - const CompositePtrCandidate::daughters& daughters = c.daughterPtrVector(); - for ( CompositePtrCandidate::daughters::const_iterator daughter = daughters.begin(); - daughter != daughters.end(); ++daughter ) { - + + const CompositePtrCandidate::daughters &daughters = c.daughterPtrVector(); + for (CompositePtrCandidate::daughters::const_iterator daughter = daughters.begin(); daughter != daughters.end(); + ++daughter) { int pdg_id = abs((*daughter)->pdgId()); - - switch ( pdg_id ) { - case 22: - numPhotons++; - break; - case 11: - numElectrons++; - break; - case 13: - numMuons++; - break; - default : {if ((*daughter)->charge() != 0) numChargedHadrons++; else numNeutralHadrons++;} + switch (pdg_id) { + case 22: + numPhotons++; + break; + case 11: + numElectrons++; + break; + case 13: + numMuons++; + break; + default: { + if ((*daughter)->charge() != 0) + numChargedHadrons++; + else + numNeutralHadrons++; + } } } - - if (numElectrons == 1) return std::string("electron"); - else if (numMuons == 1) return std::string("muon"); - switch ( numChargedHadrons ) { - case 1 : - if (numNeutralHadrons != 0) return std::string("oneProngOther"); - switch ( numPhotons ) { - case 0: - return std::string("oneProng0Pi0"); - case 2: - return std::string("oneProng1Pi0"); - case 4: - return std::string("oneProng2Pi0"); - default: - return std::string("oneProngOther"); - } - case 3 : - if (numNeutralHadrons != 0) return std::string("threeProngOther"); - switch ( numPhotons ) { - case 0: - return std::string("threeProng0Pi0"); - case 2: - return std::string("threeProng1Pi0"); + if (numElectrons == 1) + return std::string("electron"); + else if (numMuons == 1) + return std::string("muon"); + + switch (numChargedHadrons) { + case 1: + if (numNeutralHadrons != 0) + return std::string("oneProngOther"); + switch (numPhotons) { + case 0: + return std::string("oneProng0Pi0"); + case 2: + return std::string("oneProng1Pi0"); + case 4: + return std::string("oneProng2Pi0"); + default: + return std::string("oneProngOther"); + } + case 3: + if (numNeutralHadrons != 0) + return std::string("threeProngOther"); + switch (numPhotons) { + case 0: + return std::string("threeProng0Pi0"); + case 2: + return std::string("threeProng1Pi0"); + default: + return std::string("threeProngOther"); + } default: - return std::string("threeProngOther"); - } - default: - return std::string("rare"); + return std::string("rare"); } - } - diff --git a/QCDAnalysis/Skimming/interface/QCDSingleJetFilter.h b/QCDAnalysis/Skimming/interface/QCDSingleJetFilter.h index 60bb63a7c67b8..8314de06c7285 100644 --- a/QCDAnalysis/Skimming/interface/QCDSingleJetFilter.h +++ b/QCDAnalysis/Skimming/interface/QCDSingleJetFilter.h @@ -20,15 +20,13 @@ #include - //RandomGenerator Service taken out //namespace CLHEP { // class RandFlat; //} class QCDSingleJetFilter : public edm::EDFilter { - - public: +public: // Constructor QCDSingleJetFilter(const edm::ParameterSet&); @@ -38,14 +36,11 @@ class QCDSingleJetFilter : public edm::EDFilter { /// Get event properties to send to builder to fill seed collection bool filter(edm::Event&, const edm::EventSetup&) override; - - - private: - +private: bool debug; //CLHEP::RandFlat *theFlatDistrib; double theMinPt; - //,thePreScale; + //,thePreScale; edm::EDGetTokenT theTriggerJetCollectionAToken; edm::EDGetTokenT theTrigCollBToken; }; diff --git a/QCDAnalysis/Skimming/src/QCDSingleJetFilter.cc b/QCDAnalysis/Skimming/src/QCDSingleJetFilter.cc index 059006d00231b..de1f2e6c5627d 100644 --- a/QCDAnalysis/Skimming/src/QCDSingleJetFilter.cc +++ b/QCDAnalysis/Skimming/src/QCDSingleJetFilter.cc @@ -17,7 +17,6 @@ #include #include - #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "DataFormats/JetReco/interface/GenJet.h" @@ -38,16 +37,16 @@ using namespace edm; //using namespace reco; //detruktor -QCDSingleJetFilter::~QCDSingleJetFilter(){ +QCDSingleJetFilter::~QCDSingleJetFilter() { //delete theFlatDistrib; } // Constructor //QCDSingleJetFilter::QCDSingleJetFilter(const edm::ParameterSet& pset):theFlatDistrib(0),theTriggerJetCollectionA(pset.getParameter("TriggerJetCollectionA")),theTrigCollB(pset.getParameter("TriggerJetCollectionB")){ -QCDSingleJetFilter::QCDSingleJetFilter(const edm::ParameterSet& pset): - theTriggerJetCollectionAToken(consumes(pset.getParameter("TriggerJetCollectionA"))), - theTrigCollBToken(consumes(pset.getParameter("TriggerJetCollectionB"))){ - +QCDSingleJetFilter::QCDSingleJetFilter(const edm::ParameterSet& pset) + : theTriggerJetCollectionAToken( + consumes(pset.getParameter("TriggerJetCollectionA"))), + theTrigCollBToken(consumes(pset.getParameter("TriggerJetCollectionB"))) { // Local Debug flag //debug = pset.getParameter("DebugHiggsToZZ4LeptonsSkim"); @@ -70,43 +69,40 @@ QCDSingleJetFilter::QCDSingleJetFilter(const edm::ParameterSet& pset): //theFlatDistrib = new CLHEP::RandFlat(engine,0.0,1.0); } - - - // Filter event bool QCDSingleJetFilter::filter(edm::Event& event, const edm::EventSetup& setup) { - bool keepEvent = false; - using namespace edm; - using namespace std; - - //now get right Jet-Collection: - edm::Handle theTriggerCollectionJetsA; - edm::Handle theTrigCollJetsB; - - event.getByToken(theTriggerJetCollectionAToken,theTriggerCollectionJetsA); - event.getByToken(theTrigCollBToken,theTrigCollJetsB); - - for (reco::CaloJetCollection::const_iterator iter=theTriggerCollectionJetsA->begin();iter!=theTriggerCollectionJetsA->end();++iter){ - if ((*iter).pt()>=theMinPt) { - keepEvent=true; - break; - } + bool keepEvent = false; + using namespace edm; + using namespace std; + + //now get right Jet-Collection: + edm::Handle theTriggerCollectionJetsA; + edm::Handle theTrigCollJetsB; + + event.getByToken(theTriggerJetCollectionAToken, theTriggerCollectionJetsA); + event.getByToken(theTrigCollBToken, theTrigCollJetsB); + + for (reco::CaloJetCollection::const_iterator iter = theTriggerCollectionJetsA->begin(); + iter != theTriggerCollectionJetsA->end(); + ++iter) { + if ((*iter).pt() >= theMinPt) { + keepEvent = true; + break; } + } - for (reco::CaloJetCollection::const_iterator iter=theTrigCollJetsB->begin();iter!=theTrigCollJetsB->end();++iter){ - if ((*iter).pt()>=theMinPt) { - keepEvent=true; - break; - } + for (reco::CaloJetCollection::const_iterator iter = theTrigCollJetsB->begin(); iter != theTrigCollJetsB->end(); + ++iter) { + if ((*iter).pt() >= theMinPt) { + keepEvent = true; + break; } + } + //double randval = theFlatDistrib->fire(); + //if (thePreScale<1) keepEvent=false; + //else if ((randval>(1.0/thePreScale))&&keepEvent) keepEvent=false; + // cout<<"KeepEvent?: "<fire(); - //if (thePreScale<1) keepEvent=false; - //else if ((randval>(1.0/thePreScale))&&keepEvent) keepEvent=false; -// cout<<"KeepEvent?: "< #include -class AnalysisRootpleProducer : public edm::EDAnalyzer -{ - +class AnalysisRootpleProducer : public edm::EDAnalyzer { public: - // - explicit AnalysisRootpleProducer( const edm::ParameterSet& ) ; - ~AnalysisRootpleProducer() override {} // no need to delete ROOT stuff + explicit AnalysisRootpleProducer(const edm::ParameterSet&); + ~AnalysisRootpleProducer() override {} // no need to delete ROOT stuff // as it'll be deleted upon closing TFile - void analyze( const edm::Event&, const edm::EventSetup& ) override ; - void beginJob() override ; - void endJob() override ; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void beginJob() override; + void endJob() override; void fillEventInfo(int); void fillMCParticles(float, float, float, float); @@ -61,26 +58,25 @@ class AnalysisRootpleProducer : public edm::EDAnalyzer void store(); private: - bool onlyRECO; - edm::EDGetTokenT< edm::HepMCProduct > mcEventToken; // label of MC event - edm::EDGetTokenT< reco::GenJetCollection > genJetCollToken; // label of Jet made with MC particles - edm::EDGetTokenT< reco::GenJetCollection > chgJetCollToken; // label of Jet made with only charged MC particles - edm::EDGetTokenT< std::vector > chgGenPartCollToken; // label of charged MC particles - edm::EDGetTokenT< reco::BasicJetCollection > tracksJetCollToken; - edm::EDGetTokenT< reco::CaloJetCollection > recoCaloJetCollToken; - edm::EDGetTokenT< reco::CandidateCollection > tracksCollToken; - edm::EDGetTokenT< edm::TriggerResults > triggerResultsToken; - - edm::Handle< edm::HepMCProduct > EvtHandle ; - edm::Handle< std::vector > CandHandleMC ; - edm::Handle< reco::GenJetCollection > GenJetsHandle ; - edm::Handle< reco::GenJetCollection > ChgGenJetsHandle ; - edm::Handle< reco::CandidateCollection > CandHandleRECO ; - edm::Handle< reco::BasicJetCollection > TracksJetsHandle ; - edm::Handle< reco::CaloJetCollection > RecoCaloJetsHandle ; - edm::Handle< edm::TriggerResults > triggerResults; + edm::EDGetTokenT mcEventToken; // label of MC event + edm::EDGetTokenT genJetCollToken; // label of Jet made with MC particles + edm::EDGetTokenT chgJetCollToken; // label of Jet made with only charged MC particles + edm::EDGetTokenT > chgGenPartCollToken; // label of charged MC particles + edm::EDGetTokenT tracksJetCollToken; + edm::EDGetTokenT recoCaloJetCollToken; + edm::EDGetTokenT tracksCollToken; + edm::EDGetTokenT triggerResultsToken; + + edm::Handle EvtHandle; + edm::Handle > CandHandleMC; + edm::Handle GenJetsHandle; + edm::Handle ChgGenJetsHandle; + edm::Handle CandHandleRECO; + edm::Handle TracksJetsHandle; + edm::Handle RecoCaloJetsHandle; + edm::Handle triggerResults; // edm::Handle hltFilter; // not used at the moment: can access objects that fired the trigger edm::Service fs; @@ -96,14 +92,14 @@ class AnalysisRootpleProducer : public edm::EDAnalyzer static const int NTJMAX = 10000; static const int NEHJMAX = 10000; - int EventKind,NumberMCParticles,NumberTracks,NumberInclusiveJet,NumberChargedJet,NumberTracksJet,NumberCaloJet; + int EventKind, NumberMCParticles, NumberTracks, NumberInclusiveJet, NumberChargedJet, NumberTracksJet, NumberCaloJet; - float MomentumMC[NMCPMAX],TransverseMomentumMC[NMCPMAX],EtaMC[NMCPMAX],PhiMC[NMCPMAX]; - float MomentumTK[NTKMAX],TransverseMomentumTK[NTKMAX],EtaTK[NTKMAX],PhiTK[NTKMAX]; - float MomentumIJ[NIJMAX],TransverseMomentumIJ[NIJMAX],EtaIJ[NIJMAX],PhiIJ[NIJMAX]; - float MomentumCJ[NCJMAX],TransverseMomentumCJ[NCJMAX],EtaCJ[NCJMAX],PhiCJ[NCJMAX]; - float MomentumTJ[NTJMAX],TransverseMomentumTJ[NTJMAX],EtaTJ[NTJMAX],PhiTJ[NTJMAX]; - float MomentumEHJ[NEHJMAX],TransverseMomentumEHJ[NEHJMAX],EtaEHJ[NEHJMAX],PhiEHJ[NEHJMAX]; + float MomentumMC[NMCPMAX], TransverseMomentumMC[NMCPMAX], EtaMC[NMCPMAX], PhiMC[NMCPMAX]; + float MomentumTK[NTKMAX], TransverseMomentumTK[NTKMAX], EtaTK[NTKMAX], PhiTK[NTKMAX]; + float MomentumIJ[NIJMAX], TransverseMomentumIJ[NIJMAX], EtaIJ[NIJMAX], PhiIJ[NIJMAX]; + float MomentumCJ[NCJMAX], TransverseMomentumCJ[NCJMAX], EtaCJ[NCJMAX], PhiCJ[NCJMAX]; + float MomentumTJ[NTJMAX], TransverseMomentumTJ[NTJMAX], EtaTJ[NTJMAX], PhiTJ[NTJMAX]; + float MomentumEHJ[NEHJMAX], TransverseMomentumEHJ[NEHJMAX], EtaEHJ[NEHJMAX], PhiEHJ[NEHJMAX]; TClonesArray* MonteCarlo; TClonesArray* InclusiveJet; diff --git a/QCDAnalysis/UEAnalysis/interface/AnalysisRootpleProducerOnlyMC.h b/QCDAnalysis/UEAnalysis/interface/AnalysisRootpleProducerOnlyMC.h index 1f4b6eaf24e30..45472f7f7b9b1 100644 --- a/QCDAnalysis/UEAnalysis/interface/AnalysisRootpleProducerOnlyMC.h +++ b/QCDAnalysis/UEAnalysis/interface/AnalysisRootpleProducerOnlyMC.h @@ -28,17 +28,14 @@ #include "DataFormats/Candidate/interface/Candidate.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" -class AnalysisRootpleProducerOnlyMC : public edm::EDAnalyzer -{ - +class AnalysisRootpleProducerOnlyMC : public edm::EDAnalyzer { public: - - explicit AnalysisRootpleProducerOnlyMC( const edm::ParameterSet& ) ; + explicit AnalysisRootpleProducerOnlyMC(const edm::ParameterSet&); ~AnalysisRootpleProducerOnlyMC() override {} - void analyze( const edm::Event&, const edm::EventSetup& ) override ; - void beginJob() override ; - void endJob() override ; + void analyze(const edm::Event&, const edm::EventSetup&) override; + void beginJob() override; + void endJob() override; void fillEventInfo(int); void fillMCParticles(float, float, float, float); @@ -47,17 +44,15 @@ class AnalysisRootpleProducerOnlyMC : public edm::EDAnalyzer void store(); private: + edm::EDGetTokenT mcEventToken; // label of MC event + edm::EDGetTokenT genJetCollToken; // label of Jet made with MC particles + edm::EDGetTokenT chgJetCollToken; // label of Jet made with only charged MC particles + edm::EDGetTokenT > chgGenPartCollToken; // label of charged MC particles - edm::EDGetTokenT< edm::HepMCProduct > mcEventToken; // label of MC event - edm::EDGetTokenT< reco::GenJetCollection > genJetCollToken; // label of Jet made with MC particles - edm::EDGetTokenT< reco::GenJetCollection > chgJetCollToken; // label of Jet made with only charged MC particles - edm::EDGetTokenT< std::vector > chgGenPartCollToken; // label of charged MC particles - - edm::Handle< edm::HepMCProduct > EvtHandle ; - edm::Handle< std::vector > CandHandleMC ; - edm::Handle< reco::GenJetCollection > GenJetsHandle ; - edm::Handle< reco::GenJetCollection > ChgGenJetsHandle ; - + edm::Handle EvtHandle; + edm::Handle > CandHandleMC; + edm::Handle GenJetsHandle; + edm::Handle ChgGenJetsHandle; float piG; @@ -72,19 +67,18 @@ class AnalysisRootpleProducerOnlyMC : public edm::EDAnalyzer static const int NTJMAX = 10000; static const int NEHJMAX = 10000; - int EventKind,NumberMCParticles,NumberTracks,NumberInclusiveJet,NumberChargedJet,NumberTracksJet,NumberCaloJet; + int EventKind, NumberMCParticles, NumberTracks, NumberInclusiveJet, NumberChargedJet, NumberTracksJet, NumberCaloJet; - float MomentumMC[NMCPMAX],TransverseMomentumMC[NMCPMAX],EtaMC[NMCPMAX],PhiMC[NMCPMAX]; - float MomentumTK[NTKMAX],TransverseMomentumTK[NTKMAX],EtaTK[NTKMAX],PhiTK[NTKMAX]; - float MomentumIJ[NIJMAX],TransverseMomentumIJ[NIJMAX],EtaIJ[NIJMAX],PhiIJ[NIJMAX]; - float MomentumCJ[NCJMAX],TransverseMomentumCJ[NCJMAX],EtaCJ[NCJMAX],PhiCJ[NCJMAX]; - float MomentumTJ[NTJMAX],TransverseMomentumTJ[NTJMAX],EtaTJ[NTJMAX],PhiTJ[NTJMAX]; - float MomentumEHJ[NEHJMAX],TransverseMomentumEHJ[NEHJMAX],EtaEHJ[NEHJMAX],PhiEHJ[NEHJMAX]; + float MomentumMC[NMCPMAX], TransverseMomentumMC[NMCPMAX], EtaMC[NMCPMAX], PhiMC[NMCPMAX]; + float MomentumTK[NTKMAX], TransverseMomentumTK[NTKMAX], EtaTK[NTKMAX], PhiTK[NTKMAX]; + float MomentumIJ[NIJMAX], TransverseMomentumIJ[NIJMAX], EtaIJ[NIJMAX], PhiIJ[NIJMAX]; + float MomentumCJ[NCJMAX], TransverseMomentumCJ[NCJMAX], EtaCJ[NCJMAX], PhiCJ[NCJMAX]; + float MomentumTJ[NTJMAX], TransverseMomentumTJ[NTJMAX], EtaTJ[NTJMAX], PhiTJ[NTJMAX]; + float MomentumEHJ[NEHJMAX], TransverseMomentumEHJ[NEHJMAX], EtaEHJ[NEHJMAX], PhiEHJ[NEHJMAX]; TClonesArray* MonteCarlo; TClonesArray* InclusiveJet; TClonesArray* ChargedJet; - }; #endif diff --git a/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducer.cc b/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducer.cc index cbf53930f8fd1..3f042e9b90b0f 100644 --- a/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducer.cc +++ b/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducer.cc @@ -6,112 +6,105 @@ using namespace edm; using namespace std; using namespace reco; -class GreaterPt{ +class GreaterPt { public: - bool operator()( const math::XYZTLorentzVector& a, const math::XYZTLorentzVector& b) { - return a.pt() > b.pt(); - } + bool operator()(const math::XYZTLorentzVector& a, const math::XYZTLorentzVector& b) { return a.pt() > b.pt(); } }; -class GenJetSort{ +class GenJetSort { public: - bool operator()(const GenJet& a, const GenJet& b) { - return a.pt() > b.pt(); - } + bool operator()(const GenJet& a, const GenJet& b) { return a.pt() > b.pt(); } }; -class BasicJetSort{ +class BasicJetSort { public: - bool operator()(const BasicJet& a, const BasicJet& b) { - return a.pt() > b.pt(); - } + bool operator()(const BasicJet& a, const BasicJet& b) { return a.pt() > b.pt(); } }; -class CaloJetSort{ +class CaloJetSort { public: - bool operator()(const CaloJet& a, const CaloJet& b) { - return a.pt() > b.pt(); - } + bool operator()(const CaloJet& a, const CaloJet& b) { return a.pt() > b.pt(); } }; - -void AnalysisRootpleProducer::store(){ - +void AnalysisRootpleProducer::store() { AnalysisTree->Fill(); - NumberMCParticles=0; - NumberTracks=0; - NumberInclusiveJet=0; - NumberChargedJet=0; - NumberTracksJet=0; - NumberCaloJet=0; + NumberMCParticles = 0; + NumberTracks = 0; + NumberInclusiveJet = 0; + NumberChargedJet = 0; + NumberTracksJet = 0; + NumberCaloJet = 0; } -void AnalysisRootpleProducer::fillEventInfo(int e){ - EventKind = e; -} +void AnalysisRootpleProducer::fillEventInfo(int e) { EventKind = e; } -void AnalysisRootpleProducer::fillMCParticles(float p, float pt, float eta, float phi){ - MomentumMC[NumberMCParticles]=p; - TransverseMomentumMC[NumberMCParticles]=pt; - EtaMC[NumberMCParticles]=eta; - PhiMC[NumberMCParticles]=phi; +void AnalysisRootpleProducer::fillMCParticles(float p, float pt, float eta, float phi) { + MomentumMC[NumberMCParticles] = p; + TransverseMomentumMC[NumberMCParticles] = pt; + EtaMC[NumberMCParticles] = eta; + PhiMC[NumberMCParticles] = phi; NumberMCParticles++; } -void AnalysisRootpleProducer::fillTracks(float p, float pt, float eta, float phi){ - MomentumTK[NumberTracks]=p; - TransverseMomentumTK[NumberTracks]=pt; - EtaTK[NumberTracks]=eta; - PhiTK[NumberTracks]=phi; +void AnalysisRootpleProducer::fillTracks(float p, float pt, float eta, float phi) { + MomentumTK[NumberTracks] = p; + TransverseMomentumTK[NumberTracks] = pt; + EtaTK[NumberTracks] = eta; + PhiTK[NumberTracks] = phi; NumberTracks++; } -void AnalysisRootpleProducer::fillInclusiveJet(float p, float pt, float eta, float phi){ - MomentumIJ[NumberInclusiveJet]=p; - TransverseMomentumIJ[NumberInclusiveJet]=pt; - EtaIJ[NumberInclusiveJet]=eta; - PhiIJ[NumberInclusiveJet]=phi; +void AnalysisRootpleProducer::fillInclusiveJet(float p, float pt, float eta, float phi) { + MomentumIJ[NumberInclusiveJet] = p; + TransverseMomentumIJ[NumberInclusiveJet] = pt; + EtaIJ[NumberInclusiveJet] = eta; + PhiIJ[NumberInclusiveJet] = phi; NumberInclusiveJet++; } -void AnalysisRootpleProducer::fillChargedJet(float p, float pt, float eta, float phi){ - MomentumCJ[NumberChargedJet]=p; - TransverseMomentumCJ[NumberChargedJet]=pt; - EtaCJ[NumberChargedJet]=eta; - PhiCJ[NumberChargedJet]=phi; +void AnalysisRootpleProducer::fillChargedJet(float p, float pt, float eta, float phi) { + MomentumCJ[NumberChargedJet] = p; + TransverseMomentumCJ[NumberChargedJet] = pt; + EtaCJ[NumberChargedJet] = eta; + PhiCJ[NumberChargedJet] = phi; NumberChargedJet++; } -void AnalysisRootpleProducer::fillTracksJet(float p, float pt, float eta, float phi){ - MomentumTJ[NumberTracksJet]=p; - TransverseMomentumTJ[NumberTracksJet]=pt; - EtaTJ[NumberTracksJet]=eta; - PhiTJ[NumberTracksJet]=phi; +void AnalysisRootpleProducer::fillTracksJet(float p, float pt, float eta, float phi) { + MomentumTJ[NumberTracksJet] = p; + TransverseMomentumTJ[NumberTracksJet] = pt; + EtaTJ[NumberTracksJet] = eta; + PhiTJ[NumberTracksJet] = phi; NumberTracksJet++; } -void AnalysisRootpleProducer::fillCaloJet(float p, float pt, float eta, float phi){ - MomentumEHJ[NumberCaloJet]=p; - TransverseMomentumEHJ[NumberCaloJet]=pt; - EtaEHJ[NumberCaloJet]=eta; - PhiEHJ[NumberCaloJet]=phi; +void AnalysisRootpleProducer::fillCaloJet(float p, float pt, float eta, float phi) { + MomentumEHJ[NumberCaloJet] = p; + TransverseMomentumEHJ[NumberCaloJet] = pt; + EtaEHJ[NumberCaloJet] = eta; + PhiEHJ[NumberCaloJet] = phi; NumberCaloJet++; } -AnalysisRootpleProducer::AnalysisRootpleProducer( const ParameterSet& pset ) -{ +AnalysisRootpleProducer::AnalysisRootpleProducer(const ParameterSet& pset) { // flag to ignore gen-level analysis - onlyRECO = pset.getUntrackedParameter("OnlyRECO",false); + onlyRECO = pset.getUntrackedParameter("OnlyRECO", false); // particle, track and jet collections - mcEventToken = mayConsume(pset.getUntrackedParameter("MCEvent",std::string(""))); - genJetCollToken = mayConsume(pset.getUntrackedParameter("GenJetCollectionName",std::string(""))); - chgJetCollToken = mayConsume(pset.getUntrackedParameter("ChgGenJetCollectionName",std::string(""))); - tracksJetCollToken = consumes(pset.getUntrackedParameter("TracksJetCollectionName",std::string(""))); - recoCaloJetCollToken = consumes(pset.getUntrackedParameter("RecoCaloJetCollectionName",std::string(""))); - chgGenPartCollToken = mayConsume >(pset.getUntrackedParameter("ChgGenPartCollectionName",std::string(""))); - tracksCollToken = consumes(pset.getUntrackedParameter("TracksCollectionName",std::string(""))); + mcEventToken = mayConsume(pset.getUntrackedParameter("MCEvent", std::string(""))); + genJetCollToken = + mayConsume(pset.getUntrackedParameter("GenJetCollectionName", std::string(""))); + chgJetCollToken = mayConsume( + pset.getUntrackedParameter("ChgGenJetCollectionName", std::string(""))); + tracksJetCollToken = consumes( + pset.getUntrackedParameter("TracksJetCollectionName", std::string(""))); + recoCaloJetCollToken = consumes( + pset.getUntrackedParameter("RecoCaloJetCollectionName", std::string(""))); + chgGenPartCollToken = mayConsume >( + pset.getUntrackedParameter("ChgGenPartCollectionName", std::string(""))); + tracksCollToken = consumes( + pset.getUntrackedParameter("TracksCollectionName", std::string(""))); // trigger results triggerResultsToken = consumes(pset.getParameter("triggerResults")); @@ -119,66 +112,63 @@ AnalysisRootpleProducer::AnalysisRootpleProducer( const ParameterSet& pset ) // triggerName = pset.getParameter("triggerName"); piG = acos(-1.); - NumberMCParticles=0; - NumberTracks=0; - NumberInclusiveJet=0; - NumberChargedJet=0; - NumberTracksJet=0; - NumberCaloJet=0; + NumberMCParticles = 0; + NumberTracks = 0; + NumberInclusiveJet = 0; + NumberChargedJet = 0; + NumberTracksJet = 0; + NumberCaloJet = 0; } -void AnalysisRootpleProducer::beginJob() -{ - +void AnalysisRootpleProducer::beginJob() { // use TFileService for output to root file - AnalysisTree = fs->make("AnalysisTree","MBUE Analysis Tree "); + AnalysisTree = fs->make("AnalysisTree", "MBUE Analysis Tree "); - AnalysisTree->Branch("EventKind",&EventKind,"EventKind/I"); + AnalysisTree->Branch("EventKind", &EventKind, "EventKind/I"); // store p, pt, eta, phi for particles and jets // GenParticles at hadron level - AnalysisTree->Branch("NumberMCParticles",&NumberMCParticles,"NumberMCParticles/I"); - AnalysisTree->Branch("MomentumMC",MomentumMC,"MomentumMC[NumberMCParticles]/F"); - AnalysisTree->Branch("TransverseMomentumMC",TransverseMomentumMC,"TransverseMomentumMC[NumberMCParticles]/F"); - AnalysisTree->Branch("EtaMC",EtaMC,"EtaMC[NumberMCParticles]/F"); - AnalysisTree->Branch("PhiMC",PhiMC,"PhiMC[NumberMCParticles]/F"); + AnalysisTree->Branch("NumberMCParticles", &NumberMCParticles, "NumberMCParticles/I"); + AnalysisTree->Branch("MomentumMC", MomentumMC, "MomentumMC[NumberMCParticles]/F"); + AnalysisTree->Branch("TransverseMomentumMC", TransverseMomentumMC, "TransverseMomentumMC[NumberMCParticles]/F"); + AnalysisTree->Branch("EtaMC", EtaMC, "EtaMC[NumberMCParticles]/F"); + AnalysisTree->Branch("PhiMC", PhiMC, "PhiMC[NumberMCParticles]/F"); // tracks - AnalysisTree->Branch("NumberTracks",&NumberTracks,"NumberTracks/I"); - AnalysisTree->Branch("MomentumTK",MomentumTK,"MomentumTK[NumberTracks]/F"); - AnalysisTree->Branch("TrasverseMomentumTK",TransverseMomentumTK,"TransverseMomentumTK[NumberTracks]/F"); - AnalysisTree->Branch("EtaTK",EtaTK,"EtaTK[NumberTracks]/F"); - AnalysisTree->Branch("PhiTK",PhiTK,"PhiTK[NumberTracks]/F"); + AnalysisTree->Branch("NumberTracks", &NumberTracks, "NumberTracks/I"); + AnalysisTree->Branch("MomentumTK", MomentumTK, "MomentumTK[NumberTracks]/F"); + AnalysisTree->Branch("TrasverseMomentumTK", TransverseMomentumTK, "TransverseMomentumTK[NumberTracks]/F"); + AnalysisTree->Branch("EtaTK", EtaTK, "EtaTK[NumberTracks]/F"); + AnalysisTree->Branch("PhiTK", PhiTK, "PhiTK[NumberTracks]/F"); // GenJets - AnalysisTree->Branch("NumberInclusiveJet",&NumberInclusiveJet,"NumberInclusiveJet/I"); - AnalysisTree->Branch("MomentumIJ",MomentumIJ,"MomentumIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("TrasverseMomentumIJ",TransverseMomentumIJ,"TransverseMomentumIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("EtaIJ",EtaIJ,"EtaIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("PhiIJ",PhiIJ,"PhiIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("NumberInclusiveJet", &NumberInclusiveJet, "NumberInclusiveJet/I"); + AnalysisTree->Branch("MomentumIJ", MomentumIJ, "MomentumIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("TrasverseMomentumIJ", TransverseMomentumIJ, "TransverseMomentumIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("EtaIJ", EtaIJ, "EtaIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("PhiIJ", PhiIJ, "PhiIJ[NumberInclusiveJet]/F"); // jets from charged GenParticles - AnalysisTree->Branch("NumberChargedJet",&NumberChargedJet,"NumberChargedJet/I"); - AnalysisTree->Branch("MomentumCJ",MomentumCJ,"MomentumCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("TrasverseMomentumCJ",TransverseMomentumCJ,"TransverseMomentumCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("EtaCJ",EtaCJ,"EtaCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("PhiCJ",PhiCJ,"PhiCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("NumberChargedJet", &NumberChargedJet, "NumberChargedJet/I"); + AnalysisTree->Branch("MomentumCJ", MomentumCJ, "MomentumCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("TrasverseMomentumCJ", TransverseMomentumCJ, "TransverseMomentumCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("EtaCJ", EtaCJ, "EtaCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("PhiCJ", PhiCJ, "PhiCJ[NumberChargedJet]/F"); // jets from tracks - AnalysisTree->Branch("NumberTracksJet",&NumberTracksJet,"NumberTracksJet/I"); - AnalysisTree->Branch("MomentumTJ",MomentumTJ,"MomentumTJ[NumberTracksJet]/F"); - AnalysisTree->Branch("TrasverseMomentumTJ",TransverseMomentumTJ,"TransverseMomentumTJ[NumberTracksJet]/F"); - AnalysisTree->Branch("EtaTJ",EtaTJ,"EtaTJ[NumberTracksJet]/F"); - AnalysisTree->Branch("PhiTJ",PhiTJ,"PhiTJ[NumberTracksJet]/F"); + AnalysisTree->Branch("NumberTracksJet", &NumberTracksJet, "NumberTracksJet/I"); + AnalysisTree->Branch("MomentumTJ", MomentumTJ, "MomentumTJ[NumberTracksJet]/F"); + AnalysisTree->Branch("TrasverseMomentumTJ", TransverseMomentumTJ, "TransverseMomentumTJ[NumberTracksJet]/F"); + AnalysisTree->Branch("EtaTJ", EtaTJ, "EtaTJ[NumberTracksJet]/F"); + AnalysisTree->Branch("PhiTJ", PhiTJ, "PhiTJ[NumberTracksJet]/F"); // jets from calorimeter towers - AnalysisTree->Branch("NumberCaloJet",&NumberCaloJet,"NumberCaloJet/I"); - AnalysisTree->Branch("MomentumEHJ",MomentumEHJ,"MomentumEHJ[NumberCaloJet]/F"); - AnalysisTree->Branch("TrasverseMomentumEHJ",TransverseMomentumEHJ,"TransverseMomentumEHJ[NumberCaloJet]/F"); - AnalysisTree->Branch("EtaEHJ",EtaEHJ,"EtaEHJ[NumberCaloJet]/F"); - AnalysisTree->Branch("PhiEHJ",PhiEHJ,"PhiEHJ[NumberCaloJet]/F"); - + AnalysisTree->Branch("NumberCaloJet", &NumberCaloJet, "NumberCaloJet/I"); + AnalysisTree->Branch("MomentumEHJ", MomentumEHJ, "MomentumEHJ[NumberCaloJet]/F"); + AnalysisTree->Branch("TrasverseMomentumEHJ", TransverseMomentumEHJ, "TransverseMomentumEHJ[NumberCaloJet]/F"); + AnalysisTree->Branch("EtaEHJ", EtaEHJ, "EtaEHJ[NumberCaloJet]/F"); + AnalysisTree->Branch("PhiEHJ", PhiEHJ, "PhiEHJ[NumberCaloJet]/F"); // alternative storage method: // save TClonesArrays of TLorentzVectors @@ -204,56 +194,47 @@ void AnalysisRootpleProducer::beginJob() acceptedTriggers = new TClonesArray("TObjString", 10000); AnalysisTree->Branch("acceptedTriggers", "TClonesArray", &acceptedTriggers, 128000, 0); - } - -void AnalysisRootpleProducer::analyze( const Event& e, const EventSetup& ) -{ - - e.getByToken( triggerResultsToken, triggerResults ); - const edm::TriggerNames & triggerNames = e.triggerNames(*triggerResults); +void AnalysisRootpleProducer::analyze(const Event& e, const EventSetup&) { + e.getByToken(triggerResultsToken, triggerResults); + const edm::TriggerNames& triggerNames = e.triggerNames(*triggerResults); acceptedTriggers->Clear(); - unsigned int iAcceptedTriggers( 0 ); - if ( triggerResults.product()->wasrun() ) - { - //cout << "at least one path out of " << triggerResults.product()->size() << " ran? " << triggerResults.product()->wasrun() << endl; - - if ( triggerResults.product()->accept() ) - { - //cout << endl << "at least one path accepted? " << triggerResults.product()->accept() << endl; - - const unsigned int n_TriggerResults( triggerResults.product()->size() ); - for ( unsigned int itrig( 0 ); itrig < n_TriggerResults; ++itrig ) - { - if ( triggerResults.product()->accept( itrig ) ) - { - //cout << "path " << triggerNames.triggerName( itrig ); - //cout << ", module index " << triggerResults.product()->index( itrig ); - //cout << ", state (Ready = 0, Pass = 1, Fail = 2, Exception = 3) " << triggerResults.product()->state( itrig ); - //cout << ", accept " << triggerResults.product()->accept( itrig ); - //cout << endl; - - // save name of accepted trigger path - new((*acceptedTriggers)[iAcceptedTriggers]) TObjString( (triggerNames.triggerName( itrig )).c_str() ); - ++iAcceptedTriggers; - } - } - } + unsigned int iAcceptedTriggers(0); + if (triggerResults.product()->wasrun()) { + //cout << "at least one path out of " << triggerResults.product()->size() << " ran? " << triggerResults.product()->wasrun() << endl; + + if (triggerResults.product()->accept()) { + //cout << endl << "at least one path accepted? " << triggerResults.product()->accept() << endl; + + const unsigned int n_TriggerResults(triggerResults.product()->size()); + for (unsigned int itrig(0); itrig < n_TriggerResults; ++itrig) { + if (triggerResults.product()->accept(itrig)) { + //cout << "path " << triggerNames.triggerName( itrig ); + //cout << ", module index " << triggerResults.product()->index( itrig ); + //cout << ", state (Ready = 0, Pass = 1, Fail = 2, Exception = 3) " << triggerResults.product()->state( itrig ); + //cout << ", accept " << triggerResults.product()->accept( itrig ); + //cout << endl; + + // save name of accepted trigger path + new ((*acceptedTriggers)[iAcceptedTriggers]) TObjString((triggerNames.triggerName(itrig)).c_str()); + ++iAcceptedTriggers; + } + } } + } // gen level analysis // skipped, if onlyRECO flag set to true - if(!onlyRECO){ - - e.getByToken( mcEventToken , EvtHandle ); - e.getByToken( chgGenPartCollToken, CandHandleMC ); - e.getByToken( chgJetCollToken , ChgGenJetsHandle ); - e.getByToken( genJetCollToken , GenJetsHandle ); + if (!onlyRECO) { + e.getByToken(mcEventToken, EvtHandle); + e.getByToken(chgGenPartCollToken, CandHandleMC); + e.getByToken(chgJetCollToken, ChgGenJetsHandle); + e.getByToken(genJetCollToken, GenJetsHandle); - const HepMC::GenEvent* Evt = EvtHandle->GetEvent() ; + const HepMC::GenEvent* Evt = EvtHandle->GetEvent(); EventKind = Evt->signal_process_id(); @@ -269,72 +250,59 @@ void AnalysisRootpleProducer::analyze( const Event& e, const EventSetup& ) ChargedJet->Clear(); // jets from charged particles at hadron level - if (!ChgGenJetsHandle->empty()){ - - for ( GenJetCollection::const_iterator it(ChgGenJetsHandle->begin()), itEnd(ChgGenJetsHandle->end()); - it!=itEnd; ++it) - { - ChgGenJetContainer.push_back(*it); - } + if (!ChgGenJetsHandle->empty()) { + for (GenJetCollection::const_iterator it(ChgGenJetsHandle->begin()), itEnd(ChgGenJetsHandle->end()); it != itEnd; + ++it) { + ChgGenJetContainer.push_back(*it); + } - std::stable_sort(ChgGenJetContainer.begin(),ChgGenJetContainer.end(),GenJetSort()); + std::stable_sort(ChgGenJetContainer.begin(), ChgGenJetContainer.end(), GenJetSort()); std::vector::const_iterator it(ChgGenJetContainer.begin()), itEnd(ChgGenJetContainer.end()); - for ( int iChargedJet(0); it != itEnd; ++it, ++iChargedJet) - { - fillChargedJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*ChargedJet)[iChargedJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + for (int iChargedJet(0); it != itEnd; ++it, ++iChargedJet) { + fillChargedJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*ChargedJet)[iChargedJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); + } } - // GenJets - if (!GenJetsHandle->empty()){ - - for ( GenJetCollection::const_iterator it(GenJetsHandle->begin()), itEnd(GenJetsHandle->end()); - it!=itEnd; ++it ) - { - GenJetContainer.push_back(*it); - } + if (!GenJetsHandle->empty()) { + for (GenJetCollection::const_iterator it(GenJetsHandle->begin()), itEnd(GenJetsHandle->end()); it != itEnd; + ++it) { + GenJetContainer.push_back(*it); + } - std::stable_sort(GenJetContainer.begin(),GenJetContainer.end(),GenJetSort()); + std::stable_sort(GenJetContainer.begin(), GenJetContainer.end(), GenJetSort()); std::vector::const_iterator it(GenJetContainer.begin()), itEnd(GenJetContainer.end()); - for ( int iInclusiveJet(0); it != itEnd; ++it, ++iInclusiveJet) - { - fillInclusiveJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*InclusiveJet)[iInclusiveJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + for (int iInclusiveJet(0); it != itEnd; ++it, ++iInclusiveJet) { + fillInclusiveJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*InclusiveJet)[iInclusiveJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); + } } - // hadron level particles - if (!CandHandleMC->empty()){ - - for (vector::const_iterator it(CandHandleMC->begin()), itEnd(CandHandleMC->end()); - it != itEnd;it++) - { - GenPart.push_back(it->p4()); - } + if (!CandHandleMC->empty()) { + for (vector::const_iterator it(CandHandleMC->begin()), itEnd(CandHandleMC->end()); it != itEnd; + it++) { + GenPart.push_back(it->p4()); + } - std::stable_sort(GenPart.begin(),GenPart.end(),GreaterPt()); + std::stable_sort(GenPart.begin(), GenPart.end(), GreaterPt()); std::vector::const_iterator it(GenPart.begin()), itEnd(GenPart.end()); - for( int iMonteCarlo(0); it != itEnd; ++it, ++iMonteCarlo ) - { - fillMCParticles(it->P(),it->Pt(),it->Eta(),it->Phi()); - new((*MonteCarlo)[iMonteCarlo]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); - } + for (int iMonteCarlo(0); it != itEnd; ++it, ++iMonteCarlo) { + fillMCParticles(it->P(), it->Pt(), it->Eta(), it->Phi()); + new ((*MonteCarlo)[iMonteCarlo]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); + } } - } - // reco level analysis - e.getByToken( tracksCollToken , CandHandleRECO ); - e.getByToken( recoCaloJetCollToken, RecoCaloJetsHandle ); - e.getByToken( tracksJetCollToken , TracksJetsHandle ); + e.getByToken(tracksCollToken, CandHandleRECO); + e.getByToken(recoCaloJetCollToken, RecoCaloJetsHandle); + e.getByToken(tracksJetCollToken, TracksJetsHandle); std::vector Tracks; std::vector TracksJetContainer; @@ -348,61 +316,50 @@ void AnalysisRootpleProducer::analyze( const Event& e, const EventSetup& ) TracksJet->Clear(); CalorimeterJet->Clear(); - if(!RecoCaloJetsHandle->empty()) - { - for(CaloJetCollection::const_iterator it(RecoCaloJetsHandle->begin()), itEnd(RecoCaloJetsHandle->end()); - it!=itEnd;++it) - { - RecoCaloJetContainer.push_back(*it); - } - std::stable_sort(RecoCaloJetContainer.begin(),RecoCaloJetContainer.end(),CaloJetSort()); + if (!RecoCaloJetsHandle->empty()) { + for (CaloJetCollection::const_iterator it(RecoCaloJetsHandle->begin()), itEnd(RecoCaloJetsHandle->end()); + it != itEnd; + ++it) { + RecoCaloJetContainer.push_back(*it); + } + std::stable_sort(RecoCaloJetContainer.begin(), RecoCaloJetContainer.end(), CaloJetSort()); std::vector::const_iterator it(RecoCaloJetContainer.begin()), itEnd(RecoCaloJetContainer.end()); - for( int iCalorimeterJet(0); it != itEnd; ++it, ++iCalorimeterJet) - { - fillCaloJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*CalorimeterJet)[iCalorimeterJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + for (int iCalorimeterJet(0); it != itEnd; ++it, ++iCalorimeterJet) { + fillCaloJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*CalorimeterJet)[iCalorimeterJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); } + } - if(!TracksJetsHandle->empty()) - { - for(BasicJetCollection::const_iterator it(TracksJetsHandle->begin()), itEnd(TracksJetsHandle->end()); - it!=itEnd;++it) - { - TracksJetContainer.push_back(*it); - } - std::stable_sort(TracksJetContainer.begin(),TracksJetContainer.end(),BasicJetSort()); - - std::vector::const_iterator it(TracksJetContainer.begin()), itEnd(TracksJetContainer.end()); - for(int iTracksJet(0); it != itEnd; ++it, ++iTracksJet) - { - fillTracksJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*TracksJet)[iTracksJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + if (!TracksJetsHandle->empty()) { + for (BasicJetCollection::const_iterator it(TracksJetsHandle->begin()), itEnd(TracksJetsHandle->end()); it != itEnd; + ++it) { + TracksJetContainer.push_back(*it); } + std::stable_sort(TracksJetContainer.begin(), TracksJetContainer.end(), BasicJetSort()); - if(!CandHandleRECO->empty()) - { - for(CandidateCollection::const_iterator it(CandHandleRECO->begin()), itEnd(CandHandleRECO->end()); - it!=itEnd;++it) - { - Tracks.push_back(it->p4()); - } - std::stable_sort(Tracks.begin(),Tracks.end(),GreaterPt()); - - std::vector::const_iterator it( Tracks.begin()), itEnd(Tracks.end()); - for(int iTracks(0); it != itEnd; ++it, ++iTracks) - { - fillTracks(it->P(),it->Pt(),it->Eta(),it->Phi()); - new ((*Track)[iTracks]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); - } + std::vector::const_iterator it(TracksJetContainer.begin()), itEnd(TracksJetContainer.end()); + for (int iTracksJet(0); it != itEnd; ++it, ++iTracksJet) { + fillTracksJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*TracksJet)[iTracksJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); } + } - store(); -} + if (!CandHandleRECO->empty()) { + for (CandidateCollection::const_iterator it(CandHandleRECO->begin()), itEnd(CandHandleRECO->end()); it != itEnd; + ++it) { + Tracks.push_back(it->p4()); + } + std::stable_sort(Tracks.begin(), Tracks.end(), GreaterPt()); -void AnalysisRootpleProducer::endJob() -{ + std::vector::const_iterator it(Tracks.begin()), itEnd(Tracks.end()); + for (int iTracks(0); it != itEnd; ++it, ++iTracks) { + fillTracks(it->P(), it->Pt(), it->Eta(), it->Phi()); + new ((*Track)[iTracks]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); + } + } + + store(); } +void AnalysisRootpleProducer::endJob() {} diff --git a/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducerOnlyMC.cc b/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducerOnlyMC.cc index 08663008b825e..59c0ac3330e28 100644 --- a/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducerOnlyMC.cc +++ b/QCDAnalysis/UEAnalysis/src/AnalysisRootpleProducerOnlyMC.cc @@ -5,111 +5,94 @@ using namespace edm; using namespace std; using namespace reco; -class GreaterPt -{ +class GreaterPt { public: - bool operator()( const math::XYZTLorentzVector& a, const math::XYZTLorentzVector& b) - { - return a.pt() > b.pt(); - } + bool operator()(const math::XYZTLorentzVector& a, const math::XYZTLorentzVector& b) { return a.pt() > b.pt(); } }; -class GenJetSort -{ +class GenJetSort { public: - bool operator()(const GenJet& a, const GenJet& b) - { - return a.pt() > b.pt(); - } + bool operator()(const GenJet& a, const GenJet& b) { return a.pt() > b.pt(); } }; - -void AnalysisRootpleProducerOnlyMC::store() -{ +void AnalysisRootpleProducerOnlyMC::store() { AnalysisTree->Fill(); - NumberMCParticles=0; - NumberInclusiveJet=0; - NumberChargedJet=0; + NumberMCParticles = 0; + NumberInclusiveJet = 0; + NumberChargedJet = 0; } -void AnalysisRootpleProducerOnlyMC::fillEventInfo(int e) -{ - EventKind = e; -} +void AnalysisRootpleProducerOnlyMC::fillEventInfo(int e) { EventKind = e; } -void AnalysisRootpleProducerOnlyMC::fillMCParticles(float p, float pt, float eta, float phi) -{ - MomentumMC[NumberMCParticles]=p; - TransverseMomentumMC[NumberMCParticles]=pt; - EtaMC[NumberMCParticles]=eta; - PhiMC[NumberMCParticles]=phi; +void AnalysisRootpleProducerOnlyMC::fillMCParticles(float p, float pt, float eta, float phi) { + MomentumMC[NumberMCParticles] = p; + TransverseMomentumMC[NumberMCParticles] = pt; + EtaMC[NumberMCParticles] = eta; + PhiMC[NumberMCParticles] = phi; NumberMCParticles++; } -void AnalysisRootpleProducerOnlyMC::fillInclusiveJet(float p, float pt, float eta, float phi) -{ - MomentumIJ[NumberInclusiveJet]=p; - TransverseMomentumIJ[NumberInclusiveJet]=pt; - EtaIJ[NumberInclusiveJet]=eta; - PhiIJ[NumberInclusiveJet]=phi; +void AnalysisRootpleProducerOnlyMC::fillInclusiveJet(float p, float pt, float eta, float phi) { + MomentumIJ[NumberInclusiveJet] = p; + TransverseMomentumIJ[NumberInclusiveJet] = pt; + EtaIJ[NumberInclusiveJet] = eta; + PhiIJ[NumberInclusiveJet] = phi; NumberInclusiveJet++; } -void AnalysisRootpleProducerOnlyMC::fillChargedJet(float p, float pt, float eta, float phi) -{ - MomentumCJ[NumberChargedJet]=p; - TransverseMomentumCJ[NumberChargedJet]=pt; - EtaCJ[NumberChargedJet]=eta; - PhiCJ[NumberChargedJet]=phi; +void AnalysisRootpleProducerOnlyMC::fillChargedJet(float p, float pt, float eta, float phi) { + MomentumCJ[NumberChargedJet] = p; + TransverseMomentumCJ[NumberChargedJet] = pt; + EtaCJ[NumberChargedJet] = eta; + PhiCJ[NumberChargedJet] = phi; NumberChargedJet++; } -AnalysisRootpleProducerOnlyMC::AnalysisRootpleProducerOnlyMC( const ParameterSet& pset ) -{ - mcEventToken = consumes(pset.getUntrackedParameter("MCEvent",std::string(""))); - genJetCollToken = consumes(pset.getUntrackedParameter("GenJetCollectionName",std::string(""))); - chgJetCollToken = consumes(pset.getUntrackedParameter("ChgGenJetCollectionName",std::string(""))); - chgGenPartCollToken = consumes >(pset.getUntrackedParameter("ChgGenPartCollectionName",std::string(""))); +AnalysisRootpleProducerOnlyMC::AnalysisRootpleProducerOnlyMC(const ParameterSet& pset) { + mcEventToken = consumes(pset.getUntrackedParameter("MCEvent", std::string(""))); + genJetCollToken = + consumes(pset.getUntrackedParameter("GenJetCollectionName", std::string(""))); + chgJetCollToken = consumes( + pset.getUntrackedParameter("ChgGenJetCollectionName", std::string(""))); + chgGenPartCollToken = consumes >( + pset.getUntrackedParameter("ChgGenPartCollectionName", std::string(""))); piG = acos(-1.); - NumberMCParticles=0; - NumberInclusiveJet=0; - NumberChargedJet=0; + NumberMCParticles = 0; + NumberInclusiveJet = 0; + NumberChargedJet = 0; } - -void AnalysisRootpleProducerOnlyMC::beginJob() -{ +void AnalysisRootpleProducerOnlyMC::beginJob() { // use TFileService for output to root file - AnalysisTree = fs->make("AnalysisTree","MBUE Analysis Tree "); + AnalysisTree = fs->make("AnalysisTree", "MBUE Analysis Tree "); // process type - AnalysisTree->Branch("EventKind",&EventKind,"EventKind/I"); + AnalysisTree->Branch("EventKind", &EventKind, "EventKind/I"); // store p, pt, eta, phi for particles and jets // GenParticles at hadron level - AnalysisTree->Branch("NumberMCParticles",&NumberMCParticles,"NumberMCParticles/I"); - AnalysisTree->Branch("MomentumMC",MomentumMC,"MomentumMC[NumberMCParticles]/F"); - AnalysisTree->Branch("TransverseMomentumMC",TransverseMomentumMC,"TransverseMomentumMC[NumberMCParticles]/F"); - AnalysisTree->Branch("EtaMC",EtaMC,"EtaMC[NumberMCParticles]/F"); - AnalysisTree->Branch("PhiMC",PhiMC,"PhiMC[NumberMCParticles]/F"); + AnalysisTree->Branch("NumberMCParticles", &NumberMCParticles, "NumberMCParticles/I"); + AnalysisTree->Branch("MomentumMC", MomentumMC, "MomentumMC[NumberMCParticles]/F"); + AnalysisTree->Branch("TransverseMomentumMC", TransverseMomentumMC, "TransverseMomentumMC[NumberMCParticles]/F"); + AnalysisTree->Branch("EtaMC", EtaMC, "EtaMC[NumberMCParticles]/F"); + AnalysisTree->Branch("PhiMC", PhiMC, "PhiMC[NumberMCParticles]/F"); // GenJets - AnalysisTree->Branch("NumberInclusiveJet",&NumberInclusiveJet,"NumberInclusiveJet/I"); - AnalysisTree->Branch("MomentumIJ",MomentumIJ,"MomentumIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("TrasverseMomentumIJ",TransverseMomentumIJ,"TransverseMomentumIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("EtaIJ",EtaIJ,"EtaIJ[NumberInclusiveJet]/F"); - AnalysisTree->Branch("PhiIJ",PhiIJ,"PhiIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("NumberInclusiveJet", &NumberInclusiveJet, "NumberInclusiveJet/I"); + AnalysisTree->Branch("MomentumIJ", MomentumIJ, "MomentumIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("TrasverseMomentumIJ", TransverseMomentumIJ, "TransverseMomentumIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("EtaIJ", EtaIJ, "EtaIJ[NumberInclusiveJet]/F"); + AnalysisTree->Branch("PhiIJ", PhiIJ, "PhiIJ[NumberInclusiveJet]/F"); // jets from charged GenParticles - AnalysisTree->Branch("NumberChargedJet",&NumberChargedJet,"NumberChargedJet/I"); - AnalysisTree->Branch("MomentumCJ",MomentumCJ,"MomentumCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("TrasverseMomentumCJ",TransverseMomentumCJ,"TransverseMomentumCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("EtaCJ",EtaCJ,"EtaCJ[NumberChargedJet]/F"); - AnalysisTree->Branch("PhiCJ",PhiCJ,"PhiCJ[NumberChargedJet]/F"); - + AnalysisTree->Branch("NumberChargedJet", &NumberChargedJet, "NumberChargedJet/I"); + AnalysisTree->Branch("MomentumCJ", MomentumCJ, "MomentumCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("TrasverseMomentumCJ", TransverseMomentumCJ, "TransverseMomentumCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("EtaCJ", EtaCJ, "EtaCJ[NumberChargedJet]/F"); + AnalysisTree->Branch("PhiCJ", PhiCJ, "PhiCJ[NumberChargedJet]/F"); // alternative storage method: // save TClonesArrays of TLorentzVectors @@ -125,16 +108,13 @@ void AnalysisRootpleProducerOnlyMC::beginJob() AnalysisTree->Branch("ChargedJet", "TClonesArray", &ChargedJet, 128000, 0); } +void AnalysisRootpleProducerOnlyMC::analyze(const Event& e, const EventSetup&) { + e.getByToken(mcEventToken, EvtHandle); + e.getByToken(chgGenPartCollToken, CandHandleMC); + e.getByToken(chgJetCollToken, ChgGenJetsHandle); + e.getByToken(genJetCollToken, GenJetsHandle); -void AnalysisRootpleProducerOnlyMC::analyze( const Event& e, const EventSetup& ) -{ - - e.getByToken( mcEventToken , EvtHandle ); - e.getByToken( chgGenPartCollToken, CandHandleMC ); - e.getByToken( chgJetCollToken , ChgGenJetsHandle ); - e.getByToken( genJetCollToken , GenJetsHandle ); - - const HepMC::GenEvent* Evt = EvtHandle->GetEvent() ; + const HepMC::GenEvent* Evt = EvtHandle->GetEvent(); EventKind = Evt->signal_process_id(); @@ -150,64 +130,50 @@ void AnalysisRootpleProducerOnlyMC::analyze( const Event& e, const EventSetup& ) InclusiveJet->Clear(); MonteCarlo->Clear(); - if (!ChgGenJetsHandle->empty()){ - - for ( GenJetCollection::const_iterator it(ChgGenJetsHandle->begin()), itEnd(ChgGenJetsHandle->end()); - it!=itEnd; ++it) - { - ChgGenJetContainer.push_back(*it); - } + if (!ChgGenJetsHandle->empty()) { + for (GenJetCollection::const_iterator it(ChgGenJetsHandle->begin()), itEnd(ChgGenJetsHandle->end()); it != itEnd; + ++it) { + ChgGenJetContainer.push_back(*it); + } - std::stable_sort(ChgGenJetContainer.begin(),ChgGenJetContainer.end(),GenJetSort()); + std::stable_sort(ChgGenJetContainer.begin(), ChgGenJetContainer.end(), GenJetSort()); std::vector::const_iterator it(ChgGenJetContainer.begin()), itEnd(ChgGenJetContainer.end()); - for ( int iChargedJet(0); it != itEnd; ++it, ++iChargedJet) - { - fillChargedJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*ChargedJet)[iChargedJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + for (int iChargedJet(0); it != itEnd; ++it, ++iChargedJet) { + fillChargedJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*ChargedJet)[iChargedJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); + } } - if (!GenJetsHandle->empty()){ - - for ( GenJetCollection::const_iterator it(GenJetsHandle->begin()), itEnd(GenJetsHandle->end()); - it!=itEnd; ++it ) - { - GenJetContainer.push_back(*it); - } + if (!GenJetsHandle->empty()) { + for (GenJetCollection::const_iterator it(GenJetsHandle->begin()), itEnd(GenJetsHandle->end()); it != itEnd; ++it) { + GenJetContainer.push_back(*it); + } - std::stable_sort(GenJetContainer.begin(),GenJetContainer.end(),GenJetSort()); + std::stable_sort(GenJetContainer.begin(), GenJetContainer.end(), GenJetSort()); std::vector::const_iterator it(GenJetContainer.begin()), itEnd(GenJetContainer.end()); - for ( int iInclusiveJet(0); it != itEnd; ++it, ++iInclusiveJet) - { - fillInclusiveJet(it->p(),it->pt(),it->eta(),it->phi()); - new((*InclusiveJet)[iInclusiveJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); - } + for (int iInclusiveJet(0); it != itEnd; ++it, ++iInclusiveJet) { + fillInclusiveJet(it->p(), it->pt(), it->eta(), it->phi()); + new ((*InclusiveJet)[iInclusiveJet]) TLorentzVector(it->px(), it->py(), it->pz(), it->energy()); + } } - if (!CandHandleMC->empty()){ + if (!CandHandleMC->empty()) { + for (vector::const_iterator it(CandHandleMC->begin()), itEnd(CandHandleMC->end()); it != itEnd; it++) { + GenPart.push_back(it->p4()); + } - for (vector::const_iterator it(CandHandleMC->begin()), itEnd(CandHandleMC->end()); - it != itEnd;it++) - { - GenPart.push_back(it->p4()); - } - - std::stable_sort(GenPart.begin(),GenPart.end(),GreaterPt()); + std::stable_sort(GenPart.begin(), GenPart.end(), GreaterPt()); std::vector::const_iterator it(GenPart.begin()), itEnd(GenPart.end()); - for( int iMonteCarlo(0); it != itEnd; ++it, ++iMonteCarlo ) - { - fillMCParticles(it->P(),it->Pt(),it->Eta(),it->Phi()); - new((*MonteCarlo)[iMonteCarlo]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); - } + for (int iMonteCarlo(0); it != itEnd; ++it, ++iMonteCarlo) { + fillMCParticles(it->P(), it->Pt(), it->Eta(), it->Phi()); + new ((*MonteCarlo)[iMonteCarlo]) TLorentzVector(it->Px(), it->Py(), it->Pz(), it->E()); + } } store(); } -void AnalysisRootpleProducerOnlyMC::endJob() -{ -} - +void AnalysisRootpleProducerOnlyMC::endJob() {} diff --git a/TopQuarkAnalysis/Examples/bin/NiceStyle.cc b/TopQuarkAnalysis/Examples/bin/NiceStyle.cc index 130184802c7ec..a1803b4c6d228 100644 --- a/TopQuarkAnalysis/Examples/bin/NiceStyle.cc +++ b/TopQuarkAnalysis/Examples/bin/NiceStyle.cc @@ -1,39 +1,37 @@ #include void setNiceStyle() { - TStyle *MyStyle = new TStyle ("MyStyle", "My style for nicer plots"); - - Float_t xoff = MyStyle->GetLabelOffset("X"), - yoff = MyStyle->GetLabelOffset("Y"), - zoff = MyStyle->GetLabelOffset("Z"); - - MyStyle->SetCanvasBorderMode ( 0 ); - MyStyle->SetPadBorderMode ( 0 ); - MyStyle->SetPadColor ( 0 ); - MyStyle->SetCanvasColor ( 0 ); - MyStyle->SetTitleColor ( 0 ); - MyStyle->SetStatColor ( 0 ); - MyStyle->SetTitleBorderSize ( 0 ); - MyStyle->SetTitleFillColor ( 0 ); - MyStyle->SetTitleH ( 0.07 ); - MyStyle->SetTitleW ( 1.00 ); - MyStyle->SetTitleFont ( 132 ); - - MyStyle->SetLabelOffset (1.5*xoff, "X"); - MyStyle->SetLabelOffset (1.5*yoff, "Y"); - MyStyle->SetLabelOffset (1.5*zoff, "Z"); - - MyStyle->SetTitleOffset (0.9, "X"); - MyStyle->SetTitleOffset (0.9, "Y"); - MyStyle->SetTitleOffset (0.9, "Z"); - - MyStyle->SetTitleSize (0.045, "X"); - MyStyle->SetTitleSize (0.045, "Y"); - MyStyle->SetTitleSize (0.045, "Z"); - - MyStyle->SetLabelFont (132, "X"); - MyStyle->SetLabelFont (132, "Y"); - MyStyle->SetLabelFont (132, "Z"); + TStyle *MyStyle = new TStyle("MyStyle", "My style for nicer plots"); + + Float_t xoff = MyStyle->GetLabelOffset("X"), yoff = MyStyle->GetLabelOffset("Y"), zoff = MyStyle->GetLabelOffset("Z"); + + MyStyle->SetCanvasBorderMode(0); + MyStyle->SetPadBorderMode(0); + MyStyle->SetPadColor(0); + MyStyle->SetCanvasColor(0); + MyStyle->SetTitleColor(0); + MyStyle->SetStatColor(0); + MyStyle->SetTitleBorderSize(0); + MyStyle->SetTitleFillColor(0); + MyStyle->SetTitleH(0.07); + MyStyle->SetTitleW(1.00); + MyStyle->SetTitleFont(132); + + MyStyle->SetLabelOffset(1.5 * xoff, "X"); + MyStyle->SetLabelOffset(1.5 * yoff, "Y"); + MyStyle->SetLabelOffset(1.5 * zoff, "Z"); + + MyStyle->SetTitleOffset(0.9, "X"); + MyStyle->SetTitleOffset(0.9, "Y"); + MyStyle->SetTitleOffset(0.9, "Z"); + + MyStyle->SetTitleSize(0.045, "X"); + MyStyle->SetTitleSize(0.045, "Y"); + MyStyle->SetTitleSize(0.045, "Z"); + + MyStyle->SetLabelFont(132, "X"); + MyStyle->SetLabelFont(132, "Y"); + MyStyle->SetLabelFont(132, "Z"); MyStyle->SetPalette(1); diff --git a/TopQuarkAnalysis/Examples/bin/TopElecFWLiteAnalyzer.cc b/TopQuarkAnalysis/Examples/bin/TopElecFWLiteAnalyzer.cc index 7e0889d18e578..55103efa1927d 100644 --- a/TopQuarkAnalysis/Examples/bin/TopElecFWLiteAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/bin/TopElecFWLiteAnalyzer.cc @@ -13,95 +13,96 @@ #include "TopQuarkAnalysis/Examples/interface/RootHistograms.h" #include "TopQuarkAnalysis/Examples/interface/RootPostScript.h" - -int main(int argc, char* argv[]) -{ - if( argc<3 ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Wrong number of arguments! Please specify:" << std::endl - << " * filepath" << std::endl - << " * process name" << std::endl; - // ------------------------------------------------- +int main(int argc, char* argv[]) { + if (argc < 3) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Wrong number of arguments! Please specify:" << std::endl + << " * filepath" << std::endl + << " * process name" << std::endl; + // ------------------------------------------------- return -1; } // load framework libraries - gSystem->Load( "libFWCoreFWLite" ); + gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); - + // set nice style for histograms setNiceStyle(); - // define some histograms - TH1I* noElecs = new TH1I("noElecs", "N_{Elecs}", 10, 0 , 10 ); - TH1F* ptElecs = new TH1F("ptElecs", "pt_{Elecs}", 100, 0.,300.); - TH1F* enElecs = new TH1F("enElecs", "energy_{Elecs}",100, 0.,300.); - TH1F* etaElecs = new TH1F("etaElecs","eta_{Elecs}", 100, -3., 3.); - TH1F* phiElecs = new TH1F("phiElecs","phi_{Elecs}", 100, -5., 5.); - - // ------------------------------------------------- + // define some histograms + TH1I* noElecs = new TH1I("noElecs", "N_{Elecs}", 10, 0, 10); + TH1F* ptElecs = new TH1F("ptElecs", "pt_{Elecs}", 100, 0., 300.); + TH1F* enElecs = new TH1F("enElecs", "energy_{Elecs}", 100, 0., 300.); + TH1F* etaElecs = new TH1F("etaElecs", "eta_{Elecs}", 100, -3., 3.); + TH1F* phiElecs = new TH1F("phiElecs", "phi_{Elecs}", 100, -5., 5.); + + // ------------------------------------------------- std::cout << "open file: " << argv[1] << std::endl; // ------------------------------------------------- TFile* inFile = TFile::Open(argv[1]); - TTree* events_= nullptr; - if( inFile ) inFile->GetObject("Events", events_); - if( events_==nullptr ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Unable to retrieve TTree Events!" << std::endl - << " Eighter wrong file name or the the tree doesn't exists" << std::endl; - // ------------------------------------------------- + TTree* events_ = nullptr; + if (inFile) + inFile->GetObject("Events", events_); + if (events_ == nullptr) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Unable to retrieve TTree Events!" << std::endl + << " Eighter wrong file name or the the tree doesn't exists" << std::endl; + // ------------------------------------------------- return -1; } // acess branch of elecs char elecName[50]; sprintf(elecName, "patElectrons_selectedPatElectrons__%s.obj", argv[2]); - TBranch* elecs_ = events_->GetBranch( elecName ); assert( elecs_!=nullptr ); - + TBranch* elecs_ = events_->GetBranch(elecName); + assert(elecs_ != nullptr); + // loop over events and fill histograms std::vector elecs; int nevt = events_->GetEntries(); - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "start looping " << nevt << " events..." << std::endl; // ------------------------------------------------- - for(int evt=0; evtSetAddress( &elecs ); + for (int evt = 0; evt < nevt; ++evt) { + // set branch address + elecs_->SetAddress(&elecs); // get event - elecs_ ->GetEntry( evt ); - events_->GetEntry( evt, 0 ); + elecs_->GetEntry(evt); + events_->GetEntry(evt, 0); - // ------------------------------------------------- - if(evt>0 && !(evt%10)) std::cout << " processing event: " << evt << std::endl; - // ------------------------------------------------- + // ------------------------------------------------- + if (evt > 0 && !(evt % 10)) + std::cout << " processing event: " << evt << std::endl; + // ------------------------------------------------- // fill histograms noElecs->Fill(elecs.size()); - for(unsigned idx=0; idxFill(elecs[idx].pt() ); - enElecs ->Fill(elecs[idx].energy()); - etaElecs->Fill(elecs[idx].eta() ); - phiElecs->Fill(elecs[idx].phi() ); + ptElecs->Fill(elecs[idx].pt()); + enElecs->Fill(elecs[idx].energy()); + etaElecs->Fill(elecs[idx].eta()); + phiElecs->Fill(elecs[idx].phi()); } } - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "close file" << std::endl; // ------------------------------------------------- inFile->Close(); // save histograms to file - TFile outFile( "analyzeElecs.root", "recreate" ); + TFile outFile("analyzeElecs.root", "recreate"); outFile.mkdir("analyzeElec"); outFile.cd("analyzeElec"); - noElecs ->Write( ); - ptElecs ->Write( ); - enElecs ->Write( ); - etaElecs->Write( ); - phiElecs->Write( ); + noElecs->Write(); + ptElecs->Write(); + enElecs->Write(); + etaElecs->Write(); + phiElecs->Write(); outFile.Close(); // free allocated space diff --git a/TopQuarkAnalysis/Examples/bin/TopHypothesisFWLiteAnalyzer.cc b/TopQuarkAnalysis/Examples/bin/TopHypothesisFWLiteAnalyzer.cc index 3de70873499e1..5640fccdbdca9 100644 --- a/TopQuarkAnalysis/Examples/bin/TopHypothesisFWLiteAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/bin/TopHypothesisFWLiteAnalyzer.cc @@ -13,16 +13,15 @@ #include "TopQuarkAnalysis/Examples/interface/RootHistograms.h" #include "TopQuarkAnalysis/Examples/interface/RootPostScript.h" -int main(int argc, char* argv[]) -{ - if( argc<4 ){ - // ------------------------------------------------- - std::cerr << "ERROR: Wrong number of arguments!" << std::endl - << "Please specify: * file name" << std::endl - << " * process name" << std::endl - << " * HypoClassKey" << std::endl - << "Example: TopHypothesisFWLiteAnalyzer ttSemiLepEvtBuilder.root TEST kGeom" << std::endl; - // ------------------------------------------------- +int main(int argc, char* argv[]) { + if (argc < 4) { + // ------------------------------------------------- + std::cerr << "ERROR: Wrong number of arguments!" << std::endl + << "Please specify: * file name" << std::endl + << " * process name" << std::endl + << " * HypoClassKey" << std::endl + << "Example: TopHypothesisFWLiteAnalyzer ttSemiLepEvtBuilder.root TEST kGeom" << std::endl; + // ------------------------------------------------- return -1; } @@ -30,118 +29,122 @@ int main(int argc, char* argv[]) std::string hypoClassKey = argv[3]; // load framework libraries - gSystem->Load( "libFWCoreFWLite" ); + gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); - + // set nice style for histograms setNiceStyle(); - // define some histograms - TH1F* hadWPt_ = new TH1F("hadWPt", "p_{t} (W_{had}) [GeV]", 100, 0., 500.); - TH1F* hadWMass_ = new TH1F("hadWMass", "M (W_{had}) [GeV]", 50, 0., 150.); - TH1F* hadTopPt_ = new TH1F("hadTopPt", "p_{t} (t_{had}) [GeV]", 100, 0., 500.); - TH1F* hadTopMass_= new TH1F("hadTopMass", "M (t_{had}) [GeV]", 50, 50., 250.); + // define some histograms + TH1F* hadWPt_ = new TH1F("hadWPt", "p_{t} (W_{had}) [GeV]", 100, 0., 500.); + TH1F* hadWMass_ = new TH1F("hadWMass", "M (W_{had}) [GeV]", 50, 0., 150.); + TH1F* hadTopPt_ = new TH1F("hadTopPt", "p_{t} (t_{had}) [GeV]", 100, 0., 500.); + TH1F* hadTopMass_ = new TH1F("hadTopMass", "M (t_{had}) [GeV]", 50, 50., 250.); - TH1F* lepWPt_ = new TH1F("lepWPt", "p_{t} (W_{lep}) [GeV]", 100, 0., 500.); - TH1F* lepWMass_ = new TH1F("lepWMass", "M (W_{lep}) [GeV]", 50, 0., 150.); - TH1F* lepTopPt_ = new TH1F("lepTopPt", "p_{t} (t_{lep}) [GeV]", 100, 0., 500.); - TH1F* lepTopMass_= new TH1F("lepTopMass", "M (t_{lep}) [GeV]", 50, 50., 250.); + TH1F* lepWPt_ = new TH1F("lepWPt", "p_{t} (W_{lep}) [GeV]", 100, 0., 500.); + TH1F* lepWMass_ = new TH1F("lepWMass", "M (W_{lep}) [GeV]", 50, 0., 150.); + TH1F* lepTopPt_ = new TH1F("lepTopPt", "p_{t} (t_{lep}) [GeV]", 100, 0., 500.); + TH1F* lepTopMass_ = new TH1F("lepTopMass", "M (t_{lep}) [GeV]", 50, 50., 250.); - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "open file: " << argv[1] << std::endl; // ------------------------------------------------- TFile* inFile = TFile::Open(argv[1]); - TTree* events_= nullptr; - if( inFile ) inFile->GetObject("Events", events_); - if( events_==nullptr ){ - // ------------------------------------------------- - std::cerr << "ERROR: Unable to retrieve TTree Events!" << std::endl - << "Either wrong file name or the tree doesn't exist." << std::endl; - // ------------------------------------------------- + TTree* events_ = nullptr; + if (inFile) + inFile->GetObject("Events", events_); + if (events_ == nullptr) { + // ------------------------------------------------- + std::cerr << "ERROR: Unable to retrieve TTree Events!" << std::endl + << "Either wrong file name or the tree doesn't exist." << std::endl; + // ------------------------------------------------- return -1; } // acess branch of ttSemiLepEvent char decayName[50]; sprintf(decayName, "recoGenParticles_decaySubset__%s.obj", argv[2]); - TBranch* decay_ = events_->GetBranch( decayName ); // referred to from within TtGenEvent class - assert( decay_ != nullptr ); + TBranch* decay_ = events_->GetBranch(decayName); // referred to from within TtGenEvent class + assert(decay_ != nullptr); char genEvtName[50]; sprintf(genEvtName, "TtGenEvent_genEvt__%s.obj", argv[2]); - TBranch* genEvt_ = events_->GetBranch( genEvtName ); // referred to from within TtSemiLeptonicEvent class - assert( genEvt_ != nullptr ); + TBranch* genEvt_ = events_->GetBranch(genEvtName); // referred to from within TtSemiLeptonicEvent class + assert(genEvt_ != nullptr); char semiLepEvtName[50]; sprintf(semiLepEvtName, "TtSemiLeptonicEvent_ttSemiLepEvent__%s.obj", argv[2]); - TBranch* semiLepEvt_ = events_->GetBranch( semiLepEvtName ); - assert( semiLepEvt_ != nullptr ); - - // loop over events and fill histograms + TBranch* semiLepEvt_ = events_->GetBranch(semiLepEvtName); + assert(semiLepEvt_ != nullptr); + + // loop over events and fill histograms int nevt = events_->GetEntries(); TtSemiLeptonicEvent semiLepEvt; - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "start looping " << nevt << " events..." << std::endl; // ------------------------------------------------- - for(int evt=0; evtSetAddress( &semiLepEvt ); + semiLepEvt_->SetAddress(&semiLepEvt); // get event - decay_ ->GetEntry( evt ); - genEvt_ ->GetEntry( evt ); - semiLepEvt_->GetEntry( evt ); - events_ ->GetEntry( evt, 0 ); + decay_->GetEntry(evt); + genEvt_->GetEntry(evt); + semiLepEvt_->GetEntry(evt); + events_->GetEntry(evt, 0); - // ------------------------------------------------- - if(evt>0 && !(evt%10)) std::cout << " processing event: " << evt << std::endl; - // ------------------------------------------------- + // ------------------------------------------------- + if (evt > 0 && !(evt % 10)) + std::cout << " processing event: " << evt << std::endl; + // ------------------------------------------------- // fill histograms - if( !semiLepEvt.isHypoAvailable(hypoClassKey) ){ - std::cerr << "NonValidHyp:: " << "Hypothesis not available for this event" << std::endl; + if (!semiLepEvt.isHypoAvailable(hypoClassKey)) { + std::cerr << "NonValidHyp:: " + << "Hypothesis not available for this event" << std::endl; continue; } - if( !semiLepEvt.isHypoValid(hypoClassKey) ){ - std::cerr << "NonValidHyp::" << "Hypothesis not valid for this event" << std::endl; + if (!semiLepEvt.isHypoValid(hypoClassKey)) { + std::cerr << "NonValidHyp::" + << "Hypothesis not valid for this event" << std::endl; continue; } - + const reco::Candidate* hadTop = semiLepEvt.hadronicDecayTop(hypoClassKey); - const reco::Candidate* hadW = semiLepEvt.hadronicDecayW (hypoClassKey); + const reco::Candidate* hadW = semiLepEvt.hadronicDecayW(hypoClassKey); const reco::Candidate* lepTop = semiLepEvt.leptonicDecayTop(hypoClassKey); - const reco::Candidate* lepW = semiLepEvt.leptonicDecayW (hypoClassKey); - - if(hadTop && hadW && lepTop && lepW){ - hadWPt_ ->Fill( hadW->pt() ); - hadWMass_ ->Fill( hadW->mass() ); - hadTopPt_ ->Fill( hadTop->pt() ); - hadTopMass_->Fill( hadTop->mass()); - - lepWPt_ ->Fill( lepW->pt() ); - lepWMass_ ->Fill( lepW->mass() ); - lepTopPt_ ->Fill( lepTop->pt() ); - lepTopMass_->Fill( lepTop->mass()); + const reco::Candidate* lepW = semiLepEvt.leptonicDecayW(hypoClassKey); + + if (hadTop && hadW && lepTop && lepW) { + hadWPt_->Fill(hadW->pt()); + hadWMass_->Fill(hadW->mass()); + hadTopPt_->Fill(hadTop->pt()); + hadTopMass_->Fill(hadTop->mass()); + + lepWPt_->Fill(lepW->pt()); + lepWMass_->Fill(lepW->mass()); + lepTopPt_->Fill(lepTop->pt()); + lepTopMass_->Fill(lepTop->mass()); } } - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "close file" << std::endl; // ------------------------------------------------- inFile->Close(); - + // save histograms to file - TFile outFile( "analyzeHypothesis.root", "recreate" ); + TFile outFile("analyzeHypothesis.root", "recreate"); // strip the leading "k" from the hypoClassKey to build directory name TString outDir = "analyze" + std::string(hypoClassKey, 1, hypoClassKey.length()); outFile.mkdir(outDir); outFile.cd(outDir); - hadWPt_ ->Write( ); - hadWMass_ ->Write( ); - hadTopPt_ ->Write( ); - hadTopMass_->Write( ); - lepWPt_ ->Write( ); - lepWMass_ ->Write( ); - lepTopPt_ ->Write( ); - lepTopMass_->Write( ); + hadWPt_->Write(); + hadWMass_->Write(); + hadTopPt_->Write(); + hadTopMass_->Write(); + lepWPt_->Write(); + lepWMass_->Write(); + lepTopPt_->Write(); + lepTopMass_->Write(); outFile.Close(); - + // free allocated space delete hadWPt_; delete hadWMass_; diff --git a/TopQuarkAnalysis/Examples/bin/TopJetFWLiteAnalyzer.cc b/TopQuarkAnalysis/Examples/bin/TopJetFWLiteAnalyzer.cc index 259400e4cf3f2..3fb2782652da2 100644 --- a/TopQuarkAnalysis/Examples/bin/TopJetFWLiteAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/bin/TopJetFWLiteAnalyzer.cc @@ -13,95 +13,96 @@ #include "TopQuarkAnalysis/Examples/interface/RootHistograms.h" #include "TopQuarkAnalysis/Examples/interface/RootPostScript.h" - -int main(int argc, char* argv[]) -{ - if( argc<3 ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Wrong number of arguments! Please specify:" << std::endl - << " * filepath" << std::endl - << " * process name" << std::endl; - // ------------------------------------------------- +int main(int argc, char* argv[]) { + if (argc < 3) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Wrong number of arguments! Please specify:" << std::endl + << " * filepath" << std::endl + << " * process name" << std::endl; + // ------------------------------------------------- return -1; } // load framework libraries - gSystem->Load( "libFWCoreFWLite" ); + gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); - + // set nice style for histograms setNiceStyle(); - // define some histograms - TH1I* noJets = new TH1I("noJets", "N_{Jets}", 10, 0 , 10 ); - TH1F* ptJets = new TH1F("ptJets", "pt_{Jets}", 100, 0.,300.); - TH1F* enJets = new TH1F("enJets", "energy_{Jets}",100, 0.,300.); - TH1F* etaJets = new TH1F("etaJets","eta_{Jets}", 100, -3., 3.); - TH1F* phiJets = new TH1F("phiJets","phi_{Jets}", 100, -5., 5.); - - // ------------------------------------------------- + // define some histograms + TH1I* noJets = new TH1I("noJets", "N_{Jets}", 10, 0, 10); + TH1F* ptJets = new TH1F("ptJets", "pt_{Jets}", 100, 0., 300.); + TH1F* enJets = new TH1F("enJets", "energy_{Jets}", 100, 0., 300.); + TH1F* etaJets = new TH1F("etaJets", "eta_{Jets}", 100, -3., 3.); + TH1F* phiJets = new TH1F("phiJets", "phi_{Jets}", 100, -5., 5.); + + // ------------------------------------------------- std::cout << "open file: " << argv[1] << std::endl; // ------------------------------------------------- TFile* inFile = TFile::Open(argv[1]); - TTree* events_= nullptr; - if( inFile ) inFile->GetObject("Events", events_); - if( events_==nullptr ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Unable to retrieve TTree Events!" << std::endl - << " Eighter wrong file name or the the tree doesn't exists" << std::endl; - // ------------------------------------------------- + TTree* events_ = nullptr; + if (inFile) + inFile->GetObject("Events", events_); + if (events_ == nullptr) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Unable to retrieve TTree Events!" << std::endl + << " Eighter wrong file name or the the tree doesn't exists" << std::endl; + // ------------------------------------------------- return -1; } // acess branch of elecs char jetsName[50]; sprintf(jetsName, "patJets_selectedPatJets__%s.obj", argv[2]); - TBranch* jets_ = events_->GetBranch( jetsName ); assert( jets_!=nullptr ); - + TBranch* jets_ = events_->GetBranch(jetsName); + assert(jets_ != nullptr); + // loop over events and fill histograms std::vector jets; int nevt = events_->GetEntries(); - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "start looping " << nevt << " events..." << std::endl; // ------------------------------------------------- - for(int evt=0; evtSetAddress( &jets ); + for (int evt = 0; evt < nevt; ++evt) { + // set branch address + jets_->SetAddress(&jets); // get event - jets_ ->GetEntry( evt ); - events_->GetEntry( evt, 0 ); + jets_->GetEntry(evt); + events_->GetEntry(evt, 0); - // ------------------------------------------------- - if(evt>0 && !(evt%10)) std::cout << " processing event: " << evt << std::endl; - // ------------------------------------------------- + // ------------------------------------------------- + if (evt > 0 && !(evt % 10)) + std::cout << " processing event: " << evt << std::endl; + // ------------------------------------------------- // fill histograms noJets->Fill(jets.size()); - for(unsigned idx=0; idxFill(jets[idx].pt() ); - enJets ->Fill(jets[idx].energy()); - etaJets->Fill(jets[idx].eta() ); - phiJets->Fill(jets[idx].phi() ); + ptJets->Fill(jets[idx].pt()); + enJets->Fill(jets[idx].energy()); + etaJets->Fill(jets[idx].eta()); + phiJets->Fill(jets[idx].phi()); } } - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "close file" << std::endl; // ------------------------------------------------- inFile->Close(); // save histograms to file - TFile outFile( "analyzeJets.root", "recreate" ); + TFile outFile("analyzeJets.root", "recreate"); outFile.mkdir("analyzeJet"); outFile.cd("analyzeJet"); - noJets ->Write( ); - ptJets ->Write( ); - enJets ->Write( ); - etaJets->Write( ); - phiJets->Write( ); + noJets->Write(); + ptJets->Write(); + enJets->Write(); + etaJets->Write(); + phiJets->Write(); outFile.Close(); // free allocated space diff --git a/TopQuarkAnalysis/Examples/bin/TopMuonFWLiteAnalyzer.cc b/TopQuarkAnalysis/Examples/bin/TopMuonFWLiteAnalyzer.cc index a3b946fdb4c4e..a43795589107f 100644 --- a/TopQuarkAnalysis/Examples/bin/TopMuonFWLiteAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/bin/TopMuonFWLiteAnalyzer.cc @@ -14,104 +14,106 @@ #include "TopQuarkAnalysis/Examples/interface/RootHistograms.h" #include "TopQuarkAnalysis/Examples/interface/RootPostScript.h" - -int main(int argc, char* argv[]) -{ - if( argc<3 ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Wrong number of arguments! Please specify:" << std::endl - << " * filepath" << std::endl - << " * process name" << std::endl; - // ------------------------------------------------- +int main(int argc, char* argv[]) { + if (argc < 3) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Wrong number of arguments! Please specify:" << std::endl + << " * filepath" << std::endl + << " * process name" << std::endl; + // ------------------------------------------------- return -1; } - + // load framework libraries - gSystem->Load( "libFWCoreFWLite" ); + gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); - + // set nice style for histograms setNiceStyle(); - // define some histograms - TH1I* noMuons = new TH1I("noMuons", "N(Muon)", 10, 0 , 10 ); - TH1I* noLepts = new TH1I("noLepts", "N(Lepton)", 10, 0 , 10 ); - TH1F* ptMuons = new TH1F("ptMuons", "pt_{Muons}", 100, 0.,300.); - TH1F* enMuons = new TH1F("enMuons", "energy_{Muons}",100, 0.,300.); - TH1F* etaMuons = new TH1F("etaMuons","eta_{Muons}", 100, -3., 3.); - TH1F* phiMuons = new TH1F("phiMuons","phi_{Muons}", 100, -5., 5.); + // define some histograms + TH1I* noMuons = new TH1I("noMuons", "N(Muon)", 10, 0, 10); + TH1I* noLepts = new TH1I("noLepts", "N(Lepton)", 10, 0, 10); + TH1F* ptMuons = new TH1F("ptMuons", "pt_{Muons}", 100, 0., 300.); + TH1F* enMuons = new TH1F("enMuons", "energy_{Muons}", 100, 0., 300.); + TH1F* etaMuons = new TH1F("etaMuons", "eta_{Muons}", 100, -3., 3.); + TH1F* phiMuons = new TH1F("phiMuons", "phi_{Muons}", 100, -5., 5.); - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "open file: " << argv[1] << std::endl; // ------------------------------------------------- TFile* inFile = TFile::Open(argv[1]); - TTree* events_= nullptr; - if( inFile ) inFile->GetObject("Events", events_); - if( events_==nullptr ){ - // ------------------------------------------------- - std::cerr << "ERROR:: " - << "Unable to retrieve TTree Events!" << std::endl - << " Eighter wrong file name or the the tree doesn't exists" << std::endl; - // ------------------------------------------------- + TTree* events_ = nullptr; + if (inFile) + inFile->GetObject("Events", events_); + if (events_ == nullptr) { + // ------------------------------------------------- + std::cerr << "ERROR:: " + << "Unable to retrieve TTree Events!" << std::endl + << " Eighter wrong file name or the the tree doesn't exists" << std::endl; + // ------------------------------------------------- return -1; } // acess branch of muons and elecs char muonName[50]; sprintf(muonName, "patMuons_selectedPatMuons__%s.obj", argv[2]); - TBranch* muons_ = events_->GetBranch( muonName ); assert( muons_!=nullptr ); + TBranch* muons_ = events_->GetBranch(muonName); + assert(muons_ != nullptr); char elecName[50]; sprintf(elecName, "patElectrons_selectedPatElectrons__%s.obj", argv[2]); - TBranch* elecs_ = events_->GetBranch( elecName ); assert( elecs_!=nullptr ); - + TBranch* elecs_ = events_->GetBranch(elecName); + assert(elecs_ != nullptr); + // loop over events and fill histograms std::vector muons; std::vector elecs; int nevt = events_->GetEntries(); - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "start looping " << nevt << " events..." << std::endl; // ------------------------------------------------- - for(int evt=0; evtSetAddress( &muons ); - elecs_->SetAddress( &elecs ); + for (int evt = 0; evt < nevt; ++evt) { + // set branch address + muons_->SetAddress(&muons); + elecs_->SetAddress(&elecs); // get event - muons_ ->GetEntry( evt ); - elecs_ ->GetEntry( evt ); - events_->GetEntry( evt, 0 ); + muons_->GetEntry(evt); + elecs_->GetEntry(evt); + events_->GetEntry(evt, 0); - // ------------------------------------------------- - if(evt>0 && !(evt%10)) std::cout << " processing event: " << evt << std::endl; - // ------------------------------------------------- + // ------------------------------------------------- + if (evt > 0 && !(evt % 10)) + std::cout << " processing event: " << evt << std::endl; + // ------------------------------------------------- // fill histograms noMuons->Fill(muons.size()); - noLepts->Fill(muons.size()+elecs.size()); - for(unsigned idx=0; idxFill(muons.size() + elecs.size()); + for (unsigned idx = 0; idx < muons.size(); ++idx) { // fill histograms - ptMuons ->Fill(muons[idx].pt() ); - enMuons ->Fill(muons[idx].energy()); - etaMuons->Fill(muons[idx].eta() ); - phiMuons->Fill(muons[idx].phi() ); + ptMuons->Fill(muons[idx].pt()); + enMuons->Fill(muons[idx].energy()); + etaMuons->Fill(muons[idx].eta()); + phiMuons->Fill(muons[idx].phi()); } } - // ------------------------------------------------- + // ------------------------------------------------- std::cout << "close file" << std::endl; // ------------------------------------------------- inFile->Close(); // save histograms to file - TFile outFile( "analyzeMuons.root", "recreate" ); + TFile outFile("analyzeMuons.root", "recreate"); outFile.mkdir("analyzeMuon"); outFile.cd("analyzeMuon"); - noMuons ->Write( ); - noLepts ->Write( ); - ptMuons ->Write( ); - enMuons ->Write( ); - etaMuons->Write( ); - phiMuons->Write( ); + noMuons->Write(); + noLepts->Write(); + ptMuons->Write(); + enMuons->Write(); + etaMuons->Write(); + phiMuons->Write(); outFile.Close(); // free allocated space diff --git a/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.cc index e170a176fe783..96928bb82795b 100644 --- a/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.cc @@ -6,15 +6,11 @@ #include "TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.h" -HypothesisAnalyzer::HypothesisAnalyzer(const edm::ParameterSet& cfg): - semiLepEvtToken_ (consumes(cfg.getParameter("semiLepEvent"))), - hypoClassKey_(cfg.getParameter("hypoClassKey")) -{ -} +HypothesisAnalyzer::HypothesisAnalyzer(const edm::ParameterSet& cfg) + : semiLepEvtToken_(consumes(cfg.getParameter("semiLepEvent"))), + hypoClassKey_(cfg.getParameter("hypoClassKey")) {} -void -HypothesisAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setup) -{ +void HypothesisAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setup) { ////////////////////////////////////////////////////////////////////////////////////////////////// // get a handle for the TtSemiLeptonicEvent and a key to the hypothesis ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -26,7 +22,7 @@ HypothesisAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setu // check if hypothesis is available and valid in this event ////////////////////////////////////////////////////////////////////////////////////////////////// - if( !semiLepEvt->isHypoValid(hypoClassKey_) ){ + if (!semiLepEvt->isHypoValid(hypoClassKey_)) { edm::LogInfo("HypothesisAnalyzer") << "Hypothesis " << hypoClassKey_ << " not valid for this event"; return; } @@ -35,83 +31,83 @@ HypothesisAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setu // get reconstructed top quarks, W bosons, the top pair and the neutrino from the hypothesis ////////////////////////////////////////////////////////////////////////////////////////////////// - const reco::Candidate* topPair = semiLepEvt->topPair(hypoClassKey_); - const reco::Candidate* lepTop = semiLepEvt->leptonicDecayTop(hypoClassKey_); - const reco::Candidate* lepW = semiLepEvt->leptonicDecayW(hypoClassKey_); - const reco::Candidate* hadTop = semiLepEvt->hadronicDecayTop(hypoClassKey_); - const reco::Candidate* hadW = semiLepEvt->hadronicDecayW(hypoClassKey_); + const reco::Candidate* topPair = semiLepEvt->topPair(hypoClassKey_); + const reco::Candidate* lepTop = semiLepEvt->leptonicDecayTop(hypoClassKey_); + const reco::Candidate* lepW = semiLepEvt->leptonicDecayW(hypoClassKey_); + const reco::Candidate* hadTop = semiLepEvt->hadronicDecayTop(hypoClassKey_); + const reco::Candidate* hadW = semiLepEvt->hadronicDecayW(hypoClassKey_); const reco::Candidate* neutrino = semiLepEvt->singleNeutrino(hypoClassKey_); ////////////////////////////////////////////////////////////////////////////////////////////////// // fill simple histograms with kinematic variables of the reconstructed particles ////////////////////////////////////////////////////////////////////////////////////////////////// - if(topPair) - topPairMass_->Fill( topPair->mass() ); - if(hadW) { - hadWPt_ ->Fill( hadW->pt() ); - hadWEta_ ->Fill( hadW->eta() ); - hadWMass_->Fill( hadW->mass() ); + if (topPair) + topPairMass_->Fill(topPair->mass()); + if (hadW) { + hadWPt_->Fill(hadW->pt()); + hadWEta_->Fill(hadW->eta()); + hadWMass_->Fill(hadW->mass()); } - if(hadTop) { - hadTopPt_ ->Fill( hadTop->pt() ); - hadTopEta_ ->Fill( hadTop->eta() ); - hadTopMass_->Fill( hadTop->mass() ); + if (hadTop) { + hadTopPt_->Fill(hadTop->pt()); + hadTopEta_->Fill(hadTop->eta()); + hadTopMass_->Fill(hadTop->mass()); } - if(lepW) { - lepWPt_ ->Fill( lepW->pt() ); - lepWEta_ ->Fill( lepW->eta() ); - lepWMass_->Fill( lepW->mass() ); + if (lepW) { + lepWPt_->Fill(lepW->pt()); + lepWEta_->Fill(lepW->eta()); + lepWMass_->Fill(lepW->mass()); } - if(lepTop) { - lepTopPt_ ->Fill( lepTop->pt() ); - lepTopEta_ ->Fill( lepTop->eta() ); - lepTopMass_->Fill( lepTop->mass() ); + if (lepTop) { + lepTopPt_->Fill(lepTop->pt()); + lepTopEta_->Fill(lepTop->eta()); + lepTopMass_->Fill(lepTop->mass()); } - if(neutrino) - neutrinoEta_->Fill( neutrino->eta() ); + if (neutrino) + neutrinoEta_->Fill(neutrino->eta()); ////////////////////////////////////////////////////////////////////////////////////////////////// // get corresponding genParticles ////////////////////////////////////////////////////////////////////////////////////////////////// const math::XYZTLorentzVector* genTopPair = semiLepEvt->topPair(); - const reco::Candidate* genHadTop = semiLepEvt->hadronicDecayTop(); - const reco::Candidate* genHadW = semiLepEvt->hadronicDecayW(); - const reco::Candidate* genLepTop = semiLepEvt->leptonicDecayTop(); - const reco::Candidate* genLepW = semiLepEvt->leptonicDecayW(); + const reco::Candidate* genHadTop = semiLepEvt->hadronicDecayTop(); + const reco::Candidate* genHadW = semiLepEvt->hadronicDecayW(); + const reco::Candidate* genLepTop = semiLepEvt->leptonicDecayTop(); + const reco::Candidate* genLepW = semiLepEvt->leptonicDecayW(); const reco::Candidate* genNeutrino = semiLepEvt->singleNeutrino(); ////////////////////////////////////////////////////////////////////////////////////////////////// // fill pull histograms of kinematic variables with respect to the generated particles ////////////////////////////////////////////////////////////////////////////////////////////////// - if(topPair && genTopPair) - topPairPullMass_->Fill( (topPair->mass()-genTopPair->mass())/ genTopPair->mass() ); - if(hadW && genHadW) { - hadWPullPt_ ->Fill( (hadW->pt() - genHadW->pt()) / genHadW->pt() ); - hadWPullEta_ ->Fill( (hadW->eta() - genHadW->eta()) / genHadW->eta() ); - hadWPullMass_->Fill( (hadW->mass() - genHadW->mass()) / genHadW->mass() ); + if (topPair && genTopPair) + topPairPullMass_->Fill((topPair->mass() - genTopPair->mass()) / genTopPair->mass()); + if (hadW && genHadW) { + hadWPullPt_->Fill((hadW->pt() - genHadW->pt()) / genHadW->pt()); + hadWPullEta_->Fill((hadW->eta() - genHadW->eta()) / genHadW->eta()); + hadWPullMass_->Fill((hadW->mass() - genHadW->mass()) / genHadW->mass()); } - if(hadTop && genHadTop) { - hadTopPullPt_ ->Fill( (hadTop->pt() - genHadTop->pt()) / genHadTop->pt() ); - hadTopPullEta_ ->Fill( (hadTop->eta() - genHadTop->eta()) / genHadTop->eta() ); - hadTopPullMass_->Fill( (hadTop->mass() - genHadTop->mass()) / genHadTop->mass() ); + if (hadTop && genHadTop) { + hadTopPullPt_->Fill((hadTop->pt() - genHadTop->pt()) / genHadTop->pt()); + hadTopPullEta_->Fill((hadTop->eta() - genHadTop->eta()) / genHadTop->eta()); + hadTopPullMass_->Fill((hadTop->mass() - genHadTop->mass()) / genHadTop->mass()); } - if(lepW && genLepW) { - lepWPullPt_ ->Fill( (lepW->pt() - genLepW->pt()) / genLepW->pt() ); - lepWPullEta_ ->Fill( (lepW->eta() - genLepW->eta()) / genLepW->eta() ); - lepWPullMass_->Fill( (lepW->mass() - genLepW->mass()) / genLepW->mass() ); + if (lepW && genLepW) { + lepWPullPt_->Fill((lepW->pt() - genLepW->pt()) / genLepW->pt()); + lepWPullEta_->Fill((lepW->eta() - genLepW->eta()) / genLepW->eta()); + lepWPullMass_->Fill((lepW->mass() - genLepW->mass()) / genLepW->mass()); } - if(lepTop && genLepTop) { - lepTopPullPt_ ->Fill( (lepTop->pt() - genLepTop->pt()) / genLepTop->pt() ); - lepTopPullEta_ ->Fill( (lepTop->eta() - genLepTop->eta()) / genLepTop->eta() ); - lepTopPullMass_->Fill( (lepTop->mass() - genLepTop->mass()) / genLepTop->mass() ); + if (lepTop && genLepTop) { + lepTopPullPt_->Fill((lepTop->pt() - genLepTop->pt()) / genLepTop->pt()); + lepTopPullEta_->Fill((lepTop->eta() - genLepTop->eta()) / genLepTop->eta()); + lepTopPullMass_->Fill((lepTop->mass() - genLepTop->mass()) / genLepTop->mass()); } - if(neutrino && genNeutrino) - neutrinoPullEta_->Fill( (neutrino->eta()-genNeutrino->eta()) / genNeutrino->eta() ); + if (neutrino && genNeutrino) + neutrinoPullEta_->Fill((neutrino->eta() - genNeutrino->eta()) / genNeutrino->eta()); ////////////////////////////////////////////////////////////////////////////////////////////////// // fill histograms with variables describing the quality of the hypotheses @@ -120,73 +116,79 @@ HypothesisAnalyzer::analyze(const edm::Event& event, const edm::EventSetup& setu genMatchDr_->Fill(semiLepEvt->genMatchSumDR()); kinFitProb_->Fill(semiLepEvt->fitProb()); - if(hadTop && genHadTop) { - genMatchDrVsHadTopPullMass_->Fill((hadTop->mass() - genHadTop->mass()) / genHadTop->mass(), semiLepEvt->genMatchSumDR()); + if (hadTop && genHadTop) { + genMatchDrVsHadTopPullMass_->Fill((hadTop->mass() - genHadTop->mass()) / genHadTop->mass(), + semiLepEvt->genMatchSumDR()); kinFitProbVsHadTopPullMass_->Fill((hadTop->mass() - genHadTop->mass()) / genHadTop->mass(), semiLepEvt->fitProb()); } - } -void -HypothesisAnalyzer::beginJob() -{ +void HypothesisAnalyzer::beginJob() { edm::Service fs; - if( !fs ) throw edm::Exception( edm::errors::Configuration, "TFile Service is not registered in cfg file" ); + if (!fs) + throw edm::Exception(edm::errors::Configuration, "TFile Service is not registered in cfg file"); ////////////////////////////////////////////////////////////////////////////////////////////////// // book histograms ////////////////////////////////////////////////////////////////////////////////////////////////// neutrinoEta_ = fs->make("neutrinoEta", "#eta (neutrino)", 21, -4., 4.); - neutrinoPullEta_ = fs->make("neutrinoPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (neutrino)", 40, -1., 1.); + neutrinoPullEta_ = fs->make("neutrinoPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (neutrino)", 40, -1., 1.); - hadWPt_ = fs->make("hadWPt" , "p_{T} (W_{had}) [GeV]", 25, 0., 500.); - hadWEta_ = fs->make("hadWEta" , "#eta (W_{had})" , 21, -4., 4.); - hadWMass_ = fs->make("hadWMass", "M (W_{had}) [GeV]" , 25, 0., 200.); + hadWPt_ = fs->make("hadWPt", "p_{T} (W_{had}) [GeV]", 25, 0., 500.); + hadWEta_ = fs->make("hadWEta", "#eta (W_{had})", 21, -4., 4.); + hadWMass_ = fs->make("hadWMass", "M (W_{had}) [GeV]", 25, 0., 200.); - hadTopPt_ = fs->make("hadTopPt" , "p_{T} (t_{had}) [GeV]", 25, 0. , 500.); - hadTopEta_ = fs->make("hadTopEta" , "#eta (t_{had})" , 21, -4., 4.); - hadTopMass_ = fs->make("hadTopMass", "M (t_{had}) [GeV]" , 40, 0. , 400.); + hadTopPt_ = fs->make("hadTopPt", "p_{T} (t_{had}) [GeV]", 25, 0., 500.); + hadTopEta_ = fs->make("hadTopEta", "#eta (t_{had})", 21, -4., 4.); + hadTopMass_ = fs->make("hadTopMass", "M (t_{had}) [GeV]", 40, 0., 400.); - lepWPt_ = fs->make("lepWPt" , "p_{t} (W_{lep}) [GeV]", 25, 0., 500.); - lepWEta_ = fs->make("lepWEta" , "#eta (W_{lep})" , 21, -4., 4.); - lepWMass_ = fs->make("lepWMass", "M (W_{lep}) [GeV]" , 25, 0., 200.); + lepWPt_ = fs->make("lepWPt", "p_{t} (W_{lep}) [GeV]", 25, 0., 500.); + lepWEta_ = fs->make("lepWEta", "#eta (W_{lep})", 21, -4., 4.); + lepWMass_ = fs->make("lepWMass", "M (W_{lep}) [GeV]", 25, 0., 200.); - lepTopPt_ = fs->make("lepTopPt" , "p_{T} (t_{lep}) [GeV]", 25, 0. , 500.); - lepTopEta_ = fs->make("lepTopEta" , "#eta (t_{lep})" , 21, -4., 4.); - lepTopMass_ = fs->make("lepTopMass", "M (t_{lep}) [GeV]" , 40, 0. , 400.); + lepTopPt_ = fs->make("lepTopPt", "p_{T} (t_{lep}) [GeV]", 25, 0., 500.); + lepTopEta_ = fs->make("lepTopEta", "#eta (t_{lep})", 21, -4., 4.); + lepTopMass_ = fs->make("lepTopMass", "M (t_{lep}) [GeV]", 40, 0., 400.); - hadWPullPt_ = fs->make("hadWPullPt" , "(p_{T,rec}-p_{T,gen})/p_{T,gen} (W_{had})" , 40, -1., 1.); - hadWPullEta_ = fs->make("hadWPullEta" , "(#eta_{rec}-#eta_{gen})/#eta_{gen} (W_{had})", 40, -1., 1.); - hadWPullMass_ = fs->make("hadWPullMass", "(M_{rec}-M_{gen})/M_{gen} (W_{had})" , 40, -1., 1.); + hadWPullPt_ = fs->make("hadWPullPt", "(p_{T,rec}-p_{T,gen})/p_{T,gen} (W_{had})", 40, -1., 1.); + hadWPullEta_ = fs->make("hadWPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (W_{had})", 40, -1., 1.); + hadWPullMass_ = fs->make("hadWPullMass", "(M_{rec}-M_{gen})/M_{gen} (W_{had})", 40, -1., 1.); - hadTopPullPt_ = fs->make("hadTopPullPt" , "(p_{T,rec}-p_{T,gen})/p_{T,gen} (t_{had})" , 40, -1., 1.); - hadTopPullEta_ = fs->make("hadTopPullEta" , "(#eta_{rec}-#eta_{gen})/#eta_{gen} (t_{had})", 40, -1., 1.); - hadTopPullMass_ = fs->make("hadTopPullMass", "(M_{rec}-M_{gen})/M_{gen} (t_{had})" , 40, -1., 1.); + hadTopPullPt_ = fs->make("hadTopPullPt", "(p_{T,rec}-p_{T,gen})/p_{T,gen} (t_{had})", 40, -1., 1.); + hadTopPullEta_ = fs->make("hadTopPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (t_{had})", 40, -1., 1.); + hadTopPullMass_ = fs->make("hadTopPullMass", "(M_{rec}-M_{gen})/M_{gen} (t_{had})", 40, -1., 1.); - lepWPullPt_ = fs->make("lepWPullPt" , "(p_{T,rec}-p_{T,gen})/p_{T,gen} (W_{lep})" , 40, -1., 1.); - lepWPullEta_ = fs->make("lepWPullEta" , "(#eta_{rec}-#eta_{gen})/#eta_{gen} (W_{lep})", 40, -1., 1.); - lepWPullMass_ = fs->make("lepWPullMass", "(M_{rec}-M_{gen})/M_{gen} (W_{lep})" , 40, -1., 1.); + lepWPullPt_ = fs->make("lepWPullPt", "(p_{T,rec}-p_{T,gen})/p_{T,gen} (W_{lep})", 40, -1., 1.); + lepWPullEta_ = fs->make("lepWPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (W_{lep})", 40, -1., 1.); + lepWPullMass_ = fs->make("lepWPullMass", "(M_{rec}-M_{gen})/M_{gen} (W_{lep})", 40, -1., 1.); - lepTopPullPt_ = fs->make("lepTopPullPt" , "(p_{T,rec}-p_{T,gen})/p_{T,gen} (t_{lep})" , 40, -1., 1.); - lepTopPullEta_ = fs->make("lepTopPullEta" , "(#eta_{rec}-#eta_{gen})/#eta_{gen} (t_{lep})", 40, -1., 1.); - lepTopPullMass_ = fs->make("lepTopPullMass", "(M_{rec}-M_{gen})/M_{gen} (t_{lep})" , 40, -1., 1.); + lepTopPullPt_ = fs->make("lepTopPullPt", "(p_{T,rec}-p_{T,gen})/p_{T,gen} (t_{lep})", 40, -1., 1.); + lepTopPullEta_ = fs->make("lepTopPullEta", "(#eta_{rec}-#eta_{gen})/#eta_{gen} (t_{lep})", 40, -1., 1.); + lepTopPullMass_ = fs->make("lepTopPullMass", "(M_{rec}-M_{gen})/M_{gen} (t_{lep})", 40, -1., 1.); topPairMass_ = fs->make("topPairMass", "M (t#bar{t})", 36, 340., 940.); - topPairPullMass_ = fs->make("topPairPullMass", "(M_{rec}-M_{gen})/M_{gen} (t#bar{t})", 40, -1., 1.); + topPairPullMass_ = fs->make("topPairPullMass", "(M_{rec}-M_{gen})/M_{gen} (t#bar{t})", 40, -1., 1.); genMatchDr_ = fs->make("genMatchDr", "GenMatch #Sigma#DeltaR", 40, 0., 4.); - kinFitProb_ = fs->make("kinFitProb", "KinFit probability" , 50, 0., 1.); + kinFitProb_ = fs->make("kinFitProb", "KinFit probability", 50, 0., 1.); genMatchDrVsHadTopPullMass_ = fs->make("genMatchDrVsHadTopPullMass", - "GenMatch #Sigma #Delta R vs. (M_{rec}-M_{gen})/M_{gen} (t_{had}))", - 40, -1., 1., 40, 0., 4.); + "GenMatch #Sigma #Delta R vs. (M_{rec}-M_{gen})/M_{gen} (t_{had}))", + 40, + -1., + 1., + 40, + 0., + 4.); kinFitProbVsHadTopPullMass_ = fs->make("kinFitProbVsHadTopPullMass", - "KinFit probability vs. (M_{rec}-M_{gen})/M_{gen} (t_{had}))", - 40, -1., 1., 20, 0., 1.); + "KinFit probability vs. (M_{rec}-M_{gen})/M_{gen} (t_{had}))", + 40, + -1., + 1., + 20, + 0., + 1.); } -void -HypothesisAnalyzer::endJob() -{ -} +void HypothesisAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.h index bd39e69f7facf..c8a1d67622e47 100644 --- a/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/HypothesisAnalyzer.h @@ -9,15 +9,12 @@ #include "AnalysisDataFormats/TopObjects/interface/TtSemiLeptonicEvent.h" class HypothesisAnalyzer : public edm::EDAnalyzer { - - public: - +public: explicit HypothesisAnalyzer(const edm::ParameterSet&); ~HypothesisAnalyzer() override{}; - private: - - void beginJob() override ; +private: + void beginJob() override; void analyze(const edm::Event&, const edm::EventSetup&) override; void endJob() override; @@ -67,7 +64,6 @@ class HypothesisAnalyzer : public edm::EDAnalyzer { TH2F* genMatchDrVsHadTopPullMass_; TH2F* kinFitProbVsHadTopPullMass_; - }; #endif diff --git a/TopQuarkAnalysis/Examples/plugins/SealModule.cc b/TopQuarkAnalysis/Examples/plugins/SealModule.cc index 33672425018ce..ad75a7faa9665 100644 --- a/TopQuarkAnalysis/Examples/plugins/SealModule.cc +++ b/TopQuarkAnalysis/Examples/plugins/SealModule.cc @@ -12,4 +12,3 @@ DEFINE_FWK_MODULE(TopMuonAnalyzer); DEFINE_FWK_MODULE(TopElecAnalyzer); DEFINE_FWK_MODULE(TopTauAnalyzer); DEFINE_FWK_MODULE(TopJetAnalyzer); - diff --git a/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.cc index f7644b18090eb..7647dd69118c3 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.cc @@ -1,71 +1,54 @@ #include "TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.h" -TopElecAnalyzer::TopElecAnalyzer(const edm::ParameterSet& cfg): - inputToken_ (consumes >(cfg.getParameter("input" ))), - verbose_(cfg.getParameter ("verbose")) -{ +TopElecAnalyzer::TopElecAnalyzer(const edm::ParameterSet& cfg) + : inputToken_(consumes >(cfg.getParameter("input"))), + verbose_(cfg.getParameter("verbose")) { edm::Service fs; - mult_ = fs->make("mult", "multiplicity (electrons)", 10, 0 , 10); - en_ = fs->make("en" , "energy (electrons)" , 60, 0., 300.); - pt_ = fs->make("pt" , "pt (electrons)" , 60, 0., 300.); - eta_ = fs->make("eta" , "eta (electrons)" , 30, -3., 3.); - phi_ = fs->make("phi" , "phi (electrons)" , 40, -4., 4.); + mult_ = fs->make("mult", "multiplicity (electrons)", 10, 0, 10); + en_ = fs->make("en", "energy (electrons)", 60, 0., 300.); + pt_ = fs->make("pt", "pt (electrons)", 60, 0., 300.); + eta_ = fs->make("eta", "eta (electrons)", 30, -3., 3.); + phi_ = fs->make("phi", "phi (electrons)", 40, -4., 4.); } -TopElecAnalyzer::~TopElecAnalyzer() -{ -} +TopElecAnalyzer::~TopElecAnalyzer() {} -void -TopElecAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) -{ +void TopElecAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) { edm::Handle > elecs; evt.getByToken(inputToken_, elecs); // fill histograms - mult_->Fill( elecs->size() ); - for(std::vector::const_iterator elec=elecs->begin(); elec!=elecs->end(); ++elec){ - en_ ->Fill( elec->energy() ); - pt_ ->Fill( elec->pt() ); - eta_->Fill( elec->eta() ); - phi_->Fill( elec->phi() ); + mult_->Fill(elecs->size()); + for (std::vector::const_iterator elec = elecs->begin(); elec != elecs->end(); ++elec) { + en_->Fill(elec->energy()); + pt_->Fill(elec->pt()); + eta_->Fill(elec->eta()); + phi_->Fill(elec->phi()); } // produce printout if desired - if( elecs->empty() || !verbose_ ) + if (elecs->empty() || !verbose_) return; - unsigned i=0; - - std::cout << "=======================================================" - << std::endl; - std::cout << std::setw(5 ) << "ele :" - << std::setw(13) << "et :" - << std::setw(13) << "eta :" - << std::setw(13) << "phi :" - << std::setw(11) << "relIso" << std::endl; - std::cout << "-------------------------------------------------------" - << std::endl; - for(std::vector::const_iterator elec=elecs->begin(); elec!=elecs->end(); ++elec){ - std::cout << std::setw(3 ) << i << " : " - << std::setw(10) << elec->pt() << " : " - << std::setw(10) << elec->eta() << " : " - << std::setw(10) << elec->phi() << " : " - << std::setw(10) << (elec->dr03TkSumPt()+elec->dr03EcalRecHitSumEt()+elec->dr03HcalTowerSumEt())/elec->et() << std::endl; + unsigned i = 0; + + std::cout << "=======================================================" << std::endl; + std::cout << std::setw(5) << "ele :" << std::setw(13) << "et :" << std::setw(13) << "eta :" << std::setw(13) + << "phi :" << std::setw(11) << "relIso" << std::endl; + std::cout << "-------------------------------------------------------" << std::endl; + for (std::vector::const_iterator elec = elecs->begin(); elec != elecs->end(); ++elec) { + std::cout << std::setw(3) << i << " : " << std::setw(10) << elec->pt() << " : " << std::setw(10) << elec->eta() + << " : " << std::setw(10) << elec->phi() << " : " << std::setw(10) + << (elec->dr03TkSumPt() + elec->dr03EcalRecHitSumEt() + elec->dr03HcalTowerSumEt()) / elec->et() + << std::endl; i++; } - std::cout << "=======================================================" - << std::endl; + std::cout << "=======================================================" << std::endl; } -void TopElecAnalyzer::beginJob() -{ -} - -void TopElecAnalyzer::endJob() -{ -} +void TopElecAnalyzer::beginJob() {} +void TopElecAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.h index b4d55fc5de77a..651e38e73dbca 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/TopElecAnalyzer.h @@ -13,17 +13,14 @@ #include "DataFormats/PatCandidates/interface/Electron.h" class TopElecAnalyzer : public edm::EDAnalyzer { - - public: - - explicit TopElecAnalyzer(const edm::ParameterSet&); +public: + explicit TopElecAnalyzer(const edm::ParameterSet &); ~TopElecAnalyzer() override; - private: - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void beginJob() override; + void analyze(const edm::Event &, const edm::EventSetup &) override; + void endJob() override; edm::EDGetTokenT > inputToken_; bool verbose_; @@ -33,7 +30,6 @@ class TopElecAnalyzer : public edm::EDAnalyzer { TH1F *pt_; TH1F *eta_; TH1F *phi_; - }; #endif diff --git a/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.cc index a7ece93b23384..0debc785767c9 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.cc @@ -1,66 +1,57 @@ #include "TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.h" -TopGenEventAnalyzer::TopGenEventAnalyzer(const edm::ParameterSet& cfg): - inputGenEventToken_(consumes(cfg.getParameter("genEvent"))) -{ +TopGenEventAnalyzer::TopGenEventAnalyzer(const edm::ParameterSet& cfg) + : inputGenEventToken_(consumes(cfg.getParameter("genEvent"))) { edm::Service fs; - nLep_ = fs->make("nLep", "N(Lepton)", 5, 0., 5.); - topPt_ = fs->make("topPt", "pt (top)", 100, 0., 500.); - topEta_ = fs->make("topEta", "eta(top)", 40, -5., 5.); - topPhi_ = fs->make("topPhi", "phi(top)", 60, -3.5, 3.5); - topBarPt_ = fs->make("topBarPt", "pt (topBar)", 100, 0., 500.); - topBarEta_ = fs->make("topBarEta", "eta(topBar)", 40, -5., 5.); - topBarPhi_ = fs->make("topBarPhi", "phi(topBar)", 60, -3.5, 3.5); - ttbarPt_ = fs->make("ttbarPt", "pt (ttbar)", 100, 0., 500.); - ttbarEta_ = fs->make("ttbarEta", "eta(ttbar)", 40, -5., 5.); - ttbarPhi_ = fs->make("ttbarPhi", "phi(ttbar)", 60, -3.5, 3.5); - prodChan_ = fs->make("prodChan", "production mode", 3, 0, 3); - prodChan_->GetXaxis()->SetBinLabel(1, "gg" ); + nLep_ = fs->make("nLep", "N(Lepton)", 5, 0., 5.); + topPt_ = fs->make("topPt", "pt (top)", 100, 0., 500.); + topEta_ = fs->make("topEta", "eta(top)", 40, -5., 5.); + topPhi_ = fs->make("topPhi", "phi(top)", 60, -3.5, 3.5); + topBarPt_ = fs->make("topBarPt", "pt (topBar)", 100, 0., 500.); + topBarEta_ = fs->make("topBarEta", "eta(topBar)", 40, -5., 5.); + topBarPhi_ = fs->make("topBarPhi", "phi(topBar)", 60, -3.5, 3.5); + ttbarPt_ = fs->make("ttbarPt", "pt (ttbar)", 100, 0., 500.); + ttbarEta_ = fs->make("ttbarEta", "eta(ttbar)", 40, -5., 5.); + ttbarPhi_ = fs->make("ttbarPhi", "phi(ttbar)", 60, -3.5, 3.5); + prodChan_ = fs->make("prodChan", "production mode", 3, 0, 3); + prodChan_->GetXaxis()->SetBinLabel(1, "gg"); prodChan_->GetXaxis()->SetBinLabel(2, "qqbar"); prodChan_->GetXaxis()->SetBinLabel(3, "other"); } -TopGenEventAnalyzer::~TopGenEventAnalyzer() -{ -} +TopGenEventAnalyzer::~TopGenEventAnalyzer() {} -void -TopGenEventAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) -{ +void TopGenEventAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) { edm::Handle genEvent; evt.getByToken(inputGenEventToken_, genEvent); - if(!genEvent->isTtBar()) + if (!genEvent->isTtBar()) return; - if(genEvent->fromGluonFusion()) + if (genEvent->fromGluonFusion()) prodChan_->Fill("gg", 1); - else if(genEvent->fromQuarkAnnihilation()) + else if (genEvent->fromQuarkAnnihilation()) prodChan_->Fill("qqbar", 1); else prodChan_->Fill("other", 1); // fill BR's - nLep_ ->Fill(genEvent->numberOfLeptons()); + nLep_->Fill(genEvent->numberOfLeptons()); //fill top kinematic - topPt_ ->Fill(genEvent->top ()->pt ()); - topEta_ ->Fill(genEvent->top ()->eta()); - topPhi_ ->Fill(genEvent->top ()->phi()); - topBarPt_ ->Fill(genEvent->topBar()->pt ()); + topPt_->Fill(genEvent->top()->pt()); + topEta_->Fill(genEvent->top()->eta()); + topPhi_->Fill(genEvent->top()->phi()); + topBarPt_->Fill(genEvent->topBar()->pt()); topBarEta_->Fill(genEvent->topBar()->eta()); topBarPhi_->Fill(genEvent->topBar()->phi()); //fill ttbar kinematics - ttbarPt_ ->Fill(genEvent->topPair()->pt() ); + ttbarPt_->Fill(genEvent->topPair()->pt()); ttbarEta_->Fill(genEvent->topPair()->eta()); ttbarPhi_->Fill(genEvent->topPair()->phi()); } -void TopGenEventAnalyzer::beginJob() -{ -} +void TopGenEventAnalyzer::beginJob() {} -void TopGenEventAnalyzer::endJob() -{ -} +void TopGenEventAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.h index 88d55cfd95918..ee291cc930e0a 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/TopGenEventAnalyzer.h @@ -12,19 +12,15 @@ #include "AnalysisDataFormats/TopObjects/interface/TtGenEvent.h" - class TopGenEventAnalyzer : public edm::EDAnalyzer { - - public: - - explicit TopGenEventAnalyzer(const edm::ParameterSet&); +public: + explicit TopGenEventAnalyzer(const edm::ParameterSet &); ~TopGenEventAnalyzer() override; - private: - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void beginJob() override; + void analyze(const edm::Event &, const edm::EventSetup &) override; + void endJob() override; edm::EDGetTokenT inputGenEventToken_; diff --git a/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.cc index 60db228b2c647..59d5870ace070 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.cc @@ -1,96 +1,73 @@ #include "TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.h" - -TopJetAnalyzer::TopJetAnalyzer(const edm::ParameterSet& cfg): - inputToken_ (consumes >(cfg.getParameter("input" ))), - verbose_(cfg.getParameter ("verbose")) -{ +TopJetAnalyzer::TopJetAnalyzer(const edm::ParameterSet& cfg) + : inputToken_(consumes >(cfg.getParameter("input"))), + verbose_(cfg.getParameter("verbose")) { edm::Service fs; - mult_ = fs->make("mult", "multiplicity (jets)", 30, 0 , 30); - en_ = fs->make("en" , "energy (jets)", 60, 0., 300.); - pt_ = fs->make("pt" , "pt (jets)", 60, 0., 300.); - eta_ = fs->make("eta" , "eta (jets)", 30, -3., 3.); - phi_ = fs->make("phi" , "phi (jets)", 40, -4., 4.); + mult_ = fs->make("mult", "multiplicity (jets)", 30, 0, 30); + en_ = fs->make("en", "energy (jets)", 60, 0., 300.); + pt_ = fs->make("pt", "pt (jets)", 60, 0., 300.); + eta_ = fs->make("eta", "eta (jets)", 30, -3., 3.); + phi_ = fs->make("phi", "phi (jets)", 40, -4., 4.); } -TopJetAnalyzer::~TopJetAnalyzer() -{ -} +TopJetAnalyzer::~TopJetAnalyzer() {} -void -TopJetAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) -{ +void TopJetAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) { edm::Handle > jets; evt.getByToken(inputToken_, jets); // fill histograms - mult_->Fill( jets->size() ); - for(std::vector::const_iterator jet=jets->begin(); jet!=jets->end(); ++jet){ - pt_ ->Fill( jet->pt() ); - en_ ->Fill( jet->energy() ); - eta_->Fill( jet->eta() ); - phi_->Fill( jet->phi() ); + mult_->Fill(jets->size()); + for (std::vector::const_iterator jet = jets->begin(); jet != jets->end(); ++jet) { + pt_->Fill(jet->pt()); + en_->Fill(jet->energy()); + eta_->Fill(jet->eta()); + phi_->Fill(jet->phi()); } // produce printout if desired - if( jets->empty() || !verbose_ ) + if (jets->empty() || !verbose_) return; int lineWidth = 75; - if( jets->begin()->isCaloJet() ) + if (jets->begin()->isCaloJet()) lineWidth = 100; - else if( jets->begin()->isPFJet() ) + else if (jets->begin()->isPFJet()) lineWidth = 120; std::cout << std::setfill('=') << std::setw(lineWidth) << "\n" << std::setfill(' '); - std::cout << std::setw( 5) << "jet :" - << std::setw(11) << "pt :" - << std::setw( 9) << "eta :" - << std::setw( 9) << "phi :" - << std::setw(11) << "TCHE :" - << std::setw(11) << "TCHP :" - << std::setw( 9) << "SSVHE :" - << std::setw( 9) << "SSVHP :"; - if( jets->begin()->isCaloJet() ) { - std::cout << std::setw( 8) << "emf :" - << std::setw(10) << "n90Hits :" - << std::setw( 7) << "fHPD"; + std::cout << std::setw(5) << "jet :" << std::setw(11) << "pt :" << std::setw(9) << "eta :" << std::setw(9) + << "phi :" << std::setw(11) << "TCHE :" << std::setw(11) << "TCHP :" << std::setw(9) + << "SSVHE :" << std::setw(9) << "SSVHP :"; + if (jets->begin()->isCaloJet()) { + std::cout << std::setw(8) << "emf :" << std::setw(10) << "n90Hits :" << std::setw(7) << "fHPD"; } - if( jets->begin()->isPFJet() ) { - std::cout << std::setw(9) << "chf : " - << std::setw(8) << "nhf : " - << std::setw(8) << "cef : " - << std::setw(8) << "nef : " - << std::setw(6) << "nCh : " - << std::setw(6) << "nConst"; + if (jets->begin()->isPFJet()) { + std::cout << std::setw(9) << "chf : " << std::setw(8) << "nhf : " << std::setw(8) << "cef : " << std::setw(8) + << "nef : " << std::setw(6) << "nCh : " << std::setw(6) << "nConst"; } - std::cout << std::endl - << std::setfill('-') << std::setw(lineWidth) << "\n" << std::setfill(' '); - unsigned i=0; - for(std::vector::const_iterator jet=jets->begin(); jet!=jets->end(); ++jet){ - std::cout << std::setw(3) << i << " : " << std::setprecision(3) << std::fixed - << std::setw(8) << jet->pt() << " : " - << std::setw(6) << jet->eta() << " : " - << std::setw(6) << jet->phi() << " : " - << std::setw(8) << jet->bDiscriminator("trackCountingHighEffBJetTags") << " : " - << std::setw(8) << jet->bDiscriminator("trackCountingHighPurBJetTags") << " : " - << std::setw(6) << jet->bDiscriminator("simpleSecondaryVertexHighEffBJetTags") << " : " - << std::setw(6) << jet->bDiscriminator("simpleSecondaryVertexHighPurBJetTags") << " : "; - if( jet->isCaloJet() ) { - std::cout << std::setw(5) << jet->emEnergyFraction() << " : " - << std::setw(7) << jet->jetID().n90Hits << " : " - << std::setw(6) << jet->jetID().fHPD; + std::cout << std::endl << std::setfill('-') << std::setw(lineWidth) << "\n" << std::setfill(' '); + unsigned i = 0; + for (std::vector::const_iterator jet = jets->begin(); jet != jets->end(); ++jet) { + std::cout << std::setw(3) << i << " : " << std::setprecision(3) << std::fixed << std::setw(8) << jet->pt() << " : " + << std::setw(6) << jet->eta() << " : " << std::setw(6) << jet->phi() << " : " << std::setw(8) + << jet->bDiscriminator("trackCountingHighEffBJetTags") << " : " << std::setw(8) + << jet->bDiscriminator("trackCountingHighPurBJetTags") << " : " << std::setw(6) + << jet->bDiscriminator("simpleSecondaryVertexHighEffBJetTags") << " : " << std::setw(6) + << jet->bDiscriminator("simpleSecondaryVertexHighPurBJetTags") << " : "; + if (jet->isCaloJet()) { + std::cout << std::setw(5) << jet->emEnergyFraction() << " : " << std::setw(7) << jet->jetID().n90Hits << " : " + << std::setw(6) << jet->jetID().fHPD; } - if( jet->isPFJet() ) { - std::cout << std::setw(5) << jet->chargedHadronEnergyFraction() << " : " - << std::setw(5) << jet->neutralHadronEnergyFraction() << " : " - << std::setw(5) << jet->chargedEmEnergyFraction() << " : " - << std::setw(5) << jet->neutralEmEnergyFraction() << " : " - << std::setw(3) << jet->chargedMultiplicity() << " : " - << std::setw(6) << jet->nConstituents(); + if (jet->isPFJet()) { + std::cout << std::setw(5) << jet->chargedHadronEnergyFraction() << " : " << std::setw(5) + << jet->neutralHadronEnergyFraction() << " : " << std::setw(5) << jet->chargedEmEnergyFraction() + << " : " << std::setw(5) << jet->neutralEmEnergyFraction() << " : " << std::setw(3) + << jet->chargedMultiplicity() << " : " << std::setw(6) << jet->nConstituents(); } std::cout << std::endl; i++; @@ -98,12 +75,6 @@ TopJetAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) std::cout << std::setfill('=') << std::setw(lineWidth) << "\n" << std::setfill(' '); } -void TopJetAnalyzer::beginJob() -{ -} - -void TopJetAnalyzer::endJob() -{ -} - +void TopJetAnalyzer::beginJob() {} +void TopJetAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.h index 267465c2aebcd..7f0e2d3fb56e1 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/TopJetAnalyzer.h @@ -13,17 +13,14 @@ #include "DataFormats/PatCandidates/interface/Jet.h" class TopJetAnalyzer : public edm::EDAnalyzer { - - public: - - explicit TopJetAnalyzer(const edm::ParameterSet&); +public: + explicit TopJetAnalyzer(const edm::ParameterSet &); ~TopJetAnalyzer() override; - private: - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void beginJob() override; + void analyze(const edm::Event &, const edm::EventSetup &) override; + void endJob() override; edm::EDGetTokenT > inputToken_; bool verbose_; diff --git a/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.cc index ad4ac90146f60..02ee1ac814a2b 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.cc @@ -1,77 +1,55 @@ #include "DataFormats/PatCandidates/interface/Muon.h" #include "TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.h" - -TopMuonAnalyzer::TopMuonAnalyzer(const edm::ParameterSet& cfg): - inputToken_ (consumes >(cfg.getParameter("input" ))), - verbose_(cfg.getParameter ("verbose")) -{ +TopMuonAnalyzer::TopMuonAnalyzer(const edm::ParameterSet& cfg) + : inputToken_(consumes >(cfg.getParameter("input"))), + verbose_(cfg.getParameter("verbose")) { edm::Service fs; - mult_ = fs->make("mult", "multiplicity (muons)", 10, 0 , 10); - en_ = fs->make("en" , "energy (muons)", 60, 0., 300.); - pt_ = fs->make("pt" , "pt (muons)", 60, 0., 300.); - eta_ = fs->make("eta" , "eta (muons)", 30, -3., 3.); - phi_ = fs->make("phi" , "phi (muons)", 40, -4., 4.); - + mult_ = fs->make("mult", "multiplicity (muons)", 10, 0, 10); + en_ = fs->make("en", "energy (muons)", 60, 0., 300.); + pt_ = fs->make("pt", "pt (muons)", 60, 0., 300.); + eta_ = fs->make("eta", "eta (muons)", 30, -3., 3.); + phi_ = fs->make("phi", "phi (muons)", 40, -4., 4.); } -TopMuonAnalyzer::~TopMuonAnalyzer() -{ -} +TopMuonAnalyzer::~TopMuonAnalyzer() {} -void -TopMuonAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) -{ +void TopMuonAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) { edm::Handle > muons; evt.getByToken(inputToken_, muons); // fill histograms - mult_->Fill( muons->size() ); - for(std::vector::const_iterator muon=muons->begin(); muon!=muons->end(); ++muon){ - pt_ ->Fill( muon->pt() ); - en_ ->Fill( muon->energy() ); - eta_->Fill( muon->eta() ); - phi_->Fill( muon->phi() ); + mult_->Fill(muons->size()); + for (std::vector::const_iterator muon = muons->begin(); muon != muons->end(); ++muon) { + pt_->Fill(muon->pt()); + en_->Fill(muon->energy()); + eta_->Fill(muon->eta()); + phi_->Fill(muon->phi()); } // produce printout if desired - if( muons->empty() || !verbose_ ) + if (muons->empty() || !verbose_) return; - unsigned i=0; - - std::cout << "===================================================================" - << std::endl; - std::cout << std::setw(5 ) << "mu :" - << std::setw(13) << "pt :" - << std::setw(13) << "eta :" - << std::setw(13) << "phi :" - << std::setw(13) << "relIso :" - << std::setw(6 ) << "GLB :" - << std::setw(4 ) << "TRK" << std::endl; - std::cout << "-------------------------------------------------------------------" - << std::endl; - for(std::vector::const_iterator muon=muons->begin(); muon!=muons->end(); ++muon){ - std::cout << std::setw(3 ) << i << " : " - << std::setw(10) << muon->pt() << " : " - << std::setw(10) << muon->eta() << " : " - << std::setw(10) << muon->phi() << " : " - << std::setw(10) << (muon->trackIso()+muon->caloIso())/muon->pt() << " : " - << std::setw( 3) << muon->isGlobalMuon() << " : " - << std::setw( 3) << muon->isTrackerMuon() << std::endl; + unsigned i = 0; + + std::cout << "===================================================================" << std::endl; + std::cout << std::setw(5) << "mu :" << std::setw(13) << "pt :" << std::setw(13) << "eta :" << std::setw(13) + << "phi :" << std::setw(13) << "relIso :" << std::setw(6) << "GLB :" << std::setw(4) << "TRK" << std::endl; + std::cout << "-------------------------------------------------------------------" << std::endl; + for (std::vector::const_iterator muon = muons->begin(); muon != muons->end(); ++muon) { + std::cout << std::setw(3) << i << " : " << std::setw(10) << muon->pt() << " : " << std::setw(10) << muon->eta() + << " : " << std::setw(10) << muon->phi() << " : " << std::setw(10) + << (muon->trackIso() + muon->caloIso()) / muon->pt() << " : " << std::setw(3) << muon->isGlobalMuon() + << " : " << std::setw(3) << muon->isTrackerMuon() << std::endl; i++; } - std::cout << "===================================================================" - << std::endl; + std::cout << "===================================================================" << std::endl; } -void TopMuonAnalyzer::beginJob() -{ -} +void TopMuonAnalyzer::beginJob() {} -void TopMuonAnalyzer::endJob() -{ -} +void TopMuonAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.h index 1305c55ae91ca..ec324205b9842 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/TopMuonAnalyzer.h @@ -13,17 +13,14 @@ #include "DataFormats/PatCandidates/interface/Muon.h" class TopMuonAnalyzer : public edm::EDAnalyzer { - - public: - - explicit TopMuonAnalyzer(const edm::ParameterSet&); +public: + explicit TopMuonAnalyzer(const edm::ParameterSet &); ~TopMuonAnalyzer() override; - private: - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void beginJob() override; + void analyze(const edm::Event &, const edm::EventSetup &) override; + void endJob() override; edm::EDGetTokenT > inputToken_; bool verbose_; diff --git a/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.cc b/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.cc index 9dbfbfefc5753..f597335814be3 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.cc +++ b/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.cc @@ -1,44 +1,33 @@ #include "TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.h" - -TopTauAnalyzer::TopTauAnalyzer(const edm::ParameterSet& cfg): - inputToken_(consumes >(cfg.getParameter("input"))) -{ +TopTauAnalyzer::TopTauAnalyzer(const edm::ParameterSet& cfg) + : inputToken_(consumes >(cfg.getParameter("input"))) { edm::Service fs; - mult_ = fs->make("mult", "multiplicity (taus)", 30, 0 , 30); - en_ = fs->make("en" , "energy (taus)", 60, 0., 300.); - pt_ = fs->make("pt" , "pt (taus}", 60, 0., 300.); - eta_ = fs->make("eta" , "eta (taus)", 30, -3., 3.); - phi_ = fs->make("phi" , "phi (taus)", 40, -4., 4.); + mult_ = fs->make("mult", "multiplicity (taus)", 30, 0, 30); + en_ = fs->make("en", "energy (taus)", 60, 0., 300.); + pt_ = fs->make("pt", "pt (taus}", 60, 0., 300.); + eta_ = fs->make("eta", "eta (taus)", 30, -3., 3.); + phi_ = fs->make("phi", "phi (taus)", 40, -4., 4.); } -TopTauAnalyzer::~TopTauAnalyzer() -{ -} +TopTauAnalyzer::~TopTauAnalyzer() {} -void -TopTauAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) -{ +void TopTauAnalyzer::analyze(const edm::Event& evt, const edm::EventSetup& setup) { edm::Handle > taus; evt.getByToken(inputToken_, taus); // fill histograms - mult_->Fill( taus->size() ); - for(std::vector::const_iterator tau=taus->begin(); tau!=taus->end(); ++tau){ - en_ ->Fill( tau->energy() ); - pt_ ->Fill( tau->pt() ); - eta_->Fill( tau->eta() ); - phi_->Fill( tau->phi() ); + mult_->Fill(taus->size()); + for (std::vector::const_iterator tau = taus->begin(); tau != taus->end(); ++tau) { + en_->Fill(tau->energy()); + pt_->Fill(tau->pt()); + eta_->Fill(tau->eta()); + phi_->Fill(tau->phi()); } } -void TopTauAnalyzer::beginJob() -{ -} - -void TopTauAnalyzer::endJob() -{ -} +void TopTauAnalyzer::beginJob() {} +void TopTauAnalyzer::endJob() {} diff --git a/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.h b/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.h index 312a3e0c34cc7..a88cad0a74974 100644 --- a/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.h +++ b/TopQuarkAnalysis/Examples/plugins/TopTauAnalyzer.h @@ -13,17 +13,14 @@ #include "DataFormats/PatCandidates/interface/Tau.h" class TopTauAnalyzer : public edm::EDAnalyzer { - - public: - - explicit TopTauAnalyzer(const edm::ParameterSet&); +public: + explicit TopTauAnalyzer(const edm::ParameterSet &); ~TopTauAnalyzer() override; - private: - - void beginJob() override ; - void analyze(const edm::Event&, const edm::EventSetup&) override; - void endJob() override ; +private: + void beginJob() override; + void analyze(const edm::Event &, const edm::EventSetup &) override; + void endJob() override; edm::EDGetTokenT > inputToken_; diff --git a/TopQuarkAnalysis/Examples/test/runtestTqafExamples.cpp b/TopQuarkAnalysis/Examples/test/runtestTqafExamples.cpp index 87f88d6e99091..b2991bd18ae57 100644 --- a/TopQuarkAnalysis/Examples/test/runtestTqafExamples.cpp +++ b/TopQuarkAnalysis/Examples/test/runtestTqafExamples.cpp @@ -1,3 +1,3 @@ #include "FWCore/Utilities/interface/TestHelper.h" - + RUNTEST() diff --git a/TopQuarkAnalysis/TopKinFitter/interface/CovarianceMatrix.h b/TopQuarkAnalysis/TopKinFitter/interface/CovarianceMatrix.h index 121eb4ab4334d..76300c7eee2b2 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/CovarianceMatrix.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/CovarianceMatrix.h @@ -25,41 +25,48 @@ **/ class CovarianceMatrix { +public: + enum ObjectType { kUdscJet, kBJet, kMuon, kElectron, kMet }; - public: - - enum ObjectType{kUdscJet, kBJet, kMuon, kElectron, kMet}; - /// default constructor CovarianceMatrix(){}; /// constructor for the fully-hadronic channel - CovarianceMatrix(const std::vector& udscResolutions, const std::vector& bResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning); + CovarianceMatrix(const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning); /// constructor for the lepton+jets channel - CovarianceMatrix(const std::vector& udscResolutions, const std::vector& bResolutions, - const std::vector& lepResolutions, const std::vector& metResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning); + CovarianceMatrix(const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& lepResolutions, + const std::vector& metResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning); // destructor ~CovarianceMatrix(){}; /// return covariance matrix for a PAT object template - TMatrixD setupMatrix(const pat::PATObject& object, const TopKinFitter::Param param, const std::string& resolutionProvider = ""); + TMatrixD setupMatrix(const pat::PATObject& object, + const TopKinFitter::Param param, + const std::string& resolutionProvider = ""); /// return covariance matrix for a plain 4-vector TMatrixD setupMatrix(const TLorentzVector& object, const ObjectType objType, const TopKinFitter::Param param); /// get resolution for a given component of an object double getResolution(const TLorentzVector& object, const ObjectType objType, const std::string& whichResolution = ""); /// get resolution for a given PAT object template - double getResolution(const pat::PATObject& object, const std::string& whichResolution, const bool isBJet=false) { - return getResolution(TLorentzVector(object.px(), object.py(), object.pz(), object.energy()), getObjectType(object, isBJet), whichResolution); } - - private: + double getResolution(const pat::PATObject& object, const std::string& whichResolution, const bool isBJet = false) { + return getResolution(TLorentzVector(object.px(), object.py(), object.pz(), object.energy()), + getObjectType(object, isBJet), + whichResolution); + } +private: /// vector of strings for the binning of the resolutions std::vector binsUdsc_, binsB_, binsLep_, binsMet_; /// vectors for the resolution functions - std::vector funcEtUdsc_ , funcEtB_ , funcEtLep_ , funcEtMet_; + std::vector funcEtUdsc_, funcEtB_, funcEtLep_, funcEtMet_; std::vector funcEtaUdsc_, funcEtaB_, funcEtaLep_, funcEtaMet_; std::vector funcPhiUdsc_, funcPhiB_, funcPhiLep_, funcPhiMet_; /// scale factors for the jet energy resolution @@ -68,80 +75,81 @@ class CovarianceMatrix { /// determine type for a given PAT object template - ObjectType getObjectType(const pat::PATObject& object, const bool isBJet=false); + ObjectType getObjectType(const pat::PATObject& object, const bool isBJet = false); /// get eta dependent smear factor for a PAT object template - double getEtaDependentScaleFactor(const pat::PATObject& object); + double getEtaDependentScaleFactor(const pat::PATObject& object); /// get eta-dependent scale factor for a plain 4-vector double getEtaDependentScaleFactor(const TLorentzVector& object); - }; template -TMatrixD CovarianceMatrix::setupMatrix(const pat::PATObject& object, const TopKinFitter::Param param, const std::string& resolutionProvider) -{ +TMatrixD CovarianceMatrix::setupMatrix(const pat::PATObject& object, + const TopKinFitter::Param param, + const std::string& resolutionProvider) { // This part is for pat objects with resolutions embedded - if(object.hasKinResolution()) { - TMatrixD CovM3 (3,3); CovM3.Zero(); - TMatrixD CovM4 (4,4); CovM4.Zero(); + if (object.hasKinResolution()) { + TMatrixD CovM3(3, 3); + CovM3.Zero(); + TMatrixD CovM4(4, 4); + CovM4.Zero(); TMatrixD* CovM = &CovM3; - switch(param){ - case TopKinFitter::kEtEtaPhi : - CovM3(0,0) = pow(object.resolEt(resolutionProvider) , 2); - if( dynamic_cast(&object) ) - CovM3(0,0)*=getEtaDependentScaleFactor(object); - if( dynamic_cast(&object) ) - CovM3(1,1) = pow(9999., 2); - else - CovM3(1,1) = pow(object.resolEta(resolutionProvider), 2); - CovM3(2,2) = pow(object.resolPhi(resolutionProvider), 2); - CovM = &CovM3; - break; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(object.resolEt(resolutionProvider) , 2); - if( dynamic_cast(&object) ) - CovM3(0,0)*=getEtaDependentScaleFactor(object); - CovM3(1,1) = pow(object.resolTheta(resolutionProvider), 2); - CovM3(2,2) = pow(object.resolPhi(resolutionProvider) , 2); - CovM = &CovM3; - break; - case TopKinFitter::kEMom : - CovM4(0,0) = pow(1, 2); - CovM4(1,1) = pow(1, 2); - CovM4(2,2) = pow(1, 2); - CovM4(3,3) = pow(1, 2); - CovM = &CovM4; - break; + switch (param) { + case TopKinFitter::kEtEtaPhi: + CovM3(0, 0) = pow(object.resolEt(resolutionProvider), 2); + if (dynamic_cast(&object)) + CovM3(0, 0) *= getEtaDependentScaleFactor(object); + if (dynamic_cast(&object)) + CovM3(1, 1) = pow(9999., 2); + else + CovM3(1, 1) = pow(object.resolEta(resolutionProvider), 2); + CovM3(2, 2) = pow(object.resolPhi(resolutionProvider), 2); + CovM = &CovM3; + break; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(object.resolEt(resolutionProvider), 2); + if (dynamic_cast(&object)) + CovM3(0, 0) *= getEtaDependentScaleFactor(object); + CovM3(1, 1) = pow(object.resolTheta(resolutionProvider), 2); + CovM3(2, 2) = pow(object.resolPhi(resolutionProvider), 2); + CovM = &CovM3; + break; + case TopKinFitter::kEMom: + CovM4(0, 0) = pow(1, 2); + CovM4(1, 1) = pow(1, 2); + CovM4(2, 2) = pow(1, 2); + CovM4(3, 3) = pow(1, 2); + CovM = &CovM4; + break; } return *CovM; } // This part is for objects without resolutions embedded else { - const ObjectType objType = getObjectType(object, (resolutionProvider=="bjets")); + const ObjectType objType = getObjectType(object, (resolutionProvider == "bjets")); const TLorentzVector p4(object.px(), object.py(), object.pz(), object.energy()); return setupMatrix(p4, objType, param); } } template -CovarianceMatrix::ObjectType CovarianceMatrix::getObjectType(const pat::PATObject& object, const bool isBJet) -{ +CovarianceMatrix::ObjectType CovarianceMatrix::getObjectType(const pat::PATObject& object, const bool isBJet) { ObjectType objType; // jets - if( dynamic_cast(&object) ) { - if(isBJet) + if (dynamic_cast(&object)) { + if (isBJet) objType = kBJet; else objType = kUdscJet; } // muons - else if( dynamic_cast(&object) ) + else if (dynamic_cast(&object)) objType = kMuon; // electrons - else if( dynamic_cast(&object) ) + else if (dynamic_cast(&object)) objType = kElectron; // MET - else if( dynamic_cast(&object) ) + else if (dynamic_cast(&object)) objType = kMet; // catch anything else else @@ -150,19 +158,18 @@ CovarianceMatrix::ObjectType CovarianceMatrix::getObjectType(const pat::PATObjec } template -double CovarianceMatrix::getEtaDependentScaleFactor(const pat::PATObject& object) -{ +double CovarianceMatrix::getEtaDependentScaleFactor(const pat::PATObject& object) { double etaDependentScaleFactor = 1.; - for(unsigned int i=0; i=jetEnergyResolutionEtaBinning_[i] && jetEnergyResolutionEtaBinning_[i]>=0.){ - if(i==jetEnergyResolutionEtaBinning_.size()-1) { - edm::LogWarning("CovarianceMatrix") << "object eta ("<= jetEnergyResolutionEtaBinning_[i] && jetEnergyResolutionEtaBinning_[i] >= 0.) { + if (i == jetEnergyResolutionEtaBinning_.size() - 1) { + edm::LogWarning("CovarianceMatrix") << "object eta (" << std::abs(object.eta()) << ") beyond last eta bin (" + << jetEnergyResolutionEtaBinning_[i] << ") using scale factor 1.0!"; + etaDependentScaleFactor = 1.; + break; } - etaDependentScaleFactor=jetEnergyResolutionScaleFactors_[i]; - } - else + etaDependentScaleFactor = jetEnergyResolutionScaleFactors_[i]; + } else break; } return etaDependentScaleFactor; diff --git a/TopQuarkAnalysis/TopKinFitter/interface/StKinFitter.h b/TopQuarkAnalysis/TopKinFitter/interface/StKinFitter.h index 6deee2ef0d3ac..792839fb43b9e 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/StKinFitter.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/StKinFitter.h @@ -17,35 +17,42 @@ class TAbsFitParticle; class TFitConstraintM; class StKinFitter : public TopKinFitter { - - public: - - StKinFitter(); - StKinFitter(int jetParam, int lepParam, int metParam, int maxNrIter, double maxDeltaS, double maxF,const std::vector& constraints); - StKinFitter(Param jetParam, Param lepParam, Param metParam, int maxNrIter, double maxDeltaS, double maxF, const std::vector& constraints); - ~StKinFitter(); - - StEvtSolution addKinFitInfo(StEvtSolution * asol); - - private: - - void setupFitter(); - - private: - - // the particles that enter the kinematic fit - TAbsFitParticle * fitBottom_; - TAbsFitParticle * fitLight_; - TAbsFitParticle * fitLepton_; - TAbsFitParticle * fitNeutrino_; - // the constraints on the fit - TFitConstraintM * cons1_; - TFitConstraintM * cons2_; - TFitConstraintM * cons3_; - // other parameters - Param jetParam_, lepParam_, metParam_; - std::vector constraints_; +public: + StKinFitter(); + StKinFitter(int jetParam, + int lepParam, + int metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints); + StKinFitter(Param jetParam, + Param lepParam, + Param metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints); + ~StKinFitter(); + + StEvtSolution addKinFitInfo(StEvtSolution* asol); + +private: + void setupFitter(); + +private: + // the particles that enter the kinematic fit + TAbsFitParticle* fitBottom_; + TAbsFitParticle* fitLight_; + TAbsFitParticle* fitLepton_; + TAbsFitParticle* fitNeutrino_; + // the constraints on the fit + TFitConstraintM* cons1_; + TFitConstraintM* cons2_; + TFitConstraintM* cons3_; + // other parameters + Param jetParam_, lepParam_, metParam_; + std::vector constraints_; }; - #endif diff --git a/TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h b/TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h index cf5c20a0fc3aa..6eafdf8c7cf76 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h @@ -15,21 +15,22 @@ **/ class TopKinFitter { - - public: - +public: /// supported parameterizations - enum Param{ kEMom, kEtEtaPhi, kEtThetaPhi }; + enum Param { kEMom, kEtEtaPhi, kEtThetaPhi }; - public: +public: /// default constructor - explicit TopKinFitter(const int maxNrIter=200, const double maxDeltaS=5e-5, const double maxF=1e-4, - const double mW=80.4, const double mTop=173.); + explicit TopKinFitter(const int maxNrIter = 200, + const double maxDeltaS = 5e-5, + const double maxF = 1e-4, + const double mW = 80.4, + const double mTop = 173.); /// default destructor ~TopKinFitter(); /// return chi2 of fit (not normalized to degrees of freedom) - double fitS() const { return fitter_->getS(); }; + double fitS() const { return fitter_->getS(); }; /// return number of used iterations int fitNrIter() const { return fitter_->getNbIter(); }; /// return fit probability @@ -37,11 +38,11 @@ class TopKinFitter { /// allows to change the verbosity of the TKinFitter void setVerbosity(const int verbosityLevel) { fitter_->setVerbosity(verbosityLevel); }; - protected: +protected: /// convert Param to human readable form std::string param(const Param& param) const; - - protected: + +protected: /// kinematic fitter TKinFitter* fitter_; /// maximal allowed number of iterations to be used for the fit diff --git a/TopQuarkAnalysis/TopKinFitter/interface/TtFullHadKinFitter.h b/TopQuarkAnalysis/TopKinFitter/interface/TtFullHadKinFitter.h index ec9adc202bd89..f91b4fe9a3998 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/TtFullHadKinFitter.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/TtFullHadKinFitter.h @@ -27,61 +27,74 @@ class TFitConstraintM; **/ class TtFullHadKinFitter : public TopKinFitter { - - public: +public: /// supported constraints - enum Constraint{ kWPlusMass=1, kWMinusMass, kTopMass, kTopBarMass, kEqualTopMasses }; - - public: + enum Constraint { kWPlusMass = 1, kWMinusMass, kTopMass, kTopBarMass, kEqualTopMasses }; + +public: /// default constructor TtFullHadKinFitter(); /// used to convert vector of int's to vector of constraints (just used in TtFullHadKinFitter(int, int, double, double, std::vector)) std::vector intToConstraint(const std::vector& constraints); /// constructor initialized with build-in types as custom parameters (only included to keep TtHadEvtSolutionMaker.cc running) - TtFullHadKinFitter(int jetParam, int maxNrIter, double maxDeltaS, double maxF, const std::vector& constraints, - double mW=80.4, double mTop=173., - const std::vector* udscResolutions=nullptr, - const std::vector* bResolutions =nullptr, - const std::vector* jetEnergyResolutionScaleFactors=nullptr, - const std::vector* jetEnergyResolutionEtaBinning =nullptr); + TtFullHadKinFitter(int jetParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW = 80.4, + double mTop = 173., + const std::vector* udscResolutions = nullptr, + const std::vector* bResolutions = nullptr, + const std::vector* jetEnergyResolutionScaleFactors = nullptr, + const std::vector* jetEnergyResolutionEtaBinning = nullptr); /// constructor initialized with built-in types and class enum's custom parameters - TtFullHadKinFitter(Param jetParam, int maxNrIter, double maxDeltaS, double maxF, const std::vector& constraints, - double mW=80.4, double mTop=173., - const std::vector* udscResolutions=nullptr, - const std::vector* bResolutions =nullptr, - const std::vector* jetEnergyResolutionScaleFactors=nullptr, - const std::vector* jetEnergyResolutionEtaBinning =nullptr); + TtFullHadKinFitter(Param jetParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW = 80.4, + double mTop = 173., + const std::vector* udscResolutions = nullptr, + const std::vector* bResolutions = nullptr, + const std::vector* jetEnergyResolutionScaleFactors = nullptr, + const std::vector* jetEnergyResolutionEtaBinning = nullptr); /// default destructor ~TtFullHadKinFitter(); /// kinematic fit interface int fit(const std::vector& jets); /// return fitted b quark candidate - const pat::Particle fittedB() const { return (fitter_->getStatus()==0 ? fittedB_ : pat::Particle()); }; + const pat::Particle fittedB() const { return (fitter_->getStatus() == 0 ? fittedB_ : pat::Particle()); }; /// return fitted b quark candidate - const pat::Particle fittedBBar() const { return (fitter_->getStatus()==0 ? fittedBBar_ : pat::Particle()); }; + const pat::Particle fittedBBar() const { return (fitter_->getStatus() == 0 ? fittedBBar_ : pat::Particle()); }; /// return fitted light quark candidate - const pat::Particle fittedLightQ() const { return (fitter_->getStatus()==0 ? fittedLightQ_ : pat::Particle()); }; + const pat::Particle fittedLightQ() const { return (fitter_->getStatus() == 0 ? fittedLightQ_ : pat::Particle()); }; /// return fitted light quark candidate - const pat::Particle fittedLightQBar() const { return (fitter_->getStatus()==0 ? fittedLightQBar_ : pat::Particle()); }; + const pat::Particle fittedLightQBar() const { + return (fitter_->getStatus() == 0 ? fittedLightQBar_ : pat::Particle()); + }; /// return fitted light quark candidate - const pat::Particle fittedLightP() const { return (fitter_->getStatus()==0 ? fittedLightP_ : pat::Particle()); }; + const pat::Particle fittedLightP() const { return (fitter_->getStatus() == 0 ? fittedLightP_ : pat::Particle()); }; /// return fitted light quark candidate - const pat::Particle fittedLightPBar() const { return (fitter_->getStatus()==0 ? fittedLightPBar_ : pat::Particle()); }; + const pat::Particle fittedLightPBar() const { + return (fitter_->getStatus() == 0 ? fittedLightPBar_ : pat::Particle()); + }; /// add kin fit information to the old event solution (in for legacy reasons) - TtHadEvtSolution addKinFitInfo(TtHadEvtSolution * asol); - - private: + TtHadEvtSolution addKinFitInfo(TtHadEvtSolution* asol); + +private: /// print fitter setup void printSetup() const; - /// setup fitter + /// setup fitter void setupFitter(); /// initialize jet inputs void setupJets(); /// initialize constraints void setupConstraints(); - private: +private: /// input particles TAbsFitParticle* b_; TAbsFitParticle* bBar_; @@ -110,10 +123,9 @@ class TtFullHadKinFitter : public TopKinFitter { std::vector constraints_; /// get object resolutions and put them into a matrix - CovarianceMatrix * covM_; - - public: + CovarianceMatrix* covM_; +public: /// struct for fit results struct KinFitResult { int Status; @@ -126,91 +138,105 @@ class TtFullHadKinFitter : public TopKinFitter { pat::Particle LightP; pat::Particle LightPBar; std::vector JetCombi; - bool operator< (const KinFitResult& rhs) { return Chi2 < rhs.Chi2; }; + bool operator<(const KinFitResult& rhs) { return Chi2 < rhs.Chi2; }; }; /// class that does the fitting class KinFit { - public: - - /// default constructor + /// default constructor KinFit(); - /// special constructor - KinFit(bool useBTagging, unsigned int bTags, std::string bTagAlgo, double minBTagValueBJet, double maxBTagValueNonBJet, - const std::vector& udscResolutions, const std::vector& bResolutions, const std::vector& jetEnergyResolutionScaleFactors, - const std::vector& jetEnergyResolutionEtaBinning, std::string jetCorrectionLevel, int maxNJets, int maxNComb, - unsigned int maxNrIter, double maxDeltaS, double maxF, unsigned int jetParam, const std::vector& constraints, double mW, double mTop); - /// default destructor + /// special constructor + KinFit(bool useBTagging, + unsigned int bTags, + std::string bTagAlgo, + double minBTagValueBJet, + double maxBTagValueNonBJet, + const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning, + std::string jetCorrectionLevel, + int maxNJets, + int maxNComb, + unsigned int maxNrIter, + double maxDeltaS, + double maxF, + unsigned int jetParam, + const std::vector& constraints, + double mW, + double mTop); + /// default destructor ~KinFit(); - + /// set all parameters for b-tagging - void setBTagging(bool useBTagging, unsigned int bTags, std::string bTagAlgo, double minBTagValueBJet, double maxBTagValueNonBJet){ - useBTagging_ = useBTagging; - bTags_ = bTags; - bTagAlgo_ = bTagAlgo; - minBTagValueBJet_ = minBTagValueBJet; + void setBTagging(bool useBTagging, + unsigned int bTags, + std::string bTagAlgo, + double minBTagValueBJet, + double maxBTagValueNonBJet) { + useBTagging_ = useBTagging; + bTags_ = bTags; + bTagAlgo_ = bTagAlgo; + minBTagValueBJet_ = minBTagValueBJet; maxBTagValueNonBJet_ = maxBTagValueNonBJet; } /// set resolutions - void setResolutions(const std::vector& udscResolutions, const std::vector& bResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning){ - udscResolutions_ = udscResolutions; - bResolutions_ = bResolutions; + void setResolutions(const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning) { + udscResolutions_ = udscResolutions; + bResolutions_ = bResolutions; jetEnergyResolutionScaleFactors_ = jetEnergyResolutionScaleFactors; - jetEnergyResolutionEtaBinning_ = jetEnergyResolutionEtaBinning; + jetEnergyResolutionEtaBinning_ = jetEnergyResolutionEtaBinning; } /// set parameters for fitter - void setFitter(int maxNJets, unsigned int maxNrIter, double maxDeltaS, double maxF, - unsigned int jetParam, const std::vector& constraints, double mW, double mTop){ - maxNJets_ = maxNJets; - maxNrIter_ = maxNrIter; - maxDeltaS_ = maxDeltaS; - maxF_ = maxF; - jetParam_ = jetParam; + void setFitter(int maxNJets, + unsigned int maxNrIter, + double maxDeltaS, + double maxF, + unsigned int jetParam, + const std::vector& constraints, + double mW, + double mTop) { + maxNJets_ = maxNJets; + maxNrIter_ = maxNrIter; + maxDeltaS_ = maxDeltaS; + maxF_ = maxF; + jetParam_ = jetParam; constraints_ = constraints; - mW_ = mW; - mTop_ = mTop; + mW_ = mW; + mTop_ = mTop; } /// set jec level - void setJEC(std::string jetCorrectionLevel){ - jetCorrectionLevel_ = jetCorrectionLevel; - } + void setJEC(std::string jetCorrectionLevel) { jetCorrectionLevel_ = jetCorrectionLevel; } /// set useOnlyMatch - void setUseOnlyMatch(bool useOnlyMatch){ - useOnlyMatch_ = useOnlyMatch; - } + void setUseOnlyMatch(bool useOnlyMatch) { useOnlyMatch_ = useOnlyMatch; } /// set match to be used - void setMatch(const std::vector& match){ - match_ = match; - } + void setMatch(const std::vector& match) { match_ = match; } /// set the validity of a match - void setMatchInvalidity(bool invalidMatch){ - invalidMatch_ = invalidMatch; - } + void setMatchInvalidity(bool invalidMatch) { invalidMatch_ = invalidMatch; } /// set number of combinations of output - void setOutput(int maxNComb){ - maxNComb_ = maxNComb; - } + void setOutput(int maxNComb) { maxNComb_ = maxNComb; } /// do the fitting and return fit result std::list fit(const std::vector& jets); - - private: + private: // helper function for b-tagging bool doBTagging(const std::vector& jets, const unsigned int& bJetCounter, std::vector& combi); /// helper function to construct the proper corrected jet for its corresponding quarkType pat::Jet corJet(const pat::Jet& jet, const std::string& quarkType); - + // convert unsigned to Param TtFullHadKinFitter::Param param(unsigned int configParameter); // convert unsigned int to Constraint TtFullHadKinFitter::Constraint constraint(unsigned int configParameter); // convert vector of unsigned int's to vector of Contraint's std::vector constraints(const std::vector& configParameters); - - /// switch to tell whether all possible + + /// switch to tell whether all possible /// combinations should be used for the /// switch to tell whether to use b-tagging or not bool useBTagging_; @@ -256,7 +282,6 @@ class TtFullHadKinFitter : public TopKinFitter { /// kinematic fit interface TtFullHadKinFitter* fitter; - }; }; diff --git a/TopQuarkAnalysis/TopKinFitter/interface/TtFullLepKinSolver.h b/TopQuarkAnalysis/TopKinFitter/interface/TtFullLepKinSolver.h index 60d2cf48d75ed..b60f60e51e43d 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/TtFullLepKinSolver.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/TtFullLepKinSolver.h @@ -23,49 +23,51 @@ class TF2; **/ class TtFullLepKinSolver { - - public: - +public: /// struct NeutrinoSolution { double weight; reco::LeafCandidate neutrino; - reco::LeafCandidate neutrinoBar; + reco::LeafCandidate neutrinoBar; }; /// default constructor TtFullLepKinSolver(); /// constructor with parameters to configure the top-mass scan and the neutrino spectrum - TtFullLepKinSolver(const double, const double, const double, const std::vector&, const double=80.4, const double=4.8); + TtFullLepKinSolver( + const double, const double, const double, const std::vector&, const double = 80.4, const double = 4.8); /// destructor ~TtFullLepKinSolver(); /// inline void useWeightFromMC(bool useMC) { useMCforBest_ = useMC; } /// - TtDilepEvtSolution addKinSolInfo(TtDilepEvtSolution * asol); + TtDilepEvtSolution addKinSolInfo(TtDilepEvtSolution* asol); /// - void SetConstraints(const double xx=0, const double yy=0); + void SetConstraints(const double xx = 0, const double yy = 0); /// - NeutrinoSolution getNuSolution(const TLorentzVector& LV_l, - const TLorentzVector& LV_l_, - const TLorentzVector& LV_b, - const TLorentzVector& LV_b_); - - private: + NeutrinoSolution getNuSolution(const TLorentzVector& LV_l, + const TLorentzVector& LV_l_, + const TLorentzVector& LV_b, + const TLorentzVector& LV_b_); - /// - void FindCoeff(const TLorentzVector& al, - const TLorentzVector& l, - const TLorentzVector& b_al, - const TLorentzVector& b_l, - const double mt, const double mat, const double pxboost, const double pyboost, - double* q_coeff); - /// - void TopRec(const TLorentzVector& al, - const TLorentzVector& l, - const TLorentzVector& b_al, - const TLorentzVector& b_l, const double sol); +private: + /// + void FindCoeff(const TLorentzVector& al, + const TLorentzVector& l, + const TLorentzVector& b_al, + const TLorentzVector& b_l, + const double mt, + const double mat, + const double pxboost, + const double pyboost, + double* q_coeff); + /// + void TopRec(const TLorentzVector& al, + const TLorentzVector& l, + const TLorentzVector& b_al, + const TLorentzVector& b_l, + const double sol); /// double WeightSolfromMC() const; /// use the parametrized event shape to obtain the solution weight. @@ -75,11 +77,11 @@ class TtFullLepKinSolver { /// int cubic(const double* c_coeff, double* c_sol) const; /// - double sqr(const double x) const {return (x*x);} + double sqr(const double x) const { return (x * x); } /// void SWAP(double& realone, double& realtwo) const; - - private: + +private: /// const double topmass_begin; /// @@ -92,7 +94,7 @@ class TtFullLepKinSolver { const double mb; /// double pxmiss_, pymiss_; - + double C; double D; double F; @@ -110,17 +112,16 @@ class TtFullLepKinSolver { double n1; double n2; double n3; - + /// - TLorentzVector LV_n, LV_n_, LV_t, LV_t_, LV_tt_t, LV_tt_t_; + TLorentzVector LV_n, LV_n_, LV_t, LV_t_, LV_tt_t, LV_tt_t_; /// provisional - TLorentzVector genLV_n, genLV_n_; - + TLorentzVector genLV_n, genLV_n_; + /// flag to swith from WeightSolfromMC() to WeightSolfromShape() bool useMCforBest_; /// Event shape - TF2* EventShape_; + TF2* EventShape_; }; - #endif diff --git a/TopQuarkAnalysis/TopKinFitter/interface/TtSemiLepKinFitter.h b/TopQuarkAnalysis/TopKinFitter/interface/TtSemiLepKinFitter.h index a0b33105eb9e3..1266d472c5f8c 100644 --- a/TopQuarkAnalysis/TopKinFitter/interface/TtSemiLepKinFitter.h +++ b/TopQuarkAnalysis/TopKinFitter/interface/TtSemiLepKinFitter.h @@ -30,57 +30,79 @@ class TFitConstraintEp; **/ class TtSemiLepKinFitter : public TopKinFitter { - - public: - +public: /// supported constraints enum Constraint { kWHadMass = 1, kWLepMass, kTopHadMass, kTopLepMass, kNeutrinoMass, kEqualTopMasses, kSumPt }; - public: +public: /// default constructor explicit TtSemiLepKinFitter(); /// constructor initialized with built-in types and class enum's custom parameters - explicit TtSemiLepKinFitter(Param jetParam, Param lepParam, Param metParam, int maxNrIter, double maxDeltaS, double maxF, - const std::vector& constraints, double mW=80.4, double mTop=173., - const std::vector* udscResolutions=nullptr, - const std::vector* bResolutions =nullptr, - const std::vector* lepResolutions =nullptr, - const std::vector* metResolutions =nullptr, - const std::vector* jetEnergyResolutionScaleFactors=nullptr, - const std::vector* jetEnergyResolutionEtaBinning =nullptr); + explicit TtSemiLepKinFitter(Param jetParam, + Param lepParam, + Param metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW = 80.4, + double mTop = 173., + const std::vector* udscResolutions = nullptr, + const std::vector* bResolutions = nullptr, + const std::vector* lepResolutions = nullptr, + const std::vector* metResolutions = nullptr, + const std::vector* jetEnergyResolutionScaleFactors = nullptr, + const std::vector* jetEnergyResolutionEtaBinning = nullptr); /// default destructor ~TtSemiLepKinFitter(); /// kinematic fit interface for PAT objects - template int fit(const std::vector& jets, const pat::Lepton& leps, const pat::MET& met); + template + int fit(const std::vector& jets, const pat::Lepton& leps, const pat::MET& met); /// kinematic fit interface for plain 4-vecs - int fit(const TLorentzVector& p4HadP, const TLorentzVector& p4HadQ, const TLorentzVector& p4HadB, const TLorentzVector& p4LepB, - const TLorentzVector& p4Lepton, const TLorentzVector& p4Neutrino, const int leptonCharge, const CovarianceMatrix::ObjectType leptonType); + int fit(const TLorentzVector& p4HadP, + const TLorentzVector& p4HadQ, + const TLorentzVector& p4HadB, + const TLorentzVector& p4LepB, + const TLorentzVector& p4Lepton, + const TLorentzVector& p4Neutrino, + const int leptonCharge, + const CovarianceMatrix::ObjectType leptonType); /// common core of the fit interface - int fit(const TLorentzVector& p4HadP, const TLorentzVector& p4HadQ, const TLorentzVector& p4HadB, const TLorentzVector& p4LepB, - const TLorentzVector& p4Lepton, const TLorentzVector& p4Neutrino, - const TMatrixD& covHadP, const TMatrixD& covHadQ, const TMatrixD& covHadB, const TMatrixD& covLepB, - const TMatrixD& covLepton, const TMatrixD& covNeutrino, - const int leptonCharge); + int fit(const TLorentzVector& p4HadP, + const TLorentzVector& p4HadQ, + const TLorentzVector& p4HadB, + const TLorentzVector& p4LepB, + const TLorentzVector& p4Lepton, + const TLorentzVector& p4Neutrino, + const TMatrixD& covHadP, + const TMatrixD& covHadQ, + const TMatrixD& covHadB, + const TMatrixD& covLepB, + const TMatrixD& covLepton, + const TMatrixD& covNeutrino, + const int leptonCharge); /// return hadronic b quark candidate - const pat::Particle fittedHadB() const { return (fitter_->getStatus()==0 ? fittedHadB_ : pat::Particle()); }; + const pat::Particle fittedHadB() const { return (fitter_->getStatus() == 0 ? fittedHadB_ : pat::Particle()); }; /// return hadronic light quark candidate - const pat::Particle fittedHadP() const { return (fitter_->getStatus()==0 ? fittedHadP_ : pat::Particle()); }; + const pat::Particle fittedHadP() const { return (fitter_->getStatus() == 0 ? fittedHadP_ : pat::Particle()); }; /// return hadronic light quark candidate - const pat::Particle fittedHadQ() const { return (fitter_->getStatus()==0 ? fittedHadQ_ : pat::Particle()); }; + const pat::Particle fittedHadQ() const { return (fitter_->getStatus() == 0 ? fittedHadQ_ : pat::Particle()); }; /// return leptonic b quark candidate - const pat::Particle fittedLepB() const { return (fitter_->getStatus()==0 ? fittedLepB_ : pat::Particle()); }; + const pat::Particle fittedLepB() const { return (fitter_->getStatus() == 0 ? fittedLepB_ : pat::Particle()); }; /// return lepton candidate - const pat::Particle fittedLepton() const { return (fitter_->getStatus()==0 ? fittedLepton_ : pat::Particle()); }; + const pat::Particle fittedLepton() const { return (fitter_->getStatus() == 0 ? fittedLepton_ : pat::Particle()); }; /// return neutrino candidate - const pat::Particle fittedNeutrino() const { return (fitter_->getStatus()==0 ? fittedNeutrino_ : pat::Particle()); }; + const pat::Particle fittedNeutrino() const { + return (fitter_->getStatus() == 0 ? fittedNeutrino_ : pat::Particle()); + }; /// add kin fit information to the old event solution (in for legacy reasons) TtSemiEvtSolution addKinFitInfo(TtSemiEvtSolution* asol); - - private: - /// print fitter setup + +private: + /// print fitter setup void printSetup() const; - /// setup fitter + /// setup fitter void setupFitter(); /// initialize jet inputs void setupJets(); @@ -88,8 +110,8 @@ class TtSemiLepKinFitter : public TopKinFitter { void setupLeptons(); /// initialize constraints void setupConstraints(); - - private: + +private: /// input particles TAbsFitParticle* hadB_; TAbsFitParticle* hadP_; @@ -119,7 +141,7 @@ class TtSemiLepKinFitter : public TopKinFitter { pat::Particle fittedLepton_; pat::Particle fittedNeutrino_; /// jet parametrization - Param jetParam_; + Param jetParam_; /// lepton parametrization Param lepParam_; /// met parametrization @@ -131,38 +153,48 @@ class TtSemiLepKinFitter : public TopKinFitter { }; template -int TtSemiLepKinFitter::fit(const std::vector& jets, const pat::Lepton& lepton, const pat::MET& neutrino) -{ - if( jets.size()<4 ) - throw edm::Exception( edm::errors::Configuration, "Cannot run the TtSemiLepKinFitter with less than 4 jets" ); +int TtSemiLepKinFitter::fit(const std::vector& jets, + const pat::Lepton& lepton, + const pat::MET& neutrino) { + if (jets.size() < 4) + throw edm::Exception(edm::errors::Configuration, "Cannot run the TtSemiLepKinFitter with less than 4 jets"); // get jets in right order - const pat::Jet hadP = jets[TtSemiLepEvtPartons::LightQ ]; + const pat::Jet hadP = jets[TtSemiLepEvtPartons::LightQ]; const pat::Jet hadQ = jets[TtSemiLepEvtPartons::LightQBar]; - const pat::Jet hadB = jets[TtSemiLepEvtPartons::HadB ]; - const pat::Jet lepB = jets[TtSemiLepEvtPartons::LepB ]; - + const pat::Jet hadB = jets[TtSemiLepEvtPartons::HadB]; + const pat::Jet lepB = jets[TtSemiLepEvtPartons::LepB]; + // initialize particles - const TLorentzVector p4HadP( hadP.px(), hadP.py(), hadP.pz(), hadP.energy() ); - const TLorentzVector p4HadQ( hadQ.px(), hadQ.py(), hadQ.pz(), hadQ.energy() ); - const TLorentzVector p4HadB( hadB.px(), hadB.py(), hadB.pz(), hadB.energy() ); - const TLorentzVector p4LepB( lepB.px(), lepB.py(), lepB.pz(), lepB.energy() ); - const TLorentzVector p4Lepton ( lepton.px(), lepton.py(), lepton.pz(), lepton.energy() ); - const TLorentzVector p4Neutrino( neutrino.px(), neutrino.py(), 0, neutrino.et() ); + const TLorentzVector p4HadP(hadP.px(), hadP.py(), hadP.pz(), hadP.energy()); + const TLorentzVector p4HadQ(hadQ.px(), hadQ.py(), hadQ.pz(), hadQ.energy()); + const TLorentzVector p4HadB(hadB.px(), hadB.py(), hadB.pz(), hadB.energy()); + const TLorentzVector p4LepB(lepB.px(), lepB.py(), lepB.pz(), lepB.energy()); + const TLorentzVector p4Lepton(lepton.px(), lepton.py(), lepton.pz(), lepton.energy()); + const TLorentzVector p4Neutrino(neutrino.px(), neutrino.py(), 0, neutrino.et()); // initialize covariance matrices TMatrixD covHadP = covM_->setupMatrix(hadP, jetParam_); TMatrixD covHadQ = covM_->setupMatrix(hadQ, jetParam_); TMatrixD covHadB = covM_->setupMatrix(hadB, jetParam_, "bjets"); TMatrixD covLepB = covM_->setupMatrix(lepB, jetParam_, "bjets"); - TMatrixD covLepton = covM_->setupMatrix(lepton , lepParam_); + TMatrixD covLepton = covM_->setupMatrix(lepton, lepParam_); TMatrixD covNeutrino = covM_->setupMatrix(neutrino, metParam_); // now do the part that is fully independent of PAT features - return fit(p4HadP, p4HadQ, p4HadB, p4LepB, p4Lepton, p4Neutrino, - covHadP, covHadQ, covHadB, covLepB, covLepton, covNeutrino, - lepton.charge()); + return fit(p4HadP, + p4HadQ, + p4HadB, + p4LepB, + p4Lepton, + p4Neutrino, + covHadP, + covHadQ, + covHadB, + covLepB, + covLepton, + covNeutrino, + lepton.charge()); } - #endif diff --git a/TopQuarkAnalysis/TopKinFitter/plugins/SealModule.cc b/TopQuarkAnalysis/TopKinFitter/plugins/SealModule.cc index cdb4e4d5cc910..6ba4acd5d6073 100644 --- a/TopQuarkAnalysis/TopKinFitter/plugins/SealModule.cc +++ b/TopQuarkAnalysis/TopKinFitter/plugins/SealModule.cc @@ -5,8 +5,8 @@ #include "TopQuarkAnalysis/TopKinFitter/plugins/TtSemiLepKinFitProducer.h" -typedef TtSemiLepKinFitProducer< std::vector > TtSemiLepKinFitProducerMuon; -typedef TtSemiLepKinFitProducer< std::vector > TtSemiLepKinFitProducerElectron; +typedef TtSemiLepKinFitProducer > TtSemiLepKinFitProducerMuon; +typedef TtSemiLepKinFitProducer > TtSemiLepKinFitProducerElectron; DEFINE_FWK_MODULE(TtSemiLepKinFitProducerMuon); DEFINE_FWK_MODULE(TtSemiLepKinFitProducerElectron); diff --git a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.cc b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.cc index 6917b6554f5fa..42ef8cbaf42ea 100644 --- a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.cc +++ b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.cc @@ -1,92 +1,103 @@ #include "TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.h" -static const unsigned int nPartons=6; +static const unsigned int nPartons = 6; /// default constructor -TtFullHadKinFitProducer::TtFullHadKinFitProducer(const edm::ParameterSet& cfg): - jetsToken_ (consumes >(cfg.getParameter("jets"))), - matchToken_ (mayConsume > >(cfg.getParameter("match"))), - useOnlyMatch_ (cfg.getParameter("useOnlyMatch")), - bTagAlgo_ (cfg.getParameter("bTagAlgo")), - minBTagValueBJet_ (cfg.getParameter("minBTagValueBJet")), - maxBTagValueNonBJet_ (cfg.getParameter("maxBTagValueNonBJet")), - useBTagging_ (cfg.getParameter("useBTagging")), - bTags_ (cfg.getParameter("bTags")), - jetCorrectionLevel_ (cfg.getParameter("jetCorrectionLevel")), - maxNJets_ (cfg.getParameter("maxNJets")), - maxNComb_ (cfg.getParameter("maxNComb")), - maxNrIter_ (cfg.getParameter("maxNrIter")), - maxDeltaS_ (cfg.getParameter("maxDeltaS")), - maxF_ (cfg.getParameter("maxF")), - jetParam_ (cfg.getParameter("jetParametrisation")), - constraints_ (cfg.getParameter >("constraints")), - mW_ (cfg.getParameter("mW" )), - mTop_ (cfg.getParameter("mTop")), - jetEnergyResolutionScaleFactors_(cfg.getParameter >("jetEnergyResolutionScaleFactors")), - jetEnergyResolutionEtaBinning_ (cfg.getParameter >("jetEnergyResolutionEtaBinning")) -{ - if(cfg.exists("udscResolutions") && cfg.exists("bResolutions")){ - udscResolutions_ = cfg.getParameter >("udscResolutions"); - bResolutions_ = cfg.getParameter >("bResolutions"); - } - else if(cfg.exists("udscResolutions") || cfg.exists("bResolutions")){ - if(cfg.exists("udscResolutions")) throw cms::Exception("Configuration") << "Parameter 'bResolutions' is needed if parameter 'udscResolutions' is defined!\n"; - else throw cms::Exception("Configuration") << "Parameter 'udscResolutions' is needed if parameter 'bResolutions' is defined!\n"; +TtFullHadKinFitProducer::TtFullHadKinFitProducer(const edm::ParameterSet& cfg) + : jetsToken_(consumes >(cfg.getParameter("jets"))), + matchToken_(mayConsume > >(cfg.getParameter("match"))), + useOnlyMatch_(cfg.getParameter("useOnlyMatch")), + bTagAlgo_(cfg.getParameter("bTagAlgo")), + minBTagValueBJet_(cfg.getParameter("minBTagValueBJet")), + maxBTagValueNonBJet_(cfg.getParameter("maxBTagValueNonBJet")), + useBTagging_(cfg.getParameter("useBTagging")), + bTags_(cfg.getParameter("bTags")), + jetCorrectionLevel_(cfg.getParameter("jetCorrectionLevel")), + maxNJets_(cfg.getParameter("maxNJets")), + maxNComb_(cfg.getParameter("maxNComb")), + maxNrIter_(cfg.getParameter("maxNrIter")), + maxDeltaS_(cfg.getParameter("maxDeltaS")), + maxF_(cfg.getParameter("maxF")), + jetParam_(cfg.getParameter("jetParametrisation")), + constraints_(cfg.getParameter >("constraints")), + mW_(cfg.getParameter("mW")), + mTop_(cfg.getParameter("mTop")), + jetEnergyResolutionScaleFactors_(cfg.getParameter >("jetEnergyResolutionScaleFactors")), + jetEnergyResolutionEtaBinning_(cfg.getParameter >("jetEnergyResolutionEtaBinning")) { + if (cfg.exists("udscResolutions") && cfg.exists("bResolutions")) { + udscResolutions_ = cfg.getParameter >("udscResolutions"); + bResolutions_ = cfg.getParameter >("bResolutions"); + } else if (cfg.exists("udscResolutions") || cfg.exists("bResolutions")) { + if (cfg.exists("udscResolutions")) + throw cms::Exception("Configuration") + << "Parameter 'bResolutions' is needed if parameter 'udscResolutions' is defined!\n"; + else + throw cms::Exception("Configuration") + << "Parameter 'udscResolutions' is needed if parameter 'bResolutions' is defined!\n"; } // define kinematic fit interface - kinFitter = new TtFullHadKinFitter::KinFit(useBTagging_, bTags_, bTagAlgo_, minBTagValueBJet_, maxBTagValueNonBJet_, - udscResolutions_, bResolutions_, jetEnergyResolutionScaleFactors_, - jetEnergyResolutionEtaBinning_, jetCorrectionLevel_, maxNJets_, maxNComb_, - maxNrIter_, maxDeltaS_, maxF_, jetParam_, constraints_, mW_, mTop_); + kinFitter = new TtFullHadKinFitter::KinFit(useBTagging_, + bTags_, + bTagAlgo_, + minBTagValueBJet_, + maxBTagValueNonBJet_, + udscResolutions_, + bResolutions_, + jetEnergyResolutionScaleFactors_, + jetEnergyResolutionEtaBinning_, + jetCorrectionLevel_, + maxNJets_, + maxNComb_, + maxNrIter_, + maxDeltaS_, + maxF_, + jetParam_, + constraints_, + mW_, + mTop_); // produces the following collections - produces< std::vector >("PartonsB"); - produces< std::vector >("PartonsBBar"); - produces< std::vector >("PartonsLightQ"); - produces< std::vector >("PartonsLightQBar"); - produces< std::vector >("PartonsLightP"); - produces< std::vector >("PartonsLightPBar"); - - produces< std::vector > >(); - produces< std::vector >("Chi2"); - produces< std::vector >("Prob"); - produces< std::vector >("Status"); + produces >("PartonsB"); + produces >("PartonsBBar"); + produces >("PartonsLightQ"); + produces >("PartonsLightQBar"); + produces >("PartonsLightP"); + produces >("PartonsLightPBar"); + + produces > >(); + produces >("Chi2"); + produces >("Prob"); + produces >("Status"); } /// default destructor -TtFullHadKinFitProducer::~TtFullHadKinFitProducer() -{ - delete kinFitter; -} +TtFullHadKinFitProducer::~TtFullHadKinFitProducer() { delete kinFitter; } /// produce fitted object collections and meta data describing fit quality -void -TtFullHadKinFitProducer::produce(edm::Event& event, const edm::EventSetup& setup) -{ +void TtFullHadKinFitProducer::produce(edm::Event& event, const edm::EventSetup& setup) { // get jet collection edm::Handle > jets; event.getByToken(jetsToken_, jets); // get match in case that useOnlyMatch_ is true std::vector match; - bool invalidMatch=false; - if(useOnlyMatch_) { + bool invalidMatch = false; + if (useOnlyMatch_) { kinFitter->setUseOnlyMatch(true); // in case that only a ceratin match should be used, get match here edm::Handle > > matches; event.getByToken(matchToken_, matches); match = *(matches->begin()); // check if match is valid - if( match.size()!=nPartons ){ - invalidMatch=true; - } - else { - for(unsigned int idx=0; idx=(int)jets->size()) { - invalidMatch=true; - break; - } + if (match.size() != nPartons) { + invalidMatch = true; + } else { + for (unsigned int idx = 0; idx < match.size(); ++idx) { + if (match[idx] < 0 || match[idx] >= (int)jets->size()) { + invalidMatch = true; + break; + } } } /// set match to be used @@ -99,49 +110,49 @@ TtFullHadKinFitProducer::produce(edm::Event& event, const edm::EventSetup& setup std::list fitResults = kinFitter->fit(*jets); // pointer for output collections - std::unique_ptr< std::vector > pPartonsB( new std::vector ); - std::unique_ptr< std::vector > pPartonsBBar( new std::vector ); - std::unique_ptr< std::vector > pPartonsLightQ ( new std::vector ); - std::unique_ptr< std::vector > pPartonsLightQBar( new std::vector ); - std::unique_ptr< std::vector > pPartonsLightP ( new std::vector ); - std::unique_ptr< std::vector > pPartonsLightPBar( new std::vector ); + std::unique_ptr > pPartonsB(new std::vector); + std::unique_ptr > pPartonsBBar(new std::vector); + std::unique_ptr > pPartonsLightQ(new std::vector); + std::unique_ptr > pPartonsLightQBar(new std::vector); + std::unique_ptr > pPartonsLightP(new std::vector); + std::unique_ptr > pPartonsLightPBar(new std::vector); // pointer for meta information - std::unique_ptr< std::vector > > pCombi ( new std::vector > ); - std::unique_ptr< std::vector > pChi2 ( new std::vector ); - std::unique_ptr< std::vector > pProb ( new std::vector ); - std::unique_ptr< std::vector > pStatus( new std::vector ); + std::unique_ptr > > pCombi(new std::vector >); + std::unique_ptr > pChi2(new std::vector); + std::unique_ptr > pProb(new std::vector); + std::unique_ptr > pStatus(new std::vector); unsigned int iComb = 0; - for(std::list::const_iterator res = fitResults.begin(); res != fitResults.end(); ++res){ - if(maxNComb_>=1 && iComb==(unsigned int)maxNComb_){ + for (std::list::const_iterator res = fitResults.begin(); res != fitResults.end(); + ++res) { + if (maxNComb_ >= 1 && iComb == (unsigned int)maxNComb_) { break; } ++iComb; - pPartonsB ->push_back( res->B ); - pPartonsBBar ->push_back( res->BBar ); - pPartonsLightQ ->push_back( res->LightQ ); - pPartonsLightQBar->push_back( res->LightQBar ); - pPartonsLightP ->push_back( res->LightP ); - pPartonsLightPBar->push_back( res->LightPBar ); - - pCombi ->push_back( res->JetCombi ); - pChi2 ->push_back( res->Chi2 ); - pProb ->push_back( res->Prob ); - pStatus->push_back( res->Status ); - + pPartonsB->push_back(res->B); + pPartonsBBar->push_back(res->BBar); + pPartonsLightQ->push_back(res->LightQ); + pPartonsLightQBar->push_back(res->LightQBar); + pPartonsLightP->push_back(res->LightP); + pPartonsLightPBar->push_back(res->LightPBar); + + pCombi->push_back(res->JetCombi); + pChi2->push_back(res->Chi2); + pProb->push_back(res->Prob); + pStatus->push_back(res->Status); } event.put(std::move(pCombi)); - event.put(std::move(pPartonsB ), "PartonsB" ); - event.put(std::move(pPartonsBBar ), "PartonsBBar" ); - event.put(std::move(pPartonsLightQ ), "PartonsLightQ" ); + event.put(std::move(pPartonsB), "PartonsB"); + event.put(std::move(pPartonsBBar), "PartonsBBar"); + event.put(std::move(pPartonsLightQ), "PartonsLightQ"); event.put(std::move(pPartonsLightQBar), "PartonsLightQBar"); - event.put(std::move(pPartonsLightP ), "PartonsLightP" ); + event.put(std::move(pPartonsLightP), "PartonsLightP"); event.put(std::move(pPartonsLightPBar), "PartonsLightPBar"); - event.put(std::move(pChi2 ), "Chi2" ); - event.put(std::move(pProb ), "Prob" ); - event.put(std::move(pStatus ), "Status" ); + event.put(std::move(pChi2), "Chi2"); + event.put(std::move(pProb), "Prob"); + event.put(std::move(pStatus), "Status"); } #include "FWCore/Framework/interface/MakerMacros.h" diff --git a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.h b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.h index 4cb89024f56b8..12653f4d19cc0 100644 --- a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.h +++ b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullHadKinFitProducer.h @@ -20,18 +20,17 @@ **/ class TtFullHadKinFitProducer : public edm::EDProducer { - - public: +public: /// default constructor explicit TtFullHadKinFitProducer(const edm::ParameterSet& cfg); /// default destructor ~TtFullHadKinFitProducer() override; - private: +private: /// produce fitted object collections and meta data describing fit quality void produce(edm::Event& event, const edm::EventSetup& setup) override; - private: +private: /// input tag for jets edm::EDGetTokenT > jetsToken_; /// input tag for matches (in case the fit should be performed on certain matches) @@ -75,11 +74,9 @@ class TtFullHadKinFitProducer : public edm::EDProducer { std::vector jetEnergyResolutionScaleFactors_; std::vector jetEnergyResolutionEtaBinning_; - public: - +public: /// kinematic fit interface TtFullHadKinFitter::KinFit* kinFitter; - }; #endif diff --git a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullLepKinSolutionProducer.h b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullLepKinSolutionProducer.h index cb5ed53a96224..d3761e5ed7146 100644 --- a/TopQuarkAnalysis/TopKinFitter/plugins/TtFullLepKinSolutionProducer.h +++ b/TopQuarkAnalysis/TopKinFitter/plugins/TtFullLepKinSolutionProducer.h @@ -16,103 +16,86 @@ #include "DataFormats/Candidate/interface/LeafCandidate.h" #include "TopQuarkAnalysis/TopKinFitter/interface/TtFullLepKinSolver.h" - class TtFullLepKinSolutionProducer : public edm::EDProducer { - - public: - - explicit TtFullLepKinSolutionProducer(const edm::ParameterSet & iConfig); - ~TtFullLepKinSolutionProducer() override; - - void beginJob() override; - void produce(edm::Event & evt, const edm::EventSetup & iSetup) override; - void endJob() override; - - private: - - // next methods are avoidable but they make the code legible - inline bool PTComp(const reco::Candidate*, const reco::Candidate*) const; - inline bool LepDiffCharge(const reco::Candidate* , const reco::Candidate*) const; - inline bool HasPositiveCharge(const reco::Candidate*) const; - - struct Compare{ - bool operator()(std::pair a, std::pair b){ - return a.first > b.first; - } - }; - - edm::EDGetTokenT > jetsToken_; - edm::EDGetTokenT > electronsToken_; - edm::EDGetTokenT > muonsToken_; - edm::EDGetTokenT > metsToken_; - - std::string jetCorrLevel_; - int maxNJets_, maxNComb_; - bool eeChannel_, emuChannel_, mumuChannel_, searchWrongCharge_; - double tmassbegin_, tmassend_, tmassstep_; - std::vector nupars_; - - TtFullLepKinSolver* solver; +public: + explicit TtFullLepKinSolutionProducer(const edm::ParameterSet& iConfig); + ~TtFullLepKinSolutionProducer() override; + + void beginJob() override; + void produce(edm::Event& evt, const edm::EventSetup& iSetup) override; + void endJob() override; + +private: + // next methods are avoidable but they make the code legible + inline bool PTComp(const reco::Candidate*, const reco::Candidate*) const; + inline bool LepDiffCharge(const reco::Candidate*, const reco::Candidate*) const; + inline bool HasPositiveCharge(const reco::Candidate*) const; + + struct Compare { + bool operator()(std::pair a, std::pair b) { return a.first > b.first; } + }; + + edm::EDGetTokenT > jetsToken_; + edm::EDGetTokenT > electronsToken_; + edm::EDGetTokenT > muonsToken_; + edm::EDGetTokenT > metsToken_; + + std::string jetCorrLevel_; + int maxNJets_, maxNComb_; + bool eeChannel_, emuChannel_, mumuChannel_, searchWrongCharge_; + double tmassbegin_, tmassend_, tmassstep_; + std::vector nupars_; + + TtFullLepKinSolver* solver; }; -inline bool TtFullLepKinSolutionProducer::PTComp(const reco::Candidate* l1, const reco::Candidate* l2) const -{ +inline bool TtFullLepKinSolutionProducer::PTComp(const reco::Candidate* l1, const reco::Candidate* l2) const { return (l1->pt() > l2->pt()); } -inline bool TtFullLepKinSolutionProducer::LepDiffCharge(const reco::Candidate* l1, const reco::Candidate* l2) const -{ +inline bool TtFullLepKinSolutionProducer::LepDiffCharge(const reco::Candidate* l1, const reco::Candidate* l2) const { return (l1->charge() != l2->charge()); } -inline bool TtFullLepKinSolutionProducer::HasPositiveCharge(const reco::Candidate* l) const -{ +inline bool TtFullLepKinSolutionProducer::HasPositiveCharge(const reco::Candidate* l) const { return (l->charge() > 0); } -TtFullLepKinSolutionProducer::TtFullLepKinSolutionProducer(const edm::ParameterSet & iConfig) -{ +TtFullLepKinSolutionProducer::TtFullLepKinSolutionProducer(const edm::ParameterSet& iConfig) { // configurables - jetsToken_ = consumes >(iConfig.getParameter("jets")); - electronsToken_ = consumes >(iConfig.getParameter("electrons")); - muonsToken_ = consumes >(iConfig.getParameter("muons")); - metsToken_ = consumes >(iConfig.getParameter("mets")); - jetCorrLevel_= iConfig.getParameter ("jetCorrectionLevel"); - maxNJets_ = iConfig.getParameter ("maxNJets"); - maxNComb_ = iConfig.getParameter ("maxNComb"); - eeChannel_ = iConfig.getParameter("eeChannel"); - emuChannel_ = iConfig.getParameter("emuChannel"); - mumuChannel_ = iConfig.getParameter("mumuChannel"); - searchWrongCharge_ = iConfig.getParameter ("searchWrongCharge"); - tmassbegin_ = iConfig.getParameter("tmassbegin"); - tmassend_ = iConfig.getParameter("tmassend"); - tmassstep_ = iConfig.getParameter("tmassstep"); - nupars_ = iConfig.getParameter >("neutrino_parameters"); + jetsToken_ = consumes >(iConfig.getParameter("jets")); + electronsToken_ = consumes >(iConfig.getParameter("electrons")); + muonsToken_ = consumes >(iConfig.getParameter("muons")); + metsToken_ = consumes >(iConfig.getParameter("mets")); + jetCorrLevel_ = iConfig.getParameter("jetCorrectionLevel"); + maxNJets_ = iConfig.getParameter("maxNJets"); + maxNComb_ = iConfig.getParameter("maxNComb"); + eeChannel_ = iConfig.getParameter("eeChannel"); + emuChannel_ = iConfig.getParameter("emuChannel"); + mumuChannel_ = iConfig.getParameter("mumuChannel"); + searchWrongCharge_ = iConfig.getParameter("searchWrongCharge"); + tmassbegin_ = iConfig.getParameter("tmassbegin"); + tmassend_ = iConfig.getParameter("tmassend"); + tmassstep_ = iConfig.getParameter("tmassstep"); + nupars_ = iConfig.getParameter >("neutrino_parameters"); // define what will be produced - produces > > (); // vector of the particle inices (b, bbar, e1, e2, mu1, mu2) + produces > >(); // vector of the particle inices (b, bbar, e1, e2, mu1, mu2) produces >("fullLepNeutrinos"); produces >("fullLepNeutrinoBars"); - produces >("solWeight"); //weight for a specific kin solution - produces("isWrongCharge"); //true if leptons have the same charge + produces >("solWeight"); //weight for a specific kin solution + produces("isWrongCharge"); //true if leptons have the same charge } -TtFullLepKinSolutionProducer::~TtFullLepKinSolutionProducer() -{ -} +TtFullLepKinSolutionProducer::~TtFullLepKinSolutionProducer() {} -void TtFullLepKinSolutionProducer::beginJob() -{ +void TtFullLepKinSolutionProducer::beginJob() { solver = new TtFullLepKinSolver(tmassbegin_, tmassend_, tmassstep_, nupars_); } -void TtFullLepKinSolutionProducer::endJob() -{ - delete solver; -} +void TtFullLepKinSolutionProducer::endJob() { delete solver; } -void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSetup & iSetup) -{ +void TtFullLepKinSolutionProducer::produce(edm::Event& evt, const edm::EventSetup& iSetup) { //create vectors fo runsorted output std::vector > idcsV; std::vector nusV; @@ -120,10 +103,10 @@ void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSet std::vector > weightsV; //create pointer for products - std::unique_ptr > > pIdcs(new std::vector >); + std::unique_ptr > > pIdcs(new std::vector >); std::unique_ptr > pNus(new std::vector); std::unique_ptr > pNuBars(new std::vector); - std::unique_ptr > pWeight(new std::vector); + std::unique_ptr > pWeight(new std::vector); std::unique_ptr pWrongCharge(new bool); edm::Handle > jets; @@ -148,62 +131,73 @@ void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSet bool muonsFound = false; //select Jets (TopJet vector is sorted on ET) - if(jets->size()>=2) { jetsFound = true; } + if (jets->size() >= 2) { + jetsFound = true; + } //select MET (TopMET vector is sorted on ET) - if(!mets->empty()) { METFound = true; } + if (!mets->empty()) { + METFound = true; + } // If we have electrons and muons available, // build a solutions with electrons and muons. - if(muons->size() + electrons->size() >=2) { + if (muons->size() + electrons->size() >= 2) { // select leptons - if(electrons->empty()) mumu = true; - else if(muons->empty()) ee = true; - else if(electrons->size() == 1) { - if(muons->size() == 1) emu = true; - else if(PTComp(&(*electrons)[0], &(*muons)[1])) emu = true; - else mumu = true; - } - else if(electrons->size() > 1) { - if(PTComp(&(*electrons)[1], &(*muons)[0])) ee = true; - else if(muons->size() == 1) emu = true; - else if(PTComp(&(*electrons)[0], &(*muons)[1])) emu = true; - else mumu = true; + if (electrons->empty()) + mumu = true; + else if (muons->empty()) + ee = true; + else if (electrons->size() == 1) { + if (muons->size() == 1) + emu = true; + else if (PTComp(&(*electrons)[0], &(*muons)[1])) + emu = true; + else + mumu = true; + } else if (electrons->size() > 1) { + if (PTComp(&(*electrons)[1], &(*muons)[0])) + ee = true; + else if (muons->size() == 1) + emu = true; + else if (PTComp(&(*electrons)[0], &(*muons)[1])) + emu = true; + else + mumu = true; } - if(ee && eeChannel_) { - if(LepDiffCharge(&(*electrons)[0], &(*electrons)[1]) || searchWrongCharge_) { - if(HasPositiveCharge(&(*electrons)[0]) || !LepDiffCharge(&(*electrons)[0], &(*electrons)[1])) { + if (ee && eeChannel_) { + if (LepDiffCharge(&(*electrons)[0], &(*electrons)[1]) || searchWrongCharge_) { + if (HasPositiveCharge(&(*electrons)[0]) || !LepDiffCharge(&(*electrons)[0], &(*electrons)[1])) { selElectron1 = 0; selElectron2 = 1; - } - else{ + } else { selElectron1 = 1; selElectron2 = 0; - } - electronsFound = true; - if(!LepDiffCharge(&(*electrons)[0], &(*electrons)[1])) isWrongCharge = true; + } + electronsFound = true; + if (!LepDiffCharge(&(*electrons)[0], &(*electrons)[1])) + isWrongCharge = true; } - } - else if(emu && emuChannel_) { - if(LepDiffCharge(&(*electrons)[0], &(*muons)[0]) || searchWrongCharge_) { - selElectron1 = 0; + } else if (emu && emuChannel_) { + if (LepDiffCharge(&(*electrons)[0], &(*muons)[0]) || searchWrongCharge_) { + selElectron1 = 0; selMuon1 = 0; - electronMuonFound = true; - if(!LepDiffCharge(&(*electrons)[0], &(*muons)[0])) isWrongCharge = true; + electronMuonFound = true; + if (!LepDiffCharge(&(*electrons)[0], &(*muons)[0])) + isWrongCharge = true; } - } - else if(mumu && mumuChannel_) { - if(LepDiffCharge(&(*muons)[0], &(*muons)[1]) || searchWrongCharge_) { - if(HasPositiveCharge(&(*muons)[0]) || !LepDiffCharge(&(*muons)[0], &(*muons)[1])) { + } else if (mumu && mumuChannel_) { + if (LepDiffCharge(&(*muons)[0], &(*muons)[1]) || searchWrongCharge_) { + if (HasPositiveCharge(&(*muons)[0]) || !LepDiffCharge(&(*muons)[0], &(*muons)[1])) { selMuon1 = 0; selMuon2 = 1; - } - else { + } else { selMuon1 = 1; selMuon2 = 0; } - muonsFound = true; - if(!LepDiffCharge(&(*muons)[0], &(*muons)[1])) isWrongCharge = true; + muonsFound = true; + if (!LepDiffCharge(&(*muons)[0], &(*muons)[1])) + isWrongCharge = true; } } } @@ -211,180 +205,177 @@ void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSet *pWrongCharge = isWrongCharge; // Check that the above work makes sense - if(int(ee)+int(emu)+int(mumu)>1) { + if (int(ee) + int(emu) + int(mumu) > 1) { edm::LogWarning("TtFullLepKinSolutionProducer") << "Lepton selection criteria uncorrectly defined"; } // Check if the leptons for the required Channel are available - bool correctLeptons = ((electronsFound && eeChannel_) || (muonsFound && mumuChannel_) || (electronMuonFound && emuChannel_) ); + bool correctLeptons = + ((electronsFound && eeChannel_) || (muonsFound && mumuChannel_) || (electronMuonFound && emuChannel_)); // Check for equally charged leptons if for wrong charge combinations is searched - if(isWrongCharge) { correctLeptons = correctLeptons && searchWrongCharge_; } - - if(correctLeptons && METFound && jetsFound) { + if (isWrongCharge) { + correctLeptons = correctLeptons && searchWrongCharge_; + } + if (correctLeptons && METFound && jetsFound) { // run over all jets if input parameter maxNJets is -1 or // adapt maxNJets if number of present jets is smaller than selected // number of jets - int stop=maxNJets_; - if(jets->size()(stop) || stop<0) stop=jets->size(); + int stop = maxNJets_; + if (jets->size() < static_cast(stop) || stop < 0) + stop = jets->size(); // counter for number of found kinematic solutions - int nSol=0; + int nSol = 0; // consider all permutations - for (int ib = 0; ib idcs; + std::vector idcs; - // push back the indices of the jets - idcs.push_back(ib); - idcs.push_back(ibbar); + // push back the indices of the jets + idcs.push_back(ib); + idcs.push_back(ibbar); TLorentzVector LV_l1; TLorentzVector LV_l2; - TLorentzVector LV_b = TLorentzVector((*jets)[ib].correctedJet(jetCorrLevel_, "bottom").px(), - (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").py(), - (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").pz(), - (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").energy() ); + TLorentzVector LV_b = TLorentzVector((*jets)[ib].correctedJet(jetCorrLevel_, "bottom").px(), + (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").py(), + (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").pz(), + (*jets)[ib].correctedJet(jetCorrLevel_, "bottom").energy()); TLorentzVector LV_bbar = TLorentzVector((*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").px(), - (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").py(), - (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").pz(), - (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").energy()); + (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").py(), + (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").pz(), + (*jets)[ibbar].correctedJet(jetCorrLevel_, "bottom").energy()); double xconstraint = 0, yconstraint = 0; - if (ee) { + if (ee) { idcs.push_back(selElectron1); - LV_l1.SetXYZT((*electrons)[selElectron1].px(), - (*electrons)[selElectron1].py(), - (*electrons)[selElectron1].pz(), - (*electrons)[selElectron1].energy()); + LV_l1.SetXYZT((*electrons)[selElectron1].px(), + (*electrons)[selElectron1].py(), + (*electrons)[selElectron1].pz(), + (*electrons)[selElectron1].energy()); xconstraint += (*electrons)[selElectron1].px(); yconstraint += (*electrons)[selElectron1].py(); idcs.push_back(selElectron2); - LV_l2.SetXYZT((*electrons)[selElectron2].px(), - (*electrons)[selElectron2].py(), - (*electrons)[selElectron2].pz(), - (*electrons)[selElectron2].energy()); + LV_l2.SetXYZT((*electrons)[selElectron2].px(), + (*electrons)[selElectron2].py(), + (*electrons)[selElectron2].pz(), + (*electrons)[selElectron2].energy()); xconstraint += (*electrons)[selElectron2].px(); yconstraint += (*electrons)[selElectron2].py(); - idcs.push_back(-1); - idcs.push_back(-1); - } + idcs.push_back(-1); + idcs.push_back(-1); + } - else if (emu) { - if(!isWrongCharge){ - if(HasPositiveCharge(&(*electrons)[selElectron1])){ + else if (emu) { + if (!isWrongCharge) { + if (HasPositiveCharge(&(*electrons)[selElectron1])) { idcs.push_back(selElectron1); - LV_l1.SetXYZT((*electrons)[selElectron1].px(), - (*electrons)[selElectron1].py(), - (*electrons)[selElectron1].pz(), - (*electrons)[selElectron1].energy()); + LV_l1.SetXYZT((*electrons)[selElectron1].px(), + (*electrons)[selElectron1].py(), + (*electrons)[selElectron1].pz(), + (*electrons)[selElectron1].energy()); xconstraint += (*electrons)[selElectron1].px(); yconstraint += (*electrons)[selElectron1].py(); - idcs.push_back(-1); - idcs.push_back(-1); + idcs.push_back(-1); + idcs.push_back(-1); idcs.push_back(selMuon1); - LV_l2.SetXYZT((*muons)[selMuon1].px(), - (*muons)[selMuon1].py(), - (*muons)[selMuon1].pz(), - (*muons)[selMuon1].energy()); + LV_l2.SetXYZT((*muons)[selMuon1].px(), + (*muons)[selMuon1].py(), + (*muons)[selMuon1].pz(), + (*muons)[selMuon1].energy()); xconstraint += (*muons)[selMuon1].px(); yconstraint += (*muons)[selMuon1].py(); - } - else{ - idcs.push_back(-1); + } else { + idcs.push_back(-1); idcs.push_back(selMuon1); - LV_l1.SetXYZT((*muons)[selMuon1].px(), - (*muons)[selMuon1].py(), - (*muons)[selMuon1].pz(), - (*muons)[selMuon1].energy()); + LV_l1.SetXYZT((*muons)[selMuon1].px(), + (*muons)[selMuon1].py(), + (*muons)[selMuon1].pz(), + (*muons)[selMuon1].energy()); xconstraint += (*muons)[selMuon1].px(); yconstraint += (*muons)[selMuon1].py(); idcs.push_back(selElectron1); - LV_l2.SetXYZT((*electrons)[selElectron1].px(), - (*electrons)[selElectron1].py(), - (*electrons)[selElectron1].pz(), - (*electrons)[selElectron1].energy()); + LV_l2.SetXYZT((*electrons)[selElectron1].px(), + (*electrons)[selElectron1].py(), + (*electrons)[selElectron1].pz(), + (*electrons)[selElectron1].energy()); xconstraint += (*electrons)[selElectron1].px(); yconstraint += (*electrons)[selElectron1].py(); - idcs.push_back(-1); - } - } - else{ // means "if wrong charge" - if(HasPositiveCharge(&(*electrons)[selElectron1])){ // both leps positive + idcs.push_back(-1); + } + } else { // means "if wrong charge" + if (HasPositiveCharge(&(*electrons)[selElectron1])) { // both leps positive idcs.push_back(selElectron1); - LV_l1.SetXYZT((*electrons)[selElectron1].px(), - (*electrons)[selElectron1].py(), - (*electrons)[selElectron1].pz(), - (*electrons)[selElectron1].energy()); + LV_l1.SetXYZT((*electrons)[selElectron1].px(), + (*electrons)[selElectron1].py(), + (*electrons)[selElectron1].pz(), + (*electrons)[selElectron1].energy()); xconstraint += (*electrons)[selElectron1].px(); yconstraint += (*electrons)[selElectron1].py(); idcs.push_back(-1); idcs.push_back(selMuon1); - LV_l2.SetXYZT((*muons)[selMuon1].px(), - (*muons)[selMuon1].py(), - (*muons)[selMuon1].pz(), - (*muons)[selMuon1].energy()); + LV_l2.SetXYZT((*muons)[selMuon1].px(), + (*muons)[selMuon1].py(), + (*muons)[selMuon1].pz(), + (*muons)[selMuon1].energy()); xconstraint += (*muons)[selMuon1].px(); yconstraint += (*muons)[selMuon1].py(); - idcs.push_back(-1); - } - else{ // both leps negative - idcs.push_back(-1); + idcs.push_back(-1); + } else { // both leps negative + idcs.push_back(-1); idcs.push_back(selElectron1); - LV_l2.SetXYZT((*electrons)[selElectron1].px(), - (*electrons)[selElectron1].py(), - (*electrons)[selElectron1].pz(), - (*electrons)[selElectron1].energy()); + LV_l2.SetXYZT((*electrons)[selElectron1].px(), + (*electrons)[selElectron1].py(), + (*electrons)[selElectron1].pz(), + (*electrons)[selElectron1].energy()); xconstraint += (*electrons)[selElectron1].px(); yconstraint += (*electrons)[selElectron1].py(); - idcs.push_back(-1); + idcs.push_back(-1); idcs.push_back(selMuon1); - LV_l1.SetXYZT((*muons)[selMuon1].px(), - (*muons)[selMuon1].py(), - (*muons)[selMuon1].pz(), - (*muons)[selMuon1].energy()); + LV_l1.SetXYZT((*muons)[selMuon1].px(), + (*muons)[selMuon1].py(), + (*muons)[selMuon1].pz(), + (*muons)[selMuon1].energy()); xconstraint += (*muons)[selMuon1].px(); yconstraint += (*muons)[selMuon1].py(); - } - } + } + } } - else if (mumu) { - idcs.push_back(-1); - idcs.push_back(-1); + else if (mumu) { + idcs.push_back(-1); + idcs.push_back(-1); idcs.push_back(selMuon1); - LV_l1.SetXYZT((*muons)[selMuon1].px(), - (*muons)[selMuon1].py(), - (*muons)[selMuon1].pz(), - (*muons)[selMuon1].energy()); + LV_l1.SetXYZT( + (*muons)[selMuon1].px(), (*muons)[selMuon1].py(), (*muons)[selMuon1].pz(), (*muons)[selMuon1].energy()); xconstraint += (*muons)[selMuon1].px(); yconstraint += (*muons)[selMuon1].py(); idcs.push_back(selMuon2); - LV_l2.SetXYZT((*muons)[selMuon2].px(), - (*muons)[selMuon2].py(), - (*muons)[selMuon2].pz(), - (*muons)[selMuon2].energy()); + LV_l2.SetXYZT( + (*muons)[selMuon2].px(), (*muons)[selMuon2].py(), (*muons)[selMuon2].pz(), (*muons)[selMuon2].energy()); xconstraint += (*muons)[selMuon2].px(); yconstraint += (*muons)[selMuon2].py(); } @@ -394,34 +385,34 @@ void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSet // calculate neutrino momenta and eventweight solver->SetConstraints(xconstraint, yconstraint); - TtFullLepKinSolver::NeutrinoSolution nuSol= solver->getNuSolution( LV_l1, LV_l2 , LV_b, LV_bbar); + TtFullLepKinSolver::NeutrinoSolution nuSol = solver->getNuSolution(LV_l1, LV_l2, LV_b, LV_bbar); - // add solution to the vectors of solutions if solution exists - if(nuSol.weight>0){ - // add the leptons and jets indices to the vector of combinations - idcsV.push_back(idcs); + // add solution to the vectors of solutions if solution exists + if (nuSol.weight > 0) { + // add the leptons and jets indices to the vector of combinations + idcsV.push_back(idcs); - // add the neutrinos - nusV.push_back(nuSol.neutrino); - nuBarsV.push_back(nuSol.neutrinoBar); + // add the neutrinos + nusV.push_back(nuSol.neutrino); + nuBarsV.push_back(nuSol.neutrinoBar); - // add the solution weight - weightsV.push_back(std::make_pair(nuSol.weight, nSol)); + // add the solution weight + weightsV.push_back(std::make_pair(nuSol.weight, nSol)); - nSol++; - } + nSol++; + } } } } - if(weightsV.empty()){ + if (weightsV.empty()) { //create dmummy vector std::vector idcs; - for(int i=0; i<6; ++i) + for (int i = 0; i < 6; ++i) idcs.push_back(-1); idcsV.push_back(idcs); - weightsV.push_back(std::make_pair(-1,0)); + weightsV.push_back(std::make_pair(-1, 0)); reco::LeafCandidate nu; nusV.push_back(nu); reco::LeafCandidate nuBar; @@ -430,39 +421,38 @@ void TtFullLepKinSolutionProducer::produce(edm::Event & evt, const edm::EventSet // check if all vectors have correct length int weightL = weightsV.size(); - int nuL = nusV.size(); - int nuBarL = nuBarsV.size(); - int idxL = idcsV.size(); - - if(weightL!=nuL || weightL!=nuBarL || weightL!=idxL){ - edm::LogWarning("TtFullLepKinSolutionProducer") << "Output vectors are of different length:" - << "\n weight: " << weightL - << "\n nu: " << nuL - << "\n nubar: " << nuBarL - << "\n idcs: " << idxL; + int nuL = nusV.size(); + int nuBarL = nuBarsV.size(); + int idxL = idcsV.size(); + + if (weightL != nuL || weightL != nuBarL || weightL != idxL) { + edm::LogWarning("TtFullLepKinSolutionProducer") + << "Output vectors are of different length:" + << "\n weight: " << weightL << "\n nu: " << nuL << "\n nubar: " << nuBarL << "\n idcs: " << idxL; } // sort vectors by weight in decreasing order - if(weightsV.size()>1){ + if (weightsV.size() > 1) { sort(weightsV.begin(), weightsV.end(), Compare()); } // determine the number of solutions which is written in the event - int stop=weightL; - if(maxNComb_>0 && maxNComb_ 0 && maxNComb_ < stop) + stop = maxNComb_; - for(int i=0; ipush_back(weightsV[i].first); - pNus ->push_back(nusV[weightsV[i].second]); + pNus->push_back(nusV[weightsV[i].second]); pNuBars->push_back(nuBarsV[weightsV[i].second]); - pIdcs ->push_back(idcsV[weightsV[i].second]); + pIdcs->push_back(idcsV[weightsV[i].second]); } // put the results in the event evt.put(std::move(pIdcs)); - evt.put(std::move(pNus), "fullLepNeutrinos"); - evt.put(std::move(pNuBars), "fullLepNeutrinoBars"); - evt.put(std::move(pWeight), "solWeight"); + evt.put(std::move(pNus), "fullLepNeutrinos"); + evt.put(std::move(pNuBars), "fullLepNeutrinoBars"); + evt.put(std::move(pWeight), "solWeight"); evt.put(std::move(pWrongCharge), "isWrongCharge"); } diff --git a/TopQuarkAnalysis/TopKinFitter/plugins/TtSemiLepKinFitProducer.h b/TopQuarkAnalysis/TopKinFitter/plugins/TtSemiLepKinFitProducer.h index f62811bb5e7a1..8075c99ab24fa 100644 --- a/TopQuarkAnalysis/TopKinFitter/plugins/TtSemiLepKinFitProducer.h +++ b/TopQuarkAnalysis/TopKinFitter/plugins/TtSemiLepKinFitProducer.h @@ -11,13 +11,11 @@ template class TtSemiLepKinFitProducer : public edm::EDProducer { - - public: - +public: explicit TtSemiLepKinFitProducer(const edm::ParameterSet&); ~TtSemiLepKinFitProducer() override; - private: +private: // produce void produce(edm::Event&, const edm::EventSetup&) override; @@ -28,14 +26,18 @@ class TtSemiLepKinFitProducer : public edm::EDProducer { // convert unsigned to Param std::vector constraints(std::vector&); // helper function for b-tagging - bool doBTagging(bool& useBTag_, edm::Handle >& jets, std::vector& combi, - std::string& bTagAlgo_, double& minBTagValueBJets_, double& maxBTagValueNonBJets_); - - edm::EDGetTokenT > jetsToken_; + bool doBTagging(bool& useBTag_, + edm::Handle>& jets, + std::vector& combi, + std::string& bTagAlgo_, + double& minBTagValueBJets_, + double& maxBTagValueNonBJets_); + + edm::EDGetTokenT> jetsToken_; edm::EDGetTokenT lepsToken_; edm::EDGetTokenT> metsToken_; - edm::EDGetTokenT > > matchToken_; + edm::EDGetTokenT>> matchToken_; /// switch to use only a combination given by another hypothesis bool useOnlyMatch_; /// input tag for b-tagging algorithm @@ -86,111 +88,126 @@ class TtSemiLepKinFitProducer : public edm::EDProducer { pat::Particle LepL; pat::Particle LepN; std::vector JetCombi; - bool operator< (const KinFitResult& rhs) { return Chi2 < rhs.Chi2; }; + bool operator<(const KinFitResult& rhs) { return Chi2 < rhs.Chi2; }; }; }; -template -TtSemiLepKinFitProducer::TtSemiLepKinFitProducer(const edm::ParameterSet& cfg): - jetsToken_ (consumes >(cfg.getParameter("jets"))), - lepsToken_ (consumes(cfg.getParameter("leps"))), - metsToken_ (consumes >(cfg.getParameter("mets"))), - matchToken_ (mayConsume > >(cfg.getParameter("match"))), - useOnlyMatch_ (cfg.getParameter ("useOnlyMatch" )), - bTagAlgo_ (cfg.getParameter ("bTagAlgo" )), - minBTagValueBJet_ (cfg.getParameter ("minBDiscBJets" )), - maxBTagValueNonBJet_ (cfg.getParameter ("maxBDiscLightJets" )), - useBTag_ (cfg.getParameter ("useBTagging" )), - maxNJets_ (cfg.getParameter ("maxNJets" )), - maxNComb_ (cfg.getParameter ("maxNComb" )), - maxNrIter_ (cfg.getParameter ("maxNrIter" )), - maxDeltaS_ (cfg.getParameter ("maxDeltaS" )), - maxF_ (cfg.getParameter ("maxF" )), - jetParam_ (cfg.getParameter ("jetParametrisation" )), - lepParam_ (cfg.getParameter ("lepParametrisation" )), - metParam_ (cfg.getParameter ("metParametrisation" )), - constraints_ (cfg.getParameter >("constraints")), - mW_ (cfg.getParameter ("mW" )), - mTop_ (cfg.getParameter ("mTop" )), - jetEnergyResolutionScaleFactors_(cfg.getParameter >("jetEnergyResolutionScaleFactors")), - jetEnergyResolutionEtaBinning_ (cfg.getParameter >("jetEnergyResolutionEtaBinning")), - udscResolutions_(0), bResolutions_(0), lepResolutions_(0), metResolutions_(0) -{ - if(cfg.exists("udscResolutions") && cfg.exists("bResolutions") && cfg.exists("lepResolutions") && cfg.exists("metResolutions")){ - udscResolutions_ = cfg.getParameter >("udscResolutions"); - bResolutions_ = cfg.getParameter >("bResolutions" ); - lepResolutions_ = cfg.getParameter >("lepResolutions" ); - metResolutions_ = cfg.getParameter >("metResolutions" ); - } - else if(cfg.exists("udscResolutions") || cfg.exists("bResolutions") || cfg.exists("lepResolutions") || cfg.exists("metResolutions") ){ - throw cms::Exception("Configuration") << "Parameters 'udscResolutions', 'bResolutions', 'lepResolutions', 'metResolutions' should be used together.\n"; +template +TtSemiLepKinFitProducer::TtSemiLepKinFitProducer(const edm::ParameterSet& cfg) + : jetsToken_(consumes>(cfg.getParameter("jets"))), + lepsToken_(consumes(cfg.getParameter("leps"))), + metsToken_(consumes>(cfg.getParameter("mets"))), + matchToken_(mayConsume>>(cfg.getParameter("match"))), + useOnlyMatch_(cfg.getParameter("useOnlyMatch")), + bTagAlgo_(cfg.getParameter("bTagAlgo")), + minBTagValueBJet_(cfg.getParameter("minBDiscBJets")), + maxBTagValueNonBJet_(cfg.getParameter("maxBDiscLightJets")), + useBTag_(cfg.getParameter("useBTagging")), + maxNJets_(cfg.getParameter("maxNJets")), + maxNComb_(cfg.getParameter("maxNComb")), + maxNrIter_(cfg.getParameter("maxNrIter")), + maxDeltaS_(cfg.getParameter("maxDeltaS")), + maxF_(cfg.getParameter("maxF")), + jetParam_(cfg.getParameter("jetParametrisation")), + lepParam_(cfg.getParameter("lepParametrisation")), + metParam_(cfg.getParameter("metParametrisation")), + constraints_(cfg.getParameter>("constraints")), + mW_(cfg.getParameter("mW")), + mTop_(cfg.getParameter("mTop")), + jetEnergyResolutionScaleFactors_(cfg.getParameter>("jetEnergyResolutionScaleFactors")), + jetEnergyResolutionEtaBinning_(cfg.getParameter>("jetEnergyResolutionEtaBinning")), + udscResolutions_(0), + bResolutions_(0), + lepResolutions_(0), + metResolutions_(0) { + if (cfg.exists("udscResolutions") && cfg.exists("bResolutions") && cfg.exists("lepResolutions") && + cfg.exists("metResolutions")) { + udscResolutions_ = cfg.getParameter>("udscResolutions"); + bResolutions_ = cfg.getParameter>("bResolutions"); + lepResolutions_ = cfg.getParameter>("lepResolutions"); + metResolutions_ = cfg.getParameter>("metResolutions"); + } else if (cfg.exists("udscResolutions") || cfg.exists("bResolutions") || cfg.exists("lepResolutions") || + cfg.exists("metResolutions")) { + throw cms::Exception("Configuration") << "Parameters 'udscResolutions', 'bResolutions', 'lepResolutions', " + "'metResolutions' should be used together.\n"; } - fitter = new TtSemiLepKinFitter(param(jetParam_), param(lepParam_), param(metParam_), maxNrIter_, maxDeltaS_, maxF_, - constraints(constraints_), mW_, mTop_, &udscResolutions_, &bResolutions_, &lepResolutions_, &metResolutions_, - &jetEnergyResolutionScaleFactors_, &jetEnergyResolutionEtaBinning_); - - produces< std::vector >("PartonsHadP"); - produces< std::vector >("PartonsHadQ"); - produces< std::vector >("PartonsHadB"); - produces< std::vector >("PartonsLepB"); - produces< std::vector >("Leptons"); - produces< std::vector >("Neutrinos"); - - produces< std::vector > >(); - produces< std::vector >("Chi2"); - produces< std::vector >("Prob"); - produces< std::vector >("Status"); + fitter = new TtSemiLepKinFitter(param(jetParam_), + param(lepParam_), + param(metParam_), + maxNrIter_, + maxDeltaS_, + maxF_, + constraints(constraints_), + mW_, + mTop_, + &udscResolutions_, + &bResolutions_, + &lepResolutions_, + &metResolutions_, + &jetEnergyResolutionScaleFactors_, + &jetEnergyResolutionEtaBinning_); + + produces>("PartonsHadP"); + produces>("PartonsHadQ"); + produces>("PartonsHadB"); + produces>("PartonsLepB"); + produces>("Leptons"); + produces>("Neutrinos"); + + produces>>(); + produces>("Chi2"); + produces>("Prob"); + produces>("Status"); produces("NumberOfConsideredJets"); } -template -TtSemiLepKinFitProducer::~TtSemiLepKinFitProducer() -{ +template +TtSemiLepKinFitProducer::~TtSemiLepKinFitProducer() { delete fitter; } -template -bool TtSemiLepKinFitProducer::doBTagging(bool& useBTag_, edm::Handle >& jets, std::vector& combi, - std::string& bTagAlgo_, double& minBTagValueBJet_, double& maxBTagValueNonBJet_){ - - if( !useBTag_ ) { +template +bool TtSemiLepKinFitProducer::doBTagging(bool& useBTag_, + edm::Handle>& jets, + std::vector& combi, + std::string& bTagAlgo_, + double& minBTagValueBJet_, + double& maxBTagValueNonBJet_) { + if (!useBTag_) { return true; } - if( useBTag_ && - (*jets)[combi[TtSemiLepEvtPartons::HadB ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - (*jets)[combi[TtSemiLepEvtPartons::LepB ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - (*jets)[combi[TtSemiLepEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - (*jets)[combi[TtSemiLepEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + if (useBTag_ && (*jets)[combi[TtSemiLepEvtPartons::HadB]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + (*jets)[combi[TtSemiLepEvtPartons::LepB]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + (*jets)[combi[TtSemiLepEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + (*jets)[combi[TtSemiLepEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; - } - else{ + } else { return false; } } -template -void TtSemiLepKinFitProducer::produce(edm::Event& evt, const edm::EventSetup& setup) -{ - std::unique_ptr< std::vector > pPartonsHadP( new std::vector ); - std::unique_ptr< std::vector > pPartonsHadQ( new std::vector ); - std::unique_ptr< std::vector > pPartonsHadB( new std::vector ); - std::unique_ptr< std::vector > pPartonsLepB( new std::vector ); - std::unique_ptr< std::vector > pLeptons ( new std::vector ); - std::unique_ptr< std::vector > pNeutrinos ( new std::vector ); - - std::unique_ptr< std::vector > > pCombi ( new std::vector > ); - std::unique_ptr< std::vector > pChi2 ( new std::vector ); - std::unique_ptr< std::vector > pProb ( new std::vector ); - std::unique_ptr< std::vector > pStatus( new std::vector ); +template +void TtSemiLepKinFitProducer::produce(edm::Event& evt, const edm::EventSetup& setup) { + std::unique_ptr> pPartonsHadP(new std::vector); + std::unique_ptr> pPartonsHadQ(new std::vector); + std::unique_ptr> pPartonsHadB(new std::vector); + std::unique_ptr> pPartonsLepB(new std::vector); + std::unique_ptr> pLeptons(new std::vector); + std::unique_ptr> pNeutrinos(new std::vector); + + std::unique_ptr>> pCombi(new std::vector>); + std::unique_ptr> pChi2(new std::vector); + std::unique_ptr> pProb(new std::vector); + std::unique_ptr> pStatus(new std::vector); std::unique_ptr pJetsConsidered(new int); - edm::Handle > jets; + edm::Handle> jets; evt.getByToken(jetsToken_, jets); - edm::Handle > mets; + edm::Handle> mets; evt.getByToken(metsToken_, mets); edm::Handle leps; @@ -200,19 +217,20 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e std::vector match; bool invalidMatch = false; - if(useOnlyMatch_) { + if (useOnlyMatch_) { *pJetsConsidered = nPartons; - edm::Handle > > matchHandle; + edm::Handle>> matchHandle; evt.getByToken(matchToken_, matchHandle); match = *(matchHandle->begin()); // check if match is valid - if(match.size()!=nPartons) invalidMatch=true; + if (match.size() != nPartons) + invalidMatch = true; else { - for(unsigned int idx=0; idx=(int)jets->size()) { - invalidMatch=true; - break; - } + for (unsigned int idx = 0; idx < match.size(); ++idx) { + if (match[idx] < 0 || match[idx] >= (int)jets->size()) { + invalidMatch = true; + break; + } } } } @@ -222,25 +240,25 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e // or empty MET or less jets than partons or invalid match // ----------------------------------------------------- - if( leps->empty() || mets->empty() || jets->size()empty() || mets->empty() || jets->size() < nPartons || invalidMatch) { // the kinFit getters return empty objects here - pPartonsHadP->push_back( fitter->fittedHadP() ); - pPartonsHadQ->push_back( fitter->fittedHadQ() ); - pPartonsHadB->push_back( fitter->fittedHadB() ); - pPartonsLepB->push_back( fitter->fittedLepB() ); - pLeptons ->push_back( fitter->fittedLepton() ); - pNeutrinos ->push_back( fitter->fittedNeutrino() ); + pPartonsHadP->push_back(fitter->fittedHadP()); + pPartonsHadQ->push_back(fitter->fittedHadQ()); + pPartonsHadB->push_back(fitter->fittedHadB()); + pPartonsLepB->push_back(fitter->fittedLepB()); + pLeptons->push_back(fitter->fittedLepton()); + pNeutrinos->push_back(fitter->fittedNeutrino()); // indices referring to the jet combination std::vector invalidCombi; - for(unsigned int i = 0; i < nPartons; ++i) - invalidCombi.push_back( -1 ); - pCombi->push_back( invalidCombi ); + for (unsigned int i = 0; i < nPartons; ++i) + invalidCombi.push_back(-1); + pCombi->push_back(invalidCombi); // chi2 - pChi2->push_back( -1. ); + pChi2->push_back(-1.); // chi2 probability - pProb->push_back( -1. ); + pProb->push_back(-1.); // status of the fitter - pStatus->push_back( -1 ); + pStatus->push_back(-1); // number of jets *pJetsConsidered = jets->size(); // feed out all products @@ -249,11 +267,11 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e evt.put(std::move(pPartonsHadQ), "PartonsHadQ"); evt.put(std::move(pPartonsHadB), "PartonsHadB"); evt.put(std::move(pPartonsLepB), "PartonsLepB"); - evt.put(std::move(pLeptons ), "Leptons" ); - evt.put(std::move(pNeutrinos ), "Neutrinos" ); - evt.put(std::move(pChi2 ), "Chi2" ); - evt.put(std::move(pProb ), "Prob" ); - evt.put(std::move(pStatus ), "Status" ); + evt.put(std::move(pLeptons), "Leptons"); + evt.put(std::move(pNeutrinos), "Neutrinos"); + evt.put(std::move(pChi2), "Chi2"); + evt.put(std::move(pProb), "Prob"); + evt.put(std::move(pStatus), "Status"); evt.put(std::move(pJetsConsidered), "NumberOfConsideredJets"); return; } @@ -264,64 +282,65 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e // ----------------------------------------------------- std::vector jetIndices; - if(!useOnlyMatch_) { - for(unsigned int i=0; isize(); ++i){ - if(maxNJets_ >= (int) nPartons && maxNJets_ == (int) i) { - *pJetsConsidered = i; - break; + if (!useOnlyMatch_) { + for (unsigned int i = 0; i < jets->size(); ++i) { + if (maxNJets_ >= (int)nPartons && maxNJets_ == (int)i) { + *pJetsConsidered = i; + break; } jetIndices.push_back(i); } } std::vector combi; - for(unsigned int i=0; i FitResultList; - do{ - for(int cnt = 0; cnt < TMath::Factorial( combi.size() ); ++cnt){ + do { + for (int cnt = 0; cnt < TMath::Factorial(combi.size()); ++cnt) { // take into account indistinguishability of the two jets from the hadr. W decay, // reduces combinatorics by a factor of 2 - if( (combi[TtSemiLepEvtPartons::LightQ] < combi[TtSemiLepEvtPartons::LightQBar] - || useOnlyMatch_ ) && doBTagging(useBTag_, jets, combi, bTagAlgo_, minBTagValueBJet_, maxBTagValueNonBJet_) ){ - - std::vector jetCombi; - jetCombi.resize(nPartons); - jetCombi[TtSemiLepEvtPartons::LightQ ] = (*jets)[combi[TtSemiLepEvtPartons::LightQ ]]; - jetCombi[TtSemiLepEvtPartons::LightQBar] = (*jets)[combi[TtSemiLepEvtPartons::LightQBar]]; - jetCombi[TtSemiLepEvtPartons::HadB ] = (*jets)[combi[TtSemiLepEvtPartons::HadB ]]; - jetCombi[TtSemiLepEvtPartons::LepB ] = (*jets)[combi[TtSemiLepEvtPartons::LepB ]]; - - // do the kinematic fit - const int status = fitter->fit(jetCombi, (*leps)[0], (*mets)[0]); - - if( status == 0 ) { // only take into account converged fits - KinFitResult result; - result.Status = status; - result.Chi2 = fitter->fitS(); - result.Prob = fitter->fitProb(); - result.HadB = fitter->fittedHadB(); - result.HadP = fitter->fittedHadP(); - result.HadQ = fitter->fittedHadQ(); - result.LepB = fitter->fittedLepB(); - result.LepL = fitter->fittedLepton(); - result.LepN = fitter->fittedNeutrino(); - result.JetCombi = combi; - - FitResultList.push_back(result); - } - + if ((combi[TtSemiLepEvtPartons::LightQ] < combi[TtSemiLepEvtPartons::LightQBar] || useOnlyMatch_) && + doBTagging(useBTag_, jets, combi, bTagAlgo_, minBTagValueBJet_, maxBTagValueNonBJet_)) { + std::vector jetCombi; + jetCombi.resize(nPartons); + jetCombi[TtSemiLepEvtPartons::LightQ] = (*jets)[combi[TtSemiLepEvtPartons::LightQ]]; + jetCombi[TtSemiLepEvtPartons::LightQBar] = (*jets)[combi[TtSemiLepEvtPartons::LightQBar]]; + jetCombi[TtSemiLepEvtPartons::HadB] = (*jets)[combi[TtSemiLepEvtPartons::HadB]]; + jetCombi[TtSemiLepEvtPartons::LepB] = (*jets)[combi[TtSemiLepEvtPartons::LepB]]; + + // do the kinematic fit + const int status = fitter->fit(jetCombi, (*leps)[0], (*mets)[0]); + + if (status == 0) { // only take into account converged fits + KinFitResult result; + result.Status = status; + result.Chi2 = fitter->fitS(); + result.Prob = fitter->fitProb(); + result.HadB = fitter->fittedHadB(); + result.HadP = fitter->fittedHadP(); + result.HadQ = fitter->fittedHadQ(); + result.LepB = fitter->fittedLepB(); + result.LepL = fitter->fittedLepton(); + result.LepN = fitter->fittedNeutrino(); + result.JetCombi = combi; + + FitResultList.push_back(result); + } } - if(useOnlyMatch_) break; // don't go through combinatorics if useOnlyMatch was chosen - next_permutation( combi.begin(), combi.end() ); + if (useOnlyMatch_) + break; // don't go through combinatorics if useOnlyMatch was chosen + next_permutation(combi.begin(), combi.end()); } - if(useOnlyMatch_) break; // don't go through combinatorics if useOnlyMatch was chosen - } - while(stdcomb::next_combination( jetIndices.begin(), jetIndices.end(), combi.begin(), combi.end() )); + if (useOnlyMatch_) + break; // don't go through combinatorics if useOnlyMatch was chosen + } while (stdcomb::next_combination(jetIndices.begin(), jetIndices.end(), combi.begin(), combi.end())); // sort results w.r.t. chi2 values FitResultList.sort(); @@ -331,47 +350,48 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e // starting with the JetComb having the smallest chi2 // ----------------------------------------------------- - if( (unsigned)FitResultList.size() < 1 ) { // in case no fit results were stored in the list (all fits aborted) - pPartonsHadP->push_back( fitter->fittedHadP() ); - pPartonsHadQ->push_back( fitter->fittedHadQ() ); - pPartonsHadB->push_back( fitter->fittedHadB() ); - pPartonsLepB->push_back( fitter->fittedLepB() ); - pLeptons ->push_back( fitter->fittedLepton() ); - pNeutrinos ->push_back( fitter->fittedNeutrino() ); + if ((unsigned)FitResultList.size() < 1) { // in case no fit results were stored in the list (all fits aborted) + pPartonsHadP->push_back(fitter->fittedHadP()); + pPartonsHadQ->push_back(fitter->fittedHadQ()); + pPartonsHadB->push_back(fitter->fittedHadB()); + pPartonsLepB->push_back(fitter->fittedLepB()); + pLeptons->push_back(fitter->fittedLepton()); + pNeutrinos->push_back(fitter->fittedNeutrino()); // indices referring to the jet combination std::vector invalidCombi; - for(unsigned int i = 0; i < nPartons; ++i) - invalidCombi.push_back( -1 ); - pCombi->push_back( invalidCombi ); + for (unsigned int i = 0; i < nPartons; ++i) + invalidCombi.push_back(-1); + pCombi->push_back(invalidCombi); // chi2 - pChi2->push_back( -1. ); + pChi2->push_back(-1.); // chi2 probability - pProb->push_back( -1. ); + pProb->push_back(-1.); // status of the fitter - pStatus->push_back( -1 ); - } - else { + pStatus->push_back(-1); + } else { unsigned int iComb = 0; - for(typename std::list::const_iterator result = FitResultList.begin(); result != FitResultList.end(); ++result) { - if(maxNComb_ >= 1 && iComb == (unsigned int) maxNComb_) break; + for (typename std::list::const_iterator result = FitResultList.begin(); result != FitResultList.end(); + ++result) { + if (maxNComb_ >= 1 && iComb == (unsigned int)maxNComb_) + break; iComb++; // partons - pPartonsHadP->push_back( result->HadP ); - pPartonsHadQ->push_back( result->HadQ ); - pPartonsHadB->push_back( result->HadB ); - pPartonsLepB->push_back( result->LepB ); + pPartonsHadP->push_back(result->HadP); + pPartonsHadQ->push_back(result->HadQ); + pPartonsHadB->push_back(result->HadB); + pPartonsLepB->push_back(result->LepB); // lepton - pLeptons->push_back( result->LepL ); + pLeptons->push_back(result->LepL); // neutrino - pNeutrinos->push_back( result->LepN ); + pNeutrinos->push_back(result->LepN); // indices referring to the jet combination - pCombi->push_back( result->JetCombi ); + pCombi->push_back(result->JetCombi); // chi2 - pChi2->push_back( result->Chi2 ); + pChi2->push_back(result->Chi2); // chi2 probability - pProb->push_back( result->Prob ); + pProb->push_back(result->Prob); // status of the fitter - pStatus->push_back( result->Status ); + pStatus->push_back(result->Status); } } evt.put(std::move(pCombi)); @@ -379,55 +399,71 @@ void TtSemiLepKinFitProducer::produce(edm::Event& evt, const e evt.put(std::move(pPartonsHadQ), "PartonsHadQ"); evt.put(std::move(pPartonsHadB), "PartonsHadB"); evt.put(std::move(pPartonsLepB), "PartonsLepB"); - evt.put(std::move(pLeptons ), "Leptons" ); - evt.put(std::move(pNeutrinos ), "Neutrinos" ); - evt.put(std::move(pChi2 ), "Chi2" ); - evt.put(std::move(pProb ), "Prob" ); - evt.put(std::move(pStatus ), "Status" ); + evt.put(std::move(pLeptons), "Leptons"); + evt.put(std::move(pNeutrinos), "Neutrinos"); + evt.put(std::move(pChi2), "Chi2"); + evt.put(std::move(pProb), "Prob"); + evt.put(std::move(pStatus), "Status"); evt.put(std::move(pJetsConsidered), "NumberOfConsideredJets"); } -template -TtSemiLepKinFitter::Param TtSemiLepKinFitProducer::param(unsigned val) -{ +template +TtSemiLepKinFitter::Param TtSemiLepKinFitProducer::param(unsigned val) { TtSemiLepKinFitter::Param result; - switch(val){ - case TtSemiLepKinFitter::kEMom : result=TtSemiLepKinFitter::kEMom; break; - case TtSemiLepKinFitter::kEtEtaPhi : result=TtSemiLepKinFitter::kEtEtaPhi; break; - case TtSemiLepKinFitter::kEtThetaPhi : result=TtSemiLepKinFitter::kEtThetaPhi; break; - default: - throw cms::Exception("Configuration") - << "Chosen jet parametrization is not supported: " << val << "\n"; - break; + switch (val) { + case TtSemiLepKinFitter::kEMom: + result = TtSemiLepKinFitter::kEMom; + break; + case TtSemiLepKinFitter::kEtEtaPhi: + result = TtSemiLepKinFitter::kEtEtaPhi; + break; + case TtSemiLepKinFitter::kEtThetaPhi: + result = TtSemiLepKinFitter::kEtThetaPhi; + break; + default: + throw cms::Exception("Configuration") << "Chosen jet parametrization is not supported: " << val << "\n"; + break; } return result; } -template -TtSemiLepKinFitter::Constraint TtSemiLepKinFitProducer::constraint(unsigned val) -{ +template +TtSemiLepKinFitter::Constraint TtSemiLepKinFitProducer::constraint(unsigned val) { TtSemiLepKinFitter::Constraint result; - switch(val){ - case TtSemiLepKinFitter::kWHadMass : result=TtSemiLepKinFitter::kWHadMass; break; - case TtSemiLepKinFitter::kWLepMass : result=TtSemiLepKinFitter::kWLepMass; break; - case TtSemiLepKinFitter::kTopHadMass : result=TtSemiLepKinFitter::kTopHadMass; break; - case TtSemiLepKinFitter::kTopLepMass : result=TtSemiLepKinFitter::kTopLepMass; break; - case TtSemiLepKinFitter::kNeutrinoMass : result=TtSemiLepKinFitter::kNeutrinoMass; break; - case TtSemiLepKinFitter::kEqualTopMasses : result=TtSemiLepKinFitter::kEqualTopMasses; break; - case TtSemiLepKinFitter::kSumPt : result=TtSemiLepKinFitter::kSumPt; break; - default: - throw cms::Exception("Configuration") - << "Chosen fit constraint is not supported: " << val << "\n"; - break; + switch (val) { + case TtSemiLepKinFitter::kWHadMass: + result = TtSemiLepKinFitter::kWHadMass; + break; + case TtSemiLepKinFitter::kWLepMass: + result = TtSemiLepKinFitter::kWLepMass; + break; + case TtSemiLepKinFitter::kTopHadMass: + result = TtSemiLepKinFitter::kTopHadMass; + break; + case TtSemiLepKinFitter::kTopLepMass: + result = TtSemiLepKinFitter::kTopLepMass; + break; + case TtSemiLepKinFitter::kNeutrinoMass: + result = TtSemiLepKinFitter::kNeutrinoMass; + break; + case TtSemiLepKinFitter::kEqualTopMasses: + result = TtSemiLepKinFitter::kEqualTopMasses; + break; + case TtSemiLepKinFitter::kSumPt: + result = TtSemiLepKinFitter::kSumPt; + break; + default: + throw cms::Exception("Configuration") << "Chosen fit constraint is not supported: " << val << "\n"; + break; } return result; } -template -std::vector TtSemiLepKinFitProducer::constraints(std::vector& val) -{ +template +std::vector TtSemiLepKinFitProducer::constraints( + std::vector& val) { std::vector result; - for(unsigned i=0; i& udscResolutions, const std::vector& bResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning): - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning) -{ - for(std::vector::const_iterator iSet = udscResolutions.begin(); iSet != udscResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsUdsc_.push_back(iSet->getParameter("bin")); - else if(udscResolutions.size()==1) binsUdsc_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - +CovarianceMatrix::CovarianceMatrix(const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning) + : jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning) { + for (std::vector::const_iterator iSet = udscResolutions.begin(); iSet != udscResolutions.end(); + ++iSet) { + if (iSet->exists("bin")) + binsUdsc_.push_back(iSet->getParameter("bin")); + else if (udscResolutions.size() == 1) + binsUdsc_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtUdsc_.push_back(iSet->getParameter("et")); funcEtaUdsc_.push_back(iSet->getParameter("eta")); funcPhiUdsc_.push_back(iSet->getParameter("phi")); } - for(std::vector::const_iterator iSet = bResolutions.begin(); iSet != bResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsB_.push_back(iSet->getParameter("bin")); - else if(bResolutions.size()==1) binsB_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - + for (std::vector::const_iterator iSet = bResolutions.begin(); iSet != bResolutions.end(); ++iSet) { + if (iSet->exists("bin")) + binsB_.push_back(iSet->getParameter("bin")); + else if (bResolutions.size() == 1) + binsB_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtB_.push_back(iSet->getParameter("et")); funcEtaB_.push_back(iSet->getParameter("eta")); funcPhiB_.push_back(iSet->getParameter("phi")); } } -CovarianceMatrix::CovarianceMatrix(const std::vector& udscResolutions, const std::vector& bResolutions, - const std::vector& lepResolutions, const std::vector& metResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning): - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning) -{ - if(jetEnergyResolutionScaleFactors_.size()+1!=jetEnergyResolutionEtaBinning_.size()) +CovarianceMatrix::CovarianceMatrix(const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& lepResolutions, + const std::vector& metResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning) + : jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning) { + if (jetEnergyResolutionScaleFactors_.size() + 1 != jetEnergyResolutionEtaBinning_.size()) throw cms::Exception("Configuration") << "The number of scale factors does not fit to the number of eta bins!\n"; - for(unsigned int i=0; i::const_iterator iSet = udscResolutions.begin(); iSet != udscResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsUdsc_.push_back(iSet->getParameter("bin")); - else if(udscResolutions.size()==1) binsUdsc_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - + for (std::vector::const_iterator iSet = udscResolutions.begin(); iSet != udscResolutions.end(); + ++iSet) { + if (iSet->exists("bin")) + binsUdsc_.push_back(iSet->getParameter("bin")); + else if (udscResolutions.size() == 1) + binsUdsc_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtUdsc_.push_back(iSet->getParameter("et")); funcEtaUdsc_.push_back(iSet->getParameter("eta")); funcPhiUdsc_.push_back(iSet->getParameter("phi")); } - for(std::vector::const_iterator iSet = bResolutions.begin(); iSet != bResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsB_.push_back(iSet->getParameter("bin")); - else if(bResolutions.size()==1) binsB_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - + for (std::vector::const_iterator iSet = bResolutions.begin(); iSet != bResolutions.end(); ++iSet) { + if (iSet->exists("bin")) + binsB_.push_back(iSet->getParameter("bin")); + else if (bResolutions.size() == 1) + binsB_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtB_.push_back(iSet->getParameter("et")); funcEtaB_.push_back(iSet->getParameter("eta")); funcPhiB_.push_back(iSet->getParameter("phi")); } - for(std::vector::const_iterator iSet = lepResolutions.begin(); iSet != lepResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsLep_.push_back(iSet->getParameter("bin")); - else if(lepResolutions.size()==1) binsLep_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - + for (std::vector::const_iterator iSet = lepResolutions.begin(); iSet != lepResolutions.end(); + ++iSet) { + if (iSet->exists("bin")) + binsLep_.push_back(iSet->getParameter("bin")); + else if (lepResolutions.size() == 1) + binsLep_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtLep_.push_back(iSet->getParameter("et")); funcEtaLep_.push_back(iSet->getParameter("eta")); funcPhiLep_.push_back(iSet->getParameter("phi")); } - for(std::vector::const_iterator iSet = metResolutions.begin(); iSet != metResolutions.end(); ++iSet){ - if(iSet->exists("bin")) binsMet_.push_back(iSet->getParameter("bin")); - else if(metResolutions.size()==1) binsMet_.push_back(""); - else throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; - + for (std::vector::const_iterator iSet = metResolutions.begin(); iSet != metResolutions.end(); + ++iSet) { + if (iSet->exists("bin")) + binsMet_.push_back(iSet->getParameter("bin")); + else if (metResolutions.size() == 1) + binsMet_.push_back(""); + else + throw cms::Exception("Configuration") << "Parameter 'bin' is needed if more than one PSet is specified!\n"; + funcEtMet_.push_back(iSet->getParameter("et")); funcEtaMet_.push_back(iSet->getParameter("eta")); funcPhiMet_.push_back(iSet->getParameter("phi")); } } -double CovarianceMatrix::getResolution(const TLorentzVector& object, const ObjectType objType, const std::string& whichResolution) -{ - std::vector * bins_, * funcEt_, * funcEta_, * funcPhi_; +double CovarianceMatrix::getResolution(const TLorentzVector& object, + const ObjectType objType, + const std::string& whichResolution) { + std::vector*bins_, *funcEt_, *funcEta_, *funcPhi_; - switch(objType) { - case kUdscJet: - bins_ = &binsUdsc_; - funcEt_ = &funcEtUdsc_; - funcEta_ = &funcEtaUdsc_; - funcPhi_ = &funcPhiUdsc_; - break; - case kBJet: - bins_ = &binsB_; - funcEt_ = &funcEtB_; - funcEta_ = &funcEtaB_; - funcPhi_ = &funcPhiB_; - break; - case kMuon: - bins_ = &binsLep_; - funcEt_ = &funcEtLep_; - funcEta_ = &funcEtaLep_; - funcPhi_ = &funcPhiLep_; - break; - case kElectron: - bins_ = &binsLep_; - funcEt_ = &funcEtLep_; - funcEta_ = &funcEtaLep_; - funcPhi_ = &funcPhiLep_; - break; - case kMet: - bins_ = &binsMet_; - funcEt_ = &funcEtMet_; - funcEta_ = &funcEtaMet_; - funcPhi_ = &funcPhiMet_; - break; - default: - throw cms::Exception("UnsupportedObject") << "The object given is not supported!\n"; + switch (objType) { + case kUdscJet: + bins_ = &binsUdsc_; + funcEt_ = &funcEtUdsc_; + funcEta_ = &funcEtaUdsc_; + funcPhi_ = &funcPhiUdsc_; + break; + case kBJet: + bins_ = &binsB_; + funcEt_ = &funcEtB_; + funcEta_ = &funcEtaB_; + funcPhi_ = &funcPhiB_; + break; + case kMuon: + bins_ = &binsLep_; + funcEt_ = &funcEtLep_; + funcEta_ = &funcEtaLep_; + funcPhi_ = &funcPhiLep_; + break; + case kElectron: + bins_ = &binsLep_; + funcEt_ = &funcEtLep_; + funcEta_ = &funcEtaLep_; + funcPhi_ = &funcPhiLep_; + break; + case kMet: + bins_ = &binsMet_; + funcEt_ = &funcEtMet_; + funcEta_ = &funcEtaMet_; + funcPhi_ = &funcPhiMet_; + break; + default: + throw cms::Exception("UnsupportedObject") << "The object given is not supported!\n"; } - int selectedBin=-1; + int selectedBin = -1; reco::LeafCandidate candidate; - for(unsigned int i=0; isize(); ++i){ + for (unsigned int i = 0; i < bins_->size(); ++i) { StringCutObjectSelector select_(bins_->at(i)); - candidate = reco::LeafCandidate( 0, reco::LeafCandidate::LorentzVector(object.Px(), object.Py(), object.Pz(), object.Energy()) ); - if(select_(candidate)){ + candidate = reco::LeafCandidate( + 0, reco::LeafCandidate::LorentzVector(object.Px(), object.Py(), object.Pz(), object.Energy())); + if (select_(candidate)) { selectedBin = i; break; } } double res = 0; - if(selectedBin>=0){ - if(whichResolution == "et") res = StringObjectFunction(funcEt_ ->at(selectedBin)).operator()(candidate); - else if(whichResolution == "eta") res = StringObjectFunction(funcEta_->at(selectedBin)).operator()(candidate); - else if(whichResolution == "phi") res = StringObjectFunction(funcPhi_->at(selectedBin)).operator()(candidate); - else throw cms::Exception("ProgrammingError") << "Only 'et', 'eta' and 'phi' resolutions supported!\n"; + if (selectedBin >= 0) { + if (whichResolution == "et") + res = StringObjectFunction(funcEt_->at(selectedBin)).operator()(candidate); + else if (whichResolution == "eta") + res = StringObjectFunction(funcEta_->at(selectedBin)).operator()(candidate); + else if (whichResolution == "phi") + res = StringObjectFunction(funcPhi_->at(selectedBin)).operator()(candidate); + else + throw cms::Exception("ProgrammingError") << "Only 'et', 'eta' and 'phi' resolutions supported!\n"; } return res; } -TMatrixD CovarianceMatrix::setupMatrix(const TLorentzVector& object, const ObjectType objType, const TopKinFitter::Param param) -{ - TMatrixD CovM3 (3,3); CovM3.Zero(); - TMatrixD CovM4 (4,4); CovM4.Zero(); - const double pt = object.Pt(); +TMatrixD CovarianceMatrix::setupMatrix(const TLorentzVector& object, + const ObjectType objType, + const TopKinFitter::Param param) { + TMatrixD CovM3(3, 3); + CovM3.Zero(); + TMatrixD CovM4(4, 4); + CovM4.Zero(); + const double pt = object.Pt(); const double eta = object.Eta(); - switch(objType) { - case kUdscJet: - // if object is a non-b jet - { - res::HelperJet jetRes; - switch(param) { - case TopKinFitter::kEMom : - CovM4(0,0) = pow(jetRes.a (pt, eta, res::HelperJet::kUds), 2); - CovM4(1,1) = pow(jetRes.b (pt, eta, res::HelperJet::kUds), 2); - CovM4(2,2) = pow(jetRes.c (pt, eta, res::HelperJet::kUds), 2); - CovM4(3,3) = pow(jetRes.d (pt, eta, res::HelperJet::kUds), 2); - return CovM4; - case TopKinFitter::kEtEtaPhi : - if(binsUdsc_.empty()){ - CovM3(0,0) = pow(jetRes.et (pt, eta, res::HelperJet::kUds), 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); - CovM3(2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); - } - else{ - CovM3(0,0) = pow(getResolution(object, objType, "et") , 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(getResolution(object, objType, "eta"), 2); - CovM3(2,2) = pow(getResolution(object, objType, "phi"), 2); - } - return CovM3; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(jetRes.et (pt, eta, res::HelperJet::kUds), 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(jetRes.theta(pt, eta, res::HelperJet::kUds), 2); - CovM3(2,2) = pow(jetRes.phi (pt, eta, res::HelperJet::kUds), 2); - return CovM3; + switch (objType) { + case kUdscJet: + // if object is a non-b jet + { + res::HelperJet jetRes; + switch (param) { + case TopKinFitter::kEMom: + CovM4(0, 0) = pow(jetRes.a(pt, eta, res::HelperJet::kUds), 2); + CovM4(1, 1) = pow(jetRes.b(pt, eta, res::HelperJet::kUds), 2); + CovM4(2, 2) = pow(jetRes.c(pt, eta, res::HelperJet::kUds), 2); + CovM4(3, 3) = pow(jetRes.d(pt, eta, res::HelperJet::kUds), 2); + return CovM4; + case TopKinFitter::kEtEtaPhi: + if (binsUdsc_.empty()) { + CovM3(0, 0) = pow(jetRes.et(pt, eta, res::HelperJet::kUds), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); + CovM3(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); + } else { + CovM3(0, 0) = pow(getResolution(object, objType, "et"), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(getResolution(object, objType, "eta"), 2); + CovM3(2, 2) = pow(getResolution(object, objType, "phi"), 2); + } + return CovM3; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(jetRes.et(pt, eta, res::HelperJet::kUds), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(jetRes.theta(pt, eta, res::HelperJet::kUds), 2); + CovM3(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); + return CovM3; + } } - } - break; - case kBJet: - // if object is a b jet - { - res::HelperJet jetRes; - switch(param) { - case TopKinFitter::kEMom : - CovM4(0,0) = pow(jetRes.a (pt, eta, res::HelperJet::kB), 2); - CovM4(1,1) = pow(jetRes.b (pt, eta, res::HelperJet::kB), 2); - CovM4(2,2) = pow(jetRes.c (pt, eta, res::HelperJet::kB), 2); - CovM4(3,3) = pow(jetRes.d (pt, eta, res::HelperJet::kB), 2); - return CovM4; - case TopKinFitter::kEtEtaPhi : - if(binsUdsc_.empty()){ - CovM3(0,0) = pow(jetRes.et (pt, eta, res::HelperJet::kB), 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB), 2); - CovM3(2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB), 2); - } - else{ - CovM3(0,0) = pow(getResolution(object, objType, "et") , 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(getResolution(object, objType, "eta"), 2); - CovM3(2,2) = pow(getResolution(object, objType, "phi"), 2); - } - return CovM3; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(jetRes.et (pt, eta, res::HelperJet::kB), 2); - CovM3(0,0)*= pow(getEtaDependentScaleFactor(object) , 2); - CovM3(1,1) = pow(jetRes.theta(pt, eta, res::HelperJet::kB), 2); - CovM3(2,2) = pow(jetRes.phi (pt, eta, res::HelperJet::kB), 2); - return CovM3; + break; + case kBJet: + // if object is a b jet + { + res::HelperJet jetRes; + switch (param) { + case TopKinFitter::kEMom: + CovM4(0, 0) = pow(jetRes.a(pt, eta, res::HelperJet::kB), 2); + CovM4(1, 1) = pow(jetRes.b(pt, eta, res::HelperJet::kB), 2); + CovM4(2, 2) = pow(jetRes.c(pt, eta, res::HelperJet::kB), 2); + CovM4(3, 3) = pow(jetRes.d(pt, eta, res::HelperJet::kB), 2); + return CovM4; + case TopKinFitter::kEtEtaPhi: + if (binsUdsc_.empty()) { + CovM3(0, 0) = pow(jetRes.et(pt, eta, res::HelperJet::kB), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB), 2); + CovM3(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB), 2); + } else { + CovM3(0, 0) = pow(getResolution(object, objType, "et"), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(getResolution(object, objType, "eta"), 2); + CovM3(2, 2) = pow(getResolution(object, objType, "phi"), 2); + } + return CovM3; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(jetRes.et(pt, eta, res::HelperJet::kB), 2); + CovM3(0, 0) *= pow(getEtaDependentScaleFactor(object), 2); + CovM3(1, 1) = pow(jetRes.theta(pt, eta, res::HelperJet::kB), 2); + CovM3(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB), 2); + return CovM3; + } } - } - break; - case kMuon: - // if object is a muon - { - res::HelperMuon muonRes; - switch(param){ - case TopKinFitter::kEMom : - CovM3(0,0) = pow(muonRes.a (pt, eta), 2); - CovM3(1,1) = pow(muonRes.b (pt, eta), 2); - CovM3(2,2) = pow(muonRes.c (pt, eta), 2); - return CovM3; - case TopKinFitter::kEtEtaPhi : - if(binsLep_.empty()){ - CovM3(0,0) = pow(muonRes.et (pt, eta), 2); - CovM3(1,1) = pow(muonRes.eta(pt, eta), 2); - CovM3(2,2) = pow(muonRes.phi(pt, eta), 2); - } - else{ - CovM3(0,0) = pow(getResolution(object, objType, "et") , 2); - CovM3(1,1) = pow(getResolution(object, objType, "eta"), 2); - CovM3(2,2) = pow(getResolution(object, objType, "phi"), 2); - } - return CovM3; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(muonRes.et (pt, eta), 2); - CovM3(1,1) = pow(muonRes.theta(pt, eta), 2); - CovM3(2,2) = pow(muonRes.phi (pt, eta), 2); - return CovM3; + break; + case kMuon: + // if object is a muon + { + res::HelperMuon muonRes; + switch (param) { + case TopKinFitter::kEMom: + CovM3(0, 0) = pow(muonRes.a(pt, eta), 2); + CovM3(1, 1) = pow(muonRes.b(pt, eta), 2); + CovM3(2, 2) = pow(muonRes.c(pt, eta), 2); + return CovM3; + case TopKinFitter::kEtEtaPhi: + if (binsLep_.empty()) { + CovM3(0, 0) = pow(muonRes.et(pt, eta), 2); + CovM3(1, 1) = pow(muonRes.eta(pt, eta), 2); + CovM3(2, 2) = pow(muonRes.phi(pt, eta), 2); + } else { + CovM3(0, 0) = pow(getResolution(object, objType, "et"), 2); + CovM3(1, 1) = pow(getResolution(object, objType, "eta"), 2); + CovM3(2, 2) = pow(getResolution(object, objType, "phi"), 2); + } + return CovM3; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(muonRes.et(pt, eta), 2); + CovM3(1, 1) = pow(muonRes.theta(pt, eta), 2); + CovM3(2, 2) = pow(muonRes.phi(pt, eta), 2); + return CovM3; + } } - } - break; - case kElectron: - { + break; + case kElectron: { // if object is an electron res::HelperElectron elecRes; - switch(param){ - case TopKinFitter::kEMom : - CovM3(0,0) = pow(elecRes.a (pt, eta), 2); - CovM3(1,1) = pow(elecRes.b (pt, eta), 2); - CovM3(2,2) = pow(elecRes.c (pt, eta), 2); - return CovM3; - case TopKinFitter::kEtEtaPhi : - if(binsLep_.empty()){ - CovM3(0,0) = pow(elecRes.et (pt, eta), 2); - CovM3(1,1) = pow(elecRes.eta(pt, eta), 2); - CovM3(2,2) = pow(elecRes.phi(pt, eta), 2); - } - else{ - CovM3(0,0) = pow(getResolution(object, objType, "et") , 2); - CovM3(1,1) = pow(getResolution(object, objType, "eta"), 2); - CovM3(2,2) = pow(getResolution(object, objType, "phi"), 2); - } - return CovM3; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(elecRes.et (pt, eta), 2); - CovM3(1,1) = pow(elecRes.theta(pt, eta), 2); - CovM3(2,2) = pow(elecRes.phi (pt, eta), 2); - return CovM3; + switch (param) { + case TopKinFitter::kEMom: + CovM3(0, 0) = pow(elecRes.a(pt, eta), 2); + CovM3(1, 1) = pow(elecRes.b(pt, eta), 2); + CovM3(2, 2) = pow(elecRes.c(pt, eta), 2); + return CovM3; + case TopKinFitter::kEtEtaPhi: + if (binsLep_.empty()) { + CovM3(0, 0) = pow(elecRes.et(pt, eta), 2); + CovM3(1, 1) = pow(elecRes.eta(pt, eta), 2); + CovM3(2, 2) = pow(elecRes.phi(pt, eta), 2); + } else { + CovM3(0, 0) = pow(getResolution(object, objType, "et"), 2); + CovM3(1, 1) = pow(getResolution(object, objType, "eta"), 2); + CovM3(2, 2) = pow(getResolution(object, objType, "phi"), 2); + } + return CovM3; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(elecRes.et(pt, eta), 2); + CovM3(1, 1) = pow(elecRes.theta(pt, eta), 2); + CovM3(2, 2) = pow(elecRes.phi(pt, eta), 2); + return CovM3; } - } - break; - case kMet: - // if object is met - { - res::HelperMET metRes; - switch(param){ - case TopKinFitter::kEMom : - CovM3(0,0) = pow(metRes.a(pt), 2); - CovM3(1,1) = pow(metRes.b(pt), 2); - CovM3(2,2) = pow(metRes.c(pt), 2); - return CovM3; - case TopKinFitter::kEtEtaPhi : - if(binsMet_.empty()){ - CovM3(0,0) = pow(metRes.et(pt) , 2); - CovM3(1,1) = pow( 9999. , 2); - CovM3(2,2) = pow(metRes.phi(pt), 2); - } - else{ - CovM3(0,0) = pow(getResolution(object, objType, "et") , 2); - CovM3(1,1) = pow(getResolution(object, objType, "eta"), 2); - CovM3(2,2) = pow(getResolution(object, objType, "phi"), 2); - } - return CovM3; - case TopKinFitter::kEtThetaPhi : - CovM3(0,0) = pow(metRes.et(pt) , 2); - CovM3(1,1) = pow( 9999. , 2); - CovM3(2,2) = pow(metRes.phi(pt), 2); - return CovM3; + } break; + case kMet: + // if object is met + { + res::HelperMET metRes; + switch (param) { + case TopKinFitter::kEMom: + CovM3(0, 0) = pow(metRes.a(pt), 2); + CovM3(1, 1) = pow(metRes.b(pt), 2); + CovM3(2, 2) = pow(metRes.c(pt), 2); + return CovM3; + case TopKinFitter::kEtEtaPhi: + if (binsMet_.empty()) { + CovM3(0, 0) = pow(metRes.et(pt), 2); + CovM3(1, 1) = pow(9999., 2); + CovM3(2, 2) = pow(metRes.phi(pt), 2); + } else { + CovM3(0, 0) = pow(getResolution(object, objType, "et"), 2); + CovM3(1, 1) = pow(getResolution(object, objType, "eta"), 2); + CovM3(2, 2) = pow(getResolution(object, objType, "phi"), 2); + } + return CovM3; + case TopKinFitter::kEtThetaPhi: + CovM3(0, 0) = pow(metRes.et(pt), 2); + CovM3(1, 1) = pow(9999., 2); + CovM3(2, 2) = pow(metRes.phi(pt), 2); + return CovM3; + } } - } - break; + break; } cms::Exception("Logic") << "Something went wrong while trying to setup a covariance matrix!\n"; - return CovM4; //should never get here + return CovM4; //should never get here } -double CovarianceMatrix::getEtaDependentScaleFactor(const TLorentzVector& object) -{ +double CovarianceMatrix::getEtaDependentScaleFactor(const TLorentzVector& object) { double etaDependentScaleFactor = 1.; - for(unsigned int i=0; i=jetEnergyResolutionEtaBinning_[i] && jetEnergyResolutionEtaBinning_[i]>=0.){ - if(i==jetEnergyResolutionEtaBinning_.size()-1) { - edm::LogWarning("CovarianceMatrix") << "object eta ("<= jetEnergyResolutionEtaBinning_[i] && jetEnergyResolutionEtaBinning_[i] >= 0.) { + if (i == jetEnergyResolutionEtaBinning_.size() - 1) { + edm::LogWarning("CovarianceMatrix") << "object eta (" << std::abs(object.Eta()) << ") beyond last eta bin (" + << jetEnergyResolutionEtaBinning_[i] << ") using scale factor 1.0!"; + etaDependentScaleFactor = 1.; + break; } - etaDependentScaleFactor=jetEnergyResolutionScaleFactors_[i]; - } - else + etaDependentScaleFactor = jetEnergyResolutionScaleFactors_[i]; + } else break; } return etaDependentScaleFactor; diff --git a/TopQuarkAnalysis/TopKinFitter/src/StKinFitter.cc b/TopQuarkAnalysis/TopKinFitter/src/StKinFitter.cc index bac199ee72b41..f77b2562a7d39 100644 --- a/TopQuarkAnalysis/TopKinFitter/src/StKinFitter.cc +++ b/TopQuarkAnalysis/TopKinFitter/src/StKinFitter.cc @@ -24,136 +24,144 @@ #include "PhysicsTools/KinFitter/interface/TFitConstraintMGaus.h" #include "PhysicsTools/KinFitter/interface/TFitConstraintEp.h"*/ -StKinFitter::StKinFitter() : - TopKinFitter(), - jetParam_(kEMom), - lepParam_(kEMom), - metParam_(kEMom) -{ - setupFitter(); -} +StKinFitter::StKinFitter() : TopKinFitter(), jetParam_(kEMom), lepParam_(kEMom), metParam_(kEMom) { setupFitter(); } -StKinFitter::StKinFitter(int jetParam, int lepParam, int metParam, - int maxNrIter, double maxDeltaS, double maxF, const std::vector& constraints) : - TopKinFitter(maxNrIter, maxDeltaS, maxF), - jetParam_((Param) jetParam), - lepParam_((Param) lepParam), - metParam_((Param) metParam), - constraints_(constraints) -{ +StKinFitter::StKinFitter(int jetParam, + int lepParam, + int metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints) + : TopKinFitter(maxNrIter, maxDeltaS, maxF), + jetParam_((Param)jetParam), + lepParam_((Param)lepParam), + metParam_((Param)metParam), + constraints_(constraints) { setupFitter(); } -StKinFitter::StKinFitter(Param jetParam, Param lepParam, Param metParam, - int maxNrIter, double maxDeltaS, double maxF, const std::vector& constraints) : - TopKinFitter(maxNrIter, maxDeltaS, maxF), - jetParam_(jetParam), - lepParam_(lepParam), - metParam_(metParam), - constraints_(constraints) -{ +StKinFitter::StKinFitter(Param jetParam, + Param lepParam, + Param metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints) + : TopKinFitter(maxNrIter, maxDeltaS, maxF), + jetParam_(jetParam), + lepParam_(lepParam), + metParam_(metParam), + constraints_(constraints) { setupFitter(); } -StKinFitter::~StKinFitter() -{ - delete cons1_; delete cons2_; delete cons3_; - delete fitBottom_; delete fitLight_; delete fitLepton_; delete fitNeutrino_; +StKinFitter::~StKinFitter() { + delete cons1_; + delete cons2_; + delete cons3_; + delete fitBottom_; + delete fitLight_; + delete fitLepton_; + delete fitNeutrino_; } -StEvtSolution StKinFitter::addKinFitInfo(StEvtSolution * asol) -{ +StEvtSolution StKinFitter::addKinFitInfo(StEvtSolution* asol) { StEvtSolution fitsol(*asol); - TMatrixD m1(3,3), m2(3,3); - TMatrixD m1b(4,4), m2b(4,4); - TMatrixD m3(3,3), m4(3,3); - m1.Zero(); m2.Zero(); - m1b.Zero(); m2b.Zero(); - m3.Zero(); m4.Zero(); - - TLorentzVector bottomVec(fitsol.getBottom().px(),fitsol.getBottom().py(), - fitsol.getBottom().pz(),fitsol.getBottom().energy()); - TLorentzVector lightVec(fitsol.getLight().px(),fitsol.getLight().py(), - fitsol.getLight().pz(),fitsol.getLight().energy()); + TMatrixD m1(3, 3), m2(3, 3); + TMatrixD m1b(4, 4), m2b(4, 4); + TMatrixD m3(3, 3), m4(3, 3); + m1.Zero(); + m2.Zero(); + m1b.Zero(); + m2b.Zero(); + m3.Zero(); + m4.Zero(); + + TLorentzVector bottomVec( + fitsol.getBottom().px(), fitsol.getBottom().py(), fitsol.getBottom().pz(), fitsol.getBottom().energy()); + TLorentzVector lightVec( + fitsol.getLight().px(), fitsol.getLight().py(), fitsol.getLight().pz(), fitsol.getLight().energy()); TLorentzVector leplVec; - if(fitsol.getDecay()== "electron") leplVec = TLorentzVector(fitsol.getElectron().px(), fitsol.getElectron().py(), - fitsol.getElectron().pz(), fitsol.getElectron().energy()); - if(fitsol.getDecay()== "muon") leplVec = TLorentzVector(fitsol.getMuon().px(), fitsol.getMuon().py(), - fitsol.getMuon().pz(), fitsol.getMuon().energy()); - TLorentzVector lepnVec(fitsol.getNeutrino().px(), fitsol.getNeutrino().py(), - 0, fitsol.getNeutrino().et()); - + if (fitsol.getDecay() == "electron") + leplVec = TLorentzVector( + fitsol.getElectron().px(), fitsol.getElectron().py(), fitsol.getElectron().pz(), fitsol.getElectron().energy()); + if (fitsol.getDecay() == "muon") + leplVec = + TLorentzVector(fitsol.getMuon().px(), fitsol.getMuon().py(), fitsol.getMuon().pz(), fitsol.getMuon().energy()); + TLorentzVector lepnVec(fitsol.getNeutrino().px(), fitsol.getNeutrino().py(), 0, fitsol.getNeutrino().et()); + // jet resolutions { //FIXME this dirty hack needs a clean solution soon! - double pt = fitsol.getBottom().pt (); + double pt = fitsol.getBottom().pt(); double eta = fitsol.getBottom().eta(); res::HelperJet jetRes; if (jetParam_ == kEMom) { - m1b(0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m1b(1,1) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m1b(2,2) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m1b(3,3) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m2b(0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); - m2b(1,1) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); - m2b(2,2) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); - m2b(3,3) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); + m1b(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m1b(1, 1) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m1b(2, 2) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m1b(3, 3) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m2b(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); + m2b(1, 1) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); + m2b(2, 2) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); + m2b(3, 3) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); } else if (jetParam_ == kEtEtaPhi) { - m1 (0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m1 (1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB ), 2); - m1 (2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB ), 2); - m2 (0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); - m2 (1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); - m2 (2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); + m1(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m1(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB), 2); + m1(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB), 2); + m2(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); + m2(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); + m2(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); } else if (jetParam_ == kEtThetaPhi) { - m1 (0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kB ), 2); - m1 (1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB ), 2); - m1 (2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB ), 2); - m2 (0,0) = pow(jetRes.pt (pt, eta, res::HelperJet::kUds), 2); - m2 (1,1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); - m2 (2,2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); + m1(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kB), 2); + m1(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kB), 2); + m1(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kB), 2); + m2(0, 0) = pow(jetRes.pt(pt, eta, res::HelperJet::kUds), 2); + m2(1, 1) = pow(jetRes.eta(pt, eta, res::HelperJet::kUds), 2); + m2(2, 2) = pow(jetRes.phi(pt, eta, res::HelperJet::kUds), 2); } } // lepton resolutions { //FIXME this dirty hack needs a clean solution soon! - double pt = fitsol.getElectron().pt (); + double pt = fitsol.getElectron().pt(); double eta = fitsol.getElectron().eta(); - res::HelperMuon muonRes; + res::HelperMuon muonRes; res::HelperElectron elecRes; if (lepParam_ == kEMom) { - if(fitsol.getDecay()== "electron"){ - m3(0,0) = pow(elecRes.pt (pt, eta), 2); - m3(1,1) = pow(elecRes.pt (pt, eta), 2); - m3(2,2) = pow(elecRes.pt (pt, eta), 2); + if (fitsol.getDecay() == "electron") { + m3(0, 0) = pow(elecRes.pt(pt, eta), 2); + m3(1, 1) = pow(elecRes.pt(pt, eta), 2); + m3(2, 2) = pow(elecRes.pt(pt, eta), 2); } - if(fitsol.getDecay()== "muon"){ - m3(0,0) = pow(muonRes.pt (pt, eta), 2); - m3(1,1) = pow(muonRes.pt (pt, eta), 2); - m3(2,2) = pow(muonRes.pt (pt, eta), 2); + if (fitsol.getDecay() == "muon") { + m3(0, 0) = pow(muonRes.pt(pt, eta), 2); + m3(1, 1) = pow(muonRes.pt(pt, eta), 2); + m3(2, 2) = pow(muonRes.pt(pt, eta), 2); } } else if (lepParam_ == kEtEtaPhi) { - if(fitsol.getDecay()== "electron"){ - m3(0,0) = pow(elecRes.pt (pt, eta), 2); - m3(1,1) = pow(elecRes.eta(pt, eta), 2); - m3(2,2) = pow(elecRes.phi(pt, eta), 2); + if (fitsol.getDecay() == "electron") { + m3(0, 0) = pow(elecRes.pt(pt, eta), 2); + m3(1, 1) = pow(elecRes.eta(pt, eta), 2); + m3(2, 2) = pow(elecRes.phi(pt, eta), 2); } - if(fitsol.getDecay()== "muon"){ - m3(0,0) = pow(muonRes.pt (pt, eta), 2); - m3(1,1) = pow(muonRes.eta(pt, eta), 2); - m3(2,2) = pow(muonRes.phi(pt, eta), 2); + if (fitsol.getDecay() == "muon") { + m3(0, 0) = pow(muonRes.pt(pt, eta), 2); + m3(1, 1) = pow(muonRes.eta(pt, eta), 2); + m3(2, 2) = pow(muonRes.phi(pt, eta), 2); } } else if (lepParam_ == kEtThetaPhi) { - if(fitsol.getDecay()== "electron"){ - m3(0,0) = pow(elecRes.pt (pt, eta), 2); - m3(1,1) = pow(elecRes.eta(pt, eta), 2); - m3(2,2) = pow(elecRes.phi(pt, eta), 2); + if (fitsol.getDecay() == "electron") { + m3(0, 0) = pow(elecRes.pt(pt, eta), 2); + m3(1, 1) = pow(elecRes.eta(pt, eta), 2); + m3(2, 2) = pow(elecRes.phi(pt, eta), 2); } - if(fitsol.getDecay()== "muon"){ - m3(0,0) = pow(muonRes.pt (pt, eta), 2); - m3(1,1) = pow(muonRes.eta(pt, eta), 2); - m3(2,2) = pow(muonRes.phi(pt, eta), 2); + if (fitsol.getDecay() == "muon") { + m3(0, 0) = pow(muonRes.pt(pt, eta), 2); + m3(1, 1) = pow(muonRes.eta(pt, eta), 2); + m3(2, 2) = pow(muonRes.phi(pt, eta), 2); } } } @@ -163,17 +171,17 @@ StEvtSolution StKinFitter::addKinFitInfo(StEvtSolution * asol) double met = fitsol.getNeutrino().pt(); res::HelperMET metRes; if (metParam_ == kEMom) { - m4(0,0) = pow(metRes.met(met), 2); - m4(1,1) = pow( 9999., 2); - m4(2,2) = pow(metRes.met(met), 2); + m4(0, 0) = pow(metRes.met(met), 2); + m4(1, 1) = pow(9999., 2); + m4(2, 2) = pow(metRes.met(met), 2); } else if (metParam_ == kEtEtaPhi) { - m4(0,0) = pow(metRes.met(met), 2); - m4(1,1) = pow( 9999., 2); - m4(2,2) = pow(metRes.phi(met), 2); + m4(0, 0) = pow(metRes.met(met), 2); + m4(1, 1) = pow(9999., 2); + m4(2, 2) = pow(metRes.phi(met), 2); } else if (metParam_ == kEtThetaPhi) { - m4(0,0) = pow(metRes.met(met), 2); - m4(1,1) = pow( 9999., 2); - m4(2,2) = pow(metRes.phi(met), 2); + m4(0, 0) = pow(metRes.met(met), 2); + m4(1, 1) = pow(9999., 2); + m4(2, 2) = pow(metRes.phi(met), 2); } } // set the kinematics of the objects to be fitted @@ -193,19 +201,39 @@ StEvtSolution StKinFitter::addKinFitInfo(StEvtSolution * asol) // perform the fit! fitter_->fit(); - + // add fitted information to the solution if (fitter_->getStatus() == 0) { // read back the jet kinematics and resolutions - pat::Particle aFitBottom(reco::LeafCandidate(0, math::XYZTLorentzVector(fitBottom_->getCurr4Vec()->X(), fitBottom_->getCurr4Vec()->Y(), fitBottom_->getCurr4Vec()->Z(), fitBottom_->getCurr4Vec()->E()),math::XYZPoint())); - pat::Particle aFitLight(reco::LeafCandidate(0, math::XYZTLorentzVector(fitLight_->getCurr4Vec()->X(), fitLight_->getCurr4Vec()->Y(), fitLight_->getCurr4Vec()->Z(), fitLight_->getCurr4Vec()->E()),math::XYZPoint())); + pat::Particle aFitBottom(reco::LeafCandidate(0, + math::XYZTLorentzVector(fitBottom_->getCurr4Vec()->X(), + fitBottom_->getCurr4Vec()->Y(), + fitBottom_->getCurr4Vec()->Z(), + fitBottom_->getCurr4Vec()->E()), + math::XYZPoint())); + pat::Particle aFitLight(reco::LeafCandidate(0, + math::XYZTLorentzVector(fitLight_->getCurr4Vec()->X(), + fitLight_->getCurr4Vec()->Y(), + fitLight_->getCurr4Vec()->Z(), + fitLight_->getCurr4Vec()->E()), + math::XYZPoint())); // read back the lepton kinematics and resolutions - pat::Particle aFitLepton(reco::LeafCandidate(0, math::XYZTLorentzVector(fitLepton_->getCurr4Vec()->X(), fitLepton_->getCurr4Vec()->Y(), fitLepton_->getCurr4Vec()->Z(), fitLepton_->getCurr4Vec()->E()), math::XYZPoint())); + pat::Particle aFitLepton(reco::LeafCandidate(0, + math::XYZTLorentzVector(fitLepton_->getCurr4Vec()->X(), + fitLepton_->getCurr4Vec()->Y(), + fitLepton_->getCurr4Vec()->Z(), + fitLepton_->getCurr4Vec()->E()), + math::XYZPoint())); // read back the MET kinematics and resolutions - pat::Particle aFitNeutrino(reco::LeafCandidate(0, math::XYZTLorentzVector(fitNeutrino_->getCurr4Vec()->X(), fitNeutrino_->getCurr4Vec()->Y(), fitNeutrino_->getCurr4Vec()->Z(), fitNeutrino_->getCurr4Vec()->E()), math::XYZPoint())); - + pat::Particle aFitNeutrino(reco::LeafCandidate(0, + math::XYZTLorentzVector(fitNeutrino_->getCurr4Vec()->X(), + fitNeutrino_->getCurr4Vec()->Y(), + fitNeutrino_->getCurr4Vec()->Z(), + fitNeutrino_->getCurr4Vec()->E()), + math::XYZPoint())); + // finally fill the fitted particles fitsol.setFitBottom(aFitBottom); fitsol.setFitLight(aFitLight); @@ -213,47 +241,51 @@ StEvtSolution StKinFitter::addKinFitInfo(StEvtSolution * asol) fitsol.setFitNeutrino(aFitNeutrino); // store the fit's chi2 probability - fitsol.setChi2Prob( fitProb() ); + fitsol.setChi2Prob(fitProb()); } return fitsol; - } // // Setup the fitter // void StKinFitter::setupFitter() { - // FIXME: replace by messagelogger!!! - - std::cout<addParticles1(fitLepton_, fitNeutrino_); cons2_ = new TFitConstraintM("MassConstraint", "Mass-Constraint", nullptr, nullptr, mTop_); cons2_->addParticles1(fitLepton_, fitNeutrino_, fitBottom_); cons3_ = new TFitConstraintM("MassConstraint", "Mass-Constraint", nullptr, nullptr, 0.); cons3_->addParticle1(fitNeutrino_); - for (unsigned int i=0; iaddConstraint(cons1_); - if (constraints_[i] == 2) fitter_->addConstraint(cons2_); - if (constraints_[i] == 3) fitter_->addConstraint(cons3_); + for (unsigned int i = 0; i < constraints_.size(); i++) { + if (constraints_[i] == 1) + fitter_->addConstraint(cons1_); + if (constraints_[i] == 2) + fitter_->addConstraint(cons2_); + if (constraints_[i] == 3) + fitter_->addConstraint(cons3_); } fitter_->addMeasParticle(fitBottom_); fitter_->addMeasParticle(fitLight_); fitter_->addMeasParticle(fitLepton_); fitter_->addMeasParticle(fitNeutrino_); - } diff --git a/TopQuarkAnalysis/TopKinFitter/src/TopKinFitter.cc b/TopQuarkAnalysis/TopKinFitter/src/TopKinFitter.cc index 792b3b93cc098..2ca7edcf40981 100644 --- a/TopQuarkAnalysis/TopKinFitter/src/TopKinFitter.cc +++ b/TopQuarkAnalysis/TopKinFitter/src/TopKinFitter.cc @@ -1,10 +1,9 @@ #include "TopQuarkAnalysis/TopKinFitter/interface/TopKinFitter.h" /// default configuration is: max iterations = 200, max deltaS = 5e-5, maxF = 1e-4 -TopKinFitter::TopKinFitter(const int maxNrIter, const double maxDeltaS, const double maxF, - const double mW, const double mTop): - maxNrIter_(maxNrIter), maxDeltaS_(maxDeltaS), maxF_(maxF), mW_(mW), mTop_(mTop) -{ +TopKinFitter::TopKinFitter( + const int maxNrIter, const double maxDeltaS, const double maxF, const double mW, const double mTop) + : maxNrIter_(maxNrIter), maxDeltaS_(maxDeltaS), maxF_(maxF), mW_(mW), mTop_(mTop) { fitter_ = new TKinFitter("TopKinFitter", "TopKinFitter"); fitter_->setMaxNbIter(maxNrIter_); fitter_->setMaxDeltaS(maxDeltaS_); @@ -13,20 +12,21 @@ TopKinFitter::TopKinFitter(const int maxNrIter, const double maxDeltaS, const do } /// default destructor -TopKinFitter::~TopKinFitter() -{ - delete fitter_; -} +TopKinFitter::~TopKinFitter() { delete fitter_; } /// convert Param to human readable form -std::string -TopKinFitter::param(const Param& param) const -{ +std::string TopKinFitter::param(const Param& param) const { std::string parName; - switch(param){ - case kEMom : parName="EMom"; break; - case kEtEtaPhi : parName="EtEtaPhi"; break; - case kEtThetaPhi : parName="EtThetaPhi"; break; + switch (param) { + case kEMom: + parName = "EMom"; + break; + case kEtEtaPhi: + parName = "EtEtaPhi"; + break; + case kEtThetaPhi: + parName = "EtThetaPhi"; + break; } return parName; } diff --git a/TopQuarkAnalysis/TopKinFitter/src/TtFullHadKinFitter.cc b/TopQuarkAnalysis/TopKinFitter/src/TtFullHadKinFitter.cc index 6b034db72878a..828e8c18adbc5 100644 --- a/TopQuarkAnalysis/TopKinFitter/src/TtFullHadKinFitter.cc +++ b/TopQuarkAnalysis/TopKinFitter/src/TtFullHadKinFitter.cc @@ -10,164 +10,188 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" -static const unsigned int nPartons=6; +static const unsigned int nPartons = 6; /// default constructor -TtFullHadKinFitter::TtFullHadKinFitter(): - TopKinFitter(), - b_(nullptr), bBar_(nullptr), lightQ_(nullptr), lightQBar_(nullptr), lightP_(nullptr), lightPBar_(nullptr), - udscResolutions_(nullptr), bResolutions_(nullptr), - jetEnergyResolutionScaleFactors_(nullptr), jetEnergyResolutionEtaBinning_(nullptr), - jetParam_(kEMom) -{ +TtFullHadKinFitter::TtFullHadKinFitter() + : TopKinFitter(), + b_(nullptr), + bBar_(nullptr), + lightQ_(nullptr), + lightQBar_(nullptr), + lightP_(nullptr), + lightPBar_(nullptr), + udscResolutions_(nullptr), + bResolutions_(nullptr), + jetEnergyResolutionScaleFactors_(nullptr), + jetEnergyResolutionEtaBinning_(nullptr), + jetParam_(kEMom) { setupFitter(); } /// used to convert vector of int's to vector of constraints (just used in TtFullHadKinFitter(int, int, double, double, std::vector)) -std::vector -TtFullHadKinFitter::intToConstraint(const std::vector& constraints) -{ +std::vector TtFullHadKinFitter::intToConstraint( + const std::vector& constraints) { std::vector cConstraints; cConstraints.resize(constraints.size()); - for(unsigned int i=0;i& constraints, double mW, double mTop, - const std::vector* udscResolutions, - const std::vector* bResolutions, - const std::vector* jetEnergyResolutionScaleFactors, - const std::vector* jetEnergyResolutionEtaBinning): - TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), - b_(nullptr), bBar_(nullptr), lightQ_(nullptr), lightQBar_(nullptr), lightP_(nullptr), lightPBar_(nullptr), - udscResolutions_(udscResolutions), bResolutions_(bResolutions), - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), - jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), - jetParam_((Param)jetParam), constraints_(intToConstraint(constraints)) -{ +TtFullHadKinFitter::TtFullHadKinFitter(int jetParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW, + double mTop, + const std::vector* udscResolutions, + const std::vector* bResolutions, + const std::vector* jetEnergyResolutionScaleFactors, + const std::vector* jetEnergyResolutionEtaBinning) + : TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), + b_(nullptr), + bBar_(nullptr), + lightQ_(nullptr), + lightQBar_(nullptr), + lightP_(nullptr), + lightPBar_(nullptr), + udscResolutions_(udscResolutions), + bResolutions_(bResolutions), + jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), + jetParam_((Param)jetParam), + constraints_(intToConstraint(constraints)) { setupFitter(); } /// constructor initialized with build-in types and class enum's custom parameters -TtFullHadKinFitter::TtFullHadKinFitter(Param jetParam, int maxNrIter, double maxDeltaS, double maxF, - const std::vector& constraints, double mW, double mTop, - const std::vector* udscResolutions, - const std::vector* bResolutions, - const std::vector* jetEnergyResolutionScaleFactors, - const std::vector* jetEnergyResolutionEtaBinning): - TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), - b_(nullptr), bBar_(nullptr), lightQ_(nullptr), lightQBar_(nullptr), lightP_(nullptr), lightPBar_(nullptr), - udscResolutions_(udscResolutions), bResolutions_(bResolutions), - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), - jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), - jetParam_(jetParam), constraints_(constraints) -{ +TtFullHadKinFitter::TtFullHadKinFitter(Param jetParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW, + double mTop, + const std::vector* udscResolutions, + const std::vector* bResolutions, + const std::vector* jetEnergyResolutionScaleFactors, + const std::vector* jetEnergyResolutionEtaBinning) + : TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), + b_(nullptr), + bBar_(nullptr), + lightQ_(nullptr), + lightQBar_(nullptr), + lightP_(nullptr), + lightPBar_(nullptr), + udscResolutions_(udscResolutions), + bResolutions_(bResolutions), + jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), + jetParam_(jetParam), + constraints_(constraints) { setupFitter(); } /// default destructor -TtFullHadKinFitter::~TtFullHadKinFitter() -{ - delete b_; - delete bBar_; +TtFullHadKinFitter::~TtFullHadKinFitter() { + delete b_; + delete bBar_; delete lightQ_; - delete lightQBar_; - delete lightP_; + delete lightQBar_; + delete lightP_; delete lightPBar_; delete covM_; - for(std::map::iterator it = massConstr_.begin(); it != massConstr_.end(); ++it) + for (std::map::iterator it = massConstr_.begin(); it != massConstr_.end(); ++it) delete it->second; } /// print fitter setup -void -TtFullHadKinFitter::printSetup() const -{ +void TtFullHadKinFitter::printSetup() const { std::stringstream constr; - for(unsigned int i=0; iaddParticles1(lightQ_, lightQBar_); - massConstr_[kWMinusMass ]->addParticles1(lightP_, lightPBar_); - massConstr_[kTopMass ]->addParticles1(b_, lightQ_, lightQBar_); - massConstr_[kTopBarMass ]->addParticles1(bBar_, lightP_, lightPBar_); +void TtFullHadKinFitter::setupConstraints() { + massConstr_[kWPlusMass] = new TFitConstraintM("WPlusMass", "WPlusMass", nullptr, nullptr, mW_); + massConstr_[kWMinusMass] = new TFitConstraintM("WMinusMass", "WMinusMass", nullptr, nullptr, mW_); + massConstr_[kTopMass] = new TFitConstraintM("TopMass", "TopMass", nullptr, nullptr, mTop_); + massConstr_[kTopBarMass] = new TFitConstraintM("TopBarMass", "TopBarMass", nullptr, nullptr, mTop_); + massConstr_[kEqualTopMasses] = new TFitConstraintM("EqualTopMasses", "EqualTopMasses", nullptr, nullptr, 0); + + massConstr_[kWPlusMass]->addParticles1(lightQ_, lightQBar_); + massConstr_[kWMinusMass]->addParticles1(lightP_, lightPBar_); + massConstr_[kTopMass]->addParticles1(b_, lightQ_, lightQBar_); + massConstr_[kTopBarMass]->addParticles1(bBar_, lightP_, lightPBar_); massConstr_[kEqualTopMasses]->addParticles1(b_, lightQ_, lightQBar_); massConstr_[kEqualTopMasses]->addParticles2(bBar_, lightP_, lightPBar_); - } -/// setup fitter -void -TtFullHadKinFitter::setupFitter() -{ +/// setup fitter +void TtFullHadKinFitter::setupFitter() { printSetup(); setupJets(); setupConstraints(); @@ -181,101 +205,123 @@ TtFullHadKinFitter::setupFitter() fitter_->addMeasParticle(lightPBar_); // add constraints - for(unsigned int i=0; iaddConstraint(massConstr_[constraints_[i]]); } // initialize helper class used to bring the resolutions into covariance matrices - if(!udscResolutions_->empty() && !bResolutions_->empty()) - covM_ = new CovarianceMatrix(*udscResolutions_, *bResolutions_, - *jetEnergyResolutionScaleFactors_, - *jetEnergyResolutionEtaBinning_); + if (!udscResolutions_->empty() && !bResolutions_->empty()) + covM_ = new CovarianceMatrix( + *udscResolutions_, *bResolutions_, *jetEnergyResolutionScaleFactors_, *jetEnergyResolutionEtaBinning_); else covM_ = new CovarianceMatrix(); } /// kinematic fit interface -int -TtFullHadKinFitter::fit(const std::vector& jets) -{ - if( jets.size()<6 ){ - throw edm::Exception( edm::errors::Configuration, "Cannot run the TtFullHadKinFitter with less than 6 jets" ); +int TtFullHadKinFitter::fit(const std::vector& jets) { + if (jets.size() < 6) { + throw edm::Exception(edm::errors::Configuration, "Cannot run the TtFullHadKinFitter with less than 6 jets"); } // get jets in right order - const pat::Jet& b = jets[TtFullHadEvtPartons::B ]; - const pat::Jet& bBar = jets[TtFullHadEvtPartons::BBar ]; - const pat::Jet& lightQ = jets[TtFullHadEvtPartons::LightQ ]; + const pat::Jet& b = jets[TtFullHadEvtPartons::B]; + const pat::Jet& bBar = jets[TtFullHadEvtPartons::BBar]; + const pat::Jet& lightQ = jets[TtFullHadEvtPartons::LightQ]; const pat::Jet& lightQBar = jets[TtFullHadEvtPartons::LightQBar]; - const pat::Jet& lightP = jets[TtFullHadEvtPartons::LightP ]; + const pat::Jet& lightP = jets[TtFullHadEvtPartons::LightP]; const pat::Jet& lightPBar = jets[TtFullHadEvtPartons::LightPBar]; - + // initialize particles - const TLorentzVector p4B( b.px(), b.py(), b.pz(), b.energy() ); - const TLorentzVector p4BBar( bBar.px(), bBar.py(), bBar.pz(), bBar.energy() ); - const TLorentzVector p4LightQ( lightQ.px(), lightQ.py(), lightQ.pz(), lightQ.energy() ); - const TLorentzVector p4LightQBar( lightQBar.px(), lightQBar.py(), lightQBar.pz(), lightQBar.energy() ); - const TLorentzVector p4LightP( lightP.px(), lightP.py(), lightP.pz(), lightP.energy() ); - const TLorentzVector p4LightPBar( lightPBar.px(), lightPBar.py(), lightPBar.pz(), lightPBar.energy() ); + const TLorentzVector p4B(b.px(), b.py(), b.pz(), b.energy()); + const TLorentzVector p4BBar(bBar.px(), bBar.py(), bBar.pz(), bBar.energy()); + const TLorentzVector p4LightQ(lightQ.px(), lightQ.py(), lightQ.pz(), lightQ.energy()); + const TLorentzVector p4LightQBar(lightQBar.px(), lightQBar.py(), lightQBar.pz(), lightQBar.energy()); + const TLorentzVector p4LightP(lightP.px(), lightP.py(), lightP.pz(), lightP.energy()); + const TLorentzVector p4LightPBar(lightPBar.px(), lightPBar.py(), lightPBar.pz(), lightPBar.energy()); // initialize covariance matrices - TMatrixD m1 = covM_->setupMatrix(lightQ, jetParam_); + TMatrixD m1 = covM_->setupMatrix(lightQ, jetParam_); TMatrixD m2 = covM_->setupMatrix(lightQBar, jetParam_); - TMatrixD m3 = covM_->setupMatrix(b, jetParam_, "bjets"); - TMatrixD m4 = covM_->setupMatrix(lightP, jetParam_); + TMatrixD m3 = covM_->setupMatrix(b, jetParam_, "bjets"); + TMatrixD m4 = covM_->setupMatrix(lightP, jetParam_); TMatrixD m5 = covM_->setupMatrix(lightPBar, jetParam_); - TMatrixD m6 = covM_->setupMatrix(bBar , jetParam_, "bjets"); + TMatrixD m6 = covM_->setupMatrix(bBar, jetParam_, "bjets"); // set the kinematics of the objects to be fitted - b_ ->setIni4Vec(&p4B ); - bBar_ ->setIni4Vec(&p4BBar ); - lightQ_ ->setIni4Vec(&p4LightQ ); + b_->setIni4Vec(&p4B); + bBar_->setIni4Vec(&p4BBar); + lightQ_->setIni4Vec(&p4LightQ); lightQBar_->setIni4Vec(&p4LightQBar); - lightP_ ->setIni4Vec(&p4LightP ); + lightP_->setIni4Vec(&p4LightP); lightPBar_->setIni4Vec(&p4LightPBar); - + // initialize covariance matrices - lightQ_ ->setCovMatrix( &m1); - lightQBar_->setCovMatrix( &m2); - b_ ->setCovMatrix( &m3); - lightP_ ->setCovMatrix( &m4); - lightPBar_->setCovMatrix( &m5); - bBar_ ->setCovMatrix( &m6); - + lightQ_->setCovMatrix(&m1); + lightQBar_->setCovMatrix(&m2); + b_->setCovMatrix(&m3); + lightP_->setCovMatrix(&m4); + lightPBar_->setCovMatrix(&m5); + bBar_->setCovMatrix(&m6); + // perform the fit! fitter_->fit(); - + // add fitted information to the solution - if( fitter_->getStatus()==0 ){ + if (fitter_->getStatus() == 0) { // read back jet kinematics - fittedB_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(b_->getCurr4Vec()->X(), b_->getCurr4Vec()->Y(), b_->getCurr4Vec()->Z(), b_->getCurr4Vec()->E()), math::XYZPoint())); - fittedLightQ_ = pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(lightQ_->getCurr4Vec()->X(), lightQ_->getCurr4Vec()->Y(), lightQ_->getCurr4Vec()->Z(), lightQ_->getCurr4Vec()->E()), math::XYZPoint())); - fittedLightQBar_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(lightQBar_->getCurr4Vec()->X(), lightQBar_->getCurr4Vec()->Y(), lightQBar_->getCurr4Vec()->Z(), lightQBar_->getCurr4Vec()->E()), math::XYZPoint())); - - - fittedBBar_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(bBar_->getCurr4Vec()->X(), bBar_->getCurr4Vec()->Y(), bBar_->getCurr4Vec()->Z(), bBar_->getCurr4Vec()->E()), math::XYZPoint())); - fittedLightP_ = pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(lightP_->getCurr4Vec()->X(), lightP_->getCurr4Vec()->Y(), lightP_->getCurr4Vec()->Z(), lightP_->getCurr4Vec()->E()), math::XYZPoint())); - fittedLightPBar_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(lightPBar_->getCurr4Vec()->X(), lightPBar_->getCurr4Vec()->Y(), lightPBar_->getCurr4Vec()->Z(), lightPBar_->getCurr4Vec()->E()), math::XYZPoint())); + fittedB_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + b_->getCurr4Vec()->X(), b_->getCurr4Vec()->Y(), b_->getCurr4Vec()->Z(), b_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedLightQ_ = pat::Particle(reco::LeafCandidate(0, + math::XYZTLorentzVector(lightQ_->getCurr4Vec()->X(), + lightQ_->getCurr4Vec()->Y(), + lightQ_->getCurr4Vec()->Z(), + lightQ_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedLightQBar_ = pat::Particle(reco::LeafCandidate(0, + math::XYZTLorentzVector(lightQBar_->getCurr4Vec()->X(), + lightQBar_->getCurr4Vec()->Y(), + lightQBar_->getCurr4Vec()->Z(), + lightQBar_->getCurr4Vec()->E()), + math::XYZPoint())); + + fittedBBar_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + bBar_->getCurr4Vec()->X(), bBar_->getCurr4Vec()->Y(), bBar_->getCurr4Vec()->Z(), bBar_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedLightP_ = pat::Particle(reco::LeafCandidate(0, + math::XYZTLorentzVector(lightP_->getCurr4Vec()->X(), + lightP_->getCurr4Vec()->Y(), + lightP_->getCurr4Vec()->Z(), + lightP_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedLightPBar_ = pat::Particle(reco::LeafCandidate(0, + math::XYZTLorentzVector(lightPBar_->getCurr4Vec()->X(), + lightPBar_->getCurr4Vec()->Y(), + lightPBar_->getCurr4Vec()->Z(), + lightPBar_->getCurr4Vec()->E()), + math::XYZPoint())); } return fitter_->getStatus(); } /// add kin fit information to the old event solution (in for legacy reasons) -TtHadEvtSolution -TtFullHadKinFitter::addKinFitInfo(TtHadEvtSolution * asol) -{ +TtHadEvtSolution TtFullHadKinFitter::addKinFitInfo(TtHadEvtSolution* asol) { TtHadEvtSolution fitsol(*asol); std::vector jets; jets.resize(6); - jets[TtFullHadEvtPartons::LightQ ] = fitsol.getCalHadp(); + jets[TtFullHadEvtPartons::LightQ] = fitsol.getCalHadp(); jets[TtFullHadEvtPartons::LightQBar] = fitsol.getCalHadq(); - jets[TtFullHadEvtPartons::B ] = fitsol.getCalHadb(); - jets[TtFullHadEvtPartons::LightP ] = fitsol.getCalHadj(); + jets[TtFullHadEvtPartons::B] = fitsol.getCalHadb(); + jets[TtFullHadEvtPartons::LightP] = fitsol.getCalHadj(); jets[TtFullHadEvtPartons::LightPBar] = fitsol.getCalHadk(); - jets[TtFullHadEvtPartons::BBar ] = fitsol.getCalHadbbar(); + jets[TtFullHadEvtPartons::BBar] = fitsol.getCalHadbbar(); - fit( jets); + fit(jets); // add fitted information to the solution if (fitter_->getStatus() == 0) { @@ -288,176 +334,177 @@ TtFullHadKinFitter::addKinFitInfo(TtHadEvtSolution * asol) fitsol.setFitHadbbar(fittedBBar_); // store the fit's chi2 probability - fitsol.setProbChi2( fitProb() ); + fitsol.setProbChi2(fitProb()); } return fitsol; } - -/// default constructor -TtFullHadKinFitter::KinFit::KinFit() : - useBTagging_(true), - bTags_(2), - bTagAlgo_("trackCountingHighPurBJetTags"), - minBTagValueBJet_(3.41), - maxBTagValueNonBJet_(3.41), - udscResolutions_(std::vector(0)), - bResolutions_(std::vector(0)), - jetEnergyResolutionScaleFactors_(0), - jetEnergyResolutionEtaBinning_(0), - jetCorrectionLevel_("L3Absolute"), - maxNJets_(-1), - maxNComb_(1), - maxNrIter_(500), - maxDeltaS_(5e-5), - maxF_(0.0001), - jetParam_(1), - mW_(80.4), - mTop_(173.), - useOnlyMatch_(false), - match_(std::vector(0)), - invalidMatch_(false) -{ +/// default constructor +TtFullHadKinFitter::KinFit::KinFit() + : useBTagging_(true), + bTags_(2), + bTagAlgo_("trackCountingHighPurBJetTags"), + minBTagValueBJet_(3.41), + maxBTagValueNonBJet_(3.41), + udscResolutions_(std::vector(0)), + bResolutions_(std::vector(0)), + jetEnergyResolutionScaleFactors_(0), + jetEnergyResolutionEtaBinning_(0), + jetCorrectionLevel_("L3Absolute"), + maxNJets_(-1), + maxNComb_(1), + maxNrIter_(500), + maxDeltaS_(5e-5), + maxF_(0.0001), + jetParam_(1), + mW_(80.4), + mTop_(173.), + useOnlyMatch_(false), + match_(std::vector(0)), + invalidMatch_(false) { constraints_.push_back(1); constraints_.push_back(2); constraints_.push_back(5); } -/// special constructor -TtFullHadKinFitter::KinFit::KinFit(bool useBTagging, unsigned int bTags, std::string bTagAlgo, double minBTagValueBJet, double maxBTagValueNonBJet, - const std::vector& udscResolutions, const std::vector& bResolutions, - const std::vector& jetEnergyResolutionScaleFactors, const std::vector& jetEnergyResolutionEtaBinning, - std::string jetCorrectionLevel, int maxNJets, int maxNComb, - unsigned int maxNrIter, double maxDeltaS, double maxF, unsigned int jetParam, const std::vector& constraints, double mW, double mTop) : - useBTagging_(useBTagging), - bTags_(bTags), - bTagAlgo_(bTagAlgo), - minBTagValueBJet_(minBTagValueBJet), - maxBTagValueNonBJet_(maxBTagValueNonBJet), - udscResolutions_(udscResolutions), - bResolutions_(bResolutions), - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), - jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), - jetCorrectionLevel_(jetCorrectionLevel), - maxNJets_(maxNJets), - maxNComb_(maxNComb), - maxNrIter_(maxNrIter), - maxDeltaS_(maxDeltaS), - maxF_(maxF), - jetParam_(jetParam), - constraints_(constraints), - mW_(mW), - mTop_(mTop), - useOnlyMatch_(false), - invalidMatch_(false) -{ +/// special constructor +TtFullHadKinFitter::KinFit::KinFit(bool useBTagging, + unsigned int bTags, + std::string bTagAlgo, + double minBTagValueBJet, + double maxBTagValueNonBJet, + const std::vector& udscResolutions, + const std::vector& bResolutions, + const std::vector& jetEnergyResolutionScaleFactors, + const std::vector& jetEnergyResolutionEtaBinning, + std::string jetCorrectionLevel, + int maxNJets, + int maxNComb, + unsigned int maxNrIter, + double maxDeltaS, + double maxF, + unsigned int jetParam, + const std::vector& constraints, + double mW, + double mTop) + : useBTagging_(useBTagging), + bTags_(bTags), + bTagAlgo_(bTagAlgo), + minBTagValueBJet_(minBTagValueBJet), + maxBTagValueNonBJet_(maxBTagValueNonBJet), + udscResolutions_(udscResolutions), + bResolutions_(bResolutions), + jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), + jetCorrectionLevel_(jetCorrectionLevel), + maxNJets_(maxNJets), + maxNComb_(maxNComb), + maxNrIter_(maxNrIter), + maxDeltaS_(maxDeltaS), + maxF_(maxF), + jetParam_(jetParam), + constraints_(constraints), + mW_(mW), + mTop_(mTop), + useOnlyMatch_(false), + invalidMatch_(false) { // define kinematic fit interface - fitter = new TtFullHadKinFitter(param(jetParam_), maxNrIter_, maxDeltaS_, maxF_, TtFullHadKinFitter::KinFit::constraints(constraints_), mW_, mTop_, - &udscResolutions_, &bResolutions_, &jetEnergyResolutionScaleFactors_, &jetEnergyResolutionEtaBinning_); + fitter = new TtFullHadKinFitter(param(jetParam_), + maxNrIter_, + maxDeltaS_, + maxF_, + TtFullHadKinFitter::KinFit::constraints(constraints_), + mW_, + mTop_, + &udscResolutions_, + &bResolutions_, + &jetEnergyResolutionScaleFactors_, + &jetEnergyResolutionEtaBinning_); } -/// default destructor -TtFullHadKinFitter::KinFit::~KinFit() -{ - delete fitter; -} +/// default destructor +TtFullHadKinFitter::KinFit::~KinFit() { delete fitter; } -bool -TtFullHadKinFitter::KinFit::doBTagging(const std::vector& jets, const unsigned int& bJetCounter, std::vector& combi){ - - if( !useBTagging_ ) { +bool TtFullHadKinFitter::KinFit::doBTagging(const std::vector& jets, + const unsigned int& bJetCounter, + std::vector& combi) { + if (!useBTagging_) { return true; } - if( bTags_ == 2 && - jets[combi[TtFullHadEvtPartons::B ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::BBar ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightP ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + if (bTags_ == 2 && jets[combi[TtFullHadEvtPartons::B]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::BBar]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightP]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; - } - else if( bTags_ == 1 ){ - if( bJetCounter == 1 && - (jets[combi[TtFullHadEvtPartons::B ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ || - jets[combi[TtFullHadEvtPartons::BBar ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) && - jets[combi[TtFullHadEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightP ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + } else if (bTags_ == 1) { + if (bJetCounter == 1 && + (jets[combi[TtFullHadEvtPartons::B]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ || + jets[combi[TtFullHadEvtPartons::BBar]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) && + jets[combi[TtFullHadEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightP]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; - } - else if( bJetCounter > 1 && - jets[combi[TtFullHadEvtPartons::B ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::BBar ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightP ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + } else if (bJetCounter > 1 && jets[combi[TtFullHadEvtPartons::B]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::BBar]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightP]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; } - } - else if( bTags_ == 0 ){ - if( bJetCounter == 0){ + } else if (bTags_ == 0) { + if (bJetCounter == 0) { return true; - } - else if( bJetCounter == 1 && - (jets[combi[TtFullHadEvtPartons::B ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ || - jets[combi[TtFullHadEvtPartons::BBar ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) && - jets[combi[TtFullHadEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightP ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + } else if (bJetCounter == 1 && + (jets[combi[TtFullHadEvtPartons::B]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ || + jets[combi[TtFullHadEvtPartons::BBar]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) && + jets[combi[TtFullHadEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightP]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; - } - else if( bJetCounter > 1 && - jets[combi[TtFullHadEvtPartons::B ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::BBar ]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && - jets[combi[TtFullHadEvtPartons::LightQ ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightP ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && - jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ ) { + } else if (bJetCounter > 1 && jets[combi[TtFullHadEvtPartons::B]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::BBar]].bDiscriminator(bTagAlgo_) >= minBTagValueBJet_ && + jets[combi[TtFullHadEvtPartons::LightQ]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightQBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightP]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_ && + jets[combi[TtFullHadEvtPartons::LightPBar]].bDiscriminator(bTagAlgo_) < maxBTagValueNonBJet_) { return true; } - } - else if( bTags_ > 2 ){ - throw cms::Exception("Configuration") - << "Wrong number of bTags (" << bTags_ << " bTags not supported)!\n"; + } else if (bTags_ > 2) { + throw cms::Exception("Configuration") << "Wrong number of bTags (" << bTags_ << " bTags not supported)!\n"; return true; } return false; } /// helper function to construct the proper corrected jet for its corresponding quarkType -pat::Jet -TtFullHadKinFitter::KinFit::corJet(const pat::Jet& jet, const std::string& quarkType) -{ +pat::Jet TtFullHadKinFitter::KinFit::corJet(const pat::Jet& jet, const std::string& quarkType) { // jetCorrectionLevel was not configured - if(jetCorrectionLevel_.empty()) + if (jetCorrectionLevel_.empty()) throw cms::Exception("Configuration") - << "Unconfigured jetCorrectionLevel. Please use an appropriate, non-empty string.\n"; + << "Unconfigured jetCorrectionLevel. Please use an appropriate, non-empty string.\n"; // quarkType is unknown - if( !(quarkType=="wMix" || - quarkType=="uds" || - quarkType=="charm" || - quarkType=="bottom") ) - throw cms::Exception("Configuration") - << quarkType << " is unknown as a quarkType for the jetCorrectionLevel.\n"; + if (!(quarkType == "wMix" || quarkType == "uds" || quarkType == "charm" || quarkType == "bottom")) + throw cms::Exception("Configuration") << quarkType << " is unknown as a quarkType for the jetCorrectionLevel.\n"; float jecFactor = 1.; - if(quarkType=="wMix") jecFactor = 0.75 * jet.jecFactor(jetCorrectionLevel_, "uds") + 0.25 * jet.jecFactor(jetCorrectionLevel_, "charm"); - else jecFactor = jet.jecFactor(jetCorrectionLevel_, quarkType); + if (quarkType == "wMix") + jecFactor = 0.75 * jet.jecFactor(jetCorrectionLevel_, "uds") + 0.25 * jet.jecFactor(jetCorrectionLevel_, "charm"); + else + jecFactor = jet.jecFactor(jetCorrectionLevel_, quarkType); pat::Jet ret = jet; - ret.setP4(ret.p4()*jecFactor); + ret.setP4(ret.p4() * jecFactor); return ret; } -std::list -TtFullHadKinFitter::KinFit::fit(const std::vector& jets){ - - std::list fitResults; +std::list TtFullHadKinFitter::KinFit::fit(const std::vector& jets) { + std::list fitResults; /** // -------------------------------------------------------- @@ -465,28 +512,29 @@ TtFullHadKinFitter::KinFit::fit(const std::vector& jets){ // -------------------------------------------------------- **/ - if( jets.size() invalidCombi; - for(unsigned int i = 0; i < nPartons; ++i) invalidCombi.push_back( -1 ); - + for (unsigned int i = 0; i < nPartons; ++i) + invalidCombi.push_back(-1); + KinFitResult result; // status of the fitter - result.Status = -1; + result.Status = -1; // chi2 - result.Chi2 = -1.; + result.Chi2 = -1.; // chi2 probability - result.Prob = -1.; + result.Prob = -1.; // the kinFit getters return empty objects here - result.B = fitter->fittedB(); - result.BBar = fitter->fittedBBar(); - result.LightQ = fitter->fittedLightQ(); - result.LightQBar= fitter->fittedLightQBar(); - result.LightP = fitter->fittedLightP(); - result.LightPBar= fitter->fittedLightPBar(); + result.B = fitter->fittedB(); + result.BBar = fitter->fittedBBar(); + result.LightQ = fitter->fittedLightQ(); + result.LightQBar = fitter->fittedLightQBar(); + result.LightP = fitter->fittedLightP(); + result.LightPBar = fitter->fittedLightPBar(); result.JetCombi = invalidCombi; // push back fit result - fitResults.push_back( result ); + fitResults.push_back(result); return fitResults; } @@ -496,76 +544,75 @@ TtFullHadKinFitter::KinFit::fit(const std::vector& jets){ **/ std::vector jetIndices; - if(!useOnlyMatch_) { - for(unsigned int idx=0; idx=(int)nPartons && maxNJets_==(int)idx) break; + if (!useOnlyMatch_) { + for (unsigned int idx = 0; idx < jets.size(); ++idx) { + if (maxNJets_ >= (int)nPartons && maxNJets_ == (int)idx) + break; jetIndices.push_back(idx); } } - + std::vector combi; - for(unsigned int idx=0; idx::const_iterator jet = jets.begin(); jet < jets.end(); ++jet){ - if(jet->bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) ++bJetCounter; + for (std::vector::const_iterator jet = jets.begin(); jet < jets.end(); ++jet) { + if (jet->bDiscriminator(bTagAlgo_) >= minBTagValueBJet_) + ++bJetCounter; } - do{ - for(int cnt=0; cnt jetCombi; - jetCombi.resize(nPartons); - jetCombi[TtFullHadEvtPartons::LightQ ] = corJet(jets[combi[TtFullHadEvtPartons::LightQ ]], "wMix"); - jetCombi[TtFullHadEvtPartons::LightQBar] = corJet(jets[combi[TtFullHadEvtPartons::LightQBar]], "wMix"); - jetCombi[TtFullHadEvtPartons::B ] = corJet(jets[combi[TtFullHadEvtPartons::B ]], "bottom"); - jetCombi[TtFullHadEvtPartons::BBar ] = corJet(jets[combi[TtFullHadEvtPartons::BBar ]], "bottom"); - jetCombi[TtFullHadEvtPartons::LightP ] = corJet(jets[combi[TtFullHadEvtPartons::LightP ]], "wMix"); - jetCombi[TtFullHadEvtPartons::LightPBar] = corJet(jets[combi[TtFullHadEvtPartons::LightPBar]], "wMix"); - - // do the kinematic fit - int status = fitter->fit(jetCombi); - - if( status == 0 ) { - // fill struct KinFitResults if converged - TtFullHadKinFitter::KinFitResult result; - result.Status = status; - result.Chi2 = fitter->fitS(); - result.Prob = fitter->fitProb(); - result.B = fitter->fittedB(); - result.BBar = fitter->fittedBBar(); - result.LightQ = fitter->fittedLightQ(); - result.LightQBar= fitter->fittedLightQBar(); - result.LightP = fitter->fittedLightP(); - result.LightPBar= fitter->fittedLightPBar(); - result.JetCombi = combi; - // push back fit result - fitResults.push_back( result ); - } + if (((combi[TtFullHadEvtPartons::LightQ] < combi[TtFullHadEvtPartons::LightQBar] && + combi[TtFullHadEvtPartons::LightP] < combi[TtFullHadEvtPartons::LightPBar] && + combi[TtFullHadEvtPartons::B] < combi[TtFullHadEvtPartons::BBar]) || + useOnlyMatch_) && + doBTagging(jets, bJetCounter, combi)) { + std::vector jetCombi; + jetCombi.resize(nPartons); + jetCombi[TtFullHadEvtPartons::LightQ] = corJet(jets[combi[TtFullHadEvtPartons::LightQ]], "wMix"); + jetCombi[TtFullHadEvtPartons::LightQBar] = corJet(jets[combi[TtFullHadEvtPartons::LightQBar]], "wMix"); + jetCombi[TtFullHadEvtPartons::B] = corJet(jets[combi[TtFullHadEvtPartons::B]], "bottom"); + jetCombi[TtFullHadEvtPartons::BBar] = corJet(jets[combi[TtFullHadEvtPartons::BBar]], "bottom"); + jetCombi[TtFullHadEvtPartons::LightP] = corJet(jets[combi[TtFullHadEvtPartons::LightP]], "wMix"); + jetCombi[TtFullHadEvtPartons::LightPBar] = corJet(jets[combi[TtFullHadEvtPartons::LightPBar]], "wMix"); + + // do the kinematic fit + int status = fitter->fit(jetCombi); + + if (status == 0) { + // fill struct KinFitResults if converged + TtFullHadKinFitter::KinFitResult result; + result.Status = status; + result.Chi2 = fitter->fitS(); + result.Prob = fitter->fitProb(); + result.B = fitter->fittedB(); + result.BBar = fitter->fittedBBar(); + result.LightQ = fitter->fittedLightQ(); + result.LightQBar = fitter->fittedLightQBar(); + result.LightP = fitter->fittedLightP(); + result.LightPBar = fitter->fittedLightPBar(); + result.JetCombi = combi; + // push back fit result + fitResults.push_back(result); + } } // don't go through combinatorics if useOnlyMatch was chosen - if(useOnlyMatch_){ - break; + if (useOnlyMatch_) { + break; } // next permutation - std::next_permutation( combi.begin(), combi.end() ); + std::next_permutation(combi.begin(), combi.end()); } // don't go through combinatorics if useOnlyMatch was chosen - if(useOnlyMatch_){ + if (useOnlyMatch_) { break; } - } - while( stdcomb::next_combination( jetIndices.begin(), jetIndices.end(), combi.begin(), combi.end() ) ); - + } while (stdcomb::next_combination(jetIndices.begin(), jetIndices.end(), combi.begin(), combi.end())); // sort results w.r.t. chi2 values fitResults.sort(); @@ -575,72 +622,82 @@ TtFullHadKinFitter::KinFit::fit(const std::vector& jets){ JetComb having the smallest chi2 **/ - if( (unsigned)fitResults.size() < 1 ) { + if ((unsigned)fitResults.size() < 1) { // in case no fit results were stored in the list (i.e. when all fits were aborted) KinFitResult result; // status of the fitter - result.Status = -1; + result.Status = -1; // chi2 - result.Chi2 = -1.; + result.Chi2 = -1.; // chi2 probability - result.Prob = -1.; + result.Prob = -1.; // the kinFit getters return empty objects here - result.B = fitter->fittedB(); - result.BBar = fitter->fittedBBar(); - result.LightQ = fitter->fittedLightQ(); - result.LightQBar= fitter->fittedLightQBar(); - result.LightP = fitter->fittedLightP(); - result.LightPBar= fitter->fittedLightPBar(); + result.B = fitter->fittedB(); + result.BBar = fitter->fittedBBar(); + result.LightQ = fitter->fittedLightQ(); + result.LightQBar = fitter->fittedLightQBar(); + result.LightP = fitter->fittedLightP(); + result.LightPBar = fitter->fittedLightPBar(); // indices referring to the jet combination std::vector invalidCombi(nPartons, -1); result.JetCombi = invalidCombi; // push back fit result - fitResults.push_back( result ); + fitResults.push_back(result); } return fitResults; } -TtFullHadKinFitter::Param -TtFullHadKinFitter::KinFit::param(unsigned int configParameter) -{ +TtFullHadKinFitter::Param TtFullHadKinFitter::KinFit::param(unsigned int configParameter) { TtFullHadKinFitter::Param result; - switch(configParameter){ - case TtFullHadKinFitter::kEMom : result=TtFullHadKinFitter::kEMom; break; - case TtFullHadKinFitter::kEtEtaPhi : result=TtFullHadKinFitter::kEtEtaPhi; break; - case TtFullHadKinFitter::kEtThetaPhi : result=TtFullHadKinFitter::kEtThetaPhi; break; - default: - throw cms::Exception("Configuration") - << "Chosen jet parametrization is not supported: " << configParameter << "\n"; - break; + switch (configParameter) { + case TtFullHadKinFitter::kEMom: + result = TtFullHadKinFitter::kEMom; + break; + case TtFullHadKinFitter::kEtEtaPhi: + result = TtFullHadKinFitter::kEtEtaPhi; + break; + case TtFullHadKinFitter::kEtThetaPhi: + result = TtFullHadKinFitter::kEtThetaPhi; + break; + default: + throw cms::Exception("Configuration") + << "Chosen jet parametrization is not supported: " << configParameter << "\n"; + break; } return result; -} +} -TtFullHadKinFitter::Constraint -TtFullHadKinFitter::KinFit::constraint(unsigned configParameter) -{ +TtFullHadKinFitter::Constraint TtFullHadKinFitter::KinFit::constraint(unsigned configParameter) { TtFullHadKinFitter::Constraint result; - switch(configParameter){ - case TtFullHadKinFitter::kWPlusMass : result=TtFullHadKinFitter::kWPlusMass; break; - case TtFullHadKinFitter::kWMinusMass : result=TtFullHadKinFitter::kWMinusMass; break; - case TtFullHadKinFitter::kTopMass : result=TtFullHadKinFitter::kTopMass; break; - case TtFullHadKinFitter::kTopBarMass : result=TtFullHadKinFitter::kTopBarMass; break; - case TtFullHadKinFitter::kEqualTopMasses : result=TtFullHadKinFitter::kEqualTopMasses; break; - default: - throw cms::Exception("Configuration") - << "Chosen fit constraint is not supported: " << configParameter << "\n"; - break; + switch (configParameter) { + case TtFullHadKinFitter::kWPlusMass: + result = TtFullHadKinFitter::kWPlusMass; + break; + case TtFullHadKinFitter::kWMinusMass: + result = TtFullHadKinFitter::kWMinusMass; + break; + case TtFullHadKinFitter::kTopMass: + result = TtFullHadKinFitter::kTopMass; + break; + case TtFullHadKinFitter::kTopBarMass: + result = TtFullHadKinFitter::kTopBarMass; + break; + case TtFullHadKinFitter::kEqualTopMasses: + result = TtFullHadKinFitter::kEqualTopMasses; + break; + default: + throw cms::Exception("Configuration") << "Chosen fit constraint is not supported: " << configParameter << "\n"; + break; } return result; -} +} -std::vector -TtFullHadKinFitter::KinFit::constraints(const std::vector& configParameters) -{ +std::vector TtFullHadKinFitter::KinFit::constraints( + const std::vector& configParameters) { std::vector result; - for(unsigned i=0; iSetParameters(30.7137,56.2880,23.0744,59.1015,24.9145); + EventShape_ = new TF2("landau2D", "[0]*TMath::Landau(x,[1],[2],0)*TMath::Landau(y,[3],[4],0)", 0, 500, 0, 500); + EventShape_->SetParameters(30.7137, 56.2880, 23.0744, 59.1015, 24.9145); } -TtFullLepKinSolver::TtFullLepKinSolver(const double b, const double e, const double s, const std::vector& nupars, const double mW, const double mB): - topmass_begin(b), - topmass_end(e), - topmass_step(s), - mw(mW), - mb(mB), - pxmiss_(0), - pymiss_(0) -{ - EventShape_ = new TF2("landau2D","[0]*TMath::Landau(x,[1],[2],0)*TMath::Landau(y,[3],[4],0)",0,500,0,500); - EventShape_->SetParameters(nupars[0],nupars[1],nupars[2],nupars[3],nupars[4]); +TtFullLepKinSolver::TtFullLepKinSolver( + const double b, const double e, const double s, const std::vector& nupars, const double mW, const double mB) + : topmass_begin(b), topmass_end(e), topmass_step(s), mw(mW), mb(mB), pxmiss_(0), pymiss_(0) { + EventShape_ = new TF2("landau2D", "[0]*TMath::Landau(x,[1],[2],0)*TMath::Landau(y,[3],[4],0)", 0, 500, 0, 500); + EventShape_->SetParameters(nupars[0], nupars[1], nupars[2], nupars[3], nupars[4]); } // // destructor // -TtFullLepKinSolver::~TtFullLepKinSolver() -{ - delete EventShape_; -} +TtFullLepKinSolver::~TtFullLepKinSolver() { delete EventShape_; } -TtDilepEvtSolution TtFullLepKinSolver::addKinSolInfo(TtDilepEvtSolution * asol) -{ +TtDilepEvtSolution TtFullLepKinSolver::addKinSolInfo(TtDilepEvtSolution* asol) { TtDilepEvtSolution fitsol(*asol); - + //antilepton and lepton TLorentzVector LV_e, LV_e_; //b and bbar quark TLorentzVector LV_b, LV_b_; - + bool hasMCinfo = true; - if(fitsol.getGenN()) { // protect against non-dilept genevents - genLV_n = TLorentzVector(fitsol.getGenN()->px(), fitsol.getGenN()->py(), - fitsol.getGenN()->pz(), fitsol.getGenN()->energy()); - } else hasMCinfo = false; - - if(fitsol.getGenNbar()) { // protect against non-dilept genevents - genLV_n_ = TLorentzVector(fitsol.getGenNbar()->px(), fitsol.getGenNbar()->py(), - fitsol.getGenNbar()->pz(), fitsol.getGenNbar()->energy()); - } else hasMCinfo = false; + if (fitsol.getGenN()) { // protect against non-dilept genevents + genLV_n = TLorentzVector( + fitsol.getGenN()->px(), fitsol.getGenN()->py(), fitsol.getGenN()->pz(), fitsol.getGenN()->energy()); + } else + hasMCinfo = false; + + if (fitsol.getGenNbar()) { // protect against non-dilept genevents + genLV_n_ = TLorentzVector( + fitsol.getGenNbar()->px(), fitsol.getGenNbar()->py(), fitsol.getGenNbar()->pz(), fitsol.getGenNbar()->energy()); + } else + hasMCinfo = false; // if MC is to be used to select the best top mass and is not available, // then nothing can be done. Stop here. - if(useMCforBest_&&!hasMCinfo) return fitsol; + if (useMCforBest_ && !hasMCinfo) + return fitsol; // first lepton if (fitsol.getWpDecay() == "muon") { - LV_e = TLorentzVector(fitsol.getMuonp().px(), fitsol.getMuonp().py(), - fitsol.getMuonp().pz(), fitsol.getMuonp().energy()); + LV_e = TLorentzVector( + fitsol.getMuonp().px(), fitsol.getMuonp().py(), fitsol.getMuonp().pz(), fitsol.getMuonp().energy()); } else if (fitsol.getWpDecay() == "electron") { - LV_e = TLorentzVector(fitsol.getElectronp().px(), fitsol.getElectronp().py(), - fitsol.getElectronp().pz(), fitsol.getElectronp().energy()); + LV_e = TLorentzVector(fitsol.getElectronp().px(), + fitsol.getElectronp().py(), + fitsol.getElectronp().pz(), + fitsol.getElectronp().energy()); } else if (fitsol.getWpDecay() == "tau") { - LV_e = TLorentzVector(fitsol.getTaup().px(), fitsol.getTaup().py(), - fitsol.getTaup().pz(), fitsol.getTaup().energy()); + LV_e = + TLorentzVector(fitsol.getTaup().px(), fitsol.getTaup().py(), fitsol.getTaup().pz(), fitsol.getTaup().energy()); } - + // second lepton if (fitsol.getWmDecay() == "muon") { - LV_e_ = TLorentzVector(fitsol.getMuonm().px(), fitsol.getMuonm().py(), - fitsol.getMuonm().pz(), fitsol.getMuonm().energy()); + LV_e_ = TLorentzVector( + fitsol.getMuonm().px(), fitsol.getMuonm().py(), fitsol.getMuonm().pz(), fitsol.getMuonm().energy()); } else if (fitsol.getWmDecay() == "electron") { - LV_e_ = TLorentzVector(fitsol.getElectronm().px(), fitsol.getElectronm().py(), - fitsol.getElectronm().pz(), fitsol.getElectronm().energy()); + LV_e_ = TLorentzVector(fitsol.getElectronm().px(), + fitsol.getElectronm().py(), + fitsol.getElectronm().pz(), + fitsol.getElectronm().energy()); } else if (fitsol.getWmDecay() == "tau") { - LV_e_ = TLorentzVector(fitsol.getTaum().px(), fitsol.getTaum().py(), - fitsol.getTaum().pz(), fitsol.getTaum().energy()); + LV_e_ = + TLorentzVector(fitsol.getTaum().px(), fitsol.getTaum().py(), fitsol.getTaum().pz(), fitsol.getTaum().energy()); } // first jet - LV_b = TLorentzVector(fitsol.getCalJetB().px(), fitsol.getCalJetB().py(), - fitsol.getCalJetB().pz(), fitsol.getCalJetB().energy()); + LV_b = TLorentzVector( + fitsol.getCalJetB().px(), fitsol.getCalJetB().py(), fitsol.getCalJetB().pz(), fitsol.getCalJetB().energy()); // second jet - LV_b_ = TLorentzVector(fitsol.getCalJetBbar().px(), fitsol.getCalJetBbar().py(), - fitsol.getCalJetBbar().pz(), fitsol.getCalJetBbar().energy()); - + LV_b_ = TLorentzVector(fitsol.getCalJetBbar().px(), + fitsol.getCalJetBbar().py(), + fitsol.getCalJetBbar().pz(), + fitsol.getCalJetBbar().energy()); + //loop on top mass parameter double weightmax = -1e30; double mtmax = 0; - for (double mt = topmass_begin; - mt < topmass_end + 0.5*topmass_step; - mt += topmass_step) { + for (double mt = topmass_begin; mt < topmass_end + 0.5 * topmass_step; mt += topmass_step) { //cout << "mt = " << mt << endl; double q_coeff[5], q_sol[4]; FindCoeff(LV_e, LV_e_, LV_b, LV_b_, mt, mt, pxmiss_, pymiss_, q_coeff); int NSol = quartic(q_coeff, q_sol); - + //loop on all solutions for (int isol = 0; isol < NSol; isol++) { TopRec(LV_e, LV_e_, LV_b, LV_b_, q_sol[isol]); double weight = useMCforBest_ ? WeightSolfromMC() : WeightSolfromShape(); if (weight > weightmax) { - weightmax =weight; - mtmax = mt; + weightmax = weight; + mtmax = mt; } } - + //for (int i=0;i<5;i++) cout << " q_coeff["< weightmax) { - weightmax =weight; - maxLV_n.SetPxPyPzE(LV_n.Px(), LV_n.Py(), LV_n.Pz(), LV_n.E()); - maxLV_n_.SetPxPyPzE(LV_n_.Px(), LV_n_.Py(), LV_n_.Pz(), LV_n_.E()); + weightmax = weight; + maxLV_n.SetPxPyPzE(LV_n.Px(), LV_n.Py(), LV_n.Pz(), LV_n.E()); + maxLV_n_.SetPxPyPzE(LV_n_.Px(), LV_n_.Py(), LV_n_.Pz(), LV_n_.E()); } } } TtFullLepKinSolver::NeutrinoSolution nuSol; - nuSol.neutrino = reco::LeafCandidate(0, maxLV_n ); - nuSol.neutrinoBar = reco::LeafCandidate(0, maxLV_n_ ); - nuSol.weight = weightmax; + nuSol.neutrino = reco::LeafCandidate(0, maxLV_n); + nuSol.neutrinoBar = reco::LeafCandidate(0, maxLV_n_); + nuSol.weight = weightmax; return nuSol; } -void -TtFullLepKinSolver::FindCoeff(const TLorentzVector& al, - const TLorentzVector& l, - const TLorentzVector& b_al, - const TLorentzVector& b_l, - const double mt, - const double mat, - const double px_miss, - const double py_miss, - double* koeficienty) -{ +void TtFullLepKinSolver::FindCoeff(const TLorentzVector& al, + const TLorentzVector& l, + const TLorentzVector& b_al, + const TLorentzVector& b_l, + const double mt, + const double mat, + const double px_miss, + const double py_miss, + double* koeficienty) { double E, apom1, apom2, apom3; - double k11, k21, k31, k41, cpom1, cpom2, cpom3, l11, l21, l31, l41, l51, l61, k1, k2, k3, k4, k5,k6; + double k11, k21, k31, k41, cpom1, cpom2, cpom3, l11, l21, l31, l41, l51, l61, k1, k2, k3, k4, k5, k6; double l1, l2, l3, l4, l5, l6, k15, k25, k35, k45; - C = -al.Px()-b_al.Px()-l.Px()-b_l.Px() + px_miss; - D = -al.Py()-b_al.Py()-l.Py()-b_l.Py() + py_miss; + C = -al.Px() - b_al.Px() - l.Px() - b_l.Px() + px_miss; + D = -al.Py() - b_al.Py() - l.Py() - b_l.Py() + py_miss; // right side of first two linear equations - missing pT - - E = (sqr(mt)-sqr(mw)-sqr(mb))/(2*b_al.E())-sqr(mw)/(2*al.E())-al.E()+al.Px()*b_al.Px()/b_al.E()+al.Py()*b_al.Py()/b_al.E()+al.Pz()*b_al.Pz()/b_al.E(); - F = (sqr(mat)-sqr(mw)-sqr(mb))/(2*b_l.E())-sqr(mw)/(2*l.E())-l.E()+l.Px()*b_l.Px()/b_l.E()+l.Py()*b_l.Py()/b_l.E()+l.Pz()*b_l.Pz()/b_l.E(); - - m1 = al.Px()/al.E()-b_al.Px()/b_al.E(); - m2 = al.Py()/al.E()-b_al.Py()/b_al.E(); - m3 = al.Pz()/al.E()-b_al.Pz()/b_al.E(); - - n1 = l.Px()/l.E()-b_l.Px()/b_l.E(); - n2 = l.Py()/l.E()-b_l.Py()/b_l.E(); - n3 = l.Pz()/l.E()-b_l.Pz()/b_l.E(); - - pom = E-m1*C-m2*D; - apom1 = sqr(al.Px())-sqr(al.E()); - apom2 = sqr(al.Py())-sqr(al.E()); - apom3 = sqr(al.Pz())-sqr(al.E()); - - k11 = 1/sqr(al.E())*(pow(mw,4)/4+sqr(C)*apom1+sqr(D)*apom2+apom3*sqr(pom)/sqr(m3)+sqr(mw)*(al.Px()*C+al.Py()*D+al.Pz()*pom/m3)+2*al.Px()*al.Py()*C*D+2*al.Px()*al.Pz()*C*pom/m3+2*al.Py()*al.Pz()*D*pom/m3); - k21 = 1/sqr(al.E())*(-2*C*m3*n3*apom1+2*apom3*n3*m1*pom/m3-sqr(mw)*m3*n3*al.Px()+sqr(mw)*m1*n3*al.Pz()-2*al.Px()*al.Py()*D*m3*n3+2*al.Px()*al.Pz()*C*m1*n3-2*al.Px()*al.Pz()*n3*pom+2*al.Py()*al.Pz()*D*m1*n3); - k31 = 1/sqr(al.E())*(-2*D*m3*n3*apom2+2*apom3*n3*m2*pom/m3-sqr(mw)*m3*n3*al.Py()+sqr(mw)*m2*n3*al.Pz()-2*al.Px()*al.Py()*C*m3*n3+2*al.Px()*al.Pz()*C*m2*n3-2*al.Py()*al.Pz()*n3*pom+2*al.Py()*al.Pz()*D*m2*n3); - k41 = 1/sqr(al.E())*(2*apom3*m1*m2*sqr(n3)+2*al.Px()*al.Py()*sqr(m3)*sqr(n3)-2*al.Px()*al.Pz()*m2*m3*sqr(n3)-2*al.Py()*al.Pz()*m1*m3*sqr(n3)); - k51 = 1/sqr(al.E())*(apom1*sqr(m3)*sqr(n3)+apom3*sqr(m1)*sqr(n3)-2*al.Px()*al.Pz()*m1*m3*sqr(n3)); - k61 = 1/sqr(al.E())*(apom2*sqr(m3)*sqr(n3)+apom3*sqr(m2)*sqr(n3)-2*al.Py()*al.Pz()*m2*m3*sqr(n3)); - - cpom1 = sqr(l.Px())-sqr(l.E()); - cpom2 = sqr(l.Py())-sqr(l.E()); - cpom3 = sqr(l.Pz())-sqr(l.E()); - - l11 = 1/sqr(l.E())*(pow(mw,4)/4+cpom3*sqr(F)/sqr(n3)+sqr(mw)*l.Pz()*F/n3); - l21 = 1/sqr(l.E())*(-2*cpom3*F*m3*n1/n3+sqr(mw)*(l.Px()*m3*n3-l.Pz()*n1*m3)+2*l.Px()*l.Pz()*F*m3); - l31 = 1/sqr(l.E())*(-2*cpom3*F*m3*n2/n3+sqr(mw)*(l.Py()*m3*n3-l.Pz()*n2*m3)+2*l.Py()*l.Pz()*F*m3); - l41 = 1/sqr(l.E())*(2*cpom3*n1*n2*sqr(m3)+2*l.Px()*l.Py()*sqr(m3)*sqr(n3)-2*l.Px()*l.Pz()*n2*n3*sqr(m3)-2*l.Py()*l.Pz()*n1*n3*sqr(m3)); - l51 = 1/sqr(l.E())*(cpom1*sqr(m3)*sqr(n3)+cpom3*sqr(n1)*sqr(m3)-2*l.Px()*l.Pz()*n1*n3*sqr(m3)); - l61 = 1/sqr(l.E())*(cpom2*sqr(m3)*sqr(n3)+cpom3*sqr(n2)*sqr(m3)-2*l.Py()*l.Pz()*n2*n3*sqr(m3)); - - k1 = k11*k61; - k2 = k61*k21/k51; + + E = (sqr(mt) - sqr(mw) - sqr(mb)) / (2 * b_al.E()) - sqr(mw) / (2 * al.E()) - al.E() + + al.Px() * b_al.Px() / b_al.E() + al.Py() * b_al.Py() / b_al.E() + al.Pz() * b_al.Pz() / b_al.E(); + F = (sqr(mat) - sqr(mw) - sqr(mb)) / (2 * b_l.E()) - sqr(mw) / (2 * l.E()) - l.E() + l.Px() * b_l.Px() / b_l.E() + + l.Py() * b_l.Py() / b_l.E() + l.Pz() * b_l.Pz() / b_l.E(); + + m1 = al.Px() / al.E() - b_al.Px() / b_al.E(); + m2 = al.Py() / al.E() - b_al.Py() / b_al.E(); + m3 = al.Pz() / al.E() - b_al.Pz() / b_al.E(); + + n1 = l.Px() / l.E() - b_l.Px() / b_l.E(); + n2 = l.Py() / l.E() - b_l.Py() / b_l.E(); + n3 = l.Pz() / l.E() - b_l.Pz() / b_l.E(); + + pom = E - m1 * C - m2 * D; + apom1 = sqr(al.Px()) - sqr(al.E()); + apom2 = sqr(al.Py()) - sqr(al.E()); + apom3 = sqr(al.Pz()) - sqr(al.E()); + + k11 = 1 / sqr(al.E()) * + (pow(mw, 4) / 4 + sqr(C) * apom1 + sqr(D) * apom2 + apom3 * sqr(pom) / sqr(m3) + + sqr(mw) * (al.Px() * C + al.Py() * D + al.Pz() * pom / m3) + 2 * al.Px() * al.Py() * C * D + + 2 * al.Px() * al.Pz() * C * pom / m3 + 2 * al.Py() * al.Pz() * D * pom / m3); + k21 = 1 / sqr(al.E()) * + (-2 * C * m3 * n3 * apom1 + 2 * apom3 * n3 * m1 * pom / m3 - sqr(mw) * m3 * n3 * al.Px() + + sqr(mw) * m1 * n3 * al.Pz() - 2 * al.Px() * al.Py() * D * m3 * n3 + 2 * al.Px() * al.Pz() * C * m1 * n3 - + 2 * al.Px() * al.Pz() * n3 * pom + 2 * al.Py() * al.Pz() * D * m1 * n3); + k31 = 1 / sqr(al.E()) * + (-2 * D * m3 * n3 * apom2 + 2 * apom3 * n3 * m2 * pom / m3 - sqr(mw) * m3 * n3 * al.Py() + + sqr(mw) * m2 * n3 * al.Pz() - 2 * al.Px() * al.Py() * C * m3 * n3 + 2 * al.Px() * al.Pz() * C * m2 * n3 - + 2 * al.Py() * al.Pz() * n3 * pom + 2 * al.Py() * al.Pz() * D * m2 * n3); + k41 = 1 / sqr(al.E()) * + (2 * apom3 * m1 * m2 * sqr(n3) + 2 * al.Px() * al.Py() * sqr(m3) * sqr(n3) - + 2 * al.Px() * al.Pz() * m2 * m3 * sqr(n3) - 2 * al.Py() * al.Pz() * m1 * m3 * sqr(n3)); + k51 = 1 / sqr(al.E()) * + (apom1 * sqr(m3) * sqr(n3) + apom3 * sqr(m1) * sqr(n3) - 2 * al.Px() * al.Pz() * m1 * m3 * sqr(n3)); + k61 = 1 / sqr(al.E()) * + (apom2 * sqr(m3) * sqr(n3) + apom3 * sqr(m2) * sqr(n3) - 2 * al.Py() * al.Pz() * m2 * m3 * sqr(n3)); + + cpom1 = sqr(l.Px()) - sqr(l.E()); + cpom2 = sqr(l.Py()) - sqr(l.E()); + cpom3 = sqr(l.Pz()) - sqr(l.E()); + + l11 = 1 / sqr(l.E()) * (pow(mw, 4) / 4 + cpom3 * sqr(F) / sqr(n3) + sqr(mw) * l.Pz() * F / n3); + l21 = + 1 / sqr(l.E()) * + (-2 * cpom3 * F * m3 * n1 / n3 + sqr(mw) * (l.Px() * m3 * n3 - l.Pz() * n1 * m3) + 2 * l.Px() * l.Pz() * F * m3); + l31 = + 1 / sqr(l.E()) * + (-2 * cpom3 * F * m3 * n2 / n3 + sqr(mw) * (l.Py() * m3 * n3 - l.Pz() * n2 * m3) + 2 * l.Py() * l.Pz() * F * m3); + l41 = 1 / sqr(l.E()) * + (2 * cpom3 * n1 * n2 * sqr(m3) + 2 * l.Px() * l.Py() * sqr(m3) * sqr(n3) - + 2 * l.Px() * l.Pz() * n2 * n3 * sqr(m3) - 2 * l.Py() * l.Pz() * n1 * n3 * sqr(m3)); + l51 = 1 / sqr(l.E()) * + (cpom1 * sqr(m3) * sqr(n3) + cpom3 * sqr(n1) * sqr(m3) - 2 * l.Px() * l.Pz() * n1 * n3 * sqr(m3)); + l61 = 1 / sqr(l.E()) * + (cpom2 * sqr(m3) * sqr(n3) + cpom3 * sqr(n2) * sqr(m3) - 2 * l.Py() * l.Pz() * n2 * n3 * sqr(m3)); + + k1 = k11 * k61; + k2 = k61 * k21 / k51; k3 = k31; - k4 = k41/k51; - k5 = k61/k51; + k4 = k41 / k51; + k5 = k61 / k51; k6 = 1; - - l1 = l11*k61; - l2 = l21*k61/k51; + + l1 = l11 * k61; + l2 = l21 * k61 / k51; l3 = l31; - l4 = l41/k51; - l5 = l51*k61/(sqr(k51)); - l6 = l61/k61; - - k15 = k1*l5-l1*k5; - k25 = k2*l5-l2*k5; - k35 = k3*l5-l3*k5; - k45 = k4*l5-l4*k5; - - k16 = k1*l6-l1*k6; - k26 = k2*l6-l2*k6; - k36 = k3*l6-l3*k6; - k46 = k4*l6-l4*k6; - k56 = k5*l6-l5*k6; - - koeficienty[0] = k15*sqr(k36)-k35*k36*k16-k56*sqr(k16); - koeficienty[1] = 2*k15*k36*k46+k25*sqr(k36)+k35*(-k46*k16-k36*k26)-k45*k36*k16-2*k56*k26*k16; - koeficienty[2] = k15*sqr(k46)+2*k25*k36*k46+k35*(-k46*k26-k36*k56)-k56*(sqr(k26)+2*k56*k16)-k45*(k46*k16+k36*k26); - koeficienty[3] = k25*sqr(k46)-k35*k46*k56-k45*(k46*k26+k36*k56)-2*sqr(k56)*k26; - koeficienty[4] = -k45*k46*k56-pow(k56,3); - + l4 = l41 / k51; + l5 = l51 * k61 / (sqr(k51)); + l6 = l61 / k61; + + k15 = k1 * l5 - l1 * k5; + k25 = k2 * l5 - l2 * k5; + k35 = k3 * l5 - l3 * k5; + k45 = k4 * l5 - l4 * k5; + + k16 = k1 * l6 - l1 * k6; + k26 = k2 * l6 - l2 * k6; + k36 = k3 * l6 - l3 * k6; + k46 = k4 * l6 - l4 * k6; + k56 = k5 * l6 - l5 * k6; + + koeficienty[0] = k15 * sqr(k36) - k35 * k36 * k16 - k56 * sqr(k16); + koeficienty[1] = + 2 * k15 * k36 * k46 + k25 * sqr(k36) + k35 * (-k46 * k16 - k36 * k26) - k45 * k36 * k16 - 2 * k56 * k26 * k16; + koeficienty[2] = k15 * sqr(k46) + 2 * k25 * k36 * k46 + k35 * (-k46 * k26 - k36 * k56) - + k56 * (sqr(k26) + 2 * k56 * k16) - k45 * (k46 * k16 + k36 * k26); + koeficienty[3] = k25 * sqr(k46) - k35 * k46 * k56 - k45 * (k46 * k26 + k36 * k56) - 2 * sqr(k56) * k26; + koeficienty[4] = -k45 * k46 * k56 - pow(k56, 3); + // normalization of coefficients - int moc=(int(log10(fabs(koeficienty[0])))+int(log10(fabs(koeficienty[4]))))/2; - - koeficienty[0]=koeficienty[0]/TMath::Power(10,moc); - koeficienty[1]=koeficienty[1]/TMath::Power(10,moc); - koeficienty[2]=koeficienty[2]/TMath::Power(10,moc); - koeficienty[3]=koeficienty[3]/TMath::Power(10,moc); - koeficienty[4]=koeficienty[4]/TMath::Power(10,moc); + int moc = (int(log10(fabs(koeficienty[0]))) + int(log10(fabs(koeficienty[4])))) / 2; + + koeficienty[0] = koeficienty[0] / TMath::Power(10, moc); + koeficienty[1] = koeficienty[1] / TMath::Power(10, moc); + koeficienty[2] = koeficienty[2] / TMath::Power(10, moc); + koeficienty[3] = koeficienty[3] / TMath::Power(10, moc); + koeficienty[4] = koeficienty[4] / TMath::Power(10, moc); } -void TtFullLepKinSolver::TopRec(const TLorentzVector& al, +void TtFullLepKinSolver::TopRec(const TLorentzVector& al, const TLorentzVector& l, - const TLorentzVector& b_al, - const TLorentzVector& b_l, - const double sol) -{ + const TLorentzVector& b_al, + const TLorentzVector& b_l, + const double sol) { TVector3 t_ttboost; TLorentzVector aux; double pxp, pyp, pzp, pup, pvp, pwp; - - pxp = sol*(m3*n3/k51); - pyp = -(m3*n3/k61)*(k56*pow(sol,2) + k26*sol + k16)/(k36 + k46*sol); - pzp = -1/n3*(n1*pxp + n2*pyp - F); - pwp = 1/m3*(m1*pxp + m2*pyp + pom); + + pxp = sol * (m3 * n3 / k51); + pyp = -(m3 * n3 / k61) * (k56 * pow(sol, 2) + k26 * sol + k16) / (k36 + k46 * sol); + pzp = -1 / n3 * (n1 * pxp + n2 * pyp - F); + pwp = 1 / m3 * (m1 * pxp + m2 * pyp + pom); pup = C - pxp; pvp = D - pyp; - + LV_n_.SetXYZM(pxp, pyp, pzp, 0.0); LV_n.SetXYZM(pup, pvp, pwp, 0.0); - + LV_t_ = b_l + l + LV_n_; - LV_t = b_al + al + LV_n; - + LV_t = b_al + al + LV_n; + aux = (LV_t_ + LV_t); t_ttboost = -aux.BoostVector(); LV_tt_t_ = LV_t_; LV_tt_t = LV_t; LV_tt_t_.Boost(t_ttboost); - LV_tt_t.Boost(t_ttboost); + LV_tt_t.Boost(t_ttboost); } -double -TtFullLepKinSolver::WeightSolfromMC() const -{ +double TtFullLepKinSolver::WeightSolfromMC() const { double weight = 1; - weight = ((LV_n.E() > genLV_n.E())? genLV_n.E()/LV_n.E(): LV_n.E()/genLV_n.E()) - *((LV_n_.E() > genLV_n_.E())? genLV_n_.E()/LV_n_.E(): LV_n_.E()/genLV_n_.E()); + weight = ((LV_n.E() > genLV_n.E()) ? genLV_n.E() / LV_n.E() : LV_n.E() / genLV_n.E()) * + ((LV_n_.E() > genLV_n_.E()) ? genLV_n_.E() / LV_n_.E() : LV_n_.E() / genLV_n_.E()); return weight; } -double -TtFullLepKinSolver::WeightSolfromShape() const -{ - return EventShape_->Eval(LV_n.E(),LV_n_.E()); -} - -int -TtFullLepKinSolver::quartic(double *koeficienty, double* koreny) const -{ +double TtFullLepKinSolver::WeightSolfromShape() const { return EventShape_->Eval(LV_n.E(), LV_n_.E()); } + +int TtFullLepKinSolver::quartic(double* koeficienty, double* koreny) const { double w, b0, b1, b2; double c[4]; double d0, d1, h, t, z; - double *px; - - if (koeficienty[4]==0.0) + double* px; + + if (koeficienty[4] == 0.0) return cubic(koeficienty, koreny); /* quartic problem? */ - w = koeficienty[3]/(4*koeficienty[4]); + w = koeficienty[3] / (4 * koeficienty[4]); /* offset */ - b2 = -6*sqr(w) + koeficienty[2]/koeficienty[4]; + b2 = -6 * sqr(w) + koeficienty[2] / koeficienty[4]; /* koeficienty. of shifted polynomial */ - b1 = (8*sqr(w) - 2*koeficienty[2]/koeficienty[4])*w + koeficienty[1]/koeficienty[4]; - b0 = ((-3*sqr(w) + koeficienty[2]/koeficienty[4])*w - koeficienty[1]/koeficienty[4])*w + koeficienty[0]/koeficienty[4]; + b1 = (8 * sqr(w) - 2 * koeficienty[2] / koeficienty[4]) * w + koeficienty[1] / koeficienty[4]; + b0 = ((-3 * sqr(w) + koeficienty[2] / koeficienty[4]) * w - koeficienty[1] / koeficienty[4]) * w + + koeficienty[0] / koeficienty[4]; c[3] = 1.0; /* cubic resolvent */ c[2] = b2; - c[1] = -4*b0; - c[0] = sqr(b1) - 4*b0*b2; - + c[1] = -4 * b0; + c[0] = sqr(b1) - 4 * b0 * b2; + cubic(c, koreny); z = koreny[0]; //double z1=1.0,z2=2.0,z3=3.0; @@ -345,113 +344,110 @@ TtFullLepKinSolver::quartic(double *koeficienty, double* koreny) const int nreal = 0; px = koreny; - t = sqrt(0.25*sqr(z) - b0); - for(int i=-1; i<=1; i+=2) { - d0 = -0.5*z + i*t; + t = sqrt(0.25 * sqr(z) - b0); + for (int i = -1; i <= 1; i += 2) { + d0 = -0.5 * z + i * t; /* coeffs. of quadratic factor */ - d1 = (t!=0.0)? -i*0.5*b1/t : i*sqrt(-z - b2); - h = 0.25*sqr(d1) - d0; - if (h>=0.0) { + d1 = (t != 0.0) ? -i * 0.5 * b1 / t : i * sqrt(-z - b2); + h = 0.25 * sqr(d1) - d0; + if (h >= 0.0) { h = sqrt(h); nreal += 2; - *px++ = -0.5*d1 - h - w; - *px++ = -0.5*d1 + h - w; + *px++ = -0.5 * d1 - h - w; + *px++ = -0.5 * d1 + h - w; } } // if (nreal==4) { - /* sort results */ -// if (koreny[2]1.0) h = 1.0; + h = q / sqrt(-p); + if (h > 1.0) + h = 1.0; /* confine the argument of */ - if (h<-1.0) h = -1.0; + if (h < -1.0) + h = -1.0; /* acos to [-1;+1] */ phi = acos(h); - p = 2*TMath::Power(-p, 1.0/6.0); - for(unsigned i=0; i<3; i++) - koreny[i] = p*cos((phi+2*i*TMath::Pi())/3.0) - w; - if (koreny[1]0.0)? h : -h) + ((q-dis>0.0)? p : -p) - w; + h = TMath::Power(fabs(q + dis), 1.0 / 3.0); + p = TMath::Power(fabs(q - dis), 1.0 / 3.0); + koreny[0] = ((q + dis > 0.0) ? h : -h) + ((q - dis > 0.0) ? p : -p) - w; nreal = 1; } /* Perform one step of a Newton iteration in order to minimize round-off errors */ - for(unsigned i=0; i=0.0) { + p = 0.5 * coeffs[1] / coeffs[2]; + dis = sqr(p) - coeffs[0] / coeffs[2]; + if (dis >= 0.0) { /* two real solutions */ dis = sqrt(dis); koreny[0] = -p - dis; koreny[1] = -p + dis; nreal = 2; - } - else + } else /* no real solution */ nreal = 0; } - else if (coeffs[1]!=0.0) { + else if (coeffs[1] != 0.0) { /* linear problem? */ - koreny[0] = -coeffs[0]/coeffs[1]; + koreny[0] = -coeffs[0] / coeffs[1]; nreal = 1; } else /* no equation */ nreal = 0; - + return nreal; } - -void -TtFullLepKinSolver::SWAP(double& realone, double& realtwo) const -{ +void TtFullLepKinSolver::SWAP(double& realone, double& realtwo) const { if (realtwo < realone) { double aux = realtwo; realtwo = realone; diff --git a/TopQuarkAnalysis/TopKinFitter/src/TtSemiLepKinFitter.cc b/TopQuarkAnalysis/TopKinFitter/src/TtSemiLepKinFitter.cc index ca4662ce66c98..ef8eaa9b4c90f 100644 --- a/TopQuarkAnalysis/TopKinFitter/src/TtSemiLepKinFitter.cc +++ b/TopQuarkAnalysis/TopKinFitter/src/TtSemiLepKinFitter.cc @@ -12,147 +12,192 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" /// default configuration is: Parametrization kEMom, Max iterations = 200, deltaS<= 5e-5, maxF<= 1e-4, no constraints -TtSemiLepKinFitter::TtSemiLepKinFitter(): - TopKinFitter(), - hadB_(nullptr), hadP_(nullptr), hadQ_(nullptr), lepB_(nullptr), lepton_(nullptr), neutrino_(nullptr), - udscResolutions_(nullptr), bResolutions_(nullptr), lepResolutions_(nullptr), metResolutions_(nullptr), - jetEnergyResolutionScaleFactors_(nullptr), jetEnergyResolutionEtaBinning_(nullptr), - jetParam_(kEMom), lepParam_(kEMom), metParam_(kEMom) -{ +TtSemiLepKinFitter::TtSemiLepKinFitter() + : TopKinFitter(), + hadB_(nullptr), + hadP_(nullptr), + hadQ_(nullptr), + lepB_(nullptr), + lepton_(nullptr), + neutrino_(nullptr), + udscResolutions_(nullptr), + bResolutions_(nullptr), + lepResolutions_(nullptr), + metResolutions_(nullptr), + jetEnergyResolutionScaleFactors_(nullptr), + jetEnergyResolutionEtaBinning_(nullptr), + jetParam_(kEMom), + lepParam_(kEMom), + metParam_(kEMom) { setupFitter(); } -TtSemiLepKinFitter::TtSemiLepKinFitter(Param jetParam, Param lepParam, Param metParam, - int maxNrIter, double maxDeltaS, double maxF, - const std::vector& constraints, double mW, double mTop, - const std::vector* udscResolutions, - const std::vector* bResolutions, - const std::vector* lepResolutions, - const std::vector* metResolutions, - const std::vector* jetEnergyResolutionScaleFactors, - const std::vector* jetEnergyResolutionEtaBinning): - TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), - hadB_(nullptr), hadP_(nullptr), hadQ_(nullptr), lepB_(nullptr), lepton_(nullptr), neutrino_(nullptr), - udscResolutions_(udscResolutions), bResolutions_(bResolutions), lepResolutions_(lepResolutions), metResolutions_(metResolutions), - jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), - jetParam_(jetParam), lepParam_(lepParam), metParam_(metParam), constrList_(constraints) -{ +TtSemiLepKinFitter::TtSemiLepKinFitter(Param jetParam, + Param lepParam, + Param metParam, + int maxNrIter, + double maxDeltaS, + double maxF, + const std::vector& constraints, + double mW, + double mTop, + const std::vector* udscResolutions, + const std::vector* bResolutions, + const std::vector* lepResolutions, + const std::vector* metResolutions, + const std::vector* jetEnergyResolutionScaleFactors, + const std::vector* jetEnergyResolutionEtaBinning) + : TopKinFitter(maxNrIter, maxDeltaS, maxF, mW, mTop), + hadB_(nullptr), + hadP_(nullptr), + hadQ_(nullptr), + lepB_(nullptr), + lepton_(nullptr), + neutrino_(nullptr), + udscResolutions_(udscResolutions), + bResolutions_(bResolutions), + lepResolutions_(lepResolutions), + metResolutions_(metResolutions), + jetEnergyResolutionScaleFactors_(jetEnergyResolutionScaleFactors), + jetEnergyResolutionEtaBinning_(jetEnergyResolutionEtaBinning), + jetParam_(jetParam), + lepParam_(lepParam), + metParam_(metParam), + constrList_(constraints) { setupFitter(); } -TtSemiLepKinFitter::~TtSemiLepKinFitter() -{ - delete hadB_; - delete hadP_; +TtSemiLepKinFitter::~TtSemiLepKinFitter() { + delete hadB_; + delete hadP_; delete hadQ_; - delete lepB_; - delete lepton_; + delete lepB_; + delete lepton_; delete neutrino_; delete covM_; - for(std::map::iterator it = massConstr_.begin(); it != massConstr_.end(); ++it) + for (std::map::iterator it = massConstr_.begin(); it != massConstr_.end(); ++it) delete it->second; delete sumPxConstr_; delete sumPyConstr_; } -void TtSemiLepKinFitter::printSetup() const -{ +void TtSemiLepKinFitter::printSetup() const { std::stringstream constr; - for(unsigned int i=0; iaddParticles1(hadP_, hadQ_ ); - massConstr_[kWLepMass ]->addParticles1(lepton_, neutrino_); - massConstr_[kTopHadMass ]->addParticles1(hadP_, hadQ_, hadB_); - massConstr_[kTopLepMass ]->addParticles1(lepton_, neutrino_, lepB_); - massConstr_[kNeutrinoMass ]->addParticle1 (neutrino_); + massConstr_[kWHadMass]->addParticles1(hadP_, hadQ_); + massConstr_[kWLepMass]->addParticles1(lepton_, neutrino_); + massConstr_[kTopHadMass]->addParticles1(hadP_, hadQ_, hadB_); + massConstr_[kTopLepMass]->addParticles1(lepton_, neutrino_, lepB_); + massConstr_[kNeutrinoMass]->addParticle1(neutrino_); massConstr_[kEqualTopMasses]->addParticles1(hadP_, hadQ_, hadB_); massConstr_[kEqualTopMasses]->addParticles2(lepton_, neutrino_, lepB_); sumPxConstr_->addParticles(lepton_, neutrino_, hadP_, hadQ_, hadB_, lepB_); sumPyConstr_->addParticles(lepton_, neutrino_, hadP_, hadQ_, hadB_, lepB_); - if(std::find(constrList_.begin(), constrList_.end(), kSumPt)!=constrList_.end()) + if (std::find(constrList_.begin(), constrList_.end(), kSumPt) != constrList_.end()) constrainSumPt_ = true; constrainSumPt_ = false; } -void TtSemiLepKinFitter::setupFitter() -{ +void TtSemiLepKinFitter::setupFitter() { printSetup(); setupJets(); @@ -168,120 +213,168 @@ void TtSemiLepKinFitter::setupFitter() fitter_->addMeasParticle(neutrino_); // add constraints - for(unsigned int i=0; iaddConstraint(massConstr_[constrList_[i]]); } - if(constrainSumPt_) { + if (constrainSumPt_) { fitter_->addConstraint(sumPxConstr_); fitter_->addConstraint(sumPyConstr_); } // initialize helper class used to bring the resolutions into covariance matrices - if(!udscResolutions_->empty() && !bResolutions_->empty() && !lepResolutions_->empty() && !metResolutions_->empty()) - covM_ = new CovarianceMatrix(*udscResolutions_, *bResolutions_, *lepResolutions_, *metResolutions_, - *jetEnergyResolutionScaleFactors_, *jetEnergyResolutionEtaBinning_); + if (!udscResolutions_->empty() && !bResolutions_->empty() && !lepResolutions_->empty() && !metResolutions_->empty()) + covM_ = new CovarianceMatrix(*udscResolutions_, + *bResolutions_, + *lepResolutions_, + *metResolutions_, + *jetEnergyResolutionScaleFactors_, + *jetEnergyResolutionEtaBinning_); else covM_ = new CovarianceMatrix(); } -int TtSemiLepKinFitter::fit(const TLorentzVector& p4HadP, const TLorentzVector& p4HadQ, const TLorentzVector& p4HadB, const TLorentzVector& p4LepB, - const TLorentzVector& p4Lepton, const TLorentzVector& p4Neutrino, const int leptonCharge, const CovarianceMatrix::ObjectType leptonType) -{ +int TtSemiLepKinFitter::fit(const TLorentzVector& p4HadP, + const TLorentzVector& p4HadQ, + const TLorentzVector& p4HadB, + const TLorentzVector& p4LepB, + const TLorentzVector& p4Lepton, + const TLorentzVector& p4Neutrino, + const int leptonCharge, + const CovarianceMatrix::ObjectType leptonType) { // initialize covariance matrices TMatrixD covHadP = covM_->setupMatrix(p4HadP, CovarianceMatrix::kUdscJet, jetParam_); TMatrixD covHadQ = covM_->setupMatrix(p4HadQ, CovarianceMatrix::kUdscJet, jetParam_); TMatrixD covHadB = covM_->setupMatrix(p4HadB, CovarianceMatrix::kBJet, jetParam_); TMatrixD covLepB = covM_->setupMatrix(p4LepB, CovarianceMatrix::kBJet, jetParam_); - TMatrixD covLepton = covM_->setupMatrix(p4Lepton , leptonType , lepParam_); - TMatrixD covNeutrino = covM_->setupMatrix(p4Neutrino, CovarianceMatrix::kMet , metParam_); + TMatrixD covLepton = covM_->setupMatrix(p4Lepton, leptonType, lepParam_); + TMatrixD covNeutrino = covM_->setupMatrix(p4Neutrino, CovarianceMatrix::kMet, metParam_); // now do the part that is fully independent of PAT features - return fit(p4HadP, p4HadQ, p4HadB, p4LepB, p4Lepton, p4Neutrino, - covHadP, covHadQ, covHadB, covLepB, covLepton, covNeutrino, - leptonCharge); + return fit(p4HadP, + p4HadQ, + p4HadB, + p4LepB, + p4Lepton, + p4Neutrino, + covHadP, + covHadQ, + covHadB, + covLepB, + covLepton, + covNeutrino, + leptonCharge); } -int TtSemiLepKinFitter::fit(const TLorentzVector& p4HadP, const TLorentzVector& p4HadQ, const TLorentzVector& p4HadB, const TLorentzVector& p4LepB, - const TLorentzVector& p4Lepton, const TLorentzVector& p4Neutrino, - const TMatrixD& covHadP, const TMatrixD& covHadQ, const TMatrixD& covHadB, const TMatrixD& covLepB, - const TMatrixD& covLepton, const TMatrixD& covNeutrino, const int leptonCharge) -{ +int TtSemiLepKinFitter::fit(const TLorentzVector& p4HadP, + const TLorentzVector& p4HadQ, + const TLorentzVector& p4HadB, + const TLorentzVector& p4LepB, + const TLorentzVector& p4Lepton, + const TLorentzVector& p4Neutrino, + const TMatrixD& covHadP, + const TMatrixD& covHadQ, + const TMatrixD& covHadB, + const TMatrixD& covLepB, + const TMatrixD& covLepton, + const TMatrixD& covNeutrino, + const int leptonCharge) { // set the kinematics of the objects to be fitted - hadP_->setIni4Vec( &p4HadP ); - hadQ_->setIni4Vec( &p4HadQ ); - hadB_->setIni4Vec( &p4HadB ); - lepB_->setIni4Vec( &p4LepB ); - lepton_->setIni4Vec( &p4Lepton ); - neutrino_->setIni4Vec( &p4Neutrino ); + hadP_->setIni4Vec(&p4HadP); + hadQ_->setIni4Vec(&p4HadQ); + hadB_->setIni4Vec(&p4HadB); + lepB_->setIni4Vec(&p4LepB); + lepton_->setIni4Vec(&p4Lepton); + neutrino_->setIni4Vec(&p4Neutrino); - hadP_->setCovMatrix( &covHadP ); - hadQ_->setCovMatrix( &covHadQ ); - hadB_->setCovMatrix( &covHadB ); - lepB_->setCovMatrix( &covLepB ); - lepton_ ->setCovMatrix( &covLepton ); - neutrino_->setCovMatrix( &covNeutrino ); + hadP_->setCovMatrix(&covHadP); + hadQ_->setCovMatrix(&covHadQ); + hadB_->setCovMatrix(&covHadB); + lepB_->setCovMatrix(&covLepB); + lepton_->setCovMatrix(&covLepton); + neutrino_->setCovMatrix(&covNeutrino); - if(constrainSumPt_){ + if (constrainSumPt_) { // setup Px and Py constraint for curent event configuration so that sum Pt will be conserved - sumPxConstr_->setConstraint( p4HadP.Px() + p4HadQ.Px() + p4HadB.Px() + p4LepB.Px() + p4Lepton.Px() + p4Neutrino.Px() ); - sumPyConstr_->setConstraint( p4HadP.Py() + p4HadQ.Py() + p4HadB.Py() + p4LepB.Py() + p4Lepton.Py() + p4Neutrino.Py() ); + sumPxConstr_->setConstraint(p4HadP.Px() + p4HadQ.Px() + p4HadB.Px() + p4LepB.Px() + p4Lepton.Px() + + p4Neutrino.Px()); + sumPyConstr_->setConstraint(p4HadP.Py() + p4HadQ.Py() + p4HadB.Py() + p4LepB.Py() + p4Lepton.Py() + + p4Neutrino.Py()); } // now do the fit fitter_->fit(); // read back the resulting particles if the fit converged - if(fitter_->getStatus()==0){ + if (fitter_->getStatus() == 0) { // read back jet kinematics - fittedHadP_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(hadP_->getCurr4Vec()->X(), - hadP_->getCurr4Vec()->Y(), hadP_->getCurr4Vec()->Z(), hadP_->getCurr4Vec()->E()), math::XYZPoint())); - fittedHadQ_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(hadQ_->getCurr4Vec()->X(), - hadQ_->getCurr4Vec()->Y(), hadQ_->getCurr4Vec()->Z(), hadQ_->getCurr4Vec()->E()), math::XYZPoint())); - fittedHadB_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(hadB_->getCurr4Vec()->X(), - hadB_->getCurr4Vec()->Y(), hadB_->getCurr4Vec()->Z(), hadB_->getCurr4Vec()->E()), math::XYZPoint())); - fittedLepB_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(lepB_->getCurr4Vec()->X(), - lepB_->getCurr4Vec()->Y(), lepB_->getCurr4Vec()->Z(), lepB_->getCurr4Vec()->E()), math::XYZPoint())); + fittedHadP_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + hadP_->getCurr4Vec()->X(), hadP_->getCurr4Vec()->Y(), hadP_->getCurr4Vec()->Z(), hadP_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedHadQ_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + hadQ_->getCurr4Vec()->X(), hadQ_->getCurr4Vec()->Y(), hadQ_->getCurr4Vec()->Z(), hadQ_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedHadB_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + hadB_->getCurr4Vec()->X(), hadB_->getCurr4Vec()->Y(), hadB_->getCurr4Vec()->Z(), hadB_->getCurr4Vec()->E()), + math::XYZPoint())); + fittedLepB_ = pat::Particle(reco::LeafCandidate( + 0, + math::XYZTLorentzVector( + lepB_->getCurr4Vec()->X(), lepB_->getCurr4Vec()->Y(), lepB_->getCurr4Vec()->Z(), lepB_->getCurr4Vec()->E()), + math::XYZPoint())); // read back lepton kinematics - fittedLepton_= pat::Particle(reco::LeafCandidate(leptonCharge, math::XYZTLorentzVector(lepton_->getCurr4Vec()->X(), - lepton_->getCurr4Vec()->Y(), lepton_->getCurr4Vec()->Z(), lepton_->getCurr4Vec()->E()), math::XYZPoint())); + fittedLepton_ = pat::Particle(reco::LeafCandidate(leptonCharge, + math::XYZTLorentzVector(lepton_->getCurr4Vec()->X(), + lepton_->getCurr4Vec()->Y(), + lepton_->getCurr4Vec()->Z(), + lepton_->getCurr4Vec()->E()), + math::XYZPoint())); // read back the MET kinematics - fittedNeutrino_= pat::Particle(reco::LeafCandidate(0, math::XYZTLorentzVector(neutrino_->getCurr4Vec()->X(), - neutrino_->getCurr4Vec()->Y(), neutrino_->getCurr4Vec()->Z(), neutrino_->getCurr4Vec()->E()), math::XYZPoint())); - + fittedNeutrino_ = pat::Particle(reco::LeafCandidate(0, + math::XYZTLorentzVector(neutrino_->getCurr4Vec()->X(), + neutrino_->getCurr4Vec()->Y(), + neutrino_->getCurr4Vec()->Z(), + neutrino_->getCurr4Vec()->E()), + math::XYZPoint())); } return fitter_->getStatus(); } -TtSemiEvtSolution TtSemiLepKinFitter::addKinFitInfo(TtSemiEvtSolution* asol) -{ - +TtSemiEvtSolution TtSemiLepKinFitter::addKinFitInfo(TtSemiEvtSolution* asol) { TtSemiEvtSolution fitsol(*asol); std::vector jets; jets.resize(4); - jets[TtSemiLepEvtPartons::LightQ ] = fitsol.getCalHadp(); + jets[TtSemiLepEvtPartons::LightQ] = fitsol.getCalHadp(); jets[TtSemiLepEvtPartons::LightQBar] = fitsol.getCalHadq(); - jets[TtSemiLepEvtPartons::HadB ] = fitsol.getCalHadb(); - jets[TtSemiLepEvtPartons::LepB ] = fitsol.getCalLepb(); + jets[TtSemiLepEvtPartons::HadB] = fitsol.getCalHadb(); + jets[TtSemiLepEvtPartons::LepB] = fitsol.getCalLepb(); // perform the fit, either using the electron or the muon - if(fitsol.getDecay() == "electron") fit( jets, fitsol.getCalLepe(), fitsol.getCalLepn() ); - if(fitsol.getDecay() == "muon" ) fit( jets, fitsol.getCalLepm(), fitsol.getCalLepn() ); - + if (fitsol.getDecay() == "electron") + fit(jets, fitsol.getCalLepe(), fitsol.getCalLepn()); + if (fitsol.getDecay() == "muon") + fit(jets, fitsol.getCalLepm(), fitsol.getCalLepn()); + // add fitted information to the solution if (fitter_->getStatus() == 0) { // fill the fitted particles - fitsol.setFitHadb( fittedHadB() ); - fitsol.setFitHadp( fittedHadP() ); - fitsol.setFitHadq( fittedHadQ() ); - fitsol.setFitLepb( fittedLepB() ); - fitsol.setFitLepl( fittedLepton() ); - fitsol.setFitLepn( fittedNeutrino() ); + fitsol.setFitHadb(fittedHadB()); + fitsol.setFitHadp(fittedHadP()); + fitsol.setFitHadq(fittedHadQ()); + fitsol.setFitLepb(fittedLepB()); + fitsol.setFitLepl(fittedLepton()); + fitsol.setFitLepn(fittedNeutrino()); // store the fit's chi2 probability - fitsol.setProbChi2( fitProb() ); + fitsol.setProbChi2(fitProb()); } return fitsol; } diff --git a/TopQuarkAnalysis/TopKinFitter/test/runtestTqafTopKinFitter.cpp b/TopQuarkAnalysis/TopKinFitter/test/runtestTqafTopKinFitter.cpp index 87f88d6e99091..b2991bd18ae57 100644 --- a/TopQuarkAnalysis/TopKinFitter/test/runtestTqafTopKinFitter.cpp +++ b/TopQuarkAnalysis/TopKinFitter/test/runtestTqafTopKinFitter.cpp @@ -1,3 +1,3 @@ #include "FWCore/Utilities/interface/TestHelper.h" - + RUNTEST() diff --git a/TopQuarkAnalysis/TopTools/interface/JetPartonMatching.h b/TopQuarkAnalysis/TopTools/interface/JetPartonMatching.h index 70721b81c1c10..a61e55f391dc2 100644 --- a/TopQuarkAnalysis/TopTools/interface/JetPartonMatching.h +++ b/TopQuarkAnalysis/TopTools/interface/JetPartonMatching.h @@ -11,58 +11,76 @@ class JetPartonMatching { // common class for jet parton matching in ttbar // decays. Several matching algorithms are provided - public: - - typedef std::vector< std::pair > MatchingCollection; +public: + typedef std::vector > MatchingCollection; enum algorithms { totalMinDist, minSumDist, ptOrderedMinDist, unambiguousOnly }; JetPartonMatching(){}; - JetPartonMatching(const std::vector&, const std::vector&, - const int, const bool, const bool, const double); - JetPartonMatching(const std::vector&, const std::vector&, - const int, const bool, const bool, const double); - JetPartonMatching(const std::vector&, const std::vector&, - const int, const bool, const bool, const double); - JetPartonMatching(const std::vector&, const std::vector&, - const int, const bool, const bool, const double); - ~JetPartonMatching(){}; - + JetPartonMatching(const std::vector&, + const std::vector&, + const int, + const bool, + const bool, + const double); + JetPartonMatching(const std::vector&, + const std::vector&, + const int, + const bool, + const bool, + const double); + JetPartonMatching(const std::vector&, + const std::vector&, + const int, + const bool, + const bool, + const double); + JetPartonMatching(const std::vector&, + const std::vector&, + const int, + const bool, + const bool, + const double); + ~JetPartonMatching(){}; + //matching meta information unsigned int getNumberOfAvailableCombinations() { return matching.size(); } - int getNumberOfUnmatchedPartons(const unsigned int comb=0){ return (comb getMatchesForPartons(const unsigned int comb=0); - double getDistanceForParton(const unsigned int part, const unsigned int comb=0); - double getSumDistances(const unsigned int comb=0); + int getNumberOfUnmatchedPartons(const unsigned int comb = 0) { + return (comb < numberOfUnmatchedPartons.size() ? (int)numberOfUnmatchedPartons[comb] : -1); + } + int getMatchForParton(const unsigned int part, const unsigned int comb = 0); + std::vector getMatchesForPartons(const unsigned int comb = 0); + double getDistanceForParton(const unsigned int part, const unsigned int comb = 0); + double getSumDistances(const unsigned int comb = 0); //matching quantities - double getSumDeltaE (const unsigned int comb=0) { return (comb&, std::vector&, std::vector >&); + void minSumDist_recursion(const unsigned int, + std::vector&, + std::vector&, + std::vector >&); void matchingMinSumDist(); void matchingPtOrderedMinDist(); void matchingUnambiguousOnly(); - - private: - + +private: std::vector partons; std::vector jets; std::vector matching; - + std::vector numberOfUnmatchedPartons; std::vector sumDeltaE; std::vector sumDeltaPt; std::vector sumDeltaR; - + int algorithm_; bool useMaxDist_; bool useDeltaR_; diff --git a/TopQuarkAnalysis/TopTools/interface/LRHelpFunctions.h b/TopQuarkAnalysis/TopTools/interface/LRHelpFunctions.h index 7397168009d1e..c827f7b4f818f 100644 --- a/TopQuarkAnalysis/TopTools/interface/LRHelpFunctions.h +++ b/TopQuarkAnalysis/TopTools/interface/LRHelpFunctions.h @@ -32,50 +32,50 @@ #include "TText.h" #include "TCanvas.h" - class LRHelpFunctions { +public: + LRHelpFunctions(); + LRHelpFunctions(const std::vector&, + int, + const std::vector&, + const std::vector&, + const std::vector&); + LRHelpFunctions(int, double, double, const char*); + ~LRHelpFunctions(); + void recreateFitFct(const std::vector& obsNr, const std::vector& functions); + void initLRHistsAndFits(int, double, double, const char*); + void setObsFitParameters(int obs, const std::vector&); + void fillToSignalHists(const std::vector&, double weight = 1.0); + void fillToBackgroundHists(const std::vector&, double weight = 1.0); + void fillToSignalHists(int, double, double weight = 1.0); + void fillToBackgroundHists(int, double, double weight = 1.0); + void fillToSignalCorrelation(int obsNbr1, double obsVal1, int obsNbr2, double obsVal2, double weight); + void normalizeSandBhists(); + void makeAndFitSoverSplusBHists(); + void readObsHistsAndFits(const TString&, const std::vector&, bool); + void storeToROOTfile(const TString&); + void storeControlPlots(const TString&); + void fillLRSignalHist(double, double weight = 1.0); + void fillLRBackgroundHist(double, double weight = 1.0); + void makeAndFitPurityHists(); + double calcLRval(const std::vector&); + double calcPtdrLRval(const std::vector& vals, bool useCorrelation = false); + double calcProb(double); + bool obsFitIncluded(int); + void setXlabels(const std::vector& xLabels); + void setYlabels(const std::vector& yLabels); + void singlePlot(const TString& fname, int obsNbr, const TString& extension = TString("eps")); + void purityPlot(const TString& fname, const TString& extension = TString("eps")); - public: - LRHelpFunctions(); - LRHelpFunctions(const std::vector&, int, const std::vector&, const std::vector&,const std::vector&); - LRHelpFunctions(int, double, double, const char*); - ~LRHelpFunctions(); - void recreateFitFct(const std::vector& obsNr, const std::vector& functions); - void initLRHistsAndFits(int, double, double, const char*); - void setObsFitParameters(int obs,const std::vector&); - void fillToSignalHists(const std::vector&, double weight = 1.0); - void fillToBackgroundHists(const std::vector&, double weight = 1.0); - void fillToSignalHists(int, double, double weight = 1.0); - void fillToBackgroundHists(int, double, double weight = 1.0); - void fillToSignalCorrelation(int obsNbr1, double obsVal1, int obsNbr2, - double obsVal2, double weight); - void normalizeSandBhists(); - void makeAndFitSoverSplusBHists(); - void readObsHistsAndFits(const TString&,const std::vector&,bool); - void storeToROOTfile(const TString&); - void storeControlPlots(const TString&); - void fillLRSignalHist(double, double weight = 1.0); - void fillLRBackgroundHist(double, double weight = 1.0); - void makeAndFitPurityHists(); - double calcLRval(const std::vector&); - double calcPtdrLRval(const std::vector& vals, bool useCorrelation = false); - double calcProb(double); - bool obsFitIncluded(int); - void setXlabels(const std::vector & xLabels); - void setYlabels(const std::vector & yLabels); - void singlePlot(const TString& fname, int obsNbr, const TString& extension= TString("eps")); - void purityPlot(const TString& fname, const TString& extension= TString("eps")); - - - private: - std::vector hObsS, hObsB, hObsSoverSplusB; - std::vector hObsCorr; - std::vector fObsSoverSplusB; - TH1F *hLRtotS, *hLRtotB, *hLRtotSoverSplusB; - TF1 *fLRtotSoverSplusB; - TGraph *hEffvsPur, *hLRValvsPur, *hLRValvsEff; - bool constructPurity; - std::vector obsNumbers; +private: + std::vector hObsS, hObsB, hObsSoverSplusB; + std::vector hObsCorr; + std::vector fObsSoverSplusB; + TH1F *hLRtotS, *hLRtotB, *hLRtotSoverSplusB; + TF1* fLRtotSoverSplusB; + TGraph *hEffvsPur, *hLRValvsPur, *hLRValvsEff; + bool constructPurity; + std::vector obsNumbers; }; #endif diff --git a/TopQuarkAnalysis/TopTools/interface/MEzCalculator.h b/TopQuarkAnalysis/TopTools/interface/MEzCalculator.h index 2b348ec9a54f2..d3fa6272ad742 100644 --- a/TopQuarkAnalysis/TopTools/interface/MEzCalculator.h +++ b/TopQuarkAnalysis/TopTools/interface/MEzCalculator.h @@ -16,26 +16,25 @@ ________________________________________________________________**/ #include "TLorentzVector.h" class MEzCalculator { - - public: +public: /// constructor MEzCalculator(); /// destructor ~MEzCalculator(); /// Set MET - void SetMET(const pat::MET& MET) { MET_ = MET; } ; + void SetMET(const pat::MET& MET) { MET_ = MET; }; void SetMET(const TLorentzVector& MET) { - pat::Particle::LorentzVector p(MET.Px(),MET.Py(),MET.Pz(),MET.E()); - MET_.setP4(p); + pat::Particle::LorentzVector p(MET.Px(), MET.Py(), MET.Pz(), MET.E()); + MET_.setP4(p); } /// Set lepton void SetLepton(const pat::Particle& lepton, bool isMuon = true) { - lepton_ = lepton; - isMuon_ = isMuon; + lepton_ = lepton; + isMuon_ = isMuon; }; void SetLepton(const TLorentzVector& lepton) { - pat::Particle::LorentzVector p(lepton.Px(), lepton.Py(), lepton.Pz(), lepton.E() ); - lepton_.setP4(p); + pat::Particle::LorentzVector p(lepton.Px(), lepton.Py(), lepton.Pz(), lepton.E()); + lepton_.setP4(p); } /// Calculate MEz /// options to choose roots from quadratic equation: @@ -52,12 +51,11 @@ class MEzCalculator { bool IsComplex() const { return isComplex_; }; /// verbose void Print() { - std::cout << " METzCalculator: pxmu = " << lepton_.px() << " pzmu= " << lepton_.pz() << std::endl; - std::cout << " METzCalculator: pxnu = " << MET_.px() << " pynu= " << MET_.py() << std::endl; + std::cout << " METzCalculator: pxmu = " << lepton_.px() << " pzmu= " << lepton_.pz() << std::endl; + std::cout << " METzCalculator: pxnu = " << MET_.px() << " pynu= " << MET_.py() << std::endl; } - private: - +private: bool isComplex_; pat::Particle lepton_; pat::MET MET_; diff --git a/TopQuarkAnalysis/TopTools/plugins/GenTtbarCategorizer.cc b/TopQuarkAnalysis/TopTools/plugins/GenTtbarCategorizer.cc index d9f0d7218b5f8..3694c8f33b616 100644 --- a/TopQuarkAnalysis/TopTools/plugins/GenTtbarCategorizer.cc +++ b/TopQuarkAnalysis/TopTools/plugins/GenTtbarCategorizer.cc @@ -2,7 +2,7 @@ // // Package: TopQuarkAnalysis/TopTools // Class: GenTtbarCategorizer -// +// /**\class GenTtbarCategorizer GenTtbarCategorizer.cc TopQuarkAnalysis/TopTools/plugins/GenTtbarCategorizer.cc Description: Categorization of different tt+xx processes, returning unique ID for each process as e.g. tt+bb, tt+b, tt+2b, tt+cc, ... @@ -51,7 +51,6 @@ // // - // system include files #include #include @@ -67,61 +66,57 @@ #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/HepMCCandidate/interface/GenParticle.h" - // // class declaration // class GenTtbarCategorizer : public edm::EDProducer { - public: - explicit GenTtbarCategorizer(const edm::ParameterSet&); - ~GenTtbarCategorizer() override; - - static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - - private: - void beginJob() override; - void produce(edm::Event&, const edm::EventSetup&) override; - void endJob() override; - - //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; - //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; - //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; - //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; - - std::vector nHadronsOrderedJetIndices(const std::map& m_jetIndex); - - // ----------member data --------------------------- - - // Jet configuration - const double genJetPtMin_; - const double genJetAbsEtaMax_; - - // Input tags - const edm::EDGetTokenT genJetsToken_; - - const edm::EDGetTokenT > genBHadJetIndexToken_; - const edm::EDGetTokenT > genBHadFlavourToken_; - const edm::EDGetTokenT > genBHadFromTopWeakDecayToken_; - const edm::EDGetTokenT > genBHadPlusMothersToken_; - const edm::EDGetTokenT > > genBHadPlusMothersIndicesToken_; - const edm::EDGetTokenT > genBHadIndexToken_; - const edm::EDGetTokenT > genBHadLeptonHadronIndexToken_; - const edm::EDGetTokenT > genBHadLeptonViaTauToken_; - - const edm::EDGetTokenT > genCHadJetIndexToken_; - const edm::EDGetTokenT > genCHadFlavourToken_; - const edm::EDGetTokenT > genCHadFromTopWeakDecayToken_; - const edm::EDGetTokenT > genCHadBHadronIdToken_; - - +public: + explicit GenTtbarCategorizer(const edm::ParameterSet&); + ~GenTtbarCategorizer() override; + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + void beginJob() override; + void produce(edm::Event&, const edm::EventSetup&) override; + void endJob() override; + + //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; + //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; + //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; + //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; + + std::vector nHadronsOrderedJetIndices(const std::map& m_jetIndex); + + // ----------member data --------------------------- + + // Jet configuration + const double genJetPtMin_; + const double genJetAbsEtaMax_; + + // Input tags + const edm::EDGetTokenT genJetsToken_; + + const edm::EDGetTokenT > genBHadJetIndexToken_; + const edm::EDGetTokenT > genBHadFlavourToken_; + const edm::EDGetTokenT > genBHadFromTopWeakDecayToken_; + const edm::EDGetTokenT > genBHadPlusMothersToken_; + const edm::EDGetTokenT > > genBHadPlusMothersIndicesToken_; + const edm::EDGetTokenT > genBHadIndexToken_; + const edm::EDGetTokenT > genBHadLeptonHadronIndexToken_; + const edm::EDGetTokenT > genBHadLeptonViaTauToken_; + + const edm::EDGetTokenT > genCHadJetIndexToken_; + const edm::EDGetTokenT > genCHadFlavourToken_; + const edm::EDGetTokenT > genCHadFromTopWeakDecayToken_; + const edm::EDGetTokenT > genCHadBHadronIdToken_; }; // // constants, enums and typedefs // - // // static data member definitions // @@ -129,244 +124,273 @@ class GenTtbarCategorizer : public edm::EDProducer { // // constructors and destructor // -GenTtbarCategorizer::GenTtbarCategorizer(const edm::ParameterSet& iConfig): -genJetPtMin_(iConfig.getParameter("genJetPtMin")), -genJetAbsEtaMax_(iConfig.getParameter("genJetAbsEtaMax")), -genJetsToken_(consumes(iConfig.getParameter("genJets"))), -genBHadJetIndexToken_(consumes >(iConfig.getParameter("genBHadJetIndex"))), -genBHadFlavourToken_(consumes >(iConfig.getParameter("genBHadFlavour"))), -genBHadFromTopWeakDecayToken_(consumes >(iConfig.getParameter("genBHadFromTopWeakDecay"))), -genBHadPlusMothersToken_(consumes >(iConfig.getParameter("genBHadPlusMothers"))), -genBHadPlusMothersIndicesToken_(consumes > >(iConfig.getParameter("genBHadPlusMothersIndices"))), -genBHadIndexToken_(consumes >(iConfig.getParameter("genBHadIndex"))), -genBHadLeptonHadronIndexToken_(consumes >(iConfig.getParameter("genBHadLeptonHadronIndex"))), -genBHadLeptonViaTauToken_(consumes >(iConfig.getParameter("genBHadLeptonViaTau"))), -genCHadJetIndexToken_(consumes >(iConfig.getParameter("genCHadJetIndex"))), -genCHadFlavourToken_(consumes >(iConfig.getParameter("genCHadFlavour"))), -genCHadFromTopWeakDecayToken_(consumes >(iConfig.getParameter("genCHadFromTopWeakDecay"))), -genCHadBHadronIdToken_(consumes >(iConfig.getParameter("genCHadBHadronId"))) -{ - produces("genTtbarId"); +GenTtbarCategorizer::GenTtbarCategorizer(const edm::ParameterSet& iConfig) + : genJetPtMin_(iConfig.getParameter("genJetPtMin")), + genJetAbsEtaMax_(iConfig.getParameter("genJetAbsEtaMax")), + genJetsToken_(consumes(iConfig.getParameter("genJets"))), + genBHadJetIndexToken_(consumes >(iConfig.getParameter("genBHadJetIndex"))), + genBHadFlavourToken_(consumes >(iConfig.getParameter("genBHadFlavour"))), + genBHadFromTopWeakDecayToken_( + consumes >(iConfig.getParameter("genBHadFromTopWeakDecay"))), + genBHadPlusMothersToken_( + consumes >(iConfig.getParameter("genBHadPlusMothers"))), + genBHadPlusMothersIndicesToken_( + consumes > >(iConfig.getParameter("genBHadPlusMothersIndices"))), + genBHadIndexToken_(consumes >(iConfig.getParameter("genBHadIndex"))), + genBHadLeptonHadronIndexToken_( + consumes >(iConfig.getParameter("genBHadLeptonHadronIndex"))), + genBHadLeptonViaTauToken_( + consumes >(iConfig.getParameter("genBHadLeptonViaTau"))), + genCHadJetIndexToken_(consumes >(iConfig.getParameter("genCHadJetIndex"))), + genCHadFlavourToken_(consumes >(iConfig.getParameter("genCHadFlavour"))), + genCHadFromTopWeakDecayToken_( + consumes >(iConfig.getParameter("genCHadFromTopWeakDecay"))), + genCHadBHadronIdToken_(consumes >(iConfig.getParameter("genCHadBHadronId"))) { + produces("genTtbarId"); } - -GenTtbarCategorizer::~GenTtbarCategorizer() -{} - +GenTtbarCategorizer::~GenTtbarCategorizer() {} // // member functions // // ------------ method called to produce the data ------------ -void -GenTtbarCategorizer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - // Access gen jets - edm::Handle genJets; - iEvent.getByToken(genJetsToken_, genJets); - - - // Access B hadrons information - edm::Handle > genBHadFlavour; - iEvent.getByToken(genBHadFlavourToken_, genBHadFlavour); - - edm::Handle > genBHadJetIndex; - iEvent.getByToken(genBHadJetIndexToken_, genBHadJetIndex); - - edm::Handle > genBHadFromTopWeakDecay; - iEvent.getByToken(genBHadFromTopWeakDecayToken_, genBHadFromTopWeakDecay); - - edm::Handle > genBHadPlusMothers; - iEvent.getByToken(genBHadPlusMothersToken_, genBHadPlusMothers); - - edm::Handle > > genBHadPlusMothersIndices; - iEvent.getByToken(genBHadPlusMothersIndicesToken_, genBHadPlusMothersIndices); - - edm::Handle > genBHadIndex; - iEvent.getByToken(genBHadIndexToken_, genBHadIndex); - - edm::Handle > genBHadLeptonHadronIndex; - iEvent.getByToken(genBHadLeptonHadronIndexToken_, genBHadLeptonHadronIndex); - - edm::Handle > genBHadLeptonViaTau; - iEvent.getByToken(genBHadLeptonViaTauToken_, genBHadLeptonViaTau); - - - // Access C hadrons information - edm::Handle > genCHadFlavour; - iEvent.getByToken(genCHadFlavourToken_, genCHadFlavour); - - edm::Handle > genCHadJetIndex; - iEvent.getByToken(genCHadJetIndexToken_, genCHadJetIndex); - - edm::Handle > genCHadFromTopWeakDecay; - iEvent.getByToken(genCHadFromTopWeakDecayToken_, genCHadFromTopWeakDecay); - - edm::Handle > genCHadBHadronId; - iEvent.getByToken(genCHadBHadronIdToken_, genCHadBHadronId); - - - // Map - // B jets with b hadrons directly from t->b decay - std::map bJetFromTopIds; - // B jets with b hadrons from W->b decay - std::map bJetFromWIds; - // C jets with c hadrons from W->c decay - std::map cJetFromWIds; - // B jets with b hadrons before top quark decay chain - std::map bJetAdditionalIds; - // C jets with c hadrons before top quark decay chain - std::map cJetAdditionalIds; - - - // Count number of specific b hadrons in each jet - for(size_t hadronId = 0; hadronId < genBHadIndex->size(); ++hadronId) { - // Index of jet associated to the hadron - const int jetIndex = genBHadJetIndex->at(hadronId); - // Skip hadrons which have no associated jet - if(jetIndex < 0) continue; - // Skip if jet is not in acceptance - if(genJets->at(jetIndex).pt() < genJetPtMin_) continue; - if(std::fabs(genJets->at(jetIndex).eta()) > genJetAbsEtaMax_) continue; - // Flavour of the hadron's origin - const int flavour = genBHadFlavour->at(hadronId); - // Jet from t->b decay [pdgId(top)=6] - if(std::abs(flavour) == 6) { - if(bJetFromTopIds.count(jetIndex) < 1) bJetFromTopIds[jetIndex] = 1; - else bJetFromTopIds[jetIndex]++; - continue; - } - // Jet from W->b decay [pdgId(W)=24] - if(std::abs(flavour) == 24) { - if(bJetFromWIds.count(jetIndex) < 1) bJetFromWIds[jetIndex] = 1; - else bJetFromWIds[jetIndex]++; - continue; - } - // Identify jets with b hadrons not from top-quark or W-boson decay - if(bJetAdditionalIds.count(jetIndex) < 1) bJetAdditionalIds[jetIndex] = 1; - else bJetAdditionalIds[jetIndex]++; - } - - // Cleaning up b jets from W->b decays - for(std::map::iterator it = bJetFromWIds.begin(); it != bJetFromWIds.end(); ) { - // Cannot be a b jet from t->b decay - if(bJetFromTopIds.count(it->first) > 0) bJetFromWIds.erase(it++); - else ++it; - } - - // Cleaning up additional b jets - for(std::map::iterator it = bJetAdditionalIds.begin(); it != bJetAdditionalIds.end(); ) { - // Cannot be a b jet from t->b decay - if(bJetFromTopIds.count(it->first) > 0) bJetAdditionalIds.erase(it++); - // Cannot be a b jet from W->b decay - else if(bJetFromWIds.count(it->first) > 0) bJetAdditionalIds.erase(it++); - else ++it; +void GenTtbarCategorizer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + // Access gen jets + edm::Handle genJets; + iEvent.getByToken(genJetsToken_, genJets); + + // Access B hadrons information + edm::Handle > genBHadFlavour; + iEvent.getByToken(genBHadFlavourToken_, genBHadFlavour); + + edm::Handle > genBHadJetIndex; + iEvent.getByToken(genBHadJetIndexToken_, genBHadJetIndex); + + edm::Handle > genBHadFromTopWeakDecay; + iEvent.getByToken(genBHadFromTopWeakDecayToken_, genBHadFromTopWeakDecay); + + edm::Handle > genBHadPlusMothers; + iEvent.getByToken(genBHadPlusMothersToken_, genBHadPlusMothers); + + edm::Handle > > genBHadPlusMothersIndices; + iEvent.getByToken(genBHadPlusMothersIndicesToken_, genBHadPlusMothersIndices); + + edm::Handle > genBHadIndex; + iEvent.getByToken(genBHadIndexToken_, genBHadIndex); + + edm::Handle > genBHadLeptonHadronIndex; + iEvent.getByToken(genBHadLeptonHadronIndexToken_, genBHadLeptonHadronIndex); + + edm::Handle > genBHadLeptonViaTau; + iEvent.getByToken(genBHadLeptonViaTauToken_, genBHadLeptonViaTau); + + // Access C hadrons information + edm::Handle > genCHadFlavour; + iEvent.getByToken(genCHadFlavourToken_, genCHadFlavour); + + edm::Handle > genCHadJetIndex; + iEvent.getByToken(genCHadJetIndexToken_, genCHadJetIndex); + + edm::Handle > genCHadFromTopWeakDecay; + iEvent.getByToken(genCHadFromTopWeakDecayToken_, genCHadFromTopWeakDecay); + + edm::Handle > genCHadBHadronId; + iEvent.getByToken(genCHadBHadronIdToken_, genCHadBHadronId); + + // Map + // B jets with b hadrons directly from t->b decay + std::map bJetFromTopIds; + // B jets with b hadrons from W->b decay + std::map bJetFromWIds; + // C jets with c hadrons from W->c decay + std::map cJetFromWIds; + // B jets with b hadrons before top quark decay chain + std::map bJetAdditionalIds; + // C jets with c hadrons before top quark decay chain + std::map cJetAdditionalIds; + + // Count number of specific b hadrons in each jet + for (size_t hadronId = 0; hadronId < genBHadIndex->size(); ++hadronId) { + // Index of jet associated to the hadron + const int jetIndex = genBHadJetIndex->at(hadronId); + // Skip hadrons which have no associated jet + if (jetIndex < 0) + continue; + // Skip if jet is not in acceptance + if (genJets->at(jetIndex).pt() < genJetPtMin_) + continue; + if (std::fabs(genJets->at(jetIndex).eta()) > genJetAbsEtaMax_) + continue; + // Flavour of the hadron's origin + const int flavour = genBHadFlavour->at(hadronId); + // Jet from t->b decay [pdgId(top)=6] + if (std::abs(flavour) == 6) { + if (bJetFromTopIds.count(jetIndex) < 1) + bJetFromTopIds[jetIndex] = 1; + else + bJetFromTopIds[jetIndex]++; + continue; } - - // Count number of specific c hadrons in each c jet - for(size_t hadronId = 0; hadronId < genCHadJetIndex->size(); ++hadronId) { - // Index of jet associated to the hadron - const int jetIndex = genCHadJetIndex->at(hadronId); - // Skip hadrons which have no associated jet - if(jetIndex < 0) continue; - // Skip c hadrons that are coming from b hadrons - if(genCHadBHadronId->at(hadronId) >= 0) continue; - // Skip if jet is not in acceptance - if(genJets->at(jetIndex).pt() < genJetPtMin_) continue; - if(std::fabs(genJets->at(jetIndex).eta()) > genJetAbsEtaMax_) continue; - // Skip if jet contains a b hadron - if(bJetFromTopIds.count(jetIndex) > 0) continue; - if(bJetFromWIds.count(jetIndex) > 0) continue; - if(bJetAdditionalIds.count(jetIndex) > 0) continue; - // Flavour of the hadron's origin - const int flavour = genCHadFlavour->at(hadronId); - // Jet from W->c decay [pdgId(W)=24] - if(std::abs(flavour) == 24) { - if(cJetFromWIds.count(jetIndex) < 1) cJetFromWIds[jetIndex] = 1; - else cJetFromWIds[jetIndex]++; - continue; - } - // Identify jets with c hadrons not from W-boson decay - if(cJetAdditionalIds.count(jetIndex) < 1) cJetAdditionalIds[jetIndex] = 1; - else cJetAdditionalIds[jetIndex]++; + // Jet from W->b decay [pdgId(W)=24] + if (std::abs(flavour) == 24) { + if (bJetFromWIds.count(jetIndex) < 1) + bJetFromWIds[jetIndex] = 1; + else + bJetFromWIds[jetIndex]++; + continue; } + // Identify jets with b hadrons not from top-quark or W-boson decay + if (bJetAdditionalIds.count(jetIndex) < 1) + bJetAdditionalIds[jetIndex] = 1; + else + bJetAdditionalIds[jetIndex]++; + } - // Cleaning up additional c jets - for(std::map::iterator it = cJetAdditionalIds.begin(); it != cJetAdditionalIds.end(); ) { - // Cannot be a c jet from W->c decay - if(cJetFromWIds.count(it->first) > 0) cJetAdditionalIds.erase(it++); - else ++it; + // Cleaning up b jets from W->b decays + for (std::map::iterator it = bJetFromWIds.begin(); it != bJetFromWIds.end();) { + // Cannot be a b jet from t->b decay + if (bJetFromTopIds.count(it->first) > 0) + bJetFromWIds.erase(it++); + else + ++it; + } + + // Cleaning up additional b jets + for (std::map::iterator it = bJetAdditionalIds.begin(); it != bJetAdditionalIds.end();) { + // Cannot be a b jet from t->b decay + if (bJetFromTopIds.count(it->first) > 0) + bJetAdditionalIds.erase(it++); + // Cannot be a b jet from W->b decay + else if (bJetFromWIds.count(it->first) > 0) + bJetAdditionalIds.erase(it++); + else + ++it; + } + + // Count number of specific c hadrons in each c jet + for (size_t hadronId = 0; hadronId < genCHadJetIndex->size(); ++hadronId) { + // Index of jet associated to the hadron + const int jetIndex = genCHadJetIndex->at(hadronId); + // Skip hadrons which have no associated jet + if (jetIndex < 0) + continue; + // Skip c hadrons that are coming from b hadrons + if (genCHadBHadronId->at(hadronId) >= 0) + continue; + // Skip if jet is not in acceptance + if (genJets->at(jetIndex).pt() < genJetPtMin_) + continue; + if (std::fabs(genJets->at(jetIndex).eta()) > genJetAbsEtaMax_) + continue; + // Skip if jet contains a b hadron + if (bJetFromTopIds.count(jetIndex) > 0) + continue; + if (bJetFromWIds.count(jetIndex) > 0) + continue; + if (bJetAdditionalIds.count(jetIndex) > 0) + continue; + // Flavour of the hadron's origin + const int flavour = genCHadFlavour->at(hadronId); + // Jet from W->c decay [pdgId(W)=24] + if (std::abs(flavour) == 24) { + if (cJetFromWIds.count(jetIndex) < 1) + cJetFromWIds[jetIndex] = 1; + else + cJetFromWIds[jetIndex]++; + continue; } - - // Categorize event based on number of additional b/c jets - // and number of corresponding hadrons in each of them - int additionalJetEventId = bJetFromTopIds.size()*100 + bJetFromWIds.size()*1000 + cJetFromWIds.size()*10000; - // tt + 1 additional b jet - if(bJetAdditionalIds.size() == 1){ - const int nHadronsInJet = bJetAdditionalIds.begin()->second; - // tt + 1 additional b jet from 1 additional b hadron - if(nHadronsInJet == 1) additionalJetEventId += 51; - // tt + 1 additional b jet from >=2 additional b hadrons - else additionalJetEventId += 52; + // Identify jets with c hadrons not from W-boson decay + if (cJetAdditionalIds.count(jetIndex) < 1) + cJetAdditionalIds[jetIndex] = 1; + else + cJetAdditionalIds[jetIndex]++; + } + + // Cleaning up additional c jets + for (std::map::iterator it = cJetAdditionalIds.begin(); it != cJetAdditionalIds.end();) { + // Cannot be a c jet from W->c decay + if (cJetFromWIds.count(it->first) > 0) + cJetAdditionalIds.erase(it++); + else + ++it; + } + + // Categorize event based on number of additional b/c jets + // and number of corresponding hadrons in each of them + int additionalJetEventId = bJetFromTopIds.size() * 100 + bJetFromWIds.size() * 1000 + cJetFromWIds.size() * 10000; + // tt + 1 additional b jet + if (bJetAdditionalIds.size() == 1) { + const int nHadronsInJet = bJetAdditionalIds.begin()->second; + // tt + 1 additional b jet from 1 additional b hadron + if (nHadronsInJet == 1) + additionalJetEventId += 51; + // tt + 1 additional b jet from >=2 additional b hadrons + else + additionalJetEventId += 52; + } + // tt + >=2 additional b jets + else if (bJetAdditionalIds.size() > 1) { + // Check first two additional b jets (rare cases could have more) + const std::vector orderedJetIndices = nHadronsOrderedJetIndices(bJetAdditionalIds); + int nHadronsInJet1 = bJetAdditionalIds.at(orderedJetIndices.at(0)); + int nHadronsInJet2 = bJetAdditionalIds.at(orderedJetIndices.at(1)); + // tt + >=2 additional b jets each from 1 additional b hadron + if (std::max(nHadronsInJet1, nHadronsInJet2) == 1) + additionalJetEventId += 53; + // tt + >=2 additional b jets one of which from >=2 additional b hadrons + else if (std::min(nHadronsInJet1, nHadronsInJet2) == 1 && std::max(nHadronsInJet1, nHadronsInJet2) > 1) + additionalJetEventId += 54; + // tt + >=2 additional b jets each from >=2 additional b hadrons + else if (std::min(nHadronsInJet1, nHadronsInJet2) > 1) + additionalJetEventId += 55; + } + // tt + no additional b jets + else { + // tt + 1 additional c jet + if (cJetAdditionalIds.size() == 1) { + const int nHadronsInJet = cJetAdditionalIds.begin()->second; + // tt + 1 additional c jet from 1 additional c hadron + if (nHadronsInJet == 1) + additionalJetEventId += 41; + // tt + 1 additional c jet from >=2 additional c hadrons + else + additionalJetEventId += 42; } - // tt + >=2 additional b jets - else if(bJetAdditionalIds.size() > 1){ - // Check first two additional b jets (rare cases could have more) - const std::vector orderedJetIndices = nHadronsOrderedJetIndices(bJetAdditionalIds); - int nHadronsInJet1 = bJetAdditionalIds.at(orderedJetIndices.at(0)); - int nHadronsInJet2 = bJetAdditionalIds.at(orderedJetIndices.at(1)); - // tt + >=2 additional b jets each from 1 additional b hadron - if(std::max(nHadronsInJet1, nHadronsInJet2) == 1) additionalJetEventId += 53; - // tt + >=2 additional b jets one of which from >=2 additional b hadrons - else if(std::min(nHadronsInJet1, nHadronsInJet2) == 1 && std::max(nHadronsInJet1, nHadronsInJet2) > 1) additionalJetEventId += 54; - // tt + >=2 additional b jets each from >=2 additional b hadrons - else if(std::min(nHadronsInJet1, nHadronsInJet2) > 1) additionalJetEventId += 55; + // tt + >=2 additional c jets + else if (cJetAdditionalIds.size() > 1) { + // Check first two additional c jets (rare cases could have more) + const std::vector orderedJetIndices = nHadronsOrderedJetIndices(cJetAdditionalIds); + int nHadronsInJet1 = cJetAdditionalIds.at(orderedJetIndices.at(0)); + int nHadronsInJet2 = cJetAdditionalIds.at(orderedJetIndices.at(1)); + // tt + >=2 additional c jets each from 1 additional c hadron + if (std::max(nHadronsInJet1, nHadronsInJet2) == 1) + additionalJetEventId += 43; + // tt + >=2 additional c jets one of which from >=2 additional c hadrons + else if (std::min(nHadronsInJet1, nHadronsInJet2) == 1 && std::max(nHadronsInJet1, nHadronsInJet2) > 1) + additionalJetEventId += 44; + // tt + >=2 additional c jets each from >=2 additional c hadrons + else if (std::min(nHadronsInJet1, nHadronsInJet2) > 1) + additionalJetEventId += 45; } - // tt + no additional b jets - else{ - // tt + 1 additional c jet - if(cJetAdditionalIds.size() == 1){ - const int nHadronsInJet = cJetAdditionalIds.begin()->second; - // tt + 1 additional c jet from 1 additional c hadron - if(nHadronsInJet == 1) additionalJetEventId += 41; - // tt + 1 additional c jet from >=2 additional c hadrons - else additionalJetEventId += 42; - } - // tt + >=2 additional c jets - else if(cJetAdditionalIds.size() > 1){ - // Check first two additional c jets (rare cases could have more) - const std::vector orderedJetIndices = nHadronsOrderedJetIndices(cJetAdditionalIds); - int nHadronsInJet1 = cJetAdditionalIds.at(orderedJetIndices.at(0)); - int nHadronsInJet2 = cJetAdditionalIds.at(orderedJetIndices.at(1)); - // tt + >=2 additional c jets each from 1 additional c hadron - if(std::max(nHadronsInJet1, nHadronsInJet2) == 1) additionalJetEventId += 43; - // tt + >=2 additional c jets one of which from >=2 additional c hadrons - else if(std::min(nHadronsInJet1, nHadronsInJet2) == 1 && std::max(nHadronsInJet1, nHadronsInJet2) > 1) additionalJetEventId += 44; - // tt + >=2 additional c jets each from >=2 additional c hadrons - else if(std::min(nHadronsInJet1, nHadronsInJet2) > 1) additionalJetEventId += 45; - } - // tt + no additional c jets - else{ - // tt + light jets - additionalJetEventId += 0; - } + // tt + no additional c jets + else { + // tt + light jets + additionalJetEventId += 0; } - - std::unique_ptr ttbarId(new int); - *ttbarId = additionalJetEventId; - iEvent.put(std::move(ttbarId), "genTtbarId"); + } + + std::unique_ptr ttbarId(new int); + *ttbarId = additionalJetEventId; + iEvent.put(std::move(ttbarId), "genTtbarId"); } // ------------ method called once each job just before starting event loop ------------ -void -GenTtbarCategorizer::beginJob() -{} +void GenTtbarCategorizer::beginJob() {} // ------------ method called once each job just after ending the event loop ------------ -void -GenTtbarCategorizer::endJob() -{} +void GenTtbarCategorizer::endJob() {} // ------------ method called when starting to processes a run ------------ /* @@ -375,7 +399,7 @@ GenTtbarCategorizer::beginRun(edm::Run const&, edm::EventSetup const&) { } */ - + // ------------ method called when ending the processing of a run ------------ /* void @@ -383,7 +407,7 @@ GenTtbarCategorizer::endRun(edm::Run const&, edm::EventSetup const&) { } */ - + // ------------ method called when starting to processes a luminosity block ------------ /* void @@ -391,7 +415,7 @@ GenTtbarCategorizer::beginLuminosityBlock(edm::LuminosityBlock const&, edm::Even { } */ - + // ------------ method called when ending the processing of a luminosity block ------------ /* void @@ -399,33 +423,33 @@ GenTtbarCategorizer::endLuminosityBlock(edm::LuminosityBlock const&, edm::EventS { } */ - + // ------------ method returns a vector of jet indices from the given map, sorted by N hadrons in descending order ------------ -std::vector GenTtbarCategorizer::nHadronsOrderedJetIndices(const std::map& m_jetIndex) -{ - const int nElements = m_jetIndex.size(); - std::vector > v_jetNhadIndexPair; - v_jetNhadIndexPair.reserve(nElements); - for(std::map::const_iterator it = m_jetIndex.begin(); it != m_jetIndex.end(); ++it) { - const int jetIndex = it->first; - const int nHadrons = it->second; - v_jetNhadIndexPair.push_back( std::pair(nHadrons, jetIndex) ); - } - // Sorting the vector of pairs by their key value - std::sort(v_jetNhadIndexPair.begin(), v_jetNhadIndexPair.end(), std::greater >()); - // Building the vector of indices in the proper order - std::vector v_orderedJetIndices; - v_orderedJetIndices.reserve(nElements); - for(std::vector >::const_iterator it = v_jetNhadIndexPair.begin(); it != v_jetNhadIndexPair.end(); ++it) { - v_orderedJetIndices.push_back(it->second); - } - - return v_orderedJetIndices; +std::vector GenTtbarCategorizer::nHadronsOrderedJetIndices(const std::map& m_jetIndex) { + const int nElements = m_jetIndex.size(); + std::vector > v_jetNhadIndexPair; + v_jetNhadIndexPair.reserve(nElements); + for (std::map::const_iterator it = m_jetIndex.begin(); it != m_jetIndex.end(); ++it) { + const int jetIndex = it->first; + const int nHadrons = it->second; + v_jetNhadIndexPair.push_back(std::pair(nHadrons, jetIndex)); + } + // Sorting the vector of pairs by their key value + std::sort(v_jetNhadIndexPair.begin(), v_jetNhadIndexPair.end(), std::greater >()); + // Building the vector of indices in the proper order + std::vector v_orderedJetIndices; + v_orderedJetIndices.reserve(nElements); + for (std::vector >::const_iterator it = v_jetNhadIndexPair.begin(); + it != v_jetNhadIndexPair.end(); + ++it) { + v_orderedJetIndices.push_back(it->second); + } + + return v_orderedJetIndices; } - + // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ -void -GenTtbarCategorizer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { +void GenTtbarCategorizer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; diff --git a/TopQuarkAnalysis/TopTools/plugins/MuonSelectorVertex.cc b/TopQuarkAnalysis/TopTools/plugins/MuonSelectorVertex.cc index 8498050716014..09c9afad8e7c2 100644 --- a/TopQuarkAnalysis/TopTools/plugins/MuonSelectorVertex.cc +++ b/TopQuarkAnalysis/TopTools/plugins/MuonSelectorVertex.cc @@ -1,7 +1,6 @@ // // - #include "FWCore/Framework/interface/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" @@ -9,65 +8,49 @@ #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/VertexReco/interface/Vertex.h" - class MuonSelectorVertex : public edm::EDProducer { - - public: - - explicit MuonSelectorVertex( const edm::ParameterSet & iConfig ); - ~ MuonSelectorVertex() override {}; - void produce( edm::Event & iEvent, const edm::EventSetup & iSetup ) override; - - private: - - edm::EDGetTokenT< std::vector< pat::Muon > > muonSource_; - edm::EDGetTokenT< std::vector< reco::Vertex > > vertexSource_; - double maxDZ_; - +public: + explicit MuonSelectorVertex(const edm::ParameterSet& iConfig); + ~MuonSelectorVertex() override{}; + void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override; + +private: + edm::EDGetTokenT > muonSource_; + edm::EDGetTokenT > vertexSource_; + double maxDZ_; }; - #include #include #include - -MuonSelectorVertex::MuonSelectorVertex( const edm::ParameterSet & iConfig ) -: muonSource_( consumes< std::vector< pat::Muon > >( iConfig.getParameter< edm::InputTag >( "muonSource" ) ) ) -, vertexSource_( consumes< std::vector< reco::Vertex > >( iConfig.getParameter< edm::InputTag >( "vertexSource" ) ) ) -, maxDZ_( iConfig.getParameter< double >( "maxDZ" ) ) -{ - - produces< std::vector< pat::Muon > >(); - +MuonSelectorVertex::MuonSelectorVertex(const edm::ParameterSet& iConfig) + : muonSource_(consumes >(iConfig.getParameter("muonSource"))), + vertexSource_(consumes >(iConfig.getParameter("vertexSource"))), + maxDZ_(iConfig.getParameter("maxDZ")) { + produces >(); } +void MuonSelectorVertex::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { + edm::Handle > muons; + iEvent.getByToken(muonSource_, muons); -void MuonSelectorVertex::produce( edm::Event & iEvent, const edm::EventSetup & iSetup ) -{ - - edm::Handle< std::vector< pat::Muon > > muons; - iEvent.getByToken( muonSource_, muons ); + edm::Handle > vertices; + iEvent.getByToken(vertexSource_, vertices); - edm::Handle< std::vector< reco::Vertex > > vertices; - iEvent.getByToken( vertexSource_, vertices ); + std::vector* selectedMuons(new std::vector); - std::vector< pat::Muon > * selectedMuons( new std::vector< pat::Muon > ); - - if ( !vertices->empty() ) { - - for ( unsigned iMuon = 0; iMuon < muons->size(); ++iMuon ) { - if ( std::fabs( muons->at( iMuon ).vertex().z() - vertices->at( 0 ).z() ) < maxDZ_ ) { - selectedMuons->push_back( muons->at( iMuon ) ); + if (!vertices->empty()) { + for (unsigned iMuon = 0; iMuon < muons->size(); ++iMuon) { + if (std::fabs(muons->at(iMuon).vertex().z() - vertices->at(0).z()) < maxDZ_) { + selectedMuons->push_back(muons->at(iMuon)); } } } - std::unique_ptr< std::vector< pat::Muon > > selectedMuonsPtr( selectedMuons ); + std::unique_ptr > selectedMuonsPtr(selectedMuons); iEvent.put(std::move(selectedMuonsPtr)); - } - #include "FWCore/Framework/interface/MakerMacros.h" -DEFINE_FWK_MODULE( MuonSelectorVertex ); +DEFINE_FWK_MODULE(MuonSelectorVertex); diff --git a/TopQuarkAnalysis/TopTools/plugins/TtFullHadJetPartonMatch.cc b/TopQuarkAnalysis/TopTools/plugins/TtFullHadJetPartonMatch.cc index 5174fd9bb519b..f8bf6e951d91f 100644 --- a/TopQuarkAnalysis/TopTools/plugins/TtFullHadJetPartonMatch.cc +++ b/TopQuarkAnalysis/TopTools/plugins/TtFullHadJetPartonMatch.cc @@ -3,5 +3,5 @@ #include "TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h" #include "AnalysisDataFormats/TopObjects/interface/TtFullHadEvtPartons.h" -typedef TtJetPartonMatch< TtFullHadEvtPartons > TtFullHadJetPartonMatch; +typedef TtJetPartonMatch TtFullHadJetPartonMatch; DEFINE_FWK_MODULE(TtFullHadJetPartonMatch); diff --git a/TopQuarkAnalysis/TopTools/plugins/TtFullLepJetPartonMatch.cc b/TopQuarkAnalysis/TopTools/plugins/TtFullLepJetPartonMatch.cc index b727fe324bfd2..631f5aa7c3937 100644 --- a/TopQuarkAnalysis/TopTools/plugins/TtFullLepJetPartonMatch.cc +++ b/TopQuarkAnalysis/TopTools/plugins/TtFullLepJetPartonMatch.cc @@ -3,5 +3,5 @@ #include "TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h" #include "AnalysisDataFormats/TopObjects/interface/TtFullLepEvtPartons.h" -typedef TtJetPartonMatch< TtFullLepEvtPartons > TtFullLepJetPartonMatch; +typedef TtJetPartonMatch TtFullLepJetPartonMatch; DEFINE_FWK_MODULE(TtFullLepJetPartonMatch); diff --git a/TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h b/TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h index a7aa91466938a..6093272b12222 100644 --- a/TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h +++ b/TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h @@ -42,9 +42,7 @@ template class TtJetPartonMatch : public edm::EDProducer { - - public: - +public: /// default conructor explicit TtJetPartonMatch(const edm::ParameterSet&); /// default destructor @@ -52,8 +50,7 @@ class TtJetPartonMatch : public edm::EDProducer { /// write jet parton match objects into the event void produce(edm::Event&, const edm::EventSetup&) override; - private: - +private: /// convert string for algorithm into corresponding enumerator type JetPartonMatching::algorithms readAlgorithm(const std::string& str); @@ -83,19 +80,18 @@ class TtJetPartonMatch : public edm::EDProducer { int verbosity_; }; -template -TtJetPartonMatch::TtJetPartonMatch(const edm::ParameterSet& cfg): - partons_ (cfg.getParameter >("partonsToIgnore")), - genEvt_ (consumes(edm::InputTag("genEvt"))), - jets_ (consumes >(cfg.getParameter("jets"))), - maxNJets_ (cfg.getParameter ("maxNJets" )), - maxNComb_ (cfg.getParameter ("maxNComb" )), - algorithm_ (readAlgorithm(cfg.getParameter("algorithm" ))), - useDeltaR_ (cfg.getParameter ("useDeltaR" )), - useMaxDist_(cfg.getParameter ("useMaxDist" )), - maxDist_ (cfg.getParameter ("maxDist" )), - verbosity_ (cfg.getParameter ("verbosity" )) -{ +template +TtJetPartonMatch::TtJetPartonMatch(const edm::ParameterSet& cfg) + : partons_(cfg.getParameter >("partonsToIgnore")), + genEvt_(consumes(edm::InputTag("genEvt"))), + jets_(consumes >(cfg.getParameter("jets"))), + maxNJets_(cfg.getParameter("maxNJets")), + maxNComb_(cfg.getParameter("maxNComb")), + algorithm_(readAlgorithm(cfg.getParameter("algorithm"))), + useDeltaR_(cfg.getParameter("useDeltaR")), + useMaxDist_(cfg.getParameter("useMaxDist")), + maxDist_(cfg.getParameter("maxDist")), + verbosity_(cfg.getParameter("verbosity")) { // produces a vector of jet/lepton indices in the order of // * TtSemiLepEvtPartons // * TtFullHadEvtPartons @@ -107,15 +103,11 @@ TtJetPartonMatch::TtJetPartonMatch(const edm::ParameterSet& cfg): produces("NumberOfConsideredJets"); } -template -TtJetPartonMatch::~TtJetPartonMatch() -{ -} +template +TtJetPartonMatch::~TtJetPartonMatch() {} -template -void -TtJetPartonMatch::produce(edm::Event& evt, const edm::EventSetup& setup) -{ +template +void TtJetPartonMatch::produce(edm::Event& evt, const edm::EventSetup& setup) { // will write // * parton match // * sumPt @@ -141,20 +133,21 @@ TtJetPartonMatch::produce(edm::Event& evt, const edm::EventSetup& setup) // prepare vector of jets std::vector jets; - for(unsigned int ij=0; ijsize(); ++ij) { + for (unsigned int ij = 0; ij < topJets->size(); ++ij) { // take all jets if maxNJets_ == -1; otherwise use // maxNJets_ if maxNJets_ is big enough or use same // number of jets as partons if maxNJets_ < number // of partons - if(maxNJets_!=-1) { - if(maxNJets_>=(int)partons.size()) { - if((int)ij==maxNJets_) break; - } - else { - if(ij==partons.size()) break; + if (maxNJets_ != -1) { + if (maxNJets_ >= (int)partons.size()) { + if ((int)ij == maxNJets_) + break; + } else { + if (ij == partons.size()) + break; } } - jets.push_back( (const reco::Candidate*) &(*topJets)[ij] ); + jets.push_back((const reco::Candidate*)&(*topJets)[ij]); } *pJetsConsidered = jets.size(); @@ -163,16 +156,17 @@ TtJetPartonMatch::produce(edm::Event& evt, const edm::EventSetup& setup) // print some info for each event // if corresponding verbosity level set - if(verbosity_>0) + if (verbosity_ > 0) jetPartonMatch.print(); - for(unsigned int ic=0; ic=maxNComb_ && maxNComb_>=0) break; + for (unsigned int ic = 0; ic < jetPartonMatch.getNumberOfAvailableCombinations(); ++ic) { + if ((int)ic >= maxNComb_ && maxNComb_ >= 0) + break; std::vector matches = jetPartonMatch.getMatchesForPartons(ic); - partons_.expand(matches); // insert dummy indices for partons that were chosen to be ignored - match->push_back( matches ); - sumPt->push_back( jetPartonMatch.getSumDeltaPt(ic) ); - sumDR->push_back( jetPartonMatch.getSumDeltaR (ic) ); + partons_.expand(matches); // insert dummy indices for partons that were chosen to be ignored + match->push_back(matches); + sumPt->push_back(jetPartonMatch.getSumDeltaPt(ic)); + sumDR->push_back(jetPartonMatch.getSumDeltaR(ic)); } evt.put(std::move(match)); evt.put(std::move(sumPt), "SumPt"); @@ -180,16 +174,18 @@ TtJetPartonMatch::produce(edm::Event& evt, const edm::EventSetup& setup) evt.put(std::move(pJetsConsidered), "NumberOfConsideredJets"); } -template -JetPartonMatching::algorithms -TtJetPartonMatch::readAlgorithm(const std::string& str) -{ - if (str == "totalMinDist" ) return JetPartonMatching::totalMinDist; - else if(str == "minSumDist" ) return JetPartonMatching::minSumDist; - else if(str == "ptOrderedMinDist") return JetPartonMatching::ptOrderedMinDist; - else if(str == "unambiguousOnly" ) return JetPartonMatching::unambiguousOnly; - else throw cms::Exception("Configuration") - << "Chosen algorithm is not supported: " << str << "\n"; +template +JetPartonMatching::algorithms TtJetPartonMatch::readAlgorithm(const std::string& str) { + if (str == "totalMinDist") + return JetPartonMatching::totalMinDist; + else if (str == "minSumDist") + return JetPartonMatching::minSumDist; + else if (str == "ptOrderedMinDist") + return JetPartonMatching::ptOrderedMinDist; + else if (str == "unambiguousOnly") + return JetPartonMatching::unambiguousOnly; + else + throw cms::Exception("Configuration") << "Chosen algorithm is not supported: " << str << "\n"; } #endif diff --git a/TopQuarkAnalysis/TopTools/plugins/TtSemiLepJetPartonMatch.cc b/TopQuarkAnalysis/TopTools/plugins/TtSemiLepJetPartonMatch.cc index 60b6aebf251a6..af95109b782ca 100644 --- a/TopQuarkAnalysis/TopTools/plugins/TtSemiLepJetPartonMatch.cc +++ b/TopQuarkAnalysis/TopTools/plugins/TtSemiLepJetPartonMatch.cc @@ -3,5 +3,5 @@ #include "TopQuarkAnalysis/TopTools/plugins/TtJetPartonMatch.h" #include "AnalysisDataFormats/TopObjects/interface/TtSemiLepEvtPartons.h" -typedef TtJetPartonMatch< TtSemiLepEvtPartons > TtSemiLepJetPartonMatch; +typedef TtJetPartonMatch TtSemiLepJetPartonMatch; DEFINE_FWK_MODULE(TtSemiLepJetPartonMatch); diff --git a/TopQuarkAnalysis/TopTools/src/JetPartonMatching.cc b/TopQuarkAnalysis/TopTools/src/JetPartonMatching.cc index a17fb05d4f8a1..6152700ec991e 100644 --- a/TopQuarkAnalysis/TopTools/src/JetPartonMatching.cc +++ b/TopQuarkAnalysis/TopTools/src/JetPartonMatching.cc @@ -2,203 +2,211 @@ #include "FWCore/MessageLogger/interface/MessageLogger.h" #include -JetPartonMatching::JetPartonMatching(const std::vector& p, const std::vector& j, - const int algorithm = totalMinDist, const bool useMaxDist = true, - const bool useDeltaR = true, const double maxDist = 0.3) - : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) -{ +JetPartonMatching::JetPartonMatching(const std::vector& p, + const std::vector& j, + const int algorithm = totalMinDist, + const bool useMaxDist = true, + const bool useDeltaR = true, + const double maxDist = 0.3) + : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) { std::vector js; - for(unsigned int i=0; i& p, const std::vector& j, - const int algorithm = totalMinDist, const bool useMaxDist = true, - const bool useDeltaR = true, const double maxDist = 0.3) - : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) -{ +JetPartonMatching::JetPartonMatching(const std::vector& p, + const std::vector& j, + const int algorithm = totalMinDist, + const bool useMaxDist = true, + const bool useDeltaR = true, + const double maxDist = 0.3) + : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) { std::vector js; - for(unsigned int i = 0; i < j.size(); ++i) js.push_back( &(j[i]) ); - jets = js; - calculate(); + for (unsigned int i = 0; i < j.size(); ++i) + js.push_back(&(j[i])); + jets = js; + calculate(); } -JetPartonMatching::JetPartonMatching(const std::vector& p, const std::vector& j, - const int algorithm = totalMinDist, const bool useMaxDist = true, - const bool useDeltaR = true, const double maxDist = 0.3) - : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) -{ +JetPartonMatching::JetPartonMatching(const std::vector& p, + const std::vector& j, + const int algorithm = totalMinDist, + const bool useMaxDist = true, + const bool useDeltaR = true, + const double maxDist = 0.3) + : partons(p), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) { std::vector js; - for(unsigned int i = 0; i < j.size(); ++i) js.push_back( &(j[i]) ); - jets = js; - calculate(); + for (unsigned int i = 0; i < j.size(); ++i) + js.push_back(&(j[i])); + jets = js; + calculate(); } -JetPartonMatching::JetPartonMatching(const std::vector& p, const std::vector& j, - const int algorithm = totalMinDist, const bool useMaxDist = true, - const bool useDeltaR = true, const double maxDist = 0.3) - : partons(p), jets(j), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) -{ +JetPartonMatching::JetPartonMatching(const std::vector& p, + const std::vector& j, + const int algorithm = totalMinDist, + const bool useMaxDist = true, + const bool useDeltaR = true, + const double maxDist = 0.3) + : partons(p), jets(j), algorithm_(algorithm), useMaxDist_(useMaxDist), useDeltaR_(useDeltaR), maxDist_(maxDist) { calculate(); } -void -JetPartonMatching::calculate() -{ - // use maximal distance between objects +void JetPartonMatching::calculate() { + // use maximal distance between objects // in case of unambiguousOnly algorithmm - if(algorithm_==unambiguousOnly) useMaxDist_=true; + if (algorithm_ == unambiguousOnly) + useMaxDist_ = true; // check if there are empty partons in - // the vector, which happpens if the - // event is not ttbar or the decay is + // the vector, which happpens if the + // event is not ttbar or the decay is // not as expected - bool emptyParton=false; - for(unsigned int ip=0; ippdgId() ==0 ){ - emptyParton=true; + bool emptyParton = false; + for (unsigned int ip = 0; ip < partons.size(); ++ip) { + if (partons[ip]->pdgId() == 0) { + emptyParton = true; break; } } // switch algorithm, default is to match - // on the minimal sum of the distance + // on the minimal sum of the distance // (if jets or a parton is empty fill match with blanks) - if( jets.empty() || emptyParton ) { + if (jets.empty() || emptyParton) { MatchingCollection dummyMatch; - for(unsigned int ip=0; ip=0) --nUnmatchedPartons; + for (unsigned int part = 0; part < partons.size(); ++part) + if (getMatchForParton(part, comb) >= 0) + --nUnmatchedPartons; - double sumDE = -999.; + double sumDE = -999.; double sumDPt = -999.; - double sumDR = -999.; - if(nUnmatchedPartons==0){ - sumDE = 0; + double sumDR = -999.; + if (nUnmatchedPartons == 0) { + sumDE = 0; sumDPt = 0; - sumDR = 0; - for(unsigned int i=0; ienergy() - jets[match[i].second]->energy()); - sumDPt += fabs(partons[match[i].first]->pt() - jets[match[i].second]->pt()); - sumDR += distance(partons[match[i].first]->p4(), jets[match[i].second]->p4()); + sumDR = 0; + for (unsigned int i = 0; i < match.size(); ++i) { + sumDE += fabs(partons[match[i].first]->energy() - jets[match[i].second]->energy()); + sumDPt += fabs(partons[match[i].first]->pt() - jets[match[i].second]->pt()); + sumDR += distance(partons[match[i].first]->p4(), jets[match[i].second]->p4()); } } - numberOfUnmatchedPartons.push_back( nUnmatchedPartons ); - sumDeltaE .push_back( sumDE ); - sumDeltaPt.push_back( sumDPt ); - sumDeltaR .push_back( sumDR ); + numberOfUnmatchedPartons.push_back(nUnmatchedPartons); + sumDeltaE.push_back(sumDE); + sumDeltaPt.push_back(sumDPt); + sumDeltaR.push_back(sumDR); } } -double -JetPartonMatching::distance(const math::XYZTLorentzVector& v1, const math::XYZTLorentzVector& v2) -{ - // calculate the distance between two lorentz vectors +double JetPartonMatching::distance(const math::XYZTLorentzVector& v1, const math::XYZTLorentzVector& v2) { + // calculate the distance between two lorentz vectors // using DeltaR(eta, phi) or normal space angle(theta, phi) - if(useDeltaR_) return ROOT::Math::VectorUtil::DeltaR(v1, v2); + if (useDeltaR_) + return ROOT::Math::VectorUtil::DeltaR(v1, v2); return ROOT::Math::VectorUtil::Angle(v1, v2); } -void -JetPartonMatching::matchingTotalMinDist() -{ +void JetPartonMatching::matchingTotalMinDist() { // match parton to jet with shortest distance // starting with the shortest distance available // apply some outlier rejection if desired // prepare vector of pairs with distances between // all partons to all jets in the input vectors - std::vector< std::pair > distances; - for(unsigned int ip=0; ip > distances; + for (unsigned int ip = 0; ip < partons.size(); ++ip) { + for (unsigned int ij = 0; ij < jets.size(); ++ij) { double dist = distance(jets[ij]->p4(), partons[ip]->p4()); - distances.push_back(std::pair(dist, ip*jets.size()+ij)); + distances.push_back(std::pair(dist, ip * jets.size() + ij)); } } std::sort(distances.begin(), distances.end()); MatchingCollection match; - while(match.size() < partons.size()){ - unsigned int partonIndex = distances[0].second/jets.size(); - int jetIndex = distances[0].second-jets.size()*partonIndex; - + while (match.size() < partons.size()) { + unsigned int partonIndex = distances[0].second / jets.size(); + int jetIndex = distances[0].second - jets.size() * partonIndex; + // use primitive outlier rejection if desired - if(useMaxDist_&& distances[0].first>maxDist_) jetIndex = -1; + if (useMaxDist_ && distances[0].first > maxDist_) + jetIndex = -1; // prevent underflow in case of too few jets - if( distances.empty() ) + if (distances.empty()) match.push_back(std::make_pair(partonIndex, -1)); else match.push_back(std::make_pair(partonIndex, jetIndex)); - - // remove all values for the matched parton + + // remove all values for the matched parton // and the matched jet - for(unsigned int a=0; a & jetIndices, - std::vector & usedJets, std::vector > & distMatchVec) -{ +void JetPartonMatching::minSumDist_recursion(const unsigned int ip, + std::vector& jetIndices, + std::vector& usedJets, + std::vector >& distMatchVec) { // build up jet combinations recursively - if(ipp4(), jets[jetIndices[ip]]->p4()); - if(useMaxDist_ && dist > maxDist_) return; // outlier rejection + for (unsigned int ip = 0; ip < partons.size(); ++ip) { + double dist = distance(partons[ip]->p4(), jets[jetIndices[ip]]->p4()); + if (useMaxDist_ && dist > maxDist_) + return; // outlier rejection sumDist += distance(partons[ip]->p4(), jets[jetIndices[ip]]->p4()); match.push_back(std::make_pair(ip, jetIndices[ip])); } - distMatchVec.push_back( std::make_pair(sumDist, match) ); + distMatchVec.push_back(std::make_pair(sumDist, match)); return; } -void JetPartonMatching::matchingMinSumDist() -{ +void JetPartonMatching::matchingMinSumDist() { // match partons to jets with minimal sum of // the distances between all partons and jets std::vector > distMatchVec; std::vector usedJets; - for(unsigned int i=0; i > ptOrderedPartons; + std::vector > ptOrderedPartons; - for(unsigned int ip=0; ippt(), ip)); std::sort(ptOrderedPartons.begin(), ptOrderedPartons.end()); std::reverse(ptOrderedPartons.begin(), ptOrderedPartons.end()); std::vector jetIndices; - for(unsigned int ij=0; ijp4(), jets[jetIndices[ij]]->p4()); - if(dist < minDist){ - if(!useMaxDist_ || dist <= maxDist_){ - minDist = dist; - ijMin = ij; - } + if (dist < minDist) { + if (!useMaxDist_ || dist <= maxDist_) { + minDist = dist; + ijMin = ij; + } } } - - if(ijMin >= 0){ - match.push_back( std::make_pair(ptOrderedPartons[ip].second, jetIndices[ijMin]) ); + + if (ijMin >= 0) { + match.push_back(std::make_pair(ptOrderedPartons[ip].second, jetIndices[ijMin])); jetIndices.erase(jetIndices.begin() + ijMin, jetIndices.begin() + ijMin + 1); - } - else - match.push_back( std::make_pair(ptOrderedPartons[ip].second, -1) ); + } else + match.push_back(std::make_pair(ptOrderedPartons[ip].second, -1)); } matching.clear(); - matching.push_back( match ); + matching.push_back(match); return; } -void -JetPartonMatching::matchingUnambiguousOnly() -{ - // match partons to jets, only accept event +void JetPartonMatching::matchingUnambiguousOnly() { + // match partons to jets, only accept event // if there are no ambiguities std::vector jetMatched; - for(unsigned int ij=0; ijp4(), jets[ij]->p4()); - if(dist <= maxDist_){ - if(!jetMatched[ij]){ // new match for jet - jetMatched[ij] = true; - if(iMatch == -1) // new match for parton and jet - iMatch = ij; - else // parton already matched: ambiguity! - iMatch = -2; - } - else // jet already matched: ambiguity! - iMatch = -2; + if (dist <= maxDist_) { + if (!jetMatched[ij]) { // new match for jet + jetMatched[ij] = true; + if (iMatch == -1) // new match for parton and jet + iMatch = ij; + else // parton already matched: ambiguity! + iMatch = -2; + } else // jet already matched: ambiguity! + iMatch = -2; } } match.push_back(std::make_pair(ip, iMatch)); } matching.clear(); - matching.push_back( match ); + matching.push_back(match); return; } -int -JetPartonMatching::getMatchForParton(const unsigned int part, const unsigned int comb) -{ +int JetPartonMatching::getMatchForParton(const unsigned int part, const unsigned int comb) { // return index of the matched jet for a given parton // (if arguments for parton index and combinatoric index // are in the valid range) - if(comb >= matching.size()) return -9; - if(part >= matching[comb].size()) return -9; + if (comb >= matching.size()) + return -9; + if (part >= matching[comb].size()) + return -9; return (matching[comb])[part].second; } -std::vector -JetPartonMatching::getMatchesForPartons(const unsigned int comb) -{ +std::vector JetPartonMatching::getMatchesForPartons(const unsigned int comb) { // return a vector with the indices of the matched jets // (ordered according to the vector of partons) std::vector jetIndices; - for(unsigned int part=0; partp4(), partons[part]->p4() ); + if (getMatchForParton(part, comb) < 0) + return -999.; + return distance(jets[getMatchForParton(part, comb)]->p4(), partons[part]->p4()); } -double -JetPartonMatching::getSumDistances(const unsigned int comb) -{ +double JetPartonMatching::getSumDistances(const unsigned int comb) { // get sum of distances between partons and matched jets double sumDists = 0.; - for(unsigned int part=0; partSetCanvasDefW(900); } - -LRHelpFunctions::LRHelpFunctions(const std::vector& obsNr, int nrBins, const std::vector& obsMin, const std::vector& obsMax, const std::vector& functions) { +LRHelpFunctions::LRHelpFunctions(const std::vector& obsNr, + int nrBins, + const std::vector& obsMin, + const std::vector& obsMax, + const std::vector& functions) { obsNumbers = obsNr; constructPurity = false; setTDRStyle(); gStyle->SetCanvasDefW(900); - for(size_t o=0; oGetXaxis()->GetXmin(),hObsS[o]->GetXaxis()->GetXmax()) ); + TString ftSB = "F_Obs"; + ftSB += obsNr[o]; + ftSB += "_SoverSplusB"; + fObsSoverSplusB.push_back( + new TF1(ftSB, functions[o], hObsS[o]->GetXaxis()->GetXmin(), hObsS[o]->GetXaxis()->GetXmax())); } } void LRHelpFunctions::recreateFitFct(const std::vector& obsNr, const std::vector& functions) { - if (!fObsSoverSplusB.empty()) fObsSoverSplusB.clear(); - for(size_t o=0; oGetXaxis()->GetXmin(),hObsS[o]->GetXaxis()->GetXmax()) ); + TString ftSB = "F_Obs"; + ftSB += obsNr[o]; + ftSB += "_SoverSplusB"; + fObsSoverSplusB.push_back( + new TF1(ftSB, functions[o], hObsS[o]->GetXaxis()->GetXmin(), hObsS[o]->GetXaxis()->GetXmax())); } } -LRHelpFunctions::LRHelpFunctions(int nrLRbins, double LRmin, double LRmax, const char* LRfunction) { +LRHelpFunctions::LRHelpFunctions(int nrLRbins, double LRmin, double LRmax, const char* LRfunction) { constructPurity = true; setTDRStyle(); gStyle->SetCanvasDefW(900); // create LR histograms - hLRtotS = new TH1F("hLRtotS","hLRtotS",nrLRbins,LRmin,LRmax); + hLRtotS = new TH1F("hLRtotS", "hLRtotS", nrLRbins, LRmin, LRmax); hLRtotS->GetXaxis()->SetTitle("Combined LR"); - hLRtotB = new TH1F("hLRtotB","hLRtotB",nrLRbins,LRmin,LRmax); + hLRtotB = new TH1F("hLRtotB", "hLRtotB", nrLRbins, LRmin, LRmax); hLRtotB->GetXaxis()->SetTitle("Combined LR"); - hLRtotSoverSplusB = new TH1F("hLRtotSoverSplusB","hLRtotSoverSplusB",nrLRbins,LRmin,LRmax); - + hLRtotSoverSplusB = new TH1F("hLRtotSoverSplusB", "hLRtotSoverSplusB", nrLRbins, LRmin, LRmax); + // create LR fit function - fLRtotSoverSplusB = new TF1("fLRtotSoverSplusB",LRfunction,LRmin,LRmax); + fLRtotSoverSplusB = new TF1("fLRtotSoverSplusB", LRfunction, LRmin, LRmax); } - // destructor LRHelpFunctions::~LRHelpFunctions() {} - // member function to initialize the LR hists and fits -void LRHelpFunctions::initLRHistsAndFits(int nrLRbins, double LRmin, double LRmax, const char* LRfunction){ +void LRHelpFunctions::initLRHistsAndFits(int nrLRbins, double LRmin, double LRmax, const char* LRfunction) { constructPurity = true; // create LR histograms - hLRtotS = new TH1F("hLRtotS","hLRtotS",nrLRbins,LRmin,LRmax); - hLRtotB = new TH1F("hLRtotB","hLRtotB",nrLRbins,LRmin,LRmax); - hLRtotSoverSplusB = new TH1F("hLRtotSoverSplusB","hLRtotSoverSplusB",nrLRbins,LRmin,LRmax); + hLRtotS = new TH1F("hLRtotS", "hLRtotS", nrLRbins, LRmin, LRmax); + hLRtotB = new TH1F("hLRtotB", "hLRtotB", nrLRbins, LRmin, LRmax); + hLRtotSoverSplusB = new TH1F("hLRtotSoverSplusB", "hLRtotSoverSplusB", nrLRbins, LRmin, LRmax); // create LR fit function - fLRtotSoverSplusB = new TF1("fLRtotSoverSplusB",LRfunction,LRmin,LRmax); + fLRtotSoverSplusB = new TF1("fLRtotSoverSplusB", LRfunction, LRmin, LRmax); } - - // member function to set initial values to the observable fit function -void LRHelpFunctions::setObsFitParameters(int obs,const std::vector& fitPars){ - for(size_t fit=0; fitGetName()).Contains(fn)){ - for(size_t p=0; pSetParameter(p,fitPars[p]); +void LRHelpFunctions::setObsFitParameters(int obs, const std::vector& fitPars) { + for (size_t fit = 0; fit < fObsSoverSplusB.size(); fit++) { + TString fn = "_Obs"; + fn += obs; + if (((TString)fObsSoverSplusB[fit]->GetName()).Contains(fn)) { + for (size_t p = 0; p < fitPars.size(); p++) { + fObsSoverSplusB[fit]->SetParameter(p, fitPars[p]); } } } } - - - - // member function to add observable values to the signal histograms -void LRHelpFunctions::fillToSignalHists(const std::vector& obsVals, double weight){ +void LRHelpFunctions::fillToSignalHists(const std::vector& obsVals, double weight) { int hIndex = 0; - for(size_t o=0; oFill(obsVals[o], weight); - for(size_t o2=o+1; o2 Fill(obsVals[o],obsVals[o2], weight); + for (size_t o2 = o + 1; o2 < obsVals.size(); o2++) { + hObsCorr[hIndex]->Fill(obsVals[o], obsVals[o2], weight); ++hIndex; } } } // member function to add observable values to the signal histograms -void LRHelpFunctions::fillToSignalHists(int obsNbr, double obsVal, double weight){ - TString obs = "Obs"; obs += obsNbr; obs += "_"; - for(size_t f = 0; fGetName())).Contains(obs)) { +void LRHelpFunctions::fillToSignalHists(int obsNbr, double obsVal, double weight) { + TString obs = "Obs"; + obs += obsNbr; + obs += "_"; + for (size_t f = 0; f < hObsS.size(); f++) { + if (((TString)(hObsS[f]->GetName())).Contains(obs)) { hObsS[f]->Fill(obsVal, weight); return; } @@ -118,32 +132,36 @@ void LRHelpFunctions::fillToSignalHists(int obsNbr, double obsVal, double weight } // member function to add observable values to the signal histograms -void LRHelpFunctions::fillToSignalCorrelation(int obsNbr1, double obsVal1, int obsNbr2, - double obsVal2, double weight){ - TString hcorr = "Corr_Obs"; hcorr += std::min(obsNbr1,obsNbr2) ; hcorr += "_Obs"; hcorr += std::max(obsNbr1, obsNbr2); - for(size_t i=0; iGetName())) == hcorr) { +void LRHelpFunctions::fillToSignalCorrelation(int obsNbr1, double obsVal1, int obsNbr2, double obsVal2, double weight) { + TString hcorr = "Corr_Obs"; + hcorr += std::min(obsNbr1, obsNbr2); + hcorr += "_Obs"; + hcorr += std::max(obsNbr1, obsNbr2); + for (size_t i = 0; i < hObsCorr.size(); i++) { + if (((TString)(hObsCorr[i]->GetName())) == hcorr) { if (obsNbr1 < obsNbr2) { - hObsCorr[i] -> Fill(obsVal1,obsVal2, weight); + hObsCorr[i]->Fill(obsVal1, obsVal2, weight); } else { - hObsCorr[i] -> Fill(obsVal2,obsVal1, weight); + hObsCorr[i]->Fill(obsVal2, obsVal1, weight); } return; } } } - // member function to add observable values to the background histograms -void LRHelpFunctions::fillToBackgroundHists(const std::vector& obsVals, double weight){ - for(size_t o=0; oFill(obsVals[o], weight); +void LRHelpFunctions::fillToBackgroundHists(const std::vector& obsVals, double weight) { + for (size_t o = 0; o < obsVals.size(); o++) + hObsB[o]->Fill(obsVals[o], weight); } // member function to add observable values to the signal histograms -void LRHelpFunctions::fillToBackgroundHists(int obsNbr, double obsVal, double weight){ - TString obs = "Obs"; obs += obsNbr; obs += "_"; - for(size_t f = 0; fGetName())).Contains(obs)) { +void LRHelpFunctions::fillToBackgroundHists(int obsNbr, double obsVal, double weight) { + TString obs = "Obs"; + obs += obsNbr; + obs += "_"; + for (size_t f = 0; f < hObsB.size(); f++) { + if (((TString)(hObsB[f]->GetName())).Contains(obs)) { hObsB[f]->Fill(obsVal, weight); return; } @@ -151,278 +169,276 @@ void LRHelpFunctions::fillToBackgroundHists(int obsNbr, double obsVal, double we } // member function to normalize the S and B spectra -void LRHelpFunctions::normalizeSandBhists(){ - for(size_t o=0; oGetNbinsX()+1; i++){ + for (int i = 0; i <= hObsS[o]->GetNbinsX() + 1; i++) { nrSignEntries += hObsS[o]->GetBinContent(i); nrBackEntries += hObsB[o]->GetBinContent(i); - } - for(int b=0; b <= hObsS[o]->GetNbinsX()+1; b++){ - hObsS[o]->SetBinContent(b,hObsS[o]->GetBinContent(b)/(nrSignEntries)); - hObsB[o]->SetBinContent(b,hObsB[o]->GetBinContent(b)/(nrBackEntries)); - hObsS[o]->SetBinError(b,hObsS[o]->GetBinError(b)/(nrSignEntries)); - hObsB[o]->SetBinError(b,hObsB[o]->GetBinError(b)/(nrBackEntries)); + } + for (int b = 0; b <= hObsS[o]->GetNbinsX() + 1; b++) { + hObsS[o]->SetBinContent(b, hObsS[o]->GetBinContent(b) / (nrSignEntries)); + hObsB[o]->SetBinContent(b, hObsB[o]->GetBinContent(b) / (nrBackEntries)); + hObsS[o]->SetBinError(b, hObsS[o]->GetBinError(b) / (nrSignEntries)); + hObsB[o]->SetBinError(b, hObsB[o]->GetBinError(b) / (nrBackEntries)); } //std::cout<<"Integral for obs"<Integral(0,10000)<<" & obs"<Integral(0,10000)<GetNbinsX()+1; b++){ - if ((hObsS[o]->GetBinContent(b)+ hObsB[o]->GetBinContent(b)) > 0) { - hObsSoverSplusB[o]->SetBinContent(b, hObsS[o]->GetBinContent(b) / (hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b))); - double error = sqrt( pow(hObsS[o]->GetBinError(b) * hObsB[o]->GetBinContent(b)/pow(hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b),2),2) - + pow(hObsB[o]->GetBinError(b) * hObsS[o]->GetBinContent(b)/pow(hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b),2),2) ); - hObsSoverSplusB[o]->SetBinError(b,error); +void LRHelpFunctions::makeAndFitSoverSplusBHists() { + for (size_t o = 0; o < hObsS.size(); o++) { + for (int b = 0; b <= hObsS[o]->GetNbinsX() + 1; b++) { + if ((hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b)) > 0) { + hObsSoverSplusB[o]->SetBinContent( + b, hObsS[o]->GetBinContent(b) / (hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b))); + double error = sqrt(pow(hObsS[o]->GetBinError(b) * hObsB[o]->GetBinContent(b) / + pow(hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b), 2), + 2) + + pow(hObsB[o]->GetBinError(b) * hObsS[o]->GetBinContent(b) / + pow(hObsS[o]->GetBinContent(b) + hObsB[o]->GetBinContent(b), 2), + 2)); + hObsSoverSplusB[o]->SetBinError(b, error); } } - hObsSoverSplusB[o]->Fit(fObsSoverSplusB[o]->GetName(),"RQ"); + hObsSoverSplusB[o]->Fit(fObsSoverSplusB[o]->GetName(), "RQ"); } } - // member function to read the observable hists & fits from a root-file -void LRHelpFunctions::readObsHistsAndFits(const TString& fileName, const std::vector& observables, bool readLRplots){ +void LRHelpFunctions::readObsHistsAndFits(const TString& fileName, + const std::vector& observables, + bool readLRplots) { hObsS.clear(); hObsB.clear(); hObsSoverSplusB.clear(); fObsSoverSplusB.clear(); - TFile *fitFile = new TFile(fileName, "READ"); - if(observables[0] == -1){ - std::cout<<" ... will read hists and fit for all available observables in file "<GetListOfKeys(); + TFile* fitFile = new TFile(fileName, "READ"); + if (observables[0] == -1) { + std::cout << " ... will read hists and fit for all available observables in file " << fileName << std::endl; + TList* list = fitFile->GetListOfKeys(); TIter next(list); - TKey *el; + TKey* el; while ((el = (TKey*)next())) { TString keyName = el->GetName(); - if(keyName.Contains("F_") && keyName.Contains("_SoverSplusB")){ - fObsSoverSplusB.push_back( new TF1(*((TF1*) el -> ReadObj()))); - } - else if(keyName.Contains("_SoverSplusB")){ - hObsSoverSplusB.push_back( new TH1F(*((TH1F*) el -> ReadObj()))); - } - else if(keyName.Contains("_S")){ - hObsS.push_back( new TH1F(*((TH1F*) el -> ReadObj()))); - } - else if(keyName.Contains("_B")){ - hObsB.push_back( new TH1F(*((TH1F*) el -> ReadObj()))); - } - else if(keyName.Contains("Corr")){ - hObsCorr.push_back( new TH2F(*((TH2F*) el -> ReadObj()))); + if (keyName.Contains("F_") && keyName.Contains("_SoverSplusB")) { + fObsSoverSplusB.push_back(new TF1(*((TF1*)el->ReadObj()))); + } else if (keyName.Contains("_SoverSplusB")) { + hObsSoverSplusB.push_back(new TH1F(*((TH1F*)el->ReadObj()))); + } else if (keyName.Contains("_S")) { + hObsS.push_back(new TH1F(*((TH1F*)el->ReadObj()))); + } else if (keyName.Contains("_B")) { + hObsB.push_back(new TH1F(*((TH1F*)el->ReadObj()))); + } else if (keyName.Contains("Corr")) { + hObsCorr.push_back(new TH2F(*((TH2F*)el->ReadObj()))); } } - } - else{ + } else { obsNumbers = observables; - for(unsigned int obs = 0; obs < observables.size(); obs++){ - std::cout<<" ... will read hists and fit for obs "<GetKey(hStitle)->ReadObj()))); - TString hBtitle = "Obs"; hBtitle += observables[obs]; hBtitle += "_B"; - hObsB.push_back( new TH1F(*((TH1F*)fitFile->GetKey(hBtitle)->ReadObj()))); - TString hSBtitle = "Obs"; hSBtitle += observables[obs]; hSBtitle += "_SoverSplusB"; - TString fSBtitle = "F_"; fSBtitle += hSBtitle; - hObsSoverSplusB.push_back( new TH1F(*((TH1F*)fitFile->GetKey(hSBtitle)->ReadObj()))); - fObsSoverSplusB.push_back( new TF1(*((TF1*)fitFile->GetKey(fSBtitle)->ReadObj()))); - for(unsigned int obs2 = obs+1; obs2 < observables.size(); obs2++){ - TString hCorrtitle = "Corr_Obs"; hCorrtitle += observables[obs]; - hCorrtitle += "_Obs"; hCorrtitle += observables[obs2]; - hObsCorr.push_back( new TH2F(*((TH2F*)fitFile->GetKey(hCorrtitle)->ReadObj()))); + for (unsigned int obs = 0; obs < observables.size(); obs++) { + std::cout << " ... will read hists and fit for obs " << observables[obs] << " from file " << fileName + << std::endl; + TString hStitle = "Obs"; + hStitle += observables[obs]; + hStitle += "_S"; + hObsS.push_back(new TH1F(*((TH1F*)fitFile->GetKey(hStitle)->ReadObj()))); + TString hBtitle = "Obs"; + hBtitle += observables[obs]; + hBtitle += "_B"; + hObsB.push_back(new TH1F(*((TH1F*)fitFile->GetKey(hBtitle)->ReadObj()))); + TString hSBtitle = "Obs"; + hSBtitle += observables[obs]; + hSBtitle += "_SoverSplusB"; + TString fSBtitle = "F_"; + fSBtitle += hSBtitle; + hObsSoverSplusB.push_back(new TH1F(*((TH1F*)fitFile->GetKey(hSBtitle)->ReadObj()))); + fObsSoverSplusB.push_back(new TF1(*((TF1*)fitFile->GetKey(fSBtitle)->ReadObj()))); + for (unsigned int obs2 = obs + 1; obs2 < observables.size(); obs2++) { + TString hCorrtitle = "Corr_Obs"; + hCorrtitle += observables[obs]; + hCorrtitle += "_Obs"; + hCorrtitle += observables[obs2]; + hObsCorr.push_back(new TH2F(*((TH2F*)fitFile->GetKey(hCorrtitle)->ReadObj()))); } } } - - if(readLRplots){ + + if (readLRplots) { constructPurity = true; - std::cout<<" ... will LR s and B histos from file "<GetKey("hLRtotS")->ReadObj())); hLRtotB = new TH1F(*((TH1F*)fitFile->GetKey("hLRtotB")->ReadObj())); hLRtotSoverSplusB = new TH1F(*((TH1F*)fitFile->GetKey("hLRtotSoverSplusB")->ReadObj())); - fLRtotSoverSplusB = new TF1(*((TF1*)fitFile->GetKey("fLRtotSoverSplusB") -> ReadObj())); + fLRtotSoverSplusB = new TF1(*((TF1*)fitFile->GetKey("fLRtotSoverSplusB")->ReadObj())); } } - - - // member function to store all observable plots and fits to a ROOT-file -void LRHelpFunctions::storeToROOTfile(const TString& fname){ - TFile fOut(fname,"RECREATE"); +void LRHelpFunctions::storeToROOTfile(const TString& fname) { + TFile fOut(fname, "RECREATE"); fOut.cd(); - for(size_t o=0; o Write(); - hObsB[o] -> Write(); - hObsSoverSplusB[o] -> Write(); - fObsSoverSplusB[o] -> Write(); + for (size_t o = 0; o < hObsS.size(); o++) { + hObsS[o]->Write(); + hObsB[o]->Write(); + hObsSoverSplusB[o]->Write(); + fObsSoverSplusB[o]->Write(); } int hIndex = 0; - for(size_t o=0; o Write(); - ++ hIndex; + for (size_t o = 0; o < hObsS.size(); o++) { + for (size_t o2 = o + 1; o2 < hObsS.size(); o2++) { + hObsCorr[hIndex]->Write(); + ++hIndex; } } - if(constructPurity){ - hLRtotS -> Write(); - hLRtotB -> Write(); - hLRtotSoverSplusB -> Write(); - fLRtotSoverSplusB -> Write(); - hEffvsPur -> Write(); - hLRValvsPur -> Write(); - hLRValvsEff -> Write(); + if (constructPurity) { + hLRtotS->Write(); + hLRtotB->Write(); + hLRtotSoverSplusB->Write(); + fLRtotSoverSplusB->Write(); + hEffvsPur->Write(); + hLRValvsPur->Write(); + hLRValvsEff->Write(); } fOut.cd(); fOut.Write(); fOut.Close(); } - - - - // member function to make some simple control plots and store them in a ps-file -void LRHelpFunctions::storeControlPlots(const TString& fname){ - TCanvas c("dummy","",1); - c.Print(fname + "[","landscape"); - for(size_t o=0; o SetLineColor(2); - if(hObsB[o]->GetMaximum() > hObsS[o]->GetMaximum()){ - hObsB[o] -> Draw("hist"); - hObsS[o] -> Draw("histsame"); - } - else - { - hObsS[o] -> Draw("hist"); - hObsB[o] -> Draw("histsame"); - } - c2.cd(2); - hObsSoverSplusB[o] -> Draw(); - fObsSoverSplusB[o] -> Draw("same"); - c2.Print(fname,"Landscape"); +void LRHelpFunctions::storeControlPlots(const TString& fname) { + TCanvas c("dummy", "", 1); + c.Print(fname + "[", "landscape"); + for (size_t o = 0; o < hObsS.size(); o++) { + TCanvas c2("c2", "", 1); + c2.Divide(2, 1); + c2.cd(1); + hObsS[o]->SetLineColor(2); + if (hObsB[o]->GetMaximum() > hObsS[o]->GetMaximum()) { + hObsB[o]->Draw("hist"); + hObsS[o]->Draw("histsame"); + } else { + hObsS[o]->Draw("hist"); + hObsB[o]->Draw("histsame"); + } + c2.cd(2); + hObsSoverSplusB[o]->Draw(); + fObsSoverSplusB[o]->Draw("same"); + c2.Print(fname, "Landscape"); } - + int hIndex = 0; - for(size_t o=0; o Draw("box"); - TPaveText pt(0.5,0.87,0.98,0.93,"blNDC"); + for (size_t o = 0; o < hObsS.size(); o++) { + for (size_t o2 = o + 1; o2 < hObsS.size(); o2++) { + TCanvas cc("cc", "", 1); + hObsCorr[hIndex]->Draw("box"); + TPaveText pt(0.5, 0.87, 0.98, 0.93, "blNDC"); pt.SetFillStyle(1); pt.SetFillColor(0); pt.SetBorderSize(0); - TString tcorr = "Corr. of "; tcorr += (int)(100.*hObsCorr[hIndex] -> GetCorrelationFactor()); tcorr += " %"; + TString tcorr = "Corr. of "; + tcorr += (int)(100. * hObsCorr[hIndex]->GetCorrelationFactor()); + tcorr += " %"; //TText *text = pt.AddText(tcorr); pt.Draw("same"); ++hIndex; - cc.Print(fname,"Landscape"); + cc.Print(fname, "Landscape"); } } - - if(constructPurity){ - TCanvas c3("c3","",1); - c3.Divide(2,1); + + if (constructPurity) { + TCanvas c3("c3", "", 1); + c3.Divide(2, 1); c3.cd(1); - hLRtotB -> Draw(); - hLRtotS -> SetLineColor(2); - hLRtotS -> Draw("same"); + hLRtotB->Draw(); + hLRtotS->SetLineColor(2); + hLRtotS->Draw("same"); c3.cd(2); - hLRtotSoverSplusB -> Draw(); - c3.Print(fname,"Landscape"); - - TCanvas c4("c4","",1); - hEffvsPur -> Draw("AL*"); - c4.Print(fname,"Landscape"); - - TCanvas c5("c5","",1); - hLRValvsPur -> Draw("AL*"); - c5.Print(fname,"Landscape"); - - TCanvas c6("c6","",1); - hLRValvsEff -> Draw("AL*"); - c6.Print(fname,"Landscape"); - } - c.Print(fname + "]","landscape"); -} - + hLRtotSoverSplusB->Draw(); + c3.Print(fname, "Landscape"); + TCanvas c4("c4", "", 1); + hEffvsPur->Draw("AL*"); + c4.Print(fname, "Landscape"); + TCanvas c5("c5", "", 1); + hLRValvsPur->Draw("AL*"); + c5.Print(fname, "Landscape"); + + TCanvas c6("c6", "", 1); + hLRValvsEff->Draw("AL*"); + c6.Print(fname, "Landscape"); + } + c.Print(fname + "]", "landscape"); +} // member function to calculate the LR value, using the S/N definition -double LRHelpFunctions::calcLRval(const std::vector& vals){ +double LRHelpFunctions::calcLRval(const std::vector& vals) { double logLR = 0.; - for(size_t o=0; oEval(vals[o]); - double SoverN = 1./((1./SoverSplusN) - 1.); + double SoverN = 1. / ((1. / SoverSplusN) - 1.); logLR += log(SoverN); - } + } return logLR; } - // member function to calculate the LR value, using the definition that was // used in the P-TDR: S/(S+N) - + double LRHelpFunctions::calcPtdrLRval(const std::vector& vals, bool useCorrelation) { double logLR = 1.; - for(size_t o=0; oEval(vals[o]); - if (SoverSplusN<0.0001) SoverSplusN=0.0001; - if (useCorrelation){ + if (SoverSplusN < 0.0001) + SoverSplusN = 0.0001; + if (useCorrelation) { double corr = 0; - for(size_t j=0; jGetName())) == hcorr) - corr += fabs(hObsCorr[i]->GetCorrelationFactor()); - } - } + for (size_t j = 0; j < fObsSoverSplusB.size(); j++) { + if (o == j) + ++corr; + else { + TString hcorr = "Corr_Obs"; + hcorr += std::min(obsNumbers[o], obsNumbers[j]); + hcorr += "_Obs"; + hcorr += std::max(obsNumbers[o], obsNumbers[j]); + for (size_t i = 0; i < hObsCorr.size(); i++) { + if (((TString)(hObsCorr[i]->GetName())) == hcorr) + corr += fabs(hObsCorr[i]->GetCorrelationFactor()); + } + } } - logLR *= pow(SoverSplusN/fObsSoverSplusB[o]->GetMaximum(), 1./corr); - } - else logLR *= SoverSplusN/fObsSoverSplusB[o]->GetMaximum(); + logLR *= pow(SoverSplusN / fObsSoverSplusB[o]->GetMaximum(), 1. / corr); + } else + logLR *= SoverSplusN / fObsSoverSplusB[o]->GetMaximum(); } //std::cout < LRHelpf Signal LRval = "<< val< Fill(val, weight); + hLRtotS->Fill(val, weight); } - - // member function to fill a background contribution to the LR histogram -void LRHelpFunctions::fillLRBackgroundHist(double val, double weight){ +void LRHelpFunctions::fillLRBackgroundHist(double val, double weight) { // std::cout<< "@@@===> LRHelpf Backgroud LRval = "<< val< Fill(val, weight); + hLRtotB->Fill(val, weight); } - - - -// member function to make and fit the purity vs. LRval histogram, and the purity vs. efficiency graph -void LRHelpFunctions::makeAndFitPurityHists(){ - for(int b=0; b<=hLRtotS->GetNbinsX(); b++) { - float Sint = hLRtotS->Integral(b, hLRtotS->GetNbinsX()+1); - float Bint = hLRtotB->Integral(b, hLRtotB->GetNbinsX()+1); +// member function to make and fit the purity vs. LRval histogram, and the purity vs. efficiency graph +void LRHelpFunctions::makeAndFitPurityHists() { + for (int b = 0; b <= hLRtotS->GetNbinsX(); b++) { + float Sint = hLRtotS->Integral(b, hLRtotS->GetNbinsX() + 1); + float Bint = hLRtotB->Integral(b, hLRtotB->GetNbinsX() + 1); if (Sint + Bint > 0) { - hLRtotSoverSplusB->SetBinContent(b,1. * Sint / (Sint + Bint)); - hLRtotSoverSplusB->SetBinError(b,sqrt((pow(Sint*sqrt(Bint),2)+pow(Bint*sqrt(Sint),2)))/pow((Sint+Bint),2)); + hLRtotSoverSplusB->SetBinContent(b, 1. * Sint / (Sint + Bint)); + hLRtotSoverSplusB->SetBinError( + b, sqrt((pow(Sint * sqrt(Bint), 2) + pow(Bint * sqrt(Sint), 2))) / pow((Sint + Bint), 2)); } } @@ -431,70 +447,64 @@ void LRHelpFunctions::makeAndFitPurityHists(){ hLRtotSoverSplusB->GetXaxis()->SetTitle("Cut on Combined LR"); hLRtotSoverSplusB->GetYaxis()->SetTitle("Purity"); - hLRtotSoverSplusB -> Fit(fLRtotSoverSplusB->GetName(),"RQ"); - double totSignal = hLRtotS->Integral(0,hLRtotS->GetNbinsX()+1); + hLRtotSoverSplusB->Fit(fLRtotSoverSplusB->GetName(), "RQ"); + double totSignal = hLRtotS->Integral(0, hLRtotS->GetNbinsX() + 1); double Eff[200], Pur[200], LRVal[200]; - if (hLRtotS->GetNbinsX()>200) { - std::cout << "Number of bins of LR histograms can not execeed 200!"<GetNbinsX() > 200) { + std::cout << "Number of bins of LR histograms can not execeed 200!" << std::endl; return; } - for(int cut=0; (cut<=hLRtotS->GetNbinsX())&&(cut<200) ; cut ++){ - double LRcutVal = hLRtotS->GetBinLowEdge(cut); - Eff[cut] = hLRtotS->Integral(cut,hLRtotS->GetNbinsX()+1)/totSignal; - Pur[cut] = fLRtotSoverSplusB->Eval(LRcutVal); - LRVal[cut] = LRcutVal; + for (int cut = 0; (cut <= hLRtotS->GetNbinsX()) && (cut < 200); cut++) { + double LRcutVal = hLRtotS->GetBinLowEdge(cut); + Eff[cut] = hLRtotS->Integral(cut, hLRtotS->GetNbinsX() + 1) / totSignal; + Pur[cut] = fLRtotSoverSplusB->Eval(LRcutVal); + LRVal[cut] = LRcutVal; } - hEffvsPur = new TGraph(hLRtotS->GetNbinsX(),Eff,Pur); - hEffvsPur -> SetName("hEffvsPur"); - hEffvsPur -> SetTitle(""); - hEffvsPur -> GetXaxis() -> SetTitle((TString)("Efficiency of cut on log combined LR")); - hEffvsPur -> GetYaxis() -> SetTitle((TString)("Purity")); - hEffvsPur -> GetYaxis() -> SetRangeUser(0,1.1); - - hLRValvsPur = new TGraph(hLRtotS->GetNbinsX(),LRVal,Pur); - hLRValvsPur -> SetName("hLRValvsPur"); - hLRValvsPur -> SetTitle(""); - hLRValvsPur -> GetXaxis() -> SetTitle((TString)("Cut on the log combined LR value")); - hLRValvsPur -> GetYaxis() -> SetTitle((TString)("Purity")); - hLRValvsPur -> GetYaxis() -> SetRangeUser(0,1.1); - - hLRValvsEff = new TGraph(hLRtotS->GetNbinsX(),LRVal,Eff); - hLRValvsEff -> SetName("hLRValvsEff"); - hLRValvsEff -> SetTitle(""); - hLRValvsEff -> GetXaxis() -> SetTitle((TString)("Cut on the log combined LR value")); - hLRValvsEff -> GetYaxis() -> SetTitle((TString)("Efficiency of cut on log combined LR")); - hLRValvsEff -> GetYaxis() -> SetRangeUser(0,1.1); - -} - - - - -// member function to calculate the probability for signal given a logLR value -double LRHelpFunctions::calcProb(double logLR){ - return fLRtotSoverSplusB -> Eval(logLR); + hEffvsPur = new TGraph(hLRtotS->GetNbinsX(), Eff, Pur); + hEffvsPur->SetName("hEffvsPur"); + hEffvsPur->SetTitle(""); + hEffvsPur->GetXaxis()->SetTitle((TString)("Efficiency of cut on log combined LR")); + hEffvsPur->GetYaxis()->SetTitle((TString)("Purity")); + hEffvsPur->GetYaxis()->SetRangeUser(0, 1.1); + + hLRValvsPur = new TGraph(hLRtotS->GetNbinsX(), LRVal, Pur); + hLRValvsPur->SetName("hLRValvsPur"); + hLRValvsPur->SetTitle(""); + hLRValvsPur->GetXaxis()->SetTitle((TString)("Cut on the log combined LR value")); + hLRValvsPur->GetYaxis()->SetTitle((TString)("Purity")); + hLRValvsPur->GetYaxis()->SetRangeUser(0, 1.1); + + hLRValvsEff = new TGraph(hLRtotS->GetNbinsX(), LRVal, Eff); + hLRValvsEff->SetName("hLRValvsEff"); + hLRValvsEff->SetTitle(""); + hLRValvsEff->GetXaxis()->SetTitle((TString)("Cut on the log combined LR value")); + hLRValvsEff->GetYaxis()->SetTitle((TString)("Efficiency of cut on log combined LR")); + hLRValvsEff->GetYaxis()->SetRangeUser(0, 1.1); } +// member function to calculate the probability for signal given a logLR value +double LRHelpFunctions::calcProb(double logLR) { return fLRtotSoverSplusB->Eval(logLR); } // member to check if a certain S/S+B fit function is read from the root-file -bool LRHelpFunctions::obsFitIncluded(int o){ +bool LRHelpFunctions::obsFitIncluded(int o) { bool included = false; - TString obs = "_Obs"; obs += o; obs += "_"; - for(size_t f = 0; fGetName())).Contains(obs)) included = true; + TString obs = "_Obs"; + obs += o; + obs += "_"; + for (size_t f = 0; f < fObsSoverSplusB.size(); f++) { + if (((TString)(fObsSoverSplusB[f]->GetName())).Contains(obs)) + included = true; } return included; } -void LRHelpFunctions::setXlabels(const std::vector & xLabels) -{ +void LRHelpFunctions::setXlabels(const std::vector& xLabels) { if (hObsS.size() != xLabels.size()) { - std::cout << "LRHelpFunctions::setXlabels: Number of labels (" - << xLabels.size()<< ") does not match number of obervables(" - << hObsS.size()<<").\n"; + std::cout << "LRHelpFunctions::setXlabels: Number of labels (" << xLabels.size() + << ") does not match number of obervables(" << hObsS.size() << ").\n"; return; } - for(size_t i = 0; iGetXaxis()->SetTitle(TString(xLabels[i])); hObsB[i]->GetXaxis()->SetTitle(TString(xLabels[i])); hObsSoverSplusB[i]->GetXaxis()->SetTitle(TString(xLabels[i])); @@ -502,116 +512,113 @@ void LRHelpFunctions::setXlabels(const std::vector & xLabels) } } -void LRHelpFunctions::setYlabels(const std::vector & yLabels) -{ +void LRHelpFunctions::setYlabels(const std::vector& yLabels) { if (hObsS.size() != yLabels.size()) { - std::cout << "LRHelpFunctions::setYlabels: Number of labels (" - << yLabels.size()<< ") does not match number of obervables(" - << hObsS.size()<<").\n"; + std::cout << "LRHelpFunctions::setYlabels: Number of labels (" << yLabels.size() + << ") does not match number of obervables(" << hObsS.size() << ").\n"; return; } - for(size_t i = 0; iGetYaxis()->SetTitle(TString(yLabels[i])); hObsB[i]->GetYaxis()->SetTitle(TString(yLabels[i])); } } -void LRHelpFunctions::singlePlot(const TString& fname, int obsNbr, const TString& extension) { - if (!obsFitIncluded(obsNbr)) return; +void LRHelpFunctions::singlePlot(const TString& fname, int obsNbr, const TString& extension) { + if (!obsFitIncluded(obsNbr)) + return; - TStyle *tdrStyle = gROOT->GetStyle("tdrStyle"); + TStyle* tdrStyle = gROOT->GetStyle("tdrStyle"); tdrStyle->SetOptFit(0); tdrStyle->SetOptStat(0); tdrStyle->SetOptTitle(0); -// tdrStyle->SetPadTopMargin(0.01); -// tdrStyle->SetPadBottomMargin(0.01); -// tdrStyle->SetPadLeftMargin(0.01); -// tdrStyle->SetPadRightMargin(0.01); + // tdrStyle->SetPadTopMargin(0.01); + // tdrStyle->SetPadBottomMargin(0.01); + // tdrStyle->SetPadLeftMargin(0.01); + // tdrStyle->SetPadRightMargin(0.01); - TCanvas c2("c2","",600,300); + TCanvas c2("c2", "", 600, 300); c2.SetTopMargin(0.01); c2.SetBottomMargin(0.01); c2.SetLeftMargin(0.01); c2.SetRightMargin(0.01); - std::cout <GetName())).Contains(obs)) { + std::cout << fname << std::endl; + c2.Divide(2, 1); + + TString obs = "Obs"; + obs += obsNbr; + obs += "_"; + for (size_t o = 0; o < hObsB.size(); ++o) { + if (((TString)(hObsB[o]->GetName())).Contains(obs)) { c2.cd(1); - hObsS[o] -> SetLineColor(2); - if(hObsB[o]->GetMaximum() > hObsS[o]->GetMaximum()){ - hObsB[o] -> Draw("hist"); - hObsS[o] -> Draw("histsame"); - } - else - { - hObsS[o] -> Draw("hist"); - hObsB[o] -> Draw("histsame"); + hObsS[o]->SetLineColor(2); + if (hObsB[o]->GetMaximum() > hObsS[o]->GetMaximum()) { + hObsB[o]->Draw("hist"); + hObsS[o]->Draw("histsame"); + } else { + hObsS[o]->Draw("hist"); + hObsB[o]->Draw("histsame"); } c2.cd(2); - hObsSoverSplusB[o] -> Draw(); - fObsSoverSplusB[o] -> Draw("same"); + hObsSoverSplusB[o]->Draw(); + fObsSoverSplusB[o]->Draw("same"); } } - std::cout << fname+"."+extension<GetStyle("tdrStyle"); +void LRHelpFunctions::purityPlot(const TString& fname, const TString& extension) { + TStyle* tdrStyle = gROOT->GetStyle("tdrStyle"); tdrStyle->SetOptFit(0); tdrStyle->SetOptStat(0); tdrStyle->SetOptTitle(0); -// tdrStyle->SetPadTopMargin(0.01); -// tdrStyle->SetPadBottomMargin(0.01); -// tdrStyle->SetPadLeftMargin(0.01); -// tdrStyle->SetPadRightMargin(0.01); + // tdrStyle->SetPadTopMargin(0.01); + // tdrStyle->SetPadBottomMargin(0.01); + // tdrStyle->SetPadLeftMargin(0.01); + // tdrStyle->SetPadRightMargin(0.01); - TCanvas c2("c2","",600,300); + TCanvas c2("c2", "", 600, 300); c2.SetTopMargin(0.01); c2.SetBottomMargin(0.01); c2.SetLeftMargin(0.01); c2.SetRightMargin(0.01); - std::cout <Draw("AP"); c2.cd(2); hEffvsPur->Draw("AP"); - c2.Print(fname+"Purity."+extension); + c2.Print(fname + "Purity." + extension); hLRtotS->GetXaxis()->SetNdivisions(505); hLRtotB->GetXaxis()->SetNdivisions(505); - TCanvas c3("c2","",300,300); -// c3.SetTopMargin(0.01); -// c3.SetBottomMargin(0.01); -// c3.SetLeftMargin(0.01); -// c3.SetRightMargin(0.01); + TCanvas c3("c2", "", 300, 300); + // c3.SetTopMargin(0.01); + // c3.SetBottomMargin(0.01); + // c3.SetLeftMargin(0.01); + // c3.SetRightMargin(0.01); hLRtotS->GetXaxis()->SetTitle("Combined LR"); hLRtotB->GetXaxis()->SetTitle("Combined LR"); - hLRtotB -> Draw(); - hLRtotS -> SetLineColor(2); - hLRtotS -> Draw("same"); - c3.Print(fname+"Dist."+extension); - - - TCanvas c5("c3","",900,600); - c5.Divide(2,2); - c5.cd(1); - hLRtotB -> Draw(); - hLRtotS -> SetLineColor(2); - hLRtotS -> Draw("same"); - c5.cd(3); - hLRValvsEff -> Draw("AP"); - c5.cd(2); - hEffvsPur -> Draw("AP"); - c5.cd(4); - hLRtotSoverSplusB -> Draw(); - c5.Print(fname+"all."+extension); + hLRtotB->Draw(); + hLRtotS->SetLineColor(2); + hLRtotS->Draw("same"); + c3.Print(fname + "Dist." + extension); + + TCanvas c5("c3", "", 900, 600); + c5.Divide(2, 2); + c5.cd(1); + hLRtotB->Draw(); + hLRtotS->SetLineColor(2); + hLRtotS->Draw("same"); + c5.cd(3); + hLRValvsEff->Draw("AP"); + c5.cd(2); + hEffvsPur->Draw("AP"); + c5.cd(4); + hLRtotSoverSplusB->Draw(); + c5.Print(fname + "all." + extension); } diff --git a/TopQuarkAnalysis/TopTools/src/MEzCalculator.cc b/TopQuarkAnalysis/TopTools/src/MEzCalculator.cc index be57bc957dfb3..393f33cd01666 100644 --- a/TopQuarkAnalysis/TopTools/src/MEzCalculator.cc +++ b/TopQuarkAnalysis/TopTools/src/MEzCalculator.cc @@ -2,30 +2,26 @@ #include "TMath.h" /// constructor -MEzCalculator::MEzCalculator() -{ +MEzCalculator::MEzCalculator() { isComplex_ = false; isMuon_ = true; } /// destructor -MEzCalculator::~MEzCalculator() -{ -} +MEzCalculator::~MEzCalculator() {} /// member functions -double -MEzCalculator::Calculate(int type) -{ - if(type<0 || type>3) +double MEzCalculator::Calculate(int type) { + if (type < 0 || type > 3) throw cms::Exception("UnimplementedFeature") << "Type " << type << " not supported in MEzCalculator.\n"; - double M_W = 80.4; - double M_mu = 0.10566; + double M_W = 80.4; + double M_mu = 0.10566; double M_e = 0.511e-3; double M_lepton = M_mu; - if (! isMuon_ ) M_lepton = M_e; - + if (!isMuon_) + M_lepton = M_e; + double emu = lepton_.energy(); double pxmu = lepton_.px(); double pymu = lepton_.py(); @@ -35,64 +31,72 @@ MEzCalculator::Calculate(int type) double pznu = 0.; // use pznu = - B/2*A +/- sqrt(B*B-4*A*C)/(2*A) - - double a = M_W*M_W - M_lepton*M_lepton + 2.0*(pxmu*pxnu + pymu*pynu); - double A = 4.0*(emu*emu - pzmu*pzmu); - double B = -4.0*a*pzmu; - double C = 4.0*emu*emu*(pxnu*pxnu + pynu*pynu) - a*a; - - double tmproot = B*B - 4.0*A*C; - - if (tmproot<0) { - isComplex_= true; - pznu = - B/(2*A); // take real part of complex roots - } - else { + + double a = M_W * M_W - M_lepton * M_lepton + 2.0 * (pxmu * pxnu + pymu * pynu); + double A = 4.0 * (emu * emu - pzmu * pzmu); + double B = -4.0 * a * pzmu; + double C = 4.0 * emu * emu * (pxnu * pxnu + pynu * pynu) - a * a; + + double tmproot = B * B - 4.0 * A * C; + + if (tmproot < 0) { + isComplex_ = true; + pznu = -B / (2 * A); // take real part of complex roots + } else { isComplex_ = false; - double tmpsol1 = (-B + TMath::Sqrt(tmproot))/(2.0*A); - double tmpsol2 = (-B - TMath::Sqrt(tmproot))/(2.0*A); - - if (type == 0 ) { + double tmpsol1 = (-B + TMath::Sqrt(tmproot)) / (2.0 * A); + double tmpsol2 = (-B - TMath::Sqrt(tmproot)) / (2.0 * A); + + if (type == 0) { // two real roots, pick the one closest to pz of muon - if (TMath::Abs(tmpsol2-pzmu) < TMath::Abs(tmpsol1-pzmu)) { pznu = tmpsol2;} - else pznu = tmpsol1; + if (TMath::Abs(tmpsol2 - pzmu) < TMath::Abs(tmpsol1 - pzmu)) { + pznu = tmpsol2; + } else + pznu = tmpsol1; // if pznu is > 300 pick the most central root - if ( pznu > 300. ) { - if (TMath::Abs(tmpsol1) 300.) { + if (TMath::Abs(tmpsol1) < TMath::Abs(tmpsol2)) + pznu = tmpsol1; + else + pznu = tmpsol2; } } - if (type == 1 ) { + if (type == 1) { // two real roots, pick the one closest to pz of muon - if (TMath::Abs(tmpsol2-pzmu) < TMath::Abs(tmpsol1-pzmu)) { pznu = tmpsol2;} - else pznu = tmpsol1; + if (TMath::Abs(tmpsol2 - pzmu) < TMath::Abs(tmpsol1 - pzmu)) { + pznu = tmpsol2; + } else + pznu = tmpsol1; } - if (type == 2 ) { + if (type == 2) { // pick the most central root. - if (TMath::Abs(tmpsol1) costhcm2 ) pznu = tmpsol1; - else pznu = tmpsol2; - } + p3w.SetXYZ(pxmu + pxnu, pymu + pynu, pzmu + tmpsol1); + p3mu.SetXYZ(pxmu, pymu, pzmu); + + double sinthcm1 = 2. * (p3mu.Perp(p3w)) / M_W; + p3w.SetXYZ(pxmu + pxnu, pymu + pynu, pzmu + tmpsol2); + double sinthcm2 = 2. * (p3mu.Perp(p3w)) / M_W; + + double costhcm1 = TMath::Sqrt(1. - sinthcm1 * sinthcm1); + double costhcm2 = TMath::Sqrt(1. - sinthcm2 * sinthcm2); + if (costhcm1 > costhcm2) + pznu = tmpsol1; + else + pznu = tmpsol2; + } } - + //Particle neutrino; //neutrino.setP4( LorentzVector(pxnu, pynu, pznu, TMath::Sqrt(pxnu*pxnu + pynu*pynu + pznu*pznu ))) ; - + return pznu; } diff --git a/TopQuarkAnalysis/TopTools/test/TestGenTtbarCategories.cc b/TopQuarkAnalysis/TopTools/test/TestGenTtbarCategories.cc index 28a88e611380e..404fe35c95f5e 100644 --- a/TopQuarkAnalysis/TopTools/test/TestGenTtbarCategories.cc +++ b/TopQuarkAnalysis/TopTools/test/TestGenTtbarCategories.cc @@ -2,7 +2,7 @@ // // Package: TopQuarkAnalysis/TopTools // Class: TestGenTtbarCategories -// +// /**\class TestGenTtbarCategories TestGenTtbarCategories.cc PhysicsTools/JetMCAlgos/test/TestGenTtbarCategories.cc Description: Analyzer for testing corresponding producer GenTtbarCategorizer @@ -16,7 +16,6 @@ // // - // system include files #include #include @@ -38,38 +37,36 @@ // class TestGenTtbarCategories : public edm::EDAnalyzer { - public: - explicit TestGenTtbarCategories(const edm::ParameterSet&); - ~TestGenTtbarCategories(); - - static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); - - - private: - virtual void beginJob() override; - virtual void analyze(const edm::Event&, const edm::EventSetup&) override; - virtual void endJob() override; - - //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; - //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; - //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; - //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; - - // ----------member data --------------------------- - - // Input tags - const edm::EDGetTokenT genTtbarIdToken_; - - // Variables to fill - int ttbarId_; - int ttbarAdditionalJetId_; - int nBjetsFromTop_; - int nBjetsFromW_; - int nCjetsFromW_; - - // Tree to be filled - TTree* tree_; - +public: + explicit TestGenTtbarCategories(const edm::ParameterSet&); + ~TestGenTtbarCategories(); + + static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); + +private: + virtual void beginJob() override; + virtual void analyze(const edm::Event&, const edm::EventSetup&) override; + virtual void endJob() override; + + //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; + //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; + //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; + //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; + + // ----------member data --------------------------- + + // Input tags + const edm::EDGetTokenT genTtbarIdToken_; + + // Variables to fill + int ttbarId_; + int ttbarAdditionalJetId_; + int nBjetsFromTop_; + int nBjetsFromW_; + int nCjetsFromW_; + + // Tree to be filled + TTree* tree_; }; // @@ -83,61 +80,51 @@ class TestGenTtbarCategories : public edm::EDAnalyzer { // // constructors and destructor // -TestGenTtbarCategories::TestGenTtbarCategories(const edm::ParameterSet& iConfig): -genTtbarIdToken_(consumes(iConfig.getParameter("genTtbarId"))) -{} - - -TestGenTtbarCategories::~TestGenTtbarCategories() -{} +TestGenTtbarCategories::TestGenTtbarCategories(const edm::ParameterSet& iConfig) + : genTtbarIdToken_(consumes(iConfig.getParameter("genTtbarId"))) {} +TestGenTtbarCategories::~TestGenTtbarCategories() {} // // member functions // // ------------ method called for each event ------------ -void -TestGenTtbarCategories::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) -{ - edm::Handle genTtbarId; - iEvent.getByToken(genTtbarIdToken_, genTtbarId); - - // ID including information about b/c jets in acceptance from t->b/W->b/W->c decays as well as additional ones - ttbarId_ = *genTtbarId; - - // ID based only on additional b/c jets - ttbarAdditionalJetId_ = ttbarId_%100; - - // Number of b/c jets from t->b or W->b/c decays - nBjetsFromTop_ = ttbarId_%1000/100; - nBjetsFromW_ = ttbarId_%10000/1000; - nCjetsFromW_ = ttbarId_%100000/10000; - - // Filling the tree - tree_->Fill(); -} +void TestGenTtbarCategories::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { + edm::Handle genTtbarId; + iEvent.getByToken(genTtbarIdToken_, genTtbarId); + + // ID including information about b/c jets in acceptance from t->b/W->b/W->c decays as well as additional ones + ttbarId_ = *genTtbarId; + + // ID based only on additional b/c jets + ttbarAdditionalJetId_ = ttbarId_ % 100; + // Number of b/c jets from t->b or W->b/c decays + nBjetsFromTop_ = ttbarId_ % 1000 / 100; + nBjetsFromW_ = ttbarId_ % 10000 / 1000; + nCjetsFromW_ = ttbarId_ % 100000 / 10000; + + // Filling the tree + tree_->Fill(); +} // ------------ method called once each job just before starting event loop ------------ -void -TestGenTtbarCategories::beginJob() -{ - edm::Service fileService; - if(!fileService) throw edm::Exception(edm::errors::Configuration, "TFileService is not registered in cfg file"); - - tree_ = fileService->make("tree", "tree"); - tree_->Branch("ttbarId", &ttbarId_); - tree_->Branch("ttbarAdditionalJetId", &ttbarAdditionalJetId_); - tree_->Branch("nBjetsFromTop", &nBjetsFromTop_); - tree_->Branch("nBjetsFromW", &nBjetsFromW_); - tree_->Branch("nCjetsFromW", &nCjetsFromW_); +void TestGenTtbarCategories::beginJob() { + edm::Service fileService; + if (!fileService) + throw edm::Exception(edm::errors::Configuration, "TFileService is not registered in cfg file"); + + tree_ = fileService->make("tree", "tree"); + tree_->Branch("ttbarId", &ttbarId_); + tree_->Branch("ttbarAdditionalJetId", &ttbarAdditionalJetId_); + tree_->Branch("nBjetsFromTop", &nBjetsFromTop_); + tree_->Branch("nBjetsFromW", &nBjetsFromW_); + tree_->Branch("nCjetsFromW", &nCjetsFromW_); } // ------------ method called once each job just after ending the event loop ------------ -void -TestGenTtbarCategories::endJob() -{} +void TestGenTtbarCategories::endJob() {} // ------------ method called when starting to processes a run ------------ /* @@ -172,8 +159,7 @@ TestGenTtbarCategories::endLuminosityBlock(edm::LuminosityBlock const&, edm::Eve */ // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ -void -TestGenTtbarCategories::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { +void TestGenTtbarCategories::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; diff --git a/TopQuarkAnalysis/TopTools/test/runtestTqafTopTools.cpp b/TopQuarkAnalysis/TopTools/test/runtestTqafTopTools.cpp index 87f88d6e99091..b2991bd18ae57 100644 --- a/TopQuarkAnalysis/TopTools/test/runtestTqafTopTools.cpp +++ b/TopQuarkAnalysis/TopTools/test/runtestTqafTopTools.cpp @@ -1,3 +1,3 @@ #include "FWCore/Utilities/interface/TestHelper.h" - + RUNTEST() diff --git a/TopQuarkAnalysis/TopTools/test/tdrstyle.C b/TopQuarkAnalysis/TopTools/test/tdrstyle.C old mode 100755 new mode 100644 index f546bb6095e1a..75cb12a93cb03 --- a/TopQuarkAnalysis/TopTools/test/tdrstyle.C +++ b/TopQuarkAnalysis/TopTools/test/tdrstyle.C @@ -1,16 +1,16 @@ #include "TStyle.h" void setTDRStyle() { - TStyle *tdrStyle = new TStyle("tdrStyle","Style for P-TDR"); + TStyle *tdrStyle = new TStyle("tdrStyle", "Style for P-TDR"); -// For the canvas: + // For the canvas: tdrStyle->SetCanvasBorderMode(0); tdrStyle->SetCanvasColor(kWhite); - tdrStyle->SetCanvasDefH(600); //Height of canvas - tdrStyle->SetCanvasDefW(600); //Width of canvas - tdrStyle->SetCanvasDefX(0); //POsition on screen + tdrStyle->SetCanvasDefH(600); //Height of canvas + tdrStyle->SetCanvasDefW(600); //Width of canvas + tdrStyle->SetCanvasDefX(0); //POsition on screen tdrStyle->SetCanvasDefY(0); -// For the Pad: + // For the Pad: tdrStyle->SetPadBorderMode(0); // tdrStyle->SetPadBorderSize(Width_t size = 1); tdrStyle->SetPadColor(kWhite); @@ -20,7 +20,7 @@ void setTDRStyle() { tdrStyle->SetGridStyle(3); tdrStyle->SetGridWidth(1); -// For the frame: + // For the frame: tdrStyle->SetFrameBorderMode(0); tdrStyle->SetFrameBorderSize(1); tdrStyle->SetFrameFillColor(0); @@ -29,7 +29,7 @@ void setTDRStyle() { tdrStyle->SetFrameLineStyle(1); tdrStyle->SetFrameLineWidth(1); -// For the histo: + // For the histo: // tdrStyle->SetHistFillColor(1); // tdrStyle->SetHistFillStyle(0); tdrStyle->SetHistLineColor(1); @@ -41,24 +41,24 @@ void setTDRStyle() { tdrStyle->SetEndErrorSize(2); //tdrStyle->SetErrorMarker(20); tdrStyle->SetErrorX(0.); - + tdrStyle->SetMarkerStyle(20); -//For the fit/function: + //For the fit/function: tdrStyle->SetOptFit(1); tdrStyle->SetFitFormat("5.4g"); tdrStyle->SetFuncColor(2); tdrStyle->SetFuncStyle(1); tdrStyle->SetFuncWidth(1); -//For the date: + //For the date: tdrStyle->SetOptDate(0); // tdrStyle->SetDateX(Float_t x = 0.01); // tdrStyle->SetDateY(Float_t y = 0.01); -// For the statistics box: + // For the statistics box: tdrStyle->SetOptFile(0); - tdrStyle->SetOptStat(0); // To display the mean and RMS: SetOptStat("mr"); + tdrStyle->SetOptStat(0); // To display the mean and RMS: SetOptStat("mr"); tdrStyle->SetStatColor(kWhite); tdrStyle->SetStatFont(42); tdrStyle->SetStatFontSize(0.025); @@ -71,15 +71,15 @@ void setTDRStyle() { // tdrStyle->SetStatX(Float_t x = 0); // tdrStyle->SetStatY(Float_t y = 0); -// Margins: + // Margins: tdrStyle->SetPadTopMargin(0.05); tdrStyle->SetPadBottomMargin(0.13); tdrStyle->SetPadLeftMargin(0.13); tdrStyle->SetPadRightMargin(0.05); -// For the Global title: + // For the Global title: -// tdrStyle->SetOptTitle(0); + // tdrStyle->SetOptTitle(0); tdrStyle->SetTitleFont(42); tdrStyle->SetTitleColor(1); tdrStyle->SetTitleTextColor(1); @@ -92,7 +92,7 @@ void setTDRStyle() { // tdrStyle->SetTitleStyle(Style_t style = 1001); // tdrStyle->SetTitleBorderSize(2); -// For the axis titles: + // For the axis titles: tdrStyle->SetTitleColor(1, "XYZ"); tdrStyle->SetTitleFont(42, "XYZ"); @@ -103,14 +103,14 @@ void setTDRStyle() { tdrStyle->SetTitleYOffset(1.05); // tdrStyle->SetTitleOffset(1.1, "Y"); // Another way to set the Offset -// For the axis labels: + // For the axis labels: tdrStyle->SetLabelColor(1, "XYZ"); tdrStyle->SetLabelFont(42, "XYZ"); tdrStyle->SetLabelOffset(0.007, "XYZ"); tdrStyle->SetLabelSize(0.05, "XYZ"); -// For the axis: + // For the axis: tdrStyle->SetAxisColor(1, "XYZ"); tdrStyle->SetStripDecimals(kTRUE); @@ -119,12 +119,12 @@ void setTDRStyle() { tdrStyle->SetPadTickX(1); // To get tick marks on the opposite side of the frame tdrStyle->SetPadTickY(1); -// Change for log plots: + // Change for log plots: tdrStyle->SetOptLogx(0); tdrStyle->SetOptLogy(0); tdrStyle->SetOptLogz(0); -// Postscript options: + // Postscript options: // tdrStyle->SetPaperSize(15.,15.); // tdrStyle->SetLineScalePS(Float_t scale = 3); // tdrStyle->SetLineStyleString(Int_t i, const char* text); @@ -139,9 +139,4 @@ void setTDRStyle() { // tdrStyle->SetHistMinimumZero(kTRUE); tdrStyle->cd(); - } - - - -